blob: ec149dddc1d917c2d4aa010afa33afc042bc6ade [file] [log] [blame]
Lang Hames87e3bca2009-05-06 02:36:21 +00001//===-- llvm/CodeGen/Rewriter.cpp - Rewriter -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#define DEBUG_TYPE "virtregrewriter"
11#include "VirtRegRewriter.h"
Evan Cheng98116f92010-04-06 17:19:55 +000012#include "VirtRegMap.h"
Benjamin Kramercfa6ec92009-08-23 11:37:21 +000013#include "llvm/Function.h"
Evan Cheng98116f92010-04-06 17:19:55 +000014#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Benjamin Kramercfa6ec92009-08-23 11:37:21 +000015#include "llvm/CodeGen/MachineFrameInfo.h"
16#include "llvm/CodeGen/MachineInstrBuilder.h"
17#include "llvm/CodeGen/MachineRegisterInfo.h"
Benjamin Kramercfa6ec92009-08-23 11:37:21 +000018#include "llvm/Support/CommandLine.h"
19#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000020#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000021#include "llvm/Support/raw_ostream.h"
Benjamin Kramercfa6ec92009-08-23 11:37:21 +000022#include "llvm/Target/TargetInstrInfo.h"
David Greene2d4e6d32009-07-28 16:49:24 +000023#include "llvm/Target/TargetLowering.h"
Lang Hames87e3bca2009-05-06 02:36:21 +000024#include "llvm/ADT/DepthFirstIterator.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000025#include "llvm/ADT/SmallSet.h"
Lang Hames87e3bca2009-05-06 02:36:21 +000026#include "llvm/ADT/Statistic.h"
Lang Hames87e3bca2009-05-06 02:36:21 +000027using namespace llvm;
28
29STATISTIC(NumDSE , "Number of dead stores elided");
30STATISTIC(NumDSS , "Number of dead spill slots removed");
31STATISTIC(NumCommutes, "Number of instructions commuted");
32STATISTIC(NumDRM , "Number of re-materializable defs elided");
33STATISTIC(NumStores , "Number of stores added");
34STATISTIC(NumPSpills , "Number of physical register spills");
35STATISTIC(NumOmitted , "Number of reloads omited");
36STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
37STATISTIC(NumCopified, "Number of available reloads turned into copies");
38STATISTIC(NumReMats , "Number of re-materialization");
39STATISTIC(NumLoads , "Number of loads added");
40STATISTIC(NumReused , "Number of values reused");
41STATISTIC(NumDCE , "Number of copies elided");
42STATISTIC(NumSUnfold , "Number of stores unfolded");
43STATISTIC(NumModRefUnfold, "Number of modref unfolded");
44
45namespace {
Lang Hamesac276402009-06-04 18:45:36 +000046 enum RewriterName { local, trivial };
Lang Hames87e3bca2009-05-06 02:36:21 +000047}
48
49static cl::opt<RewriterName>
50RewriterOpt("rewriter",
Duncan Sands18619b22010-02-18 14:37:52 +000051 cl::desc("Rewriter to use (default=local)"),
Lang Hames87e3bca2009-05-06 02:36:21 +000052 cl::Prefix,
Lang Hamesac276402009-06-04 18:45:36 +000053 cl::values(clEnumVal(local, "local rewriter"),
Lang Hamesf41538d2009-06-02 16:53:25 +000054 clEnumVal(trivial, "trivial rewriter"),
Lang Hames87e3bca2009-05-06 02:36:21 +000055 clEnumValEnd),
56 cl::init(local));
57
Dan Gohman7db949d2009-08-07 01:32:21 +000058static cl::opt<bool>
David Greene2d4e6d32009-07-28 16:49:24 +000059ScheduleSpills("schedule-spills",
60 cl::desc("Schedule spill code"),
61 cl::init(false));
62
Lang Hames87e3bca2009-05-06 02:36:21 +000063VirtRegRewriter::~VirtRegRewriter() {}
64
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +000065/// substitutePhysReg - Replace virtual register in MachineOperand with a
66/// physical register. Do the right thing with the sub-register index.
Jakob Stoklund Olesend135f142010-02-13 02:06:10 +000067/// Note that operands may be added, so the MO reference is no longer valid.
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +000068static void substitutePhysReg(MachineOperand &MO, unsigned Reg,
69 const TargetRegisterInfo &TRI) {
Jakob Stoklund Olesen6b964cd2010-09-07 22:38:45 +000070 if (MO.getSubReg()) {
71 MO.substPhysReg(Reg, TRI);
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +000072
Jakob Stoklund Olesen6b964cd2010-09-07 22:38:45 +000073 // 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.
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +000077 MachineInstr &MI = *MO.getParent();
Jakob Stoklund Olesen6b964cd2010-09-07 22:38:45 +000078 if (MO.isUse() && !MO.isUndef() &&
79 (MO.isKill() || MI.isRegTiedToDefOperand(&MO-&MI.getOperand(0))))
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +000080 MI.addRegisterKilled(Reg, &TRI, /*AddIfNotFound=*/ true);
81 } else {
82 MO.setReg(Reg);
83 }
84}
85
Dan Gohman7db949d2009-08-07 01:32:21 +000086namespace {
Lang Hames87e3bca2009-05-06 02:36:21 +000087
Lang Hamesf41538d2009-06-02 16:53:25 +000088/// 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
90/// spill code.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000091struct TrivialRewriter : public VirtRegRewriter {
Lang Hamesf41538d2009-06-02 16:53:25 +000092
93 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
94 LiveIntervals* LIs) {
David Greene0ee52182010-01-05 01:25:52 +000095 DEBUG(dbgs() << "********** REWRITE MACHINE CODE **********\n");
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +000096 DEBUG(dbgs() << "********** Function: "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000097 << MF.getFunction()->getName() << '\n');
David Greene0ee52182010-01-05 01:25:52 +000098 DEBUG(dbgs() << "**** Machine Instrs"
Chris Lattner6456d382009-08-23 03:20:44 +000099 << "(NOTE! Does not include spills and reloads!) ****\n");
David Greene2d4e6d32009-07-28 16:49:24 +0000100 DEBUG(MF.dump());
101
Lang Hamesf41538d2009-06-02 16:53:25 +0000102 MachineRegisterInfo *mri = &MF.getRegInfo();
Lang Hames38283e22009-11-18 20:31:20 +0000103 const TargetRegisterInfo *tri = MF.getTarget().getRegisterInfo();
Lang Hamesf41538d2009-06-02 16:53:25 +0000104
105 bool changed = false;
106
107 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
108 liItr != liEnd; ++liItr) {
109
Lang Hames38283e22009-11-18 20:31:20 +0000110 const LiveInterval *li = liItr->second;
111 unsigned reg = li->reg;
112
113 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
114 if (!li->empty())
115 mri->setPhysRegUsed(reg);
116 }
117 else {
118 if (!VRM.hasPhys(reg))
119 continue;
120 unsigned pReg = VRM.getPhys(reg);
121 mri->setPhysRegUsed(pReg);
Jakob Stoklund Olesend135f142010-02-13 02:06:10 +0000122 // 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),
129 pReg, *tri);
130 changed |= !reglist.empty();
Lang Hamesf41538d2009-06-02 16:53:25 +0000131 }
Lang Hamesf41538d2009-06-02 16:53:25 +0000132 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000133
David Greene0ee52182010-01-05 01:25:52 +0000134 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
David Greene2d4e6d32009-07-28 16:49:24 +0000135 DEBUG(MF.dump());
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000136
Lang Hamesf41538d2009-06-02 16:53:25 +0000137 return changed;
138 }
139
140};
141
Dan Gohman7db949d2009-08-07 01:32:21 +0000142}
143
Lang Hames87e3bca2009-05-06 02:36:21 +0000144// ************************************************************************ //
145
Dan Gohman7db949d2009-08-07 01:32:21 +0000146namespace {
147
Lang Hames87e3bca2009-05-06 02:36:21 +0000148/// 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
150/// each register.
151///
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.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000159class AvailableSpills {
Lang Hames87e3bca2009-05-06 02:36:21 +0000160 const TargetRegisterInfo *TRI;
161 const TargetInstrInfo *TII;
162
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;
167
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;
173
174 void disallowClobberPhysRegOnly(unsigned PhysReg);
175
176 void ClobberPhysRegOnly(unsigned PhysReg);
177public:
178 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
179 : TRI(tri), TII(tii) {
180 }
181
182 /// clear - Reset the state.
183 void clear() {
184 SpillSlotsOrReMatsAvailable.clear();
185 PhysRegsAvailable.clear();
186 }
187
188 const TargetRegisterInfo *getRegInfo() const { return TRI; }
189
190 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
191 /// available in a physical register, return that PhysReg, otherwise
192 /// return 0.
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.
198 }
199 return 0;
200 }
201
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) {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000206 // If this stack slot is thought to be available in some other physreg,
Lang Hames87e3bca2009-05-06 02:36:21 +0000207 // remove its record.
208 ModifyStackSlotOrReMat(SlotOrReMat);
209
210 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
211 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
212 (unsigned)CanClobber;
213
214 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +0000215 DEBUG(dbgs() << "Remembering RM#"
Chris Lattner6456d382009-08-23 03:20:44 +0000216 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +0000217 else
David Greene0ee52182010-01-05 01:25:52 +0000218 DEBUG(dbgs() << "Remembering SS#" << SlotOrReMat);
Andrew Trick5d7ab852011-01-27 21:26:43 +0000219 DEBUG(dbgs() << " in physreg " << TRI->getName(Reg)
220 << (CanClobber ? " canclobber" : "") << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000221 }
222
223 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
224 /// the value of the specified stackslot register if it desires. The
225 /// specified stack slot must be available in a physreg for this query to
226 /// make sense.
227 bool canClobberPhysRegForSS(int SlotOrReMat) const {
228 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
229 "Value not available!");
230 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
231 }
232
233 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
234 /// physical register where values for some stack slot(s) might be
235 /// available.
236 bool canClobberPhysReg(unsigned PhysReg) const {
237 std::multimap<unsigned, int>::const_iterator I =
238 PhysRegsAvailable.lower_bound(PhysReg);
239 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
240 int SlotOrReMat = I->second;
241 I++;
242 if (!canClobberPhysRegForSS(SlotOrReMat))
243 return false;
244 }
245 return true;
246 }
247
248 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
249 /// stackslot register. The register is still available but is no longer
250 /// allowed to be modifed.
251 void disallowClobberPhysReg(unsigned PhysReg);
252
253 /// ClobberPhysReg - This is called when the specified physreg changes
254 /// value. We use this to invalidate any info about stuff that lives in
255 /// it and any of its aliases.
256 void ClobberPhysReg(unsigned PhysReg);
257
258 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
259 /// slot changes. This removes information about which register the
260 /// previous value for this slot lives in (as the previous value is dead
261 /// now).
262 void ModifyStackSlotOrReMat(int SlotOrReMat);
263
264 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
265 /// into the specified MBB. Add available physical registers as potential
266 /// live-in's. If they are reused in the MBB, they will be added to the
267 /// live-in set to make register scavenger and post-allocation scheduler.
268 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
269 std::vector<MachineOperand*> &KillOps);
270};
271
Dan Gohman7db949d2009-08-07 01:32:21 +0000272}
273
Lang Hames87e3bca2009-05-06 02:36:21 +0000274// ************************************************************************ //
275
David Greene2d4e6d32009-07-28 16:49:24 +0000276// Given a location where a reload of a spilled register or a remat of
277// a constant is to be inserted, attempt to find a safe location to
278// insert the load at an earlier point in the basic-block, to hide
279// latency of the load and to avoid address-generation interlock
280// issues.
281static MachineBasicBlock::iterator
282ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
283 MachineBasicBlock::iterator const Begin,
284 unsigned PhysReg,
285 const TargetRegisterInfo *TRI,
286 bool DoReMat,
287 int SSorRMId,
288 const TargetInstrInfo *TII,
289 const MachineFunction &MF)
290{
291 if (!ScheduleSpills)
292 return InsertLoc;
293
294 // Spill backscheduling is of primary interest to addresses, so
295 // don't do anything if the register isn't in the register class
296 // used for pointers.
297
298 const TargetLowering *TL = MF.getTarget().getTargetLowering();
299
300 if (!TL->isTypeLegal(TL->getPointerTy()))
Chris Lattner60cb5282010-10-11 05:44:40 +0000301 // Believe it or not, this is true on 16-bit targets like PIC16.
David Greene2d4e6d32009-07-28 16:49:24 +0000302 return InsertLoc;
303
304 const TargetRegisterClass *ptrRegClass =
305 TL->getRegClassFor(TL->getPointerTy());
306 if (!ptrRegClass->contains(PhysReg))
307 return InsertLoc;
308
309 // Scan upwards through the preceding instructions. If an instruction doesn't
310 // reference the stack slot or the register we're loading, we can
311 // backschedule the reload up past it.
312 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
313 while (NewInsertLoc != Begin) {
314 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
315 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
316 MachineOperand &Op = Prev->getOperand(i);
317 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
318 goto stop;
319 }
320 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
321 Prev->findRegisterDefOperand(PhysReg))
322 goto stop;
323 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
324 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
325 Prev->findRegisterDefOperand(*Alias))
326 goto stop;
327 NewInsertLoc = Prev;
328 }
329stop:;
330
331 // If we made it to the beginning of the block, turn around and move back
332 // down just past any existing reloads. They're likely to be reloads/remats
333 // for instructions earlier than what our current reload/remat is for, so
334 // they should be scheduled earlier.
335 if (NewInsertLoc == Begin) {
336 int FrameIdx;
337 while (InsertLoc != NewInsertLoc &&
338 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
339 TII->isTriviallyReMaterializable(NewInsertLoc)))
340 ++NewInsertLoc;
341 }
342
343 return NewInsertLoc;
344}
Dan Gohman7db949d2009-08-07 01:32:21 +0000345
346namespace {
347
Lang Hames87e3bca2009-05-06 02:36:21 +0000348// ReusedOp - For each reused operand, we keep track of a bit of information,
349// in case we need to rollback upon processing a new operand. See comments
350// below.
351struct ReusedOp {
352 // The MachineInstr operand that reused an available value.
353 unsigned Operand;
354
355 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
356 unsigned StackSlotOrReMat;
357
358 // PhysRegReused - The physical register the value was available in.
359 unsigned PhysRegReused;
360
361 // AssignedPhysReg - The physreg that was assigned for use by the reload.
362 unsigned AssignedPhysReg;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000363
Lang Hames87e3bca2009-05-06 02:36:21 +0000364 // VirtReg - The virtual register itself.
365 unsigned VirtReg;
366
367 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
368 unsigned vreg)
369 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
370 AssignedPhysReg(apr), VirtReg(vreg) {}
371};
372
373/// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
374/// is reused instead of reloaded.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000375class ReuseInfo {
Lang Hames87e3bca2009-05-06 02:36:21 +0000376 MachineInstr &MI;
377 std::vector<ReusedOp> Reuses;
378 BitVector PhysRegsClobbered;
379public:
380 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
381 PhysRegsClobbered.resize(tri->getNumRegs());
382 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000383
Lang Hames87e3bca2009-05-06 02:36:21 +0000384 bool hasReuses() const {
385 return !Reuses.empty();
386 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000387
Lang Hames87e3bca2009-05-06 02:36:21 +0000388 /// addReuse - If we choose to reuse a virtual register that is already
389 /// available instead of reloading it, remember that we did so.
390 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
391 unsigned PhysRegReused, unsigned AssignedPhysReg,
392 unsigned VirtReg) {
393 // If the reload is to the assigned register anyway, no undo will be
394 // required.
395 if (PhysRegReused == AssignedPhysReg) return;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000396
Lang Hames87e3bca2009-05-06 02:36:21 +0000397 // Otherwise, remember this.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000398 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
Lang Hames87e3bca2009-05-06 02:36:21 +0000399 AssignedPhysReg, VirtReg));
400 }
401
402 void markClobbered(unsigned PhysReg) {
403 PhysRegsClobbered.set(PhysReg);
404 }
405
406 bool isClobbered(unsigned PhysReg) const {
407 return PhysRegsClobbered.test(PhysReg);
408 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000409
Lang Hames87e3bca2009-05-06 02:36:21 +0000410 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
411 /// is some other operand that is using the specified register, either pick
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000412 /// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000413 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
414 MachineFunction &MF, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000415 AvailableSpills &Spills,
416 std::vector<MachineInstr*> &MaybeDeadStores,
417 SmallSet<unsigned, 8> &Rejected,
418 BitVector &RegKills,
419 std::vector<MachineOperand*> &KillOps,
420 VirtRegMap &VRM);
421
422 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
423 /// 'Rejected' set to remember which registers have been considered and
424 /// rejected for the reload. This avoids infinite looping in case like
425 /// this:
426 /// t1 := op t2, t3
427 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
428 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
429 /// t1 <- desires r1
430 /// sees r1 is taken by t2, tries t2's reload register r0
431 /// sees r0 is taken by t3, tries t3's reload register r1
432 /// sees r1 is taken by t2, tries t2's reload register r0 ...
Evan Cheng5d885022009-07-21 09:15:00 +0000433 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000434 AvailableSpills &Spills,
435 std::vector<MachineInstr*> &MaybeDeadStores,
436 BitVector &RegKills,
437 std::vector<MachineOperand*> &KillOps,
438 VirtRegMap &VRM) {
439 SmallSet<unsigned, 8> Rejected;
Evan Cheng5d885022009-07-21 09:15:00 +0000440 MachineFunction &MF = *MI->getParent()->getParent();
441 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
442 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
443 Rejected, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +0000444 }
445};
446
Dan Gohman7db949d2009-08-07 01:32:21 +0000447}
Lang Hames87e3bca2009-05-06 02:36:21 +0000448
449// ****************** //
450// Utility Functions //
451// ****************** //
452
Lang Hames87e3bca2009-05-06 02:36:21 +0000453/// findSinglePredSuccessor - Return via reference a vector of machine basic
454/// blocks each of which is a successor of the specified BB and has no other
455/// predecessor.
456static void findSinglePredSuccessor(MachineBasicBlock *MBB,
Jim Grosbach57cb4f82010-07-27 17:38:47 +0000457 SmallVectorImpl<MachineBasicBlock *> &Succs){
Lang Hames87e3bca2009-05-06 02:36:21 +0000458 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
459 SE = MBB->succ_end(); SI != SE; ++SI) {
460 MachineBasicBlock *SuccMBB = *SI;
461 if (SuccMBB->pred_size() == 1)
462 Succs.push_back(SuccMBB);
463 }
464}
465
Andrew Trick5d7ab852011-01-27 21:26:43 +0000466/// ResurrectConfirmedKill - Helper for ResurrectKill. This register is killed
467/// but not re-defined and it's being reused. Remove the kill flag for the
468/// register and unset the kill's marker and last kill operand.
469static void ResurrectConfirmedKill(unsigned Reg, const TargetRegisterInfo* TRI,
470 BitVector &RegKills,
471 std::vector<MachineOperand*> &KillOps) {
472 DEBUG(dbgs() << "Resurrect " << TRI->getName(Reg) << "\n");
473
474 MachineOperand *KillOp = KillOps[Reg];
475 KillOp->setIsKill(false);
476 // KillOps[Reg] might be a def of a super-register.
477 unsigned KReg = KillOp->getReg();
478 if (!RegKills[KReg])
479 return;
480
Andrew Trickfcfcdbc2011-02-22 06:52:56 +0000481 assert(KillOps[KReg]->getParent() == KillOp->getParent() &&
482 "invalid superreg kill flags");
Andrew Trick5d7ab852011-01-27 21:26:43 +0000483 KillOps[KReg] = NULL;
484 RegKills.reset(KReg);
485
486 // If it's a def of a super-register. Its other sub-regsters are no
487 // longer killed as well.
488 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
489 DEBUG(dbgs() << " Resurrect subreg " << TRI->getName(*SR) << "\n");
490
Andrew Trickfcfcdbc2011-02-22 06:52:56 +0000491 assert(KillOps[*SR]->getParent() == KillOp->getParent() &&
492 "invalid subreg kill flags");
Andrew Trick5d7ab852011-01-27 21:26:43 +0000493 KillOps[*SR] = NULL;
494 RegKills.reset(*SR);
495 }
496}
497
498/// ResurrectKill - Invalidate kill info associated with a previous MI. An
499/// optimization may have decided that it's safe to reuse a previously killed
500/// register. If we fail to erase the invalid kill flags, then the register
501/// scavenger may later clobber the register used by this MI. Note that this
502/// must be done even if this MI is being deleted! Consider:
503///
504/// USE $r1 (vreg1) <kill>
505/// ...
506/// $r1(vreg3) = COPY $r1 (vreg2)
507///
508/// RegAlloc has smartly assigned all three vregs to the same physreg. Initially
509/// vreg1's only use is a kill. The rewriter doesn't know it should be live
510/// until it rewrites vreg2. At that points it sees that the copy is dead and
511/// deletes it. However, deleting the copy implicitly forwards liveness of $r1
512/// (it's copy coalescing). We must resurrect $r1 by removing the kill flag at
513/// vreg1 before deleting the copy.
514static void ResurrectKill(MachineInstr &MI, unsigned Reg,
515 const TargetRegisterInfo* TRI, BitVector &RegKills,
516 std::vector<MachineOperand*> &KillOps) {
517 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
518 ResurrectConfirmedKill(Reg, TRI, RegKills, KillOps);
519 return;
520 }
521 // No previous kill for this reg. Check for subreg kills as well.
522 // d4 =
523 // store d4, fi#0
524 // ...
525 // = s8<kill>
526 // ...
527 // = d4 <avoiding reload>
528 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
529 unsigned SReg = *SR;
530 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI)
531 ResurrectConfirmedKill(SReg, TRI, RegKills, KillOps);
Evan Cheng427a6b62009-05-15 06:48:19 +0000532 }
533}
534
Lang Hames87e3bca2009-05-06 02:36:21 +0000535/// InvalidateKills - MI is going to be deleted. If any of its operands are
536/// marked kill, then invalidate the information.
Evan Cheng427a6b62009-05-15 06:48:19 +0000537static void InvalidateKills(MachineInstr &MI,
538 const TargetRegisterInfo* TRI,
539 BitVector &RegKills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000540 std::vector<MachineOperand*> &KillOps,
541 SmallVector<unsigned, 2> *KillRegs = NULL) {
542 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
543 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000544 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000545 continue;
546 unsigned Reg = MO.getReg();
547 if (TargetRegisterInfo::isVirtualRegister(Reg))
548 continue;
549 if (KillRegs)
550 KillRegs->push_back(Reg);
551 assert(Reg < KillOps.size());
552 if (KillOps[Reg] == &MO) {
Andrew Trick5d7ab852011-01-27 21:26:43 +0000553 // This operand was the kill, now no longer.
Lang Hames87e3bca2009-05-06 02:36:21 +0000554 KillOps[Reg] = NULL;
Evan Cheng427a6b62009-05-15 06:48:19 +0000555 RegKills.reset(Reg);
556 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
557 if (RegKills[*SR]) {
Andrew Trick5d7ab852011-01-27 21:26:43 +0000558 assert(KillOps[*SR] == &MO && "bad subreg kill flags");
Evan Cheng427a6b62009-05-15 06:48:19 +0000559 KillOps[*SR] = NULL;
560 RegKills.reset(*SR);
561 }
562 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000563 }
Andrew Trick5d7ab852011-01-27 21:26:43 +0000564 else {
565 // This operand may have reused a previously killed reg. Keep it live in
566 // case it continues to be used after erasing this instruction.
567 ResurrectKill(MI, Reg, TRI, RegKills, KillOps);
568 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000569 }
570}
571
572/// InvalidateRegDef - If the def operand of the specified def MI is now dead
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000573/// (since its spill instruction is removed), mark it isDead. Also checks if
Lang Hames87e3bca2009-05-06 02:36:21 +0000574/// the def MI has other definition operands that are not dead. Returns it by
575/// reference.
576static bool InvalidateRegDef(MachineBasicBlock::iterator I,
577 MachineInstr &NewDef, unsigned Reg,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000578 bool &HasLiveDef,
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000579 const TargetRegisterInfo *TRI) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000580 // Due to remat, it's possible this reg isn't being reused. That is,
581 // the def of this reg (by prev MI) is now dead.
582 MachineInstr *DefMI = I;
583 MachineOperand *DefOp = NULL;
584 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
585 MachineOperand &MO = DefMI->getOperand(i);
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000586 if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
Evan Cheng4784f1f2009-06-30 08:49:04 +0000587 continue;
588 if (MO.getReg() == Reg)
589 DefOp = &MO;
590 else if (!MO.isDead())
591 HasLiveDef = true;
Lang Hames87e3bca2009-05-06 02:36:21 +0000592 }
593 if (!DefOp)
594 return false;
595
596 bool FoundUse = false, Done = false;
597 MachineBasicBlock::iterator E = &NewDef;
598 ++I; ++E;
599 for (; !Done && I != E; ++I) {
600 MachineInstr *NMI = I;
601 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
602 MachineOperand &MO = NMI->getOperand(j);
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000603 if (!MO.isReg() || MO.getReg() == 0 ||
604 (MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
Lang Hames87e3bca2009-05-06 02:36:21 +0000605 continue;
606 if (MO.isUse())
607 FoundUse = true;
608 Done = true; // Stop after scanning all the operands of this MI.
609 }
610 }
611 if (!FoundUse) {
612 // Def is dead!
613 DefOp->setIsDead();
614 return true;
615 }
616 return false;
617}
618
619/// UpdateKills - Track and update kill info. If a MI reads a register that is
620/// marked kill, then it must be due to register reuse. Transfer the kill info
621/// over.
Evan Cheng427a6b62009-05-15 06:48:19 +0000622static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
623 BitVector &RegKills,
624 std::vector<MachineOperand*> &KillOps) {
Dale Johannesen4d12d3b2010-03-26 19:21:26 +0000625 // These do not affect kill info at all.
626 if (MI.isDebugValue())
627 return;
Lang Hames87e3bca2009-05-06 02:36:21 +0000628 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
629 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000630 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000631 continue;
632 unsigned Reg = MO.getReg();
633 if (Reg == 0)
634 continue;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000635
Andrew Trick5d7ab852011-01-27 21:26:43 +0000636 // This operand may have reused a previously killed reg. Keep it live.
637 ResurrectKill(MI, Reg, TRI, RegKills, KillOps);
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000638
Lang Hames87e3bca2009-05-06 02:36:21 +0000639 if (MO.isKill()) {
640 RegKills.set(Reg);
641 KillOps[Reg] = &MO;
Evan Cheng427a6b62009-05-15 06:48:19 +0000642 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
643 RegKills.set(*SR);
644 KillOps[*SR] = &MO;
645 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000646 }
647 }
648
649 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
650 const MachineOperand &MO = MI.getOperand(i);
Evan Chengd57cdd52009-11-14 02:55:43 +0000651 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000652 continue;
653 unsigned Reg = MO.getReg();
654 RegKills.reset(Reg);
655 KillOps[Reg] = NULL;
656 // It also defines (or partially define) aliases.
Evan Cheng427a6b62009-05-15 06:48:19 +0000657 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
658 RegKills.reset(*SR);
659 KillOps[*SR] = NULL;
Lang Hames87e3bca2009-05-06 02:36:21 +0000660 }
Evan Cheng1f6a3c82009-11-13 23:16:41 +0000661 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
662 RegKills.reset(*SR);
663 KillOps[*SR] = NULL;
664 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000665 }
666}
667
668/// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
669///
670static void ReMaterialize(MachineBasicBlock &MBB,
671 MachineBasicBlock::iterator &MII,
672 unsigned DestReg, unsigned Reg,
673 const TargetInstrInfo *TII,
674 const TargetRegisterInfo *TRI,
675 VirtRegMap &VRM) {
Evan Cheng5f159922009-07-16 20:15:00 +0000676 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
Daniel Dunbar24cd3c42009-07-16 22:08:25 +0000677#ifndef NDEBUG
Evan Cheng5f159922009-07-16 20:15:00 +0000678 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
Evan Chengc1b46f92009-07-17 00:32:06 +0000679 assert(TID.getNumDefs() == 1 &&
Evan Cheng5f159922009-07-16 20:15:00 +0000680 "Don't know how to remat instructions that define > 1 values!");
681#endif
Jakob Stoklund Olesen9edf7de2010-06-02 22:47:25 +0000682 TII->reMaterialize(MBB, MII, DestReg, 0, ReMatDefMI, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000683 MachineInstr *NewMI = prior(MII);
684 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
685 MachineOperand &MO = NewMI->getOperand(i);
686 if (!MO.isReg() || MO.getReg() == 0)
687 continue;
688 unsigned VirtReg = MO.getReg();
689 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
690 continue;
691 assert(MO.isUse());
Lang Hames87e3bca2009-05-06 02:36:21 +0000692 unsigned Phys = VRM.getPhys(VirtReg);
Evan Cheng427c3ba2009-10-25 07:51:47 +0000693 assert(Phys && "Virtual register is not assigned a register?");
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +0000694 substitutePhysReg(MO, Phys, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000695 }
696 ++NumReMats;
697}
698
699/// findSuperReg - Find the SubReg's super-register of given register class
700/// where its SubIdx sub-register is SubReg.
701static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
702 unsigned SubIdx, const TargetRegisterInfo *TRI) {
703 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
704 I != E; ++I) {
705 unsigned Reg = *I;
706 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
707 return Reg;
708 }
709 return 0;
710}
711
712// ******************************** //
713// Available Spills Implementation //
714// ******************************** //
715
716/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
717/// stackslot register. The register is still available but is no longer
718/// allowed to be modifed.
719void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
720 std::multimap<unsigned, int>::iterator I =
721 PhysRegsAvailable.lower_bound(PhysReg);
722 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
723 int SlotOrReMat = I->second;
724 I++;
725 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
726 "Bidirectional map mismatch!");
727 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
David Greene0ee52182010-01-05 01:25:52 +0000728 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +0000729 << " copied, it is available for use but can no longer be modified\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000730 }
731}
732
733/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
734/// stackslot register and its aliases. The register and its aliases may
735/// still available but is no longer allowed to be modifed.
736void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
737 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
738 disallowClobberPhysRegOnly(*AS);
739 disallowClobberPhysRegOnly(PhysReg);
740}
741
742/// ClobberPhysRegOnly - This is called when the specified physreg changes
743/// value. We use this to invalidate any info about stuff we thing lives in it.
744void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
745 std::multimap<unsigned, int>::iterator I =
746 PhysRegsAvailable.lower_bound(PhysReg);
747 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
748 int SlotOrReMat = I->second;
749 PhysRegsAvailable.erase(I++);
750 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
751 "Bidirectional map mismatch!");
752 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
David Greene0ee52182010-01-05 01:25:52 +0000753 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +0000754 << " clobbered, invalidating ");
Lang Hames87e3bca2009-05-06 02:36:21 +0000755 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +0000756 DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000757 else
David Greene0ee52182010-01-05 01:25:52 +0000758 DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000759 }
760}
761
762/// ClobberPhysReg - This is called when the specified physreg changes
763/// value. We use this to invalidate any info about stuff we thing lives in
764/// it and any of its aliases.
765void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
766 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
767 ClobberPhysRegOnly(*AS);
768 ClobberPhysRegOnly(PhysReg);
769}
770
771/// AddAvailableRegsToLiveIn - Availability information is being kept coming
772/// into the specified MBB. Add available physical registers as potential
773/// live-in's. If they are reused in the MBB, they will be added to the
774/// live-in set to make register scavenger and post-allocation scheduler.
775void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
776 BitVector &RegKills,
777 std::vector<MachineOperand*> &KillOps) {
778 std::set<unsigned> NotAvailable;
779 for (std::multimap<unsigned, int>::iterator
780 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
781 I != E; ++I) {
782 unsigned Reg = I->first;
Rafael Espindoladb776092010-07-11 16:45:17 +0000783 const TargetRegisterClass* RC = TRI->getMinimalPhysRegClass(Reg);
Lang Hames87e3bca2009-05-06 02:36:21 +0000784 // FIXME: A temporary workaround. We can't reuse available value if it's
785 // not safe to move the def of the virtual register's class. e.g.
786 // X86::RFP* register classes. Do not add it as a live-in.
787 if (!TII->isSafeToMoveRegClassDefs(RC))
788 // This is no longer available.
789 NotAvailable.insert(Reg);
790 else {
791 MBB.addLiveIn(Reg);
Andrew Trick5d7ab852011-01-27 21:26:43 +0000792 if (RegKills[Reg])
793 ResurrectConfirmedKill(Reg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +0000794 }
795
796 // Skip over the same register.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000797 std::multimap<unsigned, int>::iterator NI = llvm::next(I);
Lang Hames87e3bca2009-05-06 02:36:21 +0000798 while (NI != E && NI->first == Reg) {
799 ++I;
800 ++NI;
801 }
802 }
803
804 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
805 E = NotAvailable.end(); I != E; ++I) {
806 ClobberPhysReg(*I);
807 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
808 *SubRegs; ++SubRegs)
809 ClobberPhysReg(*SubRegs);
810 }
811}
812
813/// ModifyStackSlotOrReMat - This method is called when the value in a stack
814/// slot changes. This removes information about which register the previous
815/// value for this slot lives in (as the previous value is dead now).
816void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
817 std::map<int, unsigned>::iterator It =
818 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
819 if (It == SpillSlotsOrReMatsAvailable.end()) return;
820 unsigned Reg = It->second >> 1;
821 SpillSlotsOrReMatsAvailable.erase(It);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000822
Lang Hames87e3bca2009-05-06 02:36:21 +0000823 // This register may hold the value of multiple stack slots, only remove this
824 // stack slot from the set of values the register contains.
825 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
826 for (; ; ++I) {
827 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
828 "Map inverse broken!");
829 if (I->second == SlotOrReMat) break;
830 }
831 PhysRegsAvailable.erase(I);
832}
833
834// ************************** //
835// Reuse Info Implementation //
836// ************************** //
837
838/// GetRegForReload - We are about to emit a reload into PhysReg. If there
839/// is some other operand that is using the specified register, either pick
840/// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000841unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
842 unsigned PhysReg,
843 MachineFunction &MF,
844 MachineInstr *MI, AvailableSpills &Spills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000845 std::vector<MachineInstr*> &MaybeDeadStores,
846 SmallSet<unsigned, 8> &Rejected,
847 BitVector &RegKills,
848 std::vector<MachineOperand*> &KillOps,
849 VirtRegMap &VRM) {
Evan Cheng5d885022009-07-21 09:15:00 +0000850 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
851 const TargetRegisterInfo *TRI = Spills.getRegInfo();
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000852
Lang Hames87e3bca2009-05-06 02:36:21 +0000853 if (Reuses.empty()) return PhysReg; // This is most often empty.
854
855 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
856 ReusedOp &Op = Reuses[ro];
857 // If we find some other reuse that was supposed to use this register
858 // exactly for its reload, we can change this reload to use ITS reload
859 // register. That is, unless its reload register has already been
860 // considered and subsequently rejected because it has also been reused
861 // by another operand.
862 if (Op.PhysRegReused == PhysReg &&
Evan Cheng5d885022009-07-21 09:15:00 +0000863 Rejected.count(Op.AssignedPhysReg) == 0 &&
864 RC->contains(Op.AssignedPhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000865 // Yup, use the reload register that we didn't use before.
866 unsigned NewReg = Op.AssignedPhysReg;
867 Rejected.insert(PhysReg);
Jim Grosbach57cb4f82010-07-27 17:38:47 +0000868 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores,
869 Rejected, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +0000870 } else {
871 // Otherwise, we might also have a problem if a previously reused
Evan Cheng5d885022009-07-21 09:15:00 +0000872 // value aliases the new register. If so, codegen the previous reload
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000873 // and use this one.
Lang Hames87e3bca2009-05-06 02:36:21 +0000874 unsigned PRRU = Op.PhysRegReused;
Lang Hames3f2f3f52009-09-03 02:52:02 +0000875 if (TRI->regsOverlap(PRRU, PhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000876 // Okay, we found out that an alias of a reused register
877 // was used. This isn't good because it means we have
878 // to undo a previous reuse.
879 MachineBasicBlock *MBB = MI->getParent();
880 const TargetRegisterClass *AliasRC =
881 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
882
883 // Copy Op out of the vector and remove it, we're going to insert an
884 // explicit load for it.
885 ReusedOp NewOp = Op;
886 Reuses.erase(Reuses.begin()+ro);
887
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000888 // MI may be using only a sub-register of PhysRegUsed.
889 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
890 unsigned SubIdx = 0;
891 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
892 "A reuse cannot be a virtual register");
893 if (PRRU != RealPhysRegUsed) {
894 // What was the sub-register index?
Evan Chengfae3e922009-11-14 03:42:17 +0000895 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
896 assert(SubIdx &&
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000897 "Operand physreg is not a sub-register of PhysRegUsed");
898 }
899
Lang Hames87e3bca2009-05-06 02:36:21 +0000900 // Ok, we're going to try to reload the assigned physreg into the
901 // slot that we were supposed to in the first place. However, that
902 // register could hold a reuse. Check to see if it conflicts or
903 // would prefer us to use a different register.
Evan Cheng5d885022009-07-21 09:15:00 +0000904 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
905 MF, MI, Spills, MaybeDeadStores,
906 Rejected, RegKills, KillOps, VRM);
David Greene2d4e6d32009-07-28 16:49:24 +0000907
908 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
909 int SSorRMId = DoReMat
John McCall795ee9d2010-04-06 23:35:53 +0000910 ? VRM.getReMatId(NewOp.VirtReg) : (int) NewOp.StackSlotOrReMat;
David Greene2d4e6d32009-07-28 16:49:24 +0000911
912 // Back-schedule reloads and remats.
913 MachineBasicBlock::iterator InsertLoc =
914 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
915 DoReMat, SSorRMId, TII, MF);
916
917 if (DoReMat) {
918 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
919 TRI, VRM);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000920 } else {
David Greene2d4e6d32009-07-28 16:49:24 +0000921 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
Evan Cheng746ad692010-05-06 19:06:44 +0000922 NewOp.StackSlotOrReMat, AliasRC, TRI);
David Greene2d4e6d32009-07-28 16:49:24 +0000923 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +0000924 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
925 // Any stores to this stack slot are not dead anymore.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000926 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
Lang Hames87e3bca2009-05-06 02:36:21 +0000927 ++NumLoads;
928 }
929 Spills.ClobberPhysReg(NewPhysReg);
930 Spills.ClobberPhysReg(NewOp.PhysRegReused);
931
Evan Cheng427c3ba2009-10-25 07:51:47 +0000932 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
Lang Hames87e3bca2009-05-06 02:36:21 +0000933 MI->getOperand(NewOp.Operand).setReg(RReg);
934 MI->getOperand(NewOp.Operand).setSubReg(0);
935
936 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
David Greene2d4e6d32009-07-28 16:49:24 +0000937 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
David Greene0ee52182010-01-05 01:25:52 +0000938 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000939
David Greene0ee52182010-01-05 01:25:52 +0000940 DEBUG(dbgs() << "Reuse undone!\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000941 --NumReused;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000942
Lang Hames87e3bca2009-05-06 02:36:21 +0000943 // Finally, PhysReg is now available, go ahead and use it.
944 return PhysReg;
945 }
946 }
947 }
948 return PhysReg;
949}
950
951// ************************************************************************ //
952
953/// FoldsStackSlotModRef - Return true if the specified MI folds the specified
954/// stack slot mod/ref. It also checks if it's possible to unfold the
955/// instruction by having it define a specified physical register instead.
956static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
957 const TargetInstrInfo *TII,
958 const TargetRegisterInfo *TRI,
959 VirtRegMap &VRM) {
960 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
961 return false;
962
963 bool Found = false;
964 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
965 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
966 unsigned VirtReg = I->second.first;
967 VirtRegMap::ModRef MR = I->second.second;
968 if (MR & VirtRegMap::isModRef)
969 if (VRM.getStackSlot(VirtReg) == SS) {
970 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
971 break;
972 }
973 }
974 if (!Found)
975 return false;
976
977 // Does the instruction uses a register that overlaps the scratch register?
978 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
979 MachineOperand &MO = MI.getOperand(i);
980 if (!MO.isReg() || MO.getReg() == 0)
981 continue;
982 unsigned Reg = MO.getReg();
983 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
984 if (!VRM.hasPhys(Reg))
985 continue;
986 Reg = VRM.getPhys(Reg);
987 }
988 if (TRI->regsOverlap(PhysReg, Reg))
989 return false;
990 }
991 return true;
992}
993
994/// FindFreeRegister - Find a free register of a given register class by looking
995/// at (at most) the last two machine instructions.
996static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
997 MachineBasicBlock &MBB,
998 const TargetRegisterClass *RC,
999 const TargetRegisterInfo *TRI,
1000 BitVector &AllocatableRegs) {
1001 BitVector Defs(TRI->getNumRegs());
1002 BitVector Uses(TRI->getNumRegs());
1003 SmallVector<unsigned, 4> LocalUses;
1004 SmallVector<unsigned, 4> Kills;
1005
1006 // Take a look at 2 instructions at most.
Evan Cheng28a1e482010-03-30 05:49:07 +00001007 unsigned Count = 0;
1008 while (Count < 2) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001009 if (MII == MBB.begin())
1010 break;
1011 MachineInstr *PrevMI = prior(MII);
Evan Cheng28a1e482010-03-30 05:49:07 +00001012 MII = PrevMI;
1013
1014 if (PrevMI->isDebugValue())
1015 continue; // Skip over dbg_value instructions.
1016 ++Count;
1017
Lang Hames87e3bca2009-05-06 02:36:21 +00001018 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
1019 MachineOperand &MO = PrevMI->getOperand(i);
1020 if (!MO.isReg() || MO.getReg() == 0)
1021 continue;
1022 unsigned Reg = MO.getReg();
1023 if (MO.isDef()) {
1024 Defs.set(Reg);
1025 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1026 Defs.set(*AS);
1027 } else {
1028 LocalUses.push_back(Reg);
1029 if (MO.isKill() && AllocatableRegs[Reg])
1030 Kills.push_back(Reg);
1031 }
1032 }
1033
1034 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1035 unsigned Kill = Kills[i];
1036 if (!Defs[Kill] && !Uses[Kill] &&
Rafael Espindoladb776092010-07-11 16:45:17 +00001037 RC->contains(Kill))
Lang Hames87e3bca2009-05-06 02:36:21 +00001038 return Kill;
1039 }
1040 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1041 unsigned Reg = LocalUses[i];
1042 Uses.set(Reg);
1043 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1044 Uses.set(*AS);
1045 }
Lang Hames87e3bca2009-05-06 02:36:21 +00001046 }
1047
1048 return 0;
1049}
1050
1051static
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001052void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1053 const TargetRegisterInfo &TRI) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001054 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1055 MachineOperand &MO = MI->getOperand(i);
1056 if (MO.isReg() && MO.getReg() == VirtReg)
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001057 substitutePhysReg(MO, PhysReg, TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001058 }
1059}
1060
Evan Chengeca24fb2009-05-12 23:07:00 +00001061namespace {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001062
1063struct RefSorter {
1064 bool operator()(const std::pair<MachineInstr*, int> &A,
1065 const std::pair<MachineInstr*, int> &B) {
1066 return A.second < B.second;
1067 }
1068};
Lang Hames87e3bca2009-05-06 02:36:21 +00001069
1070// ***************************** //
1071// Local Spiller Implementation //
1072// ***************************** //
1073
Nick Lewycky6726b6d2009-10-25 06:33:48 +00001074class LocalRewriter : public VirtRegRewriter {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001075 MachineRegisterInfo *MRI;
Lang Hames87e3bca2009-05-06 02:36:21 +00001076 const TargetRegisterInfo *TRI;
1077 const TargetInstrInfo *TII;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001078 VirtRegMap *VRM;
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001079 LiveIntervals *LIs;
Lang Hames87e3bca2009-05-06 02:36:21 +00001080 BitVector AllocatableRegs;
1081 DenseMap<MachineInstr*, unsigned> DistanceMap;
Evan Chengbd6cb4b2010-04-29 18:51:00 +00001082 DenseMap<int, SmallVector<MachineInstr*,4> > Slot2DbgValues;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001083
1084 MachineBasicBlock *MBB; // Basic block currently being processed.
1085
Lang Hames87e3bca2009-05-06 02:36:21 +00001086public:
1087
1088 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001089 LiveIntervals* LIs);
Lang Hames87e3bca2009-05-06 02:36:21 +00001090
1091private:
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001092 void EraseInstr(MachineInstr *MI) {
1093 VRM->RemoveMachineInstrFromMaps(MI);
1094 LIs->RemoveMachineInstrFromMaps(MI);
1095 MI->eraseFromParent();
1096 }
Lang Hames87e3bca2009-05-06 02:36:21 +00001097
Lang Hames87e3bca2009-05-06 02:36:21 +00001098 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
Lang Hames87e3bca2009-05-06 02:36:21 +00001099 MachineBasicBlock::iterator &MII,
1100 std::vector<MachineInstr*> &MaybeDeadStores,
1101 AvailableSpills &Spills,
1102 BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001103 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001104
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001105 bool OptimizeByUnfold(MachineBasicBlock::iterator &MII,
Lang Hames87e3bca2009-05-06 02:36:21 +00001106 std::vector<MachineInstr*> &MaybeDeadStores,
1107 AvailableSpills &Spills,
1108 BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001109 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001110
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001111 bool CommuteToFoldReload(MachineBasicBlock::iterator &MII,
Lang Hames87e3bca2009-05-06 02:36:21 +00001112 unsigned VirtReg, unsigned SrcReg, int SS,
1113 AvailableSpills &Spills,
1114 BitVector &RegKills,
1115 std::vector<MachineOperand*> &KillOps,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001116 const TargetRegisterInfo *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001117
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001118 void SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
Lang Hames87e3bca2009-05-06 02:36:21 +00001119 int Idx, unsigned PhysReg, int StackSlot,
1120 const TargetRegisterClass *RC,
1121 bool isAvailable, MachineInstr *&LastStore,
1122 AvailableSpills &Spills,
1123 SmallSet<MachineInstr*, 4> &ReMatDefs,
1124 BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001125 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001126
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001127 void TransferDeadness(unsigned Reg, BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001128 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001129
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001130 bool InsertEmergencySpills(MachineInstr *MI);
1131
1132 bool InsertRestores(MachineInstr *MI,
1133 AvailableSpills &Spills,
1134 BitVector &RegKills,
1135 std::vector<MachineOperand*> &KillOps);
1136
1137 bool InsertSpills(MachineInstr *MI);
1138
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00001139 void ProcessUses(MachineInstr &MI, AvailableSpills &Spills,
1140 std::vector<MachineInstr*> &MaybeDeadStores,
1141 BitVector &RegKills,
1142 ReuseInfo &ReusedOperands,
1143 std::vector<MachineOperand*> &KillOps);
1144
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001145 void RewriteMBB(LiveIntervals *LIs,
1146 AvailableSpills &Spills, BitVector &RegKills,
1147 std::vector<MachineOperand*> &KillOps);
1148};
1149}
1150
1151bool LocalRewriter::runOnMachineFunction(MachineFunction &MF, VirtRegMap &vrm,
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001152 LiveIntervals* lis) {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001153 MRI = &MF.getRegInfo();
1154 TRI = MF.getTarget().getRegisterInfo();
1155 TII = MF.getTarget().getInstrInfo();
1156 VRM = &vrm;
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001157 LIs = lis;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001158 AllocatableRegs = TRI->getAllocatableSet(MF);
1159 DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
1160 << MF.getFunction()->getName() << "':\n");
1161 DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
1162 " reloads!) ****\n");
Jakob Stoklund Olesen7fd747b2011-01-12 22:28:48 +00001163 DEBUG(MF.print(dbgs(), LIs->getSlotIndexes()));
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001164
1165 // Spills - Keep track of which spilled values are available in physregs
1166 // so that we can choose to reuse the physregs instead of emitting
1167 // reloads. This is usually refreshed per basic block.
1168 AvailableSpills Spills(TRI, TII);
1169
1170 // Keep track of kill information.
1171 BitVector RegKills(TRI->getNumRegs());
1172 std::vector<MachineOperand*> KillOps;
1173 KillOps.resize(TRI->getNumRegs(), NULL);
1174
1175 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1176 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1177 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1178
1179 // Traverse the basic blocks depth first.
1180 MachineBasicBlock *Entry = MF.begin();
1181 SmallPtrSet<MachineBasicBlock*,16> Visited;
1182 for (df_ext_iterator<MachineBasicBlock*,
1183 SmallPtrSet<MachineBasicBlock*,16> >
1184 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1185 DFI != E; ++DFI) {
1186 MBB = *DFI;
1187 if (!EarlyVisited.count(MBB))
1188 RewriteMBB(LIs, Spills, RegKills, KillOps);
1189
1190 // If this MBB is the only predecessor of a successor. Keep the
1191 // availability information and visit it next.
1192 do {
1193 // Keep visiting single predecessor successor as long as possible.
1194 SinglePredSuccs.clear();
1195 findSinglePredSuccessor(MBB, SinglePredSuccs);
1196 if (SinglePredSuccs.empty())
1197 MBB = 0;
1198 else {
1199 // FIXME: More than one successors, each of which has MBB has
1200 // the only predecessor.
1201 MBB = SinglePredSuccs[0];
1202 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1203 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1204 RewriteMBB(LIs, Spills, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001205 }
1206 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001207 } while (MBB);
Lang Hames87e3bca2009-05-06 02:36:21 +00001208
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001209 // Clear the availability info.
1210 Spills.clear();
Lang Hames87e3bca2009-05-06 02:36:21 +00001211 }
1212
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001213 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
Jakob Stoklund Olesen7fd747b2011-01-12 22:28:48 +00001214 DEBUG(MF.print(dbgs(), LIs->getSlotIndexes()));
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001215
1216 // Mark unused spill slots.
1217 MachineFrameInfo *MFI = MF.getFrameInfo();
1218 int SS = VRM->getLowSpillSlot();
Evan Chengbd6cb4b2010-04-29 18:51:00 +00001219 if (SS != VirtRegMap::NO_STACK_SLOT) {
1220 for (int e = VRM->getHighSpillSlot(); SS <= e; ++SS) {
1221 SmallVector<MachineInstr*, 4> &DbgValues = Slot2DbgValues[SS];
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001222 if (!VRM->isSpillSlotUsed(SS)) {
1223 MFI->RemoveStackObject(SS);
Evan Chengbd6cb4b2010-04-29 18:51:00 +00001224 for (unsigned j = 0, ee = DbgValues.size(); j != ee; ++j) {
1225 MachineInstr *DVMI = DbgValues[j];
Evan Chengbd6cb4b2010-04-29 18:51:00 +00001226 DEBUG(dbgs() << "Removing debug info referencing FI#" << SS << '\n');
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001227 EraseInstr(DVMI);
Evan Chengbd6cb4b2010-04-29 18:51:00 +00001228 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001229 ++NumDSS;
1230 }
Evan Chengbd6cb4b2010-04-29 18:51:00 +00001231 DbgValues.clear();
1232 }
1233 }
1234 Slot2DbgValues.clear();
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001235
1236 return true;
1237}
1238
1239/// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1240/// a scratch register is available.
1241/// xorq %r12<kill>, %r13
1242/// addq %rax, -184(%rbp)
1243/// addq %r13, -184(%rbp)
1244/// ==>
1245/// xorq %r12<kill>, %r13
1246/// movq -184(%rbp), %r12
1247/// addq %rax, %r12
1248/// addq %r13, %r12
1249/// movq %r12, -184(%rbp)
1250bool LocalRewriter::
1251OptimizeByUnfold2(unsigned VirtReg, int SS,
1252 MachineBasicBlock::iterator &MII,
1253 std::vector<MachineInstr*> &MaybeDeadStores,
1254 AvailableSpills &Spills,
1255 BitVector &RegKills,
1256 std::vector<MachineOperand*> &KillOps) {
1257
1258 MachineBasicBlock::iterator NextMII = llvm::next(MII);
Evan Cheng28a1e482010-03-30 05:49:07 +00001259 // Skip over dbg_value instructions.
1260 while (NextMII != MBB->end() && NextMII->isDebugValue())
1261 NextMII = llvm::next(NextMII);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001262 if (NextMII == MBB->end())
1263 return false;
1264
1265 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1266 return false;
1267
1268 // Now let's see if the last couple of instructions happens to have freed up
1269 // a register.
1270 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1271 unsigned PhysReg = FindFreeRegister(MII, *MBB, RC, TRI, AllocatableRegs);
1272 if (!PhysReg)
1273 return false;
1274
1275 MachineFunction &MF = *MBB->getParent();
1276 TRI = MF.getTarget().getRegisterInfo();
1277 MachineInstr &MI = *MII;
1278 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, *VRM))
1279 return false;
1280
1281 // If the next instruction also folds the same SS modref and can be unfoled,
1282 // then it's worthwhile to issue a load from SS into the free register and
1283 // then unfold these instructions.
1284 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM))
1285 return false;
1286
1287 // Back-schedule reloads and remats.
1288 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, false, SS, TII, MF);
1289
1290 // Load from SS to the spare physical register.
Evan Cheng746ad692010-05-06 19:06:44 +00001291 TII->loadRegFromStackSlot(*MBB, MII, PhysReg, SS, RC, TRI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001292 // This invalidates Phys.
1293 Spills.ClobberPhysReg(PhysReg);
1294 // Remember it's available.
1295 Spills.addAvailable(SS, PhysReg);
1296 MaybeDeadStores[SS] = NULL;
1297
1298 // Unfold current MI.
1299 SmallVector<MachineInstr*, 4> NewMIs;
1300 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1301 llvm_unreachable("Unable unfold the load / store folding instruction!");
1302 assert(NewMIs.size() == 1);
1303 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1304 VRM->transferRestorePts(&MI, NewMIs[0]);
1305 MII = MBB->insert(MII, NewMIs[0]);
1306 InvalidateKills(MI, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001307 EraseInstr(&MI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001308 ++NumModRefUnfold;
1309
1310 // Unfold next instructions that fold the same SS.
1311 do {
1312 MachineInstr &NextMI = *NextMII;
1313 NextMII = llvm::next(NextMII);
1314 NewMIs.clear();
1315 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1316 llvm_unreachable("Unable unfold the load / store folding instruction!");
1317 assert(NewMIs.size() == 1);
1318 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1319 VRM->transferRestorePts(&NextMI, NewMIs[0]);
1320 MBB->insert(NextMII, NewMIs[0]);
1321 InvalidateKills(NextMI, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001322 EraseInstr(&NextMI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001323 ++NumModRefUnfold;
Evan Cheng28a1e482010-03-30 05:49:07 +00001324 // Skip over dbg_value instructions.
1325 while (NextMII != MBB->end() && NextMII->isDebugValue())
1326 NextMII = llvm::next(NextMII);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001327 if (NextMII == MBB->end())
1328 break;
1329 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM));
1330
1331 // Store the value back into SS.
Evan Cheng746ad692010-05-06 19:06:44 +00001332 TII->storeRegToStackSlot(*MBB, NextMII, PhysReg, true, SS, RC, TRI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001333 MachineInstr *StoreMI = prior(NextMII);
1334 VRM->addSpillSlotUse(SS, StoreMI);
1335 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1336
1337 return true;
1338}
1339
1340/// OptimizeByUnfold - Turn a store folding instruction into a load folding
1341/// instruction. e.g.
1342/// xorl %edi, %eax
1343/// movl %eax, -32(%ebp)
1344/// movl -36(%ebp), %eax
1345/// orl %eax, -32(%ebp)
1346/// ==>
1347/// xorl %edi, %eax
1348/// orl -36(%ebp), %eax
1349/// mov %eax, -32(%ebp)
1350/// This enables unfolding optimization for a subsequent instruction which will
1351/// also eliminate the newly introduced store instruction.
1352bool LocalRewriter::
1353OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1354 std::vector<MachineInstr*> &MaybeDeadStores,
1355 AvailableSpills &Spills,
1356 BitVector &RegKills,
1357 std::vector<MachineOperand*> &KillOps) {
1358 MachineFunction &MF = *MBB->getParent();
1359 MachineInstr &MI = *MII;
1360 unsigned UnfoldedOpc = 0;
1361 unsigned UnfoldPR = 0;
1362 unsigned UnfoldVR = 0;
1363 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1364 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1365 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
1366 // Only transform a MI that folds a single register.
1367 if (UnfoldedOpc)
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001368 return false;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001369 UnfoldVR = I->second.first;
1370 VirtRegMap::ModRef MR = I->second.second;
1371 // MI2VirtMap be can updated which invalidate the iterator.
1372 // Increment the iterator first.
1373 ++I;
1374 if (VRM->isAssignedReg(UnfoldVR))
1375 continue;
1376 // If this reference is not a use, any previous store is now dead.
1377 // Otherwise, the store to this stack slot is not dead anymore.
1378 FoldedSS = VRM->getStackSlot(UnfoldVR);
1379 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1380 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1381 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1382 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001383 continue;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001384 UnfoldPR = PhysReg;
1385 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1386 false, true);
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001387 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001388 }
1389
1390 if (!UnfoldedOpc) {
1391 if (!UnfoldVR)
1392 return false;
1393
1394 // Look for other unfolding opportunities.
1395 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MII, MaybeDeadStores, Spills,
1396 RegKills, KillOps);
1397 }
1398
1399 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1400 MachineOperand &MO = MI.getOperand(i);
1401 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1402 continue;
1403 unsigned VirtReg = MO.getReg();
1404 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1405 continue;
1406 if (VRM->isAssignedReg(VirtReg)) {
1407 unsigned PhysReg = VRM->getPhys(VirtReg);
1408 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1409 return false;
1410 } else if (VRM->isReMaterialized(VirtReg))
1411 continue;
1412 int SS = VRM->getStackSlot(VirtReg);
1413 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1414 if (PhysReg) {
1415 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1416 return false;
1417 continue;
1418 }
1419 if (VRM->hasPhys(VirtReg)) {
1420 PhysReg = VRM->getPhys(VirtReg);
1421 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1422 continue;
1423 }
1424
1425 // Ok, we'll need to reload the value into a register which makes
1426 // it impossible to perform the store unfolding optimization later.
1427 // Let's see if it is possible to fold the load if the store is
1428 // unfolded. This allows us to perform the store unfolding
1429 // optimization.
1430 SmallVector<MachineInstr*, 4> NewMIs;
1431 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1432 assert(NewMIs.size() == 1);
1433 MachineInstr *NewMI = NewMIs.back();
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001434 MBB->insert(MII, NewMI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001435 NewMIs.clear();
1436 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1437 assert(Idx != -1);
1438 SmallVector<unsigned, 1> Ops;
1439 Ops.push_back(Idx);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001440 MachineInstr *FoldedMI = TII->foldMemoryOperand(NewMI, Ops, SS);
1441 NewMI->eraseFromParent();
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001442 if (FoldedMI) {
1443 VRM->addSpillSlotUse(SS, FoldedMI);
1444 if (!VRM->hasPhys(UnfoldVR))
1445 VRM->assignVirt2Phys(UnfoldVR, UnfoldPR);
1446 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001447 MII = FoldedMI;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001448 InvalidateKills(MI, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001449 EraseInstr(&MI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001450 return true;
1451 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001452 }
1453 }
1454
1455 return false;
1456}
1457
1458/// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1459/// where SrcReg is r1 and it is tied to r0. Return true if after
1460/// commuting this instruction it will be r0 = op r2, r1.
1461static bool CommuteChangesDestination(MachineInstr *DefMI,
1462 const TargetInstrDesc &TID,
1463 unsigned SrcReg,
1464 const TargetInstrInfo *TII,
1465 unsigned &DstIdx) {
1466 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1467 return false;
1468 if (!DefMI->getOperand(1).isReg() ||
1469 DefMI->getOperand(1).getReg() != SrcReg)
1470 return false;
1471 unsigned DefIdx;
1472 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1473 return false;
1474 unsigned SrcIdx1, SrcIdx2;
1475 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1476 return false;
1477 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1478 DstIdx = 2;
1479 return true;
1480 }
1481 return false;
1482}
1483
1484/// CommuteToFoldReload -
1485/// Look for
1486/// r1 = load fi#1
1487/// r1 = op r1, r2<kill>
1488/// store r1, fi#1
1489///
1490/// If op is commutable and r2 is killed, then we can xform these to
1491/// r2 = op r2, fi#1
1492/// store r2, fi#1
1493bool LocalRewriter::
1494CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1495 unsigned VirtReg, unsigned SrcReg, int SS,
1496 AvailableSpills &Spills,
1497 BitVector &RegKills,
1498 std::vector<MachineOperand*> &KillOps,
1499 const TargetRegisterInfo *TRI) {
1500 if (MII == MBB->begin() || !MII->killsRegister(SrcReg))
1501 return false;
1502
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001503 MachineInstr &MI = *MII;
1504 MachineBasicBlock::iterator DefMII = prior(MII);
1505 MachineInstr *DefMI = DefMII;
1506 const TargetInstrDesc &TID = DefMI->getDesc();
1507 unsigned NewDstIdx;
1508 if (DefMII != MBB->begin() &&
1509 TID.isCommutable() &&
1510 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1511 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1512 unsigned NewReg = NewDstMO.getReg();
1513 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1514 return false;
1515 MachineInstr *ReloadMI = prior(DefMII);
1516 int FrameIdx;
1517 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1518 if (DestReg != SrcReg || FrameIdx != SS)
1519 return false;
1520 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1521 if (UseIdx == -1)
1522 return false;
1523 unsigned DefIdx;
1524 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1525 return false;
1526 assert(DefMI->getOperand(DefIdx).isReg() &&
1527 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1528
1529 // Now commute def instruction.
1530 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1531 if (!CommutedMI)
1532 return false;
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001533 MBB->insert(MII, CommutedMI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001534 SmallVector<unsigned, 1> Ops;
1535 Ops.push_back(NewDstIdx);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001536 MachineInstr *FoldedMI = TII->foldMemoryOperand(CommutedMI, Ops, SS);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001537 // Not needed since foldMemoryOperand returns new MI.
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001538 CommutedMI->eraseFromParent();
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001539 if (!FoldedMI)
1540 return false;
1541
1542 VRM->addSpillSlotUse(SS, FoldedMI);
1543 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1544 // Insert new def MI and spill MI.
1545 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
Evan Cheng746ad692010-05-06 19:06:44 +00001546 TII->storeRegToStackSlot(*MBB, &MI, NewReg, true, SS, RC, TRI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001547 MII = prior(MII);
1548 MachineInstr *StoreMI = MII;
1549 VRM->addSpillSlotUse(SS, StoreMI);
1550 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001551 MII = FoldedMI; // Update MII to backtrack.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001552
1553 // Delete all 3 old instructions.
1554 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001555 EraseInstr(ReloadMI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001556 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001557 EraseInstr(DefMI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001558 InvalidateKills(MI, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001559 EraseInstr(&MI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001560
1561 // If NewReg was previously holding value of some SS, it's now clobbered.
1562 // This has to be done now because it's a physical register. When this
1563 // instruction is re-visited, it's ignored.
1564 Spills.ClobberPhysReg(NewReg);
1565
1566 ++NumCommutes;
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001567 return true;
1568 }
1569
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001570 return false;
1571}
Lang Hames87e3bca2009-05-06 02:36:21 +00001572
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001573/// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1574/// the last store to the same slot is now dead. If so, remove the last store.
1575void LocalRewriter::
1576SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1577 int Idx, unsigned PhysReg, int StackSlot,
1578 const TargetRegisterClass *RC,
1579 bool isAvailable, MachineInstr *&LastStore,
1580 AvailableSpills &Spills,
1581 SmallSet<MachineInstr*, 4> &ReMatDefs,
1582 BitVector &RegKills,
1583 std::vector<MachineOperand*> &KillOps) {
Evan Chengeca24fb2009-05-12 23:07:00 +00001584
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001585 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
Evan Cheng746ad692010-05-06 19:06:44 +00001586 TII->storeRegToStackSlot(*MBB, llvm::next(MII), PhysReg, true, StackSlot, RC,
1587 TRI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001588 MachineInstr *StoreMI = prior(oldNextMII);
1589 VRM->addSpillSlotUse(StackSlot, StoreMI);
1590 DEBUG(dbgs() << "Store:\t" << *StoreMI);
Evan Chengeca24fb2009-05-12 23:07:00 +00001591
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001592 // If there is a dead store to this stack slot, nuke it now.
1593 if (LastStore) {
1594 DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
1595 ++NumDSE;
1596 SmallVector<unsigned, 2> KillRegs;
1597 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1598 MachineBasicBlock::iterator PrevMII = LastStore;
1599 bool CheckDef = PrevMII != MBB->begin();
1600 if (CheckDef)
1601 --PrevMII;
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001602 EraseInstr(LastStore);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001603 if (CheckDef) {
1604 // Look at defs of killed registers on the store. Mark the defs
1605 // as dead since the store has been deleted and they aren't
1606 // being reused.
1607 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1608 bool HasOtherDef = false;
1609 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1610 MachineInstr *DeadDef = PrevMII;
1611 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1612 // FIXME: This assumes a remat def does not have side effects.
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001613 EraseInstr(DeadDef);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001614 ++NumDRM;
1615 }
Evan Chengeca24fb2009-05-12 23:07:00 +00001616 }
Lang Hames87e3bca2009-05-06 02:36:21 +00001617 }
1618 }
1619 }
1620
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001621 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1622 // the last of multiple instructions is the actual store.
1623 LastStore = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001624
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001625 // If the stack slot value was previously available in some other
1626 // register, change it now. Otherwise, make the register available,
1627 // in PhysReg.
1628 Spills.ModifyStackSlotOrReMat(StackSlot);
1629 Spills.ClobberPhysReg(PhysReg);
1630 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1631 ++NumStores;
1632}
Lang Hames87e3bca2009-05-06 02:36:21 +00001633
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001634/// isSafeToDelete - Return true if this instruction doesn't produce any side
1635/// effect and all of its defs are dead.
1636static bool isSafeToDelete(MachineInstr &MI) {
1637 const TargetInstrDesc &TID = MI.getDesc();
Evan Chenge32effb2011-02-16 00:37:02 +00001638 if (TID.mayLoad() || TID.mayStore() || TID.isTerminator() ||
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001639 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
Evan Chengc36b7062011-01-07 23:50:32 +00001640 MI.isLabel() || MI.isDebugValue() ||
1641 MI.hasUnmodeledSideEffects())
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001642 return false;
Evan Chengc36b7062011-01-07 23:50:32 +00001643
1644 // Technically speaking inline asm without side effects and no defs can still
1645 // be deleted. But there is so much bad inline asm code out there, we should
1646 // let them be.
1647 if (MI.isInlineAsm())
1648 return false;
1649
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001650 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1651 MachineOperand &MO = MI.getOperand(i);
1652 if (!MO.isReg() || !MO.getReg())
1653 continue;
1654 if (MO.isDef() && !MO.isDead())
1655 return false;
1656 if (MO.isUse() && MO.isKill())
1657 // FIXME: We can't remove kill markers or else the scavenger will assert.
1658 // An alternative is to add a ADD pseudo instruction to replace kill
1659 // markers.
1660 return false;
1661 }
1662 return true;
1663}
Lang Hames87e3bca2009-05-06 02:36:21 +00001664
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001665/// TransferDeadness - A identity copy definition is dead and it's being
1666/// removed. Find the last def or use and mark it as dead / kill.
1667void LocalRewriter::
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001668TransferDeadness(unsigned Reg, BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001669 std::vector<MachineOperand*> &KillOps) {
1670 SmallPtrSet<MachineInstr*, 4> Seens;
1671 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1672 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
1673 RE = MRI->reg_end(); RI != RE; ++RI) {
1674 MachineInstr *UDMI = &*RI;
Evan Cheng28a1e482010-03-30 05:49:07 +00001675 if (UDMI->isDebugValue() || UDMI->getParent() != MBB)
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001676 continue;
1677 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001678 if (DI == DistanceMap.end())
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001679 continue;
1680 if (Seens.insert(UDMI))
1681 Refs.push_back(std::make_pair(UDMI, DI->second));
1682 }
Lang Hames87e3bca2009-05-06 02:36:21 +00001683
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001684 if (Refs.empty())
1685 return;
1686 std::sort(Refs.begin(), Refs.end(), RefSorter());
Lang Hames87e3bca2009-05-06 02:36:21 +00001687
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001688 while (!Refs.empty()) {
1689 MachineInstr *LastUDMI = Refs.back().first;
1690 Refs.pop_back();
Lang Hames87e3bca2009-05-06 02:36:21 +00001691
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001692 MachineOperand *LastUD = NULL;
1693 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1694 MachineOperand &MO = LastUDMI->getOperand(i);
1695 if (!MO.isReg() || MO.getReg() != Reg)
1696 continue;
1697 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1698 LastUD = &MO;
1699 if (LastUDMI->isRegTiedToDefOperand(i))
1700 break;
1701 }
1702 if (LastUD->isDef()) {
1703 // If the instruction has no side effect, delete it and propagate
1704 // backward further. Otherwise, mark is dead and we are done.
1705 if (!isSafeToDelete(*LastUDMI)) {
1706 LastUD->setIsDead();
1707 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001708 }
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00001709 EraseInstr(LastUDMI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001710 } else {
1711 LastUD->setIsKill();
1712 RegKills.set(Reg);
1713 KillOps[Reg] = LastUD;
1714 break;
1715 }
1716 }
1717}
Lang Hames87e3bca2009-05-06 02:36:21 +00001718
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001719/// InsertEmergencySpills - Insert emergency spills before MI if requested by
1720/// VRM. Return true if spills were inserted.
1721bool LocalRewriter::InsertEmergencySpills(MachineInstr *MI) {
1722 if (!VRM->hasEmergencySpills(MI))
1723 return false;
1724 MachineBasicBlock::iterator MII = MI;
1725 SmallSet<int, 4> UsedSS;
1726 std::vector<unsigned> &EmSpills = VRM->getEmergencySpills(MI);
1727 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1728 unsigned PhysReg = EmSpills[i];
Rafael Espindola0bfd0922010-07-12 00:52:33 +00001729 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001730 assert(RC && "Unable to determine register class!");
1731 int SS = VRM->getEmergencySpillSlot(RC);
1732 if (UsedSS.count(SS))
1733 llvm_unreachable("Need to spill more than one physical registers!");
1734 UsedSS.insert(SS);
Evan Cheng746ad692010-05-06 19:06:44 +00001735 TII->storeRegToStackSlot(*MBB, MII, PhysReg, true, SS, RC, TRI);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001736 MachineInstr *StoreMI = prior(MII);
1737 VRM->addSpillSlotUse(SS, StoreMI);
1738
1739 // Back-schedule reloads and remats.
1740 MachineBasicBlock::iterator InsertLoc =
1741 ComputeReloadLoc(llvm::next(MII), MBB->begin(), PhysReg, TRI, false, SS,
1742 TII, *MBB->getParent());
1743
Evan Cheng746ad692010-05-06 19:06:44 +00001744 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SS, RC, TRI);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001745
1746 MachineInstr *LoadMI = prior(InsertLoc);
1747 VRM->addSpillSlotUse(SS, LoadMI);
1748 ++NumPSpills;
1749 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1750 }
1751 return true;
1752}
1753
1754/// InsertRestores - Restore registers before MI is requested by VRM. Return
1755/// true is any instructions were inserted.
1756bool LocalRewriter::InsertRestores(MachineInstr *MI,
1757 AvailableSpills &Spills,
1758 BitVector &RegKills,
1759 std::vector<MachineOperand*> &KillOps) {
1760 if (!VRM->isRestorePt(MI))
1761 return false;
1762 MachineBasicBlock::iterator MII = MI;
1763 std::vector<unsigned> &RestoreRegs = VRM->getRestorePtRestores(MI);
1764 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1765 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1766 if (!VRM->getPreSplitReg(VirtReg))
1767 continue; // Split interval spilled again.
1768 unsigned Phys = VRM->getPhys(VirtReg);
1769 MRI->setPhysRegUsed(Phys);
1770
1771 // Check if the value being restored if available. If so, it must be
1772 // from a predecessor BB that fallthrough into this BB. We do not
1773 // expect:
1774 // BB1:
1775 // r1 = load fi#1
1776 // ...
1777 // = r1<kill>
1778 // ... # r1 not clobbered
1779 // ...
1780 // = load fi#1
1781 bool DoReMat = VRM->isReMaterialized(VirtReg);
1782 int SSorRMId = DoReMat
1783 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001784 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1785 if (InReg == Phys) {
1786 // If the value is already available in the expected register, save
1787 // a reload / remat.
1788 if (SSorRMId)
1789 DEBUG(dbgs() << "Reusing RM#"
1790 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1791 else
1792 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1793 DEBUG(dbgs() << " from physreg "
1794 << TRI->getName(InReg) << " for vreg"
1795 << VirtReg <<" instead of reloading into physreg "
1796 << TRI->getName(Phys) << '\n');
Andrew Trick5d7ab852011-01-27 21:26:43 +00001797
1798 // Reusing a physreg may resurrect it. But we expect ProcessUses to update
1799 // the kill flags for the current instruction after processing it.
1800
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001801 ++NumOmitted;
1802 continue;
1803 } else if (InReg && InReg != Phys) {
1804 if (SSorRMId)
1805 DEBUG(dbgs() << "Reusing RM#"
1806 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1807 else
1808 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1809 DEBUG(dbgs() << " from physreg "
1810 << TRI->getName(InReg) << " for vreg"
1811 << VirtReg <<" by copying it into physreg "
1812 << TRI->getName(Phys) << '\n');
1813
1814 // If the reloaded / remat value is available in another register,
1815 // copy it to the desired register.
1816
1817 // Back-schedule reloads and remats.
1818 MachineBasicBlock::iterator InsertLoc =
1819 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1820 *MBB->getParent());
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001821 MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI->getDebugLoc(),
1822 TII->get(TargetOpcode::COPY), Phys)
1823 .addReg(InReg, RegState::Kill);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001824
1825 // This invalidates Phys.
1826 Spills.ClobberPhysReg(Phys);
1827 // Remember it's available.
1828 Spills.addAvailable(SSorRMId, Phys);
1829
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001830 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001831 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1832
1833 DEBUG(dbgs() << '\t' << *CopyMI);
1834 ++NumCopified;
1835 continue;
1836 }
1837
1838 // Back-schedule reloads and remats.
1839 MachineBasicBlock::iterator InsertLoc =
1840 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1841 *MBB->getParent());
1842
1843 if (VRM->isReMaterialized(VirtReg)) {
1844 ReMaterialize(*MBB, InsertLoc, Phys, VirtReg, TII, TRI, *VRM);
1845 } else {
1846 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
Evan Cheng746ad692010-05-06 19:06:44 +00001847 TII->loadRegFromStackSlot(*MBB, InsertLoc, Phys, SSorRMId, RC, TRI);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001848 MachineInstr *LoadMI = prior(InsertLoc);
1849 VRM->addSpillSlotUse(SSorRMId, LoadMI);
1850 ++NumLoads;
1851 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1852 }
1853
1854 // This invalidates Phys.
1855 Spills.ClobberPhysReg(Phys);
1856 // Remember it's available.
1857 Spills.addAvailable(SSorRMId, Phys);
1858
1859 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1860 DEBUG(dbgs() << '\t' << *prior(MII));
1861 }
1862 return true;
1863}
1864
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00001865/// InsertSpills - Insert spills after MI if requested by VRM. Return
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001866/// true if spills were inserted.
1867bool LocalRewriter::InsertSpills(MachineInstr *MI) {
1868 if (!VRM->isSpillPt(MI))
1869 return false;
1870 MachineBasicBlock::iterator MII = MI;
1871 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1872 VRM->getSpillPtSpills(MI);
1873 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1874 unsigned VirtReg = SpillRegs[i].first;
1875 bool isKill = SpillRegs[i].second;
1876 if (!VRM->getPreSplitReg(VirtReg))
1877 continue; // Split interval spilled again.
1878 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
1879 unsigned Phys = VRM->getPhys(VirtReg);
1880 int StackSlot = VRM->getStackSlot(VirtReg);
1881 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1882 TII->storeRegToStackSlot(*MBB, llvm::next(MII), Phys, isKill, StackSlot,
Evan Cheng746ad692010-05-06 19:06:44 +00001883 RC, TRI);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001884 MachineInstr *StoreMI = prior(oldNextMII);
1885 VRM->addSpillSlotUse(StackSlot, StoreMI);
1886 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1887 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1888 }
1889 return true;
1890}
1891
1892
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00001893/// ProcessUses - Process all of MI's spilled operands and all available
1894/// operands.
1895void LocalRewriter::ProcessUses(MachineInstr &MI, AvailableSpills &Spills,
1896 std::vector<MachineInstr*> &MaybeDeadStores,
1897 BitVector &RegKills,
1898 ReuseInfo &ReusedOperands,
1899 std::vector<MachineOperand*> &KillOps) {
1900 // Clear kill info.
1901 SmallSet<unsigned, 2> KilledMIRegs;
1902 SmallVector<unsigned, 4> VirtUseOps;
1903 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1904 MachineOperand &MO = MI.getOperand(i);
1905 if (!MO.isReg() || MO.getReg() == 0)
1906 continue; // Ignore non-register operands.
1907
1908 unsigned VirtReg = MO.getReg();
Andrew Trick5d7ab852011-01-27 21:26:43 +00001909
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00001910 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1911 // Ignore physregs for spilling, but remember that it is used by this
1912 // function.
1913 MRI->setPhysRegUsed(VirtReg);
1914 continue;
1915 }
1916
1917 // We want to process implicit virtual register uses first.
1918 if (MO.isImplicit())
1919 // If the virtual register is implicitly defined, emit a implicit_def
1920 // before so scavenger knows it's "defined".
1921 // FIXME: This is a horrible hack done the by register allocator to
1922 // remat a definition with virtual register operand.
1923 VirtUseOps.insert(VirtUseOps.begin(), i);
1924 else
1925 VirtUseOps.push_back(i);
Jakob Stoklund Olesen40ef4fe2010-10-11 18:10:36 +00001926
1927 // A partial def causes problems because the same operand both reads and
1928 // writes the register. This rewriter is designed to rewrite uses and defs
1929 // separately, so a partial def would already have been rewritten to a
1930 // physreg by the time we get to processing defs.
1931 // Add an implicit use operand to model the partial def.
1932 if (MO.isDef() && MO.getSubReg() && MI.readsVirtualRegister(VirtReg) &&
1933 MI.findRegisterUseOperandIdx(VirtReg) == -1) {
1934 VirtUseOps.insert(VirtUseOps.begin(), MI.getNumOperands());
1935 MI.addOperand(MachineOperand::CreateReg(VirtReg,
1936 false, // isDef
1937 true)); // isImplicit
1938 DEBUG(dbgs() << "Partial redef: " << MI);
1939 }
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00001940 }
1941
1942 // Process all of the spilled uses and all non spilled reg references.
1943 SmallVector<int, 2> PotentialDeadStoreSlots;
1944 KilledMIRegs.clear();
1945 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1946 unsigned i = VirtUseOps[j];
1947 unsigned VirtReg = MI.getOperand(i).getReg();
1948 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1949 "Not a virtual register?");
1950
1951 unsigned SubIdx = MI.getOperand(i).getSubReg();
1952 if (VRM->isAssignedReg(VirtReg)) {
1953 // This virtual register was assigned a physreg!
1954 unsigned Phys = VRM->getPhys(VirtReg);
1955 MRI->setPhysRegUsed(Phys);
1956 if (MI.getOperand(i).isDef())
1957 ReusedOperands.markClobbered(Phys);
1958 substitutePhysReg(MI.getOperand(i), Phys, *TRI);
1959 if (VRM->isImplicitlyDefined(VirtReg))
1960 // FIXME: Is this needed?
1961 BuildMI(*MBB, &MI, MI.getDebugLoc(),
1962 TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
1963 continue;
1964 }
1965
1966 // This virtual register is now known to be a spilled value.
1967 if (!MI.getOperand(i).isUse())
1968 continue; // Handle defs in the loop below (handle use&def here though)
1969
1970 bool AvoidReload = MI.getOperand(i).isUndef();
1971 // Check if it is defined by an implicit def. It should not be spilled.
1972 // Note, this is for correctness reason. e.g.
1973 // 8 %reg1024<def> = IMPLICIT_DEF
1974 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1975 // The live range [12, 14) are not part of the r1024 live interval since
1976 // it's defined by an implicit def. It will not conflicts with live
1977 // interval of r1025. Now suppose both registers are spilled, you can
1978 // easily see a situation where both registers are reloaded before
1979 // the INSERT_SUBREG and both target registers that would overlap.
1980 bool DoReMat = VRM->isReMaterialized(VirtReg);
1981 int SSorRMId = DoReMat
1982 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1983 int ReuseSlot = SSorRMId;
1984
1985 // Check to see if this stack slot is available.
1986 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1987
1988 // If this is a sub-register use, make sure the reuse register is in the
1989 // right register class. For example, for x86 not all of the 32-bit
1990 // registers have accessible sub-registers.
1991 // Similarly so for EXTRACT_SUBREG. Consider this:
1992 // EDI = op
1993 // MOV32_mr fi#1, EDI
1994 // ...
1995 // = EXTRACT_SUBREG fi#1
1996 // fi#1 is available in EDI, but it cannot be reused because it's not in
1997 // the right register file.
1998 if (PhysReg && !AvoidReload && SubIdx) {
1999 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2000 if (!RC->contains(PhysReg))
2001 PhysReg = 0;
2002 }
2003
2004 if (PhysReg && !AvoidReload) {
2005 // This spilled operand might be part of a two-address operand. If this
2006 // is the case, then changing it will necessarily require changing the
2007 // def part of the instruction as well. However, in some cases, we
2008 // aren't allowed to modify the reused register. If none of these cases
2009 // apply, reuse it.
2010 bool CanReuse = true;
2011 bool isTied = MI.isRegTiedToDefOperand(i);
2012 if (isTied) {
2013 // Okay, we have a two address operand. We can reuse this physreg as
2014 // long as we are allowed to clobber the value and there isn't an
2015 // earlier def that has already clobbered the physreg.
2016 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
2017 Spills.canClobberPhysReg(PhysReg);
2018 }
2019 // If this is an asm, and a PhysReg alias is used elsewhere as an
2020 // earlyclobber operand, we can't also use it as an input.
2021 if (MI.isInlineAsm()) {
2022 for (unsigned k = 0, e = MI.getNumOperands(); k != e; ++k) {
2023 MachineOperand &MOk = MI.getOperand(k);
2024 if (MOk.isReg() && MOk.isEarlyClobber() &&
2025 TRI->regsOverlap(MOk.getReg(), PhysReg)) {
2026 CanReuse = false;
2027 DEBUG(dbgs() << "Not reusing physreg " << TRI->getName(PhysReg)
2028 << " for vreg" << VirtReg << ": " << MOk << '\n');
2029 break;
2030 }
2031 }
2032 }
2033
2034 if (CanReuse) {
2035 // If this stack slot value is already available, reuse it!
2036 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2037 DEBUG(dbgs() << "Reusing RM#"
2038 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2039 else
2040 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2041 DEBUG(dbgs() << " from physreg "
2042 << TRI->getName(PhysReg) << " for vreg"
2043 << VirtReg <<" instead of reloading into physreg "
2044 << TRI->getName(VRM->getPhys(VirtReg)) << '\n');
2045 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2046 MI.getOperand(i).setReg(RReg);
2047 MI.getOperand(i).setSubReg(0);
2048
Andrew Trick5d7ab852011-01-27 21:26:43 +00002049 // Reusing a physreg may resurrect it. But we expect ProcessUses to
2050 // update the kill flags for the current instr after processing it.
2051
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00002052 // The only technical detail we have is that we don't know that
2053 // PhysReg won't be clobbered by a reloaded stack slot that occurs
2054 // later in the instruction. In particular, consider 'op V1, V2'.
2055 // If V1 is available in physreg R0, we would choose to reuse it
2056 // here, instead of reloading it into the register the allocator
2057 // indicated (say R1). However, V2 might have to be reloaded
2058 // later, and it might indicate that it needs to live in R0. When
2059 // this occurs, we need to have information available that
2060 // indicates it is safe to use R1 for the reload instead of R0.
2061 //
2062 // To further complicate matters, we might conflict with an alias,
2063 // or R0 and R1 might not be compatible with each other. In this
2064 // case, we actually insert a reload for V1 in R1, ensuring that
2065 // we can get at R0 or its alias.
2066 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
2067 VRM->getPhys(VirtReg), VirtReg);
2068 if (isTied)
2069 // Only mark it clobbered if this is a use&def operand.
2070 ReusedOperands.markClobbered(PhysReg);
2071 ++NumReused;
2072
2073 if (MI.getOperand(i).isKill() &&
2074 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
2075
2076 // The store of this spilled value is potentially dead, but we
2077 // won't know for certain until we've confirmed that the re-use
2078 // above is valid, which means waiting until the other operands
2079 // are processed. For now we just track the spill slot, we'll
2080 // remove it after the other operands are processed if valid.
2081
2082 PotentialDeadStoreSlots.push_back(ReuseSlot);
2083 }
2084
2085 // Mark is isKill if it's there no other uses of the same virtual
2086 // register and it's not a two-address operand. IsKill will be
2087 // unset if reg is reused.
2088 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
2089 MI.getOperand(i).setIsKill();
2090 KilledMIRegs.insert(VirtReg);
2091 }
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00002092 continue;
2093 } // CanReuse
2094
2095 // Otherwise we have a situation where we have a two-address instruction
2096 // whose mod/ref operand needs to be reloaded. This reload is already
2097 // available in some register "PhysReg", but if we used PhysReg as the
2098 // operand to our 2-addr instruction, the instruction would modify
2099 // PhysReg. This isn't cool if something later uses PhysReg and expects
2100 // to get its initial value.
2101 //
2102 // To avoid this problem, and to avoid doing a load right after a store,
2103 // we emit a copy from PhysReg into the designated register for this
2104 // operand.
2105 //
2106 // This case also applies to an earlyclobber'd PhysReg.
2107 unsigned DesignatedReg = VRM->getPhys(VirtReg);
2108 assert(DesignatedReg && "Must map virtreg to physreg!");
2109
2110 // Note that, if we reused a register for a previous operand, the
2111 // register we want to reload into might not actually be
2112 // available. If this occurs, use the register indicated by the
2113 // reuser.
2114 if (ReusedOperands.hasReuses())
2115 DesignatedReg = ReusedOperands.
2116 GetRegForReload(VirtReg, DesignatedReg, &MI, Spills,
2117 MaybeDeadStores, RegKills, KillOps, *VRM);
2118
2119 // If the mapped designated register is actually the physreg we have
2120 // incoming, we don't need to inserted a dead copy.
2121 if (DesignatedReg == PhysReg) {
2122 // If this stack slot value is already available, reuse it!
2123 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2124 DEBUG(dbgs() << "Reusing RM#"
2125 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2126 else
2127 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2128 DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
2129 << " for vreg" << VirtReg
2130 << " instead of reloading into same physreg.\n");
2131 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2132 MI.getOperand(i).setReg(RReg);
2133 MI.getOperand(i).setSubReg(0);
2134 ReusedOperands.markClobbered(RReg);
2135 ++NumReused;
2136 continue;
2137 }
2138
2139 MRI->setPhysRegUsed(DesignatedReg);
2140 ReusedOperands.markClobbered(DesignatedReg);
2141
2142 // Back-schedule reloads and remats.
2143 MachineBasicBlock::iterator InsertLoc =
2144 ComputeReloadLoc(&MI, MBB->begin(), PhysReg, TRI, DoReMat,
2145 SSorRMId, TII, *MBB->getParent());
2146 MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI.getDebugLoc(),
2147 TII->get(TargetOpcode::COPY),
2148 DesignatedReg).addReg(PhysReg);
2149 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2150 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2151
2152 // This invalidates DesignatedReg.
2153 Spills.ClobberPhysReg(DesignatedReg);
2154
2155 Spills.addAvailable(ReuseSlot, DesignatedReg);
2156 unsigned RReg =
2157 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2158 MI.getOperand(i).setReg(RReg);
2159 MI.getOperand(i).setSubReg(0);
2160 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2161 ++NumReused;
2162 continue;
2163 } // if (PhysReg)
2164
Andrew Trick5d7ab852011-01-27 21:26:43 +00002165 // Otherwise, reload it and remember that we have it.
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00002166 PhysReg = VRM->getPhys(VirtReg);
2167 assert(PhysReg && "Must map virtreg to physreg!");
2168
2169 // Note that, if we reused a register for a previous operand, the
2170 // register we want to reload into might not actually be
2171 // available. If this occurs, use the register indicated by the
2172 // reuser.
2173 if (ReusedOperands.hasReuses())
2174 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2175 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2176
2177 MRI->setPhysRegUsed(PhysReg);
2178 ReusedOperands.markClobbered(PhysReg);
2179 if (AvoidReload)
2180 ++NumAvoided;
2181 else {
2182 // Back-schedule reloads and remats.
2183 MachineBasicBlock::iterator InsertLoc =
2184 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI, DoReMat,
2185 SSorRMId, TII, *MBB->getParent());
2186
2187 if (DoReMat) {
2188 ReMaterialize(*MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, *VRM);
2189 } else {
2190 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2191 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SSorRMId, RC,TRI);
2192 MachineInstr *LoadMI = prior(InsertLoc);
2193 VRM->addSpillSlotUse(SSorRMId, LoadMI);
2194 ++NumLoads;
2195 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
2196 }
2197 // This invalidates PhysReg.
2198 Spills.ClobberPhysReg(PhysReg);
2199
2200 // Any stores to this stack slot are not dead anymore.
2201 if (!DoReMat)
2202 MaybeDeadStores[SSorRMId] = NULL;
2203 Spills.addAvailable(SSorRMId, PhysReg);
2204 // Assumes this is the last use. IsKill will be unset if reg is reused
2205 // unless it's a two-address operand.
2206 if (!MI.isRegTiedToDefOperand(i) &&
2207 KilledMIRegs.count(VirtReg) == 0) {
2208 MI.getOperand(i).setIsKill();
2209 KilledMIRegs.insert(VirtReg);
2210 }
2211
2212 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2213 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2214 }
2215 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2216 MI.getOperand(i).setReg(RReg);
2217 MI.getOperand(i).setSubReg(0);
2218 }
2219
2220 // Ok - now we can remove stores that have been confirmed dead.
2221 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2222 // This was the last use and the spilled value is still available
2223 // for reuse. That means the spill was unnecessary!
2224 int PDSSlot = PotentialDeadStoreSlots[j];
2225 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2226 if (DeadStore) {
2227 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2228 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00002229 EraseInstr(DeadStore);
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00002230 MaybeDeadStores[PDSSlot] = NULL;
2231 ++NumDSE;
2232 }
2233 }
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00002234}
2235
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002236/// rewriteMBB - Keep track of which spills are available even after the
Jim Grosbachae64eed2010-07-27 17:14:29 +00002237/// register allocator is done with them. If possible, avoid reloading vregs.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002238void
2239LocalRewriter::RewriteMBB(LiveIntervals *LIs,
2240 AvailableSpills &Spills, BitVector &RegKills,
2241 std::vector<MachineOperand*> &KillOps) {
Lang Hames87e3bca2009-05-06 02:36:21 +00002242
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002243 DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
2244 << MBB->getName() << "':\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00002245
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002246 MachineFunction &MF = *MBB->getParent();
David Greene2d4e6d32009-07-28 16:49:24 +00002247
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002248 // MaybeDeadStores - When we need to write a value back into a stack slot,
2249 // keep track of the inserted store. If the stack slot value is never read
2250 // (because the value was used from some available register, for example), and
2251 // subsequently stored to, the original store is dead. This map keeps track
2252 // of inserted stores that are not used. If we see a subsequent store to the
2253 // same stack slot, the original store is deleted.
2254 std::vector<MachineInstr*> MaybeDeadStores;
2255 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
David Greene2d4e6d32009-07-28 16:49:24 +00002256
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002257 // ReMatDefs - These are rematerializable def MIs which are not deleted.
2258 SmallSet<MachineInstr*, 4> ReMatDefs;
Lang Hames87e3bca2009-05-06 02:36:21 +00002259
Jakob Stoklund Olesen2afb7502010-05-21 16:36:13 +00002260 // Keep track of the registers we have already spilled in case there are
2261 // multiple defs of the same register in MI.
2262 SmallSet<unsigned, 8> SpilledMIRegs;
2263
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002264 RegKills.reset();
2265 KillOps.clear();
2266 KillOps.resize(TRI->getNumRegs(), NULL);
Lang Hames87e3bca2009-05-06 02:36:21 +00002267
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002268 DistanceMap.clear();
2269 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2270 MII != E; ) {
2271 MachineBasicBlock::iterator NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00002272
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002273 if (OptimizeByUnfold(MII, MaybeDeadStores, Spills, RegKills, KillOps))
2274 NextMII = llvm::next(MII);
2275
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00002276 if (InsertEmergencySpills(MII))
2277 NextMII = llvm::next(MII);
2278
2279 InsertRestores(MII, Spills, RegKills, KillOps);
2280
2281 if (InsertSpills(MII))
2282 NextMII = llvm::next(MII);
2283
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00002284 bool Erased = false;
2285 bool BackTracked = false;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002286 MachineInstr &MI = *MII;
2287
Evan Chengbd6cb4b2010-04-29 18:51:00 +00002288 // Remember DbgValue's which reference stack slots.
2289 if (MI.isDebugValue() && MI.getOperand(0).isFI())
2290 Slot2DbgValues[MI.getOperand(0).getIndex()].push_back(&MI);
2291
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002292 /// ReusedOperands - Keep track of operand reuse in case we need to undo
2293 /// reuse.
2294 ReuseInfo ReusedOperands(MI, TRI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002295
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00002296 ProcessUses(MI, Spills, MaybeDeadStores, RegKills, ReusedOperands, KillOps);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002297
2298 DEBUG(dbgs() << '\t' << MI);
2299
2300
2301 // If we have folded references to memory operands, make sure we clear all
2302 // physical registers that may contain the value of the spilled virtual
2303 // register
Jakob Stoklund Olesena330d4c2010-08-05 18:12:19 +00002304
2305 // Copy the folded virts to a small vector, we may change MI2VirtMap.
2306 SmallVector<std::pair<unsigned, VirtRegMap::ModRef>, 4> FoldedVirts;
2307 // C++0x FTW!
2308 for (std::pair<VirtRegMap::MI2VirtMapTy::const_iterator,
2309 VirtRegMap::MI2VirtMapTy::const_iterator> FVRange =
2310 VRM->getFoldedVirts(&MI);
2311 FVRange.first != FVRange.second; ++FVRange.first)
2312 FoldedVirts.push_back(FVRange.first->second);
2313
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002314 SmallSet<int, 2> FoldedSS;
Jakob Stoklund Olesena330d4c2010-08-05 18:12:19 +00002315 for (unsigned FVI = 0, FVE = FoldedVirts.size(); FVI != FVE; ++FVI) {
2316 unsigned VirtReg = FoldedVirts[FVI].first;
2317 VirtRegMap::ModRef MR = FoldedVirts[FVI].second;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002318 DEBUG(dbgs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2319
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002320 int SS = VRM->getStackSlot(VirtReg);
2321 if (SS == VirtRegMap::NO_STACK_SLOT)
2322 continue;
2323 FoldedSS.insert(SS);
2324 DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
2325
2326 // If this folded instruction is just a use, check to see if it's a
2327 // straight load from the virt reg slot.
2328 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2329 int FrameIdx;
2330 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2331 if (DestReg && FrameIdx == SS) {
2332 // If this spill slot is available, turn it into a copy (or nothing)
2333 // instead of leaving it as a load!
2334 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2335 DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
2336 if (DestReg != InReg) {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002337 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00002338 MachineInstr *CopyMI = BuildMI(*MBB, &MI, MI.getDebugLoc(),
2339 TII->get(TargetOpcode::COPY))
2340 .addReg(DestReg, RegState::Define, DefMO->getSubReg())
2341 .addReg(InReg, RegState::Kill);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002342 // Revisit the copy so we make sure to notice the effects of the
2343 // operation on the destreg (either needing to RA it if it's
2344 // virtual or needing to clobber any values if it's physical).
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00002345 NextMII = CopyMI;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002346 NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002347 BackTracked = true;
2348 } else {
2349 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
Andrew Trick5d7ab852011-01-27 21:26:43 +00002350 // InvalidateKills resurrects any prior kill of the copy's source
2351 // allowing the source reg to be reused in place of the copy.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002352 Spills.disallowClobberPhysReg(InReg);
2353 }
2354
2355 InvalidateKills(MI, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00002356 EraseInstr(&MI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002357 Erased = true;
2358 goto ProcessNextInst;
2359 }
2360 } else {
2361 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2362 SmallVector<MachineInstr*, 4> NewMIs;
2363 if (PhysReg &&
Jim Grosbach57cb4f82010-07-27 17:38:47 +00002364 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)){
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002365 MBB->insert(MII, NewMIs[0]);
2366 InvalidateKills(MI, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00002367 EraseInstr(&MI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002368 Erased = true;
2369 --NextMII; // backtrack to the unfolded instruction.
2370 BackTracked = true;
2371 goto ProcessNextInst;
2372 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002373 }
2374 }
2375
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002376 // If this reference is not a use, any previous store is now dead.
2377 // Otherwise, the store to this stack slot is not dead anymore.
2378 MachineInstr* DeadStore = MaybeDeadStores[SS];
2379 if (DeadStore) {
2380 bool isDead = !(MR & VirtRegMap::isRef);
2381 MachineInstr *NewStore = NULL;
2382 if (MR & VirtRegMap::isModRef) {
2383 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2384 SmallVector<MachineInstr*, 4> NewMIs;
2385 // We can reuse this physreg as long as we are allowed to clobber
2386 // the value and there isn't an earlier def that has already clobbered
2387 // the physreg.
2388 if (PhysReg &&
2389 !ReusedOperands.isClobbered(PhysReg) &&
2390 Spills.canClobberPhysReg(PhysReg) &&
2391 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2392 MachineOperand *KillOpnd =
2393 DeadStore->findRegisterUseOperand(PhysReg, true);
2394 // Note, if the store is storing a sub-register, it's possible the
2395 // super-register is needed below.
2396 if (KillOpnd && !KillOpnd->getSubReg() &&
2397 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2398 MBB->insert(MII, NewMIs[0]);
2399 NewStore = NewMIs[1];
2400 MBB->insert(MII, NewStore);
2401 VRM->addSpillSlotUse(SS, NewStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002402 InvalidateKills(MI, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00002403 EraseInstr(&MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002404 Erased = true;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002405 --NextMII;
Lang Hames87e3bca2009-05-06 02:36:21 +00002406 --NextMII; // backtrack to the unfolded instruction.
2407 BackTracked = true;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002408 isDead = true;
2409 ++NumSUnfold;
2410 }
2411 }
2412 }
2413
2414 if (isDead) { // Previous store is dead.
2415 // If we get here, the store is dead, nuke it now.
2416 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2417 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00002418 EraseInstr(DeadStore);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002419 if (!NewStore)
2420 ++NumDSE;
2421 }
2422
2423 MaybeDeadStores[SS] = NULL;
2424 if (NewStore) {
2425 // Treat this store as a spill merged into a copy. That makes the
2426 // stack slot value available.
2427 VRM->virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2428 goto ProcessNextInst;
2429 }
2430 }
2431
2432 // If the spill slot value is available, and this is a new definition of
2433 // the value, the value is not available anymore.
2434 if (MR & VirtRegMap::isMod) {
2435 // Notice that the value in this stack slot has been modified.
2436 Spills.ModifyStackSlotOrReMat(SS);
2437
2438 // If this is *just* a mod of the value, check to see if this is just a
2439 // store to the spill slot (i.e. the spill got merged into the copy). If
2440 // so, realize that the vreg is available now, and add the store to the
2441 // MaybeDeadStore info.
2442 int StackSlot;
2443 if (!(MR & VirtRegMap::isRef)) {
2444 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2445 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2446 "Src hasn't been allocated yet?");
2447
2448 if (CommuteToFoldReload(MII, VirtReg, SrcReg, StackSlot,
2449 Spills, RegKills, KillOps, TRI)) {
2450 NextMII = llvm::next(MII);
2451 BackTracked = true;
Lang Hames87e3bca2009-05-06 02:36:21 +00002452 goto ProcessNextInst;
2453 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002454
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002455 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2456 // this as a potentially dead store in case there is a subsequent
2457 // store into the stack slot without a read from it.
2458 MaybeDeadStores[StackSlot] = &MI;
Lang Hames87e3bca2009-05-06 02:36:21 +00002459
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002460 // If the stack slot value was previously available in some other
2461 // register, change it now. Otherwise, make the register
2462 // available in PhysReg.
2463 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
Lang Hames87e3bca2009-05-06 02:36:21 +00002464 }
2465 }
2466 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002467 }
2468
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002469 // Process all of the spilled defs.
Jakob Stoklund Olesen2afb7502010-05-21 16:36:13 +00002470 SpilledMIRegs.clear();
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002471 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2472 MachineOperand &MO = MI.getOperand(i);
2473 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2474 continue;
Lang Hames87e3bca2009-05-06 02:36:21 +00002475
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002476 unsigned VirtReg = MO.getReg();
2477 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2478 // Check to see if this is a noop copy. If so, eliminate the
2479 // instruction before considering the dest reg to be changed.
2480 // Also check if it's copying from an "undef", if so, we can't
2481 // eliminate this or else the undef marker is lost and it will
2482 // confuses the scavenger. This is extremely rare.
Jakob Stoklund Olesen1769ccc2010-07-09 01:27:19 +00002483 if (MI.isIdentityCopy() && !MI.getOperand(1).isUndef() &&
2484 MI.getNumOperands() == 2) {
2485 ++NumDCE;
2486 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2487 SmallVector<unsigned, 2> KillRegs;
2488 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2489 if (MO.isDead() && !KillRegs.empty()) {
2490 // Source register or an implicit super/sub-register use is killed.
2491 assert(TRI->regsOverlap(KillRegs[0], MI.getOperand(0).getReg()));
2492 // Last def is now dead.
2493 TransferDeadness(MI.getOperand(1).getReg(), RegKills, KillOps);
2494 }
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00002495 EraseInstr(&MI);
Jakob Stoklund Olesen1769ccc2010-07-09 01:27:19 +00002496 Erased = true;
2497 Spills.disallowClobberPhysReg(VirtReg);
2498 goto ProcessNextInst;
2499 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002500
2501 // If it's not a no-op copy, it clobbers the value in the destreg.
2502 Spills.ClobberPhysReg(VirtReg);
2503 ReusedOperands.markClobbered(VirtReg);
2504
2505 // Check to see if this instruction is a load from a stack slot into
2506 // a register. If so, this provides the stack slot value in the reg.
2507 int FrameIdx;
2508 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2509 assert(DestReg == VirtReg && "Unknown load situation!");
2510
2511 // If it is a folded reference, then it's not safe to clobber.
2512 bool Folded = FoldedSS.count(FrameIdx);
2513 // Otherwise, if it wasn't available, remember that it is now!
2514 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2515 goto ProcessNextInst;
2516 }
2517
2518 continue;
2519 }
2520
2521 unsigned SubIdx = MO.getSubReg();
2522 bool DoReMat = VRM->isReMaterialized(VirtReg);
2523 if (DoReMat)
2524 ReMatDefs.insert(&MI);
2525
2526 // The only vregs left are stack slot definitions.
2527 int StackSlot = VRM->getStackSlot(VirtReg);
2528 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2529
2530 // If this def is part of a two-address operand, make sure to execute
2531 // the store from the correct physical register.
2532 unsigned PhysReg;
2533 unsigned TiedOp;
2534 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2535 PhysReg = MI.getOperand(TiedOp).getReg();
2536 if (SubIdx) {
2537 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2538 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2539 "Can't find corresponding super-register!");
2540 PhysReg = SuperReg;
2541 }
2542 } else {
2543 PhysReg = VRM->getPhys(VirtReg);
2544 if (ReusedOperands.isClobbered(PhysReg)) {
2545 // Another def has taken the assigned physreg. It must have been a
2546 // use&def which got it due to reuse. Undo the reuse!
2547 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2548 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2549 }
2550 }
2551
2552 assert(PhysReg && "VR not assigned a physical register?");
2553 MRI->setPhysRegUsed(PhysReg);
2554 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2555 ReusedOperands.markClobbered(RReg);
2556 MI.getOperand(i).setReg(RReg);
2557 MI.getOperand(i).setSubReg(0);
2558
Jakob Stoklund Olesen2afb7502010-05-21 16:36:13 +00002559 if (!MO.isDead() && SpilledMIRegs.insert(VirtReg)) {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002560 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2561 SpillRegToStackSlot(MII, -1, PhysReg, StackSlot, RC, true,
2562 LastStore, Spills, ReMatDefs, RegKills, KillOps);
2563 NextMII = llvm::next(MII);
2564
2565 // Check to see if this is a noop copy. If so, eliminate the
2566 // instruction before considering the dest reg to be changed.
Jakob Stoklund Olesen1769ccc2010-07-09 01:27:19 +00002567 if (MI.isIdentityCopy()) {
2568 ++NumDCE;
2569 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2570 InvalidateKills(MI, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00002571 EraseInstr(&MI);
Jakob Stoklund Olesen1769ccc2010-07-09 01:27:19 +00002572 Erased = true;
2573 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2574 goto ProcessNextInst;
2575 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002576 }
2577 }
2578 ProcessNextInst:
2579 // Delete dead instructions without side effects.
2580 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2581 InvalidateKills(MI, TRI, RegKills, KillOps);
Jakob Stoklund Olesenee547092011-01-12 22:28:51 +00002582 EraseInstr(&MI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002583 Erased = true;
2584 }
2585 if (!Erased)
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00002586 DistanceMap.insert(std::make_pair(&MI, DistanceMap.size()));
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002587 if (!Erased && !BackTracked) {
2588 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2589 UpdateKills(*II, TRI, RegKills, KillOps);
2590 }
2591 MII = NextMII;
2592 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002593
Dan Gohman7db949d2009-08-07 01:32:21 +00002594}
2595
Lang Hames87e3bca2009-05-06 02:36:21 +00002596llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2597 switch (RewriterOpt) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002598 default: llvm_unreachable("Unreachable!");
Lang Hames87e3bca2009-05-06 02:36:21 +00002599 case local:
2600 return new LocalRewriter();
Lang Hamesf41538d2009-06-02 16:53:25 +00002601 case trivial:
2602 return new TrivialRewriter();
Lang Hames87e3bca2009-05-06 02:36:21 +00002603 }
2604}