blob: f44eccd40cc71a253bdf467ccfa2fccd8af9f303 [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"
25#include "llvm/ADT/Statistic.h"
Lang Hames87e3bca2009-05-06 02:36:21 +000026#include <algorithm>
27using 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);
219 DEBUG(dbgs() << " in physreg " << TRI->getName(Reg) << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000220 }
221
222 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
223 /// the value of the specified stackslot register if it desires. The
224 /// specified stack slot must be available in a physreg for this query to
225 /// make sense.
226 bool canClobberPhysRegForSS(int SlotOrReMat) const {
227 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
228 "Value not available!");
229 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
230 }
231
232 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
233 /// physical register where values for some stack slot(s) might be
234 /// available.
235 bool canClobberPhysReg(unsigned PhysReg) const {
236 std::multimap<unsigned, int>::const_iterator I =
237 PhysRegsAvailable.lower_bound(PhysReg);
238 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
239 int SlotOrReMat = I->second;
240 I++;
241 if (!canClobberPhysRegForSS(SlotOrReMat))
242 return false;
243 }
244 return true;
245 }
246
247 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
248 /// stackslot register. The register is still available but is no longer
249 /// allowed to be modifed.
250 void disallowClobberPhysReg(unsigned PhysReg);
251
252 /// ClobberPhysReg - This is called when the specified physreg changes
253 /// value. We use this to invalidate any info about stuff that lives in
254 /// it and any of its aliases.
255 void ClobberPhysReg(unsigned PhysReg);
256
257 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
258 /// slot changes. This removes information about which register the
259 /// previous value for this slot lives in (as the previous value is dead
260 /// now).
261 void ModifyStackSlotOrReMat(int SlotOrReMat);
262
263 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
264 /// into the specified MBB. Add available physical registers as potential
265 /// live-in's. If they are reused in the MBB, they will be added to the
266 /// live-in set to make register scavenger and post-allocation scheduler.
267 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
268 std::vector<MachineOperand*> &KillOps);
269};
270
Dan Gohman7db949d2009-08-07 01:32:21 +0000271}
272
Lang Hames87e3bca2009-05-06 02:36:21 +0000273// ************************************************************************ //
274
David Greene2d4e6d32009-07-28 16:49:24 +0000275// Given a location where a reload of a spilled register or a remat of
276// a constant is to be inserted, attempt to find a safe location to
277// insert the load at an earlier point in the basic-block, to hide
278// latency of the load and to avoid address-generation interlock
279// issues.
280static MachineBasicBlock::iterator
281ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
282 MachineBasicBlock::iterator const Begin,
283 unsigned PhysReg,
284 const TargetRegisterInfo *TRI,
285 bool DoReMat,
286 int SSorRMId,
287 const TargetInstrInfo *TII,
288 const MachineFunction &MF)
289{
290 if (!ScheduleSpills)
291 return InsertLoc;
292
293 // Spill backscheduling is of primary interest to addresses, so
294 // don't do anything if the register isn't in the register class
295 // used for pointers.
296
297 const TargetLowering *TL = MF.getTarget().getTargetLowering();
298
299 if (!TL->isTypeLegal(TL->getPointerTy()))
Chris Lattner60cb5282010-10-11 05:44:40 +0000300 // Believe it or not, this is true on 16-bit targets like PIC16.
David Greene2d4e6d32009-07-28 16:49:24 +0000301 return InsertLoc;
302
303 const TargetRegisterClass *ptrRegClass =
304 TL->getRegClassFor(TL->getPointerTy());
305 if (!ptrRegClass->contains(PhysReg))
306 return InsertLoc;
307
308 // Scan upwards through the preceding instructions. If an instruction doesn't
309 // reference the stack slot or the register we're loading, we can
310 // backschedule the reload up past it.
311 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
312 while (NewInsertLoc != Begin) {
313 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
314 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
315 MachineOperand &Op = Prev->getOperand(i);
316 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
317 goto stop;
318 }
319 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
320 Prev->findRegisterDefOperand(PhysReg))
321 goto stop;
322 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
323 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
324 Prev->findRegisterDefOperand(*Alias))
325 goto stop;
326 NewInsertLoc = Prev;
327 }
328stop:;
329
330 // If we made it to the beginning of the block, turn around and move back
331 // down just past any existing reloads. They're likely to be reloads/remats
332 // for instructions earlier than what our current reload/remat is for, so
333 // they should be scheduled earlier.
334 if (NewInsertLoc == Begin) {
335 int FrameIdx;
336 while (InsertLoc != NewInsertLoc &&
337 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
338 TII->isTriviallyReMaterializable(NewInsertLoc)))
339 ++NewInsertLoc;
340 }
341
342 return NewInsertLoc;
343}
Dan Gohman7db949d2009-08-07 01:32:21 +0000344
345namespace {
346
Lang Hames87e3bca2009-05-06 02:36:21 +0000347// ReusedOp - For each reused operand, we keep track of a bit of information,
348// in case we need to rollback upon processing a new operand. See comments
349// below.
350struct ReusedOp {
351 // The MachineInstr operand that reused an available value.
352 unsigned Operand;
353
354 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
355 unsigned StackSlotOrReMat;
356
357 // PhysRegReused - The physical register the value was available in.
358 unsigned PhysRegReused;
359
360 // AssignedPhysReg - The physreg that was assigned for use by the reload.
361 unsigned AssignedPhysReg;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000362
Lang Hames87e3bca2009-05-06 02:36:21 +0000363 // VirtReg - The virtual register itself.
364 unsigned VirtReg;
365
366 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
367 unsigned vreg)
368 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
369 AssignedPhysReg(apr), VirtReg(vreg) {}
370};
371
372/// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
373/// is reused instead of reloaded.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000374class ReuseInfo {
Lang Hames87e3bca2009-05-06 02:36:21 +0000375 MachineInstr &MI;
376 std::vector<ReusedOp> Reuses;
377 BitVector PhysRegsClobbered;
378public:
379 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
380 PhysRegsClobbered.resize(tri->getNumRegs());
381 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000382
Lang Hames87e3bca2009-05-06 02:36:21 +0000383 bool hasReuses() const {
384 return !Reuses.empty();
385 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000386
Lang Hames87e3bca2009-05-06 02:36:21 +0000387 /// addReuse - If we choose to reuse a virtual register that is already
388 /// available instead of reloading it, remember that we did so.
389 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
390 unsigned PhysRegReused, unsigned AssignedPhysReg,
391 unsigned VirtReg) {
392 // If the reload is to the assigned register anyway, no undo will be
393 // required.
394 if (PhysRegReused == AssignedPhysReg) return;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000395
Lang Hames87e3bca2009-05-06 02:36:21 +0000396 // Otherwise, remember this.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000397 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
Lang Hames87e3bca2009-05-06 02:36:21 +0000398 AssignedPhysReg, VirtReg));
399 }
400
401 void markClobbered(unsigned PhysReg) {
402 PhysRegsClobbered.set(PhysReg);
403 }
404
405 bool isClobbered(unsigned PhysReg) const {
406 return PhysRegsClobbered.test(PhysReg);
407 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000408
Lang Hames87e3bca2009-05-06 02:36:21 +0000409 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
410 /// is some other operand that is using the specified register, either pick
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000411 /// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000412 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
413 MachineFunction &MF, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000414 AvailableSpills &Spills,
415 std::vector<MachineInstr*> &MaybeDeadStores,
416 SmallSet<unsigned, 8> &Rejected,
417 BitVector &RegKills,
418 std::vector<MachineOperand*> &KillOps,
419 VirtRegMap &VRM);
420
421 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
422 /// 'Rejected' set to remember which registers have been considered and
423 /// rejected for the reload. This avoids infinite looping in case like
424 /// this:
425 /// t1 := op t2, t3
426 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
427 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
428 /// t1 <- desires r1
429 /// sees r1 is taken by t2, tries t2's reload register r0
430 /// sees r0 is taken by t3, tries t3's reload register r1
431 /// sees r1 is taken by t2, tries t2's reload register r0 ...
Evan Cheng5d885022009-07-21 09:15:00 +0000432 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000433 AvailableSpills &Spills,
434 std::vector<MachineInstr*> &MaybeDeadStores,
435 BitVector &RegKills,
436 std::vector<MachineOperand*> &KillOps,
437 VirtRegMap &VRM) {
438 SmallSet<unsigned, 8> Rejected;
Evan Cheng5d885022009-07-21 09:15:00 +0000439 MachineFunction &MF = *MI->getParent()->getParent();
440 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
441 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
442 Rejected, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +0000443 }
444};
445
Dan Gohman7db949d2009-08-07 01:32:21 +0000446}
Lang Hames87e3bca2009-05-06 02:36:21 +0000447
448// ****************** //
449// Utility Functions //
450// ****************** //
451
Lang Hames87e3bca2009-05-06 02:36:21 +0000452/// findSinglePredSuccessor - Return via reference a vector of machine basic
453/// blocks each of which is a successor of the specified BB and has no other
454/// predecessor.
455static void findSinglePredSuccessor(MachineBasicBlock *MBB,
Jim Grosbach57cb4f82010-07-27 17:38:47 +0000456 SmallVectorImpl<MachineBasicBlock *> &Succs){
Lang Hames87e3bca2009-05-06 02:36:21 +0000457 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
458 SE = MBB->succ_end(); SI != SE; ++SI) {
459 MachineBasicBlock *SuccMBB = *SI;
460 if (SuccMBB->pred_size() == 1)
461 Succs.push_back(SuccMBB);
462 }
463}
464
Evan Cheng427a6b62009-05-15 06:48:19 +0000465/// InvalidateKill - Invalidate register kill information for a specific
466/// register. This also unsets the kills marker on the last kill operand.
467static void InvalidateKill(unsigned Reg,
468 const TargetRegisterInfo* TRI,
469 BitVector &RegKills,
470 std::vector<MachineOperand*> &KillOps) {
471 if (RegKills[Reg]) {
472 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000473 // KillOps[Reg] might be a def of a super-register.
474 unsigned KReg = KillOps[Reg]->getReg();
475 KillOps[KReg] = NULL;
476 RegKills.reset(KReg);
477 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
Evan Cheng427a6b62009-05-15 06:48:19 +0000478 if (RegKills[*SR]) {
479 KillOps[*SR]->setIsKill(false);
480 KillOps[*SR] = NULL;
481 RegKills.reset(*SR);
482 }
483 }
484 }
485}
486
Lang Hames87e3bca2009-05-06 02:36:21 +0000487/// InvalidateKills - MI is going to be deleted. If any of its operands are
488/// marked kill, then invalidate the information.
Evan Cheng427a6b62009-05-15 06:48:19 +0000489static void InvalidateKills(MachineInstr &MI,
490 const TargetRegisterInfo* TRI,
491 BitVector &RegKills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000492 std::vector<MachineOperand*> &KillOps,
493 SmallVector<unsigned, 2> *KillRegs = NULL) {
494 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
495 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000496 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000497 continue;
498 unsigned Reg = MO.getReg();
499 if (TargetRegisterInfo::isVirtualRegister(Reg))
500 continue;
501 if (KillRegs)
502 KillRegs->push_back(Reg);
503 assert(Reg < KillOps.size());
504 if (KillOps[Reg] == &MO) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000505 KillOps[Reg] = NULL;
Evan Cheng427a6b62009-05-15 06:48:19 +0000506 RegKills.reset(Reg);
507 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
508 if (RegKills[*SR]) {
509 KillOps[*SR] = NULL;
510 RegKills.reset(*SR);
511 }
512 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000513 }
514 }
515}
516
517/// InvalidateRegDef - If the def operand of the specified def MI is now dead
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000518/// (since its spill instruction is removed), mark it isDead. Also checks if
Lang Hames87e3bca2009-05-06 02:36:21 +0000519/// the def MI has other definition operands that are not dead. Returns it by
520/// reference.
521static bool InvalidateRegDef(MachineBasicBlock::iterator I,
522 MachineInstr &NewDef, unsigned Reg,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000523 bool &HasLiveDef,
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000524 const TargetRegisterInfo *TRI) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000525 // Due to remat, it's possible this reg isn't being reused. That is,
526 // the def of this reg (by prev MI) is now dead.
527 MachineInstr *DefMI = I;
528 MachineOperand *DefOp = NULL;
529 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
530 MachineOperand &MO = DefMI->getOperand(i);
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000531 if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
Evan Cheng4784f1f2009-06-30 08:49:04 +0000532 continue;
533 if (MO.getReg() == Reg)
534 DefOp = &MO;
535 else if (!MO.isDead())
536 HasLiveDef = true;
Lang Hames87e3bca2009-05-06 02:36:21 +0000537 }
538 if (!DefOp)
539 return false;
540
541 bool FoundUse = false, Done = false;
542 MachineBasicBlock::iterator E = &NewDef;
543 ++I; ++E;
544 for (; !Done && I != E; ++I) {
545 MachineInstr *NMI = I;
546 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
547 MachineOperand &MO = NMI->getOperand(j);
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000548 if (!MO.isReg() || MO.getReg() == 0 ||
549 (MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
Lang Hames87e3bca2009-05-06 02:36:21 +0000550 continue;
551 if (MO.isUse())
552 FoundUse = true;
553 Done = true; // Stop after scanning all the operands of this MI.
554 }
555 }
556 if (!FoundUse) {
557 // Def is dead!
558 DefOp->setIsDead();
559 return true;
560 }
561 return false;
562}
563
564/// UpdateKills - Track and update kill info. If a MI reads a register that is
565/// marked kill, then it must be due to register reuse. Transfer the kill info
566/// over.
Evan Cheng427a6b62009-05-15 06:48:19 +0000567static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
568 BitVector &RegKills,
569 std::vector<MachineOperand*> &KillOps) {
Dale Johannesen4d12d3b2010-03-26 19:21:26 +0000570 // These do not affect kill info at all.
571 if (MI.isDebugValue())
572 return;
Lang Hames87e3bca2009-05-06 02:36:21 +0000573 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
574 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000575 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000576 continue;
577 unsigned Reg = MO.getReg();
578 if (Reg == 0)
579 continue;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000580
Lang Hames87e3bca2009-05-06 02:36:21 +0000581 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
582 // That can't be right. Register is killed but not re-defined and it's
583 // being reused. Let's fix that.
584 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000585 // KillOps[Reg] might be a def of a super-register.
586 unsigned KReg = KillOps[Reg]->getReg();
587 KillOps[KReg] = NULL;
588 RegKills.reset(KReg);
589
590 // Must be a def of a super-register. Its other sub-regsters are no
591 // longer killed as well.
592 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
593 KillOps[*SR] = NULL;
594 RegKills.reset(*SR);
595 }
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000596 } else {
597 // Check for subreg kills as well.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000598 // d4 =
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000599 // store d4, fi#0
600 // ...
601 // = s8<kill>
602 // ...
603 // = d4 <avoiding reload>
604 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
605 unsigned SReg = *SR;
606 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
607 KillOps[SReg]->setIsKill(false);
608 unsigned KReg = KillOps[SReg]->getReg();
609 KillOps[KReg] = NULL;
610 RegKills.reset(KReg);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000611
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000612 for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
613 KillOps[*SSR] = NULL;
614 RegKills.reset(*SSR);
615 }
616 }
617 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000618 }
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000619
Lang Hames87e3bca2009-05-06 02:36:21 +0000620 if (MO.isKill()) {
621 RegKills.set(Reg);
622 KillOps[Reg] = &MO;
Evan Cheng427a6b62009-05-15 06:48:19 +0000623 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
624 RegKills.set(*SR);
625 KillOps[*SR] = &MO;
626 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000627 }
628 }
629
630 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
631 const MachineOperand &MO = MI.getOperand(i);
Evan Chengd57cdd52009-11-14 02:55:43 +0000632 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000633 continue;
634 unsigned Reg = MO.getReg();
635 RegKills.reset(Reg);
636 KillOps[Reg] = NULL;
637 // It also defines (or partially define) aliases.
Evan Cheng427a6b62009-05-15 06:48:19 +0000638 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
639 RegKills.reset(*SR);
640 KillOps[*SR] = NULL;
Lang Hames87e3bca2009-05-06 02:36:21 +0000641 }
Evan Cheng1f6a3c82009-11-13 23:16:41 +0000642 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
643 RegKills.reset(*SR);
644 KillOps[*SR] = NULL;
645 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000646 }
647}
648
649/// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
650///
651static void ReMaterialize(MachineBasicBlock &MBB,
652 MachineBasicBlock::iterator &MII,
653 unsigned DestReg, unsigned Reg,
654 const TargetInstrInfo *TII,
655 const TargetRegisterInfo *TRI,
656 VirtRegMap &VRM) {
Evan Cheng5f159922009-07-16 20:15:00 +0000657 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
Daniel Dunbar24cd3c42009-07-16 22:08:25 +0000658#ifndef NDEBUG
Evan Cheng5f159922009-07-16 20:15:00 +0000659 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
Evan Chengc1b46f92009-07-17 00:32:06 +0000660 assert(TID.getNumDefs() == 1 &&
Evan Cheng5f159922009-07-16 20:15:00 +0000661 "Don't know how to remat instructions that define > 1 values!");
662#endif
Jakob Stoklund Olesen9edf7de2010-06-02 22:47:25 +0000663 TII->reMaterialize(MBB, MII, DestReg, 0, ReMatDefMI, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000664 MachineInstr *NewMI = prior(MII);
665 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
666 MachineOperand &MO = NewMI->getOperand(i);
667 if (!MO.isReg() || MO.getReg() == 0)
668 continue;
669 unsigned VirtReg = MO.getReg();
670 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
671 continue;
672 assert(MO.isUse());
Lang Hames87e3bca2009-05-06 02:36:21 +0000673 unsigned Phys = VRM.getPhys(VirtReg);
Evan Cheng427c3ba2009-10-25 07:51:47 +0000674 assert(Phys && "Virtual register is not assigned a register?");
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +0000675 substitutePhysReg(MO, Phys, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000676 }
677 ++NumReMats;
678}
679
680/// findSuperReg - Find the SubReg's super-register of given register class
681/// where its SubIdx sub-register is SubReg.
682static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
683 unsigned SubIdx, const TargetRegisterInfo *TRI) {
684 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
685 I != E; ++I) {
686 unsigned Reg = *I;
687 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
688 return Reg;
689 }
690 return 0;
691}
692
693// ******************************** //
694// Available Spills Implementation //
695// ******************************** //
696
697/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
698/// stackslot register. The register is still available but is no longer
699/// allowed to be modifed.
700void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
701 std::multimap<unsigned, int>::iterator I =
702 PhysRegsAvailable.lower_bound(PhysReg);
703 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
704 int SlotOrReMat = I->second;
705 I++;
706 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
707 "Bidirectional map mismatch!");
708 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
David Greene0ee52182010-01-05 01:25:52 +0000709 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +0000710 << " copied, it is available for use but can no longer be modified\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000711 }
712}
713
714/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
715/// stackslot register and its aliases. The register and its aliases may
716/// still available but is no longer allowed to be modifed.
717void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
718 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
719 disallowClobberPhysRegOnly(*AS);
720 disallowClobberPhysRegOnly(PhysReg);
721}
722
723/// ClobberPhysRegOnly - This is called when the specified physreg changes
724/// value. We use this to invalidate any info about stuff we thing lives in it.
725void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
726 std::multimap<unsigned, int>::iterator I =
727 PhysRegsAvailable.lower_bound(PhysReg);
728 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
729 int SlotOrReMat = I->second;
730 PhysRegsAvailable.erase(I++);
731 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
732 "Bidirectional map mismatch!");
733 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
David Greene0ee52182010-01-05 01:25:52 +0000734 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +0000735 << " clobbered, invalidating ");
Lang Hames87e3bca2009-05-06 02:36:21 +0000736 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +0000737 DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000738 else
David Greene0ee52182010-01-05 01:25:52 +0000739 DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000740 }
741}
742
743/// ClobberPhysReg - This is called when the specified physreg changes
744/// value. We use this to invalidate any info about stuff we thing lives in
745/// it and any of its aliases.
746void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
747 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
748 ClobberPhysRegOnly(*AS);
749 ClobberPhysRegOnly(PhysReg);
750}
751
752/// AddAvailableRegsToLiveIn - Availability information is being kept coming
753/// into the specified MBB. Add available physical registers as potential
754/// live-in's. If they are reused in the MBB, they will be added to the
755/// live-in set to make register scavenger and post-allocation scheduler.
756void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
757 BitVector &RegKills,
758 std::vector<MachineOperand*> &KillOps) {
759 std::set<unsigned> NotAvailable;
760 for (std::multimap<unsigned, int>::iterator
761 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
762 I != E; ++I) {
763 unsigned Reg = I->first;
Rafael Espindoladb776092010-07-11 16:45:17 +0000764 const TargetRegisterClass* RC = TRI->getMinimalPhysRegClass(Reg);
Lang Hames87e3bca2009-05-06 02:36:21 +0000765 // FIXME: A temporary workaround. We can't reuse available value if it's
766 // not safe to move the def of the virtual register's class. e.g.
767 // X86::RFP* register classes. Do not add it as a live-in.
768 if (!TII->isSafeToMoveRegClassDefs(RC))
769 // This is no longer available.
770 NotAvailable.insert(Reg);
771 else {
772 MBB.addLiveIn(Reg);
Evan Cheng427a6b62009-05-15 06:48:19 +0000773 InvalidateKill(Reg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +0000774 }
775
776 // Skip over the same register.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000777 std::multimap<unsigned, int>::iterator NI = llvm::next(I);
Lang Hames87e3bca2009-05-06 02:36:21 +0000778 while (NI != E && NI->first == Reg) {
779 ++I;
780 ++NI;
781 }
782 }
783
784 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
785 E = NotAvailable.end(); I != E; ++I) {
786 ClobberPhysReg(*I);
787 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
788 *SubRegs; ++SubRegs)
789 ClobberPhysReg(*SubRegs);
790 }
791}
792
793/// ModifyStackSlotOrReMat - This method is called when the value in a stack
794/// slot changes. This removes information about which register the previous
795/// value for this slot lives in (as the previous value is dead now).
796void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
797 std::map<int, unsigned>::iterator It =
798 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
799 if (It == SpillSlotsOrReMatsAvailable.end()) return;
800 unsigned Reg = It->second >> 1;
801 SpillSlotsOrReMatsAvailable.erase(It);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000802
Lang Hames87e3bca2009-05-06 02:36:21 +0000803 // This register may hold the value of multiple stack slots, only remove this
804 // stack slot from the set of values the register contains.
805 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
806 for (; ; ++I) {
807 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
808 "Map inverse broken!");
809 if (I->second == SlotOrReMat) break;
810 }
811 PhysRegsAvailable.erase(I);
812}
813
814// ************************** //
815// Reuse Info Implementation //
816// ************************** //
817
818/// GetRegForReload - We are about to emit a reload into PhysReg. If there
819/// is some other operand that is using the specified register, either pick
820/// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000821unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
822 unsigned PhysReg,
823 MachineFunction &MF,
824 MachineInstr *MI, AvailableSpills &Spills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000825 std::vector<MachineInstr*> &MaybeDeadStores,
826 SmallSet<unsigned, 8> &Rejected,
827 BitVector &RegKills,
828 std::vector<MachineOperand*> &KillOps,
829 VirtRegMap &VRM) {
Evan Cheng5d885022009-07-21 09:15:00 +0000830 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
831 const TargetRegisterInfo *TRI = Spills.getRegInfo();
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000832
Lang Hames87e3bca2009-05-06 02:36:21 +0000833 if (Reuses.empty()) return PhysReg; // This is most often empty.
834
835 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
836 ReusedOp &Op = Reuses[ro];
837 // If we find some other reuse that was supposed to use this register
838 // exactly for its reload, we can change this reload to use ITS reload
839 // register. That is, unless its reload register has already been
840 // considered and subsequently rejected because it has also been reused
841 // by another operand.
842 if (Op.PhysRegReused == PhysReg &&
Evan Cheng5d885022009-07-21 09:15:00 +0000843 Rejected.count(Op.AssignedPhysReg) == 0 &&
844 RC->contains(Op.AssignedPhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000845 // Yup, use the reload register that we didn't use before.
846 unsigned NewReg = Op.AssignedPhysReg;
847 Rejected.insert(PhysReg);
Jim Grosbach57cb4f82010-07-27 17:38:47 +0000848 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores,
849 Rejected, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +0000850 } else {
851 // Otherwise, we might also have a problem if a previously reused
Evan Cheng5d885022009-07-21 09:15:00 +0000852 // value aliases the new register. If so, codegen the previous reload
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000853 // and use this one.
Lang Hames87e3bca2009-05-06 02:36:21 +0000854 unsigned PRRU = Op.PhysRegReused;
Lang Hames3f2f3f52009-09-03 02:52:02 +0000855 if (TRI->regsOverlap(PRRU, PhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000856 // Okay, we found out that an alias of a reused register
857 // was used. This isn't good because it means we have
858 // to undo a previous reuse.
859 MachineBasicBlock *MBB = MI->getParent();
860 const TargetRegisterClass *AliasRC =
861 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
862
863 // Copy Op out of the vector and remove it, we're going to insert an
864 // explicit load for it.
865 ReusedOp NewOp = Op;
866 Reuses.erase(Reuses.begin()+ro);
867
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000868 // MI may be using only a sub-register of PhysRegUsed.
869 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
870 unsigned SubIdx = 0;
871 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
872 "A reuse cannot be a virtual register");
873 if (PRRU != RealPhysRegUsed) {
874 // What was the sub-register index?
Evan Chengfae3e922009-11-14 03:42:17 +0000875 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
876 assert(SubIdx &&
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000877 "Operand physreg is not a sub-register of PhysRegUsed");
878 }
879
Lang Hames87e3bca2009-05-06 02:36:21 +0000880 // Ok, we're going to try to reload the assigned physreg into the
881 // slot that we were supposed to in the first place. However, that
882 // register could hold a reuse. Check to see if it conflicts or
883 // would prefer us to use a different register.
Evan Cheng5d885022009-07-21 09:15:00 +0000884 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
885 MF, MI, Spills, MaybeDeadStores,
886 Rejected, RegKills, KillOps, VRM);
David Greene2d4e6d32009-07-28 16:49:24 +0000887
888 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
889 int SSorRMId = DoReMat
John McCall795ee9d2010-04-06 23:35:53 +0000890 ? VRM.getReMatId(NewOp.VirtReg) : (int) NewOp.StackSlotOrReMat;
David Greene2d4e6d32009-07-28 16:49:24 +0000891
892 // Back-schedule reloads and remats.
893 MachineBasicBlock::iterator InsertLoc =
894 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
895 DoReMat, SSorRMId, TII, MF);
896
897 if (DoReMat) {
898 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
899 TRI, VRM);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000900 } else {
David Greene2d4e6d32009-07-28 16:49:24 +0000901 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
Evan Cheng746ad692010-05-06 19:06:44 +0000902 NewOp.StackSlotOrReMat, AliasRC, TRI);
David Greene2d4e6d32009-07-28 16:49:24 +0000903 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +0000904 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
905 // Any stores to this stack slot are not dead anymore.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000906 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
Lang Hames87e3bca2009-05-06 02:36:21 +0000907 ++NumLoads;
908 }
909 Spills.ClobberPhysReg(NewPhysReg);
910 Spills.ClobberPhysReg(NewOp.PhysRegReused);
911
Evan Cheng427c3ba2009-10-25 07:51:47 +0000912 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
Lang Hames87e3bca2009-05-06 02:36:21 +0000913 MI->getOperand(NewOp.Operand).setReg(RReg);
914 MI->getOperand(NewOp.Operand).setSubReg(0);
915
916 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
David Greene2d4e6d32009-07-28 16:49:24 +0000917 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
David Greene0ee52182010-01-05 01:25:52 +0000918 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000919
David Greene0ee52182010-01-05 01:25:52 +0000920 DEBUG(dbgs() << "Reuse undone!\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000921 --NumReused;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000922
Lang Hames87e3bca2009-05-06 02:36:21 +0000923 // Finally, PhysReg is now available, go ahead and use it.
924 return PhysReg;
925 }
926 }
927 }
928 return PhysReg;
929}
930
931// ************************************************************************ //
932
933/// FoldsStackSlotModRef - Return true if the specified MI folds the specified
934/// stack slot mod/ref. It also checks if it's possible to unfold the
935/// instruction by having it define a specified physical register instead.
936static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
937 const TargetInstrInfo *TII,
938 const TargetRegisterInfo *TRI,
939 VirtRegMap &VRM) {
940 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
941 return false;
942
943 bool Found = false;
944 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
945 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
946 unsigned VirtReg = I->second.first;
947 VirtRegMap::ModRef MR = I->second.second;
948 if (MR & VirtRegMap::isModRef)
949 if (VRM.getStackSlot(VirtReg) == SS) {
950 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
951 break;
952 }
953 }
954 if (!Found)
955 return false;
956
957 // Does the instruction uses a register that overlaps the scratch register?
958 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
959 MachineOperand &MO = MI.getOperand(i);
960 if (!MO.isReg() || MO.getReg() == 0)
961 continue;
962 unsigned Reg = MO.getReg();
963 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
964 if (!VRM.hasPhys(Reg))
965 continue;
966 Reg = VRM.getPhys(Reg);
967 }
968 if (TRI->regsOverlap(PhysReg, Reg))
969 return false;
970 }
971 return true;
972}
973
974/// FindFreeRegister - Find a free register of a given register class by looking
975/// at (at most) the last two machine instructions.
976static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
977 MachineBasicBlock &MBB,
978 const TargetRegisterClass *RC,
979 const TargetRegisterInfo *TRI,
980 BitVector &AllocatableRegs) {
981 BitVector Defs(TRI->getNumRegs());
982 BitVector Uses(TRI->getNumRegs());
983 SmallVector<unsigned, 4> LocalUses;
984 SmallVector<unsigned, 4> Kills;
985
986 // Take a look at 2 instructions at most.
Evan Cheng28a1e482010-03-30 05:49:07 +0000987 unsigned Count = 0;
988 while (Count < 2) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000989 if (MII == MBB.begin())
990 break;
991 MachineInstr *PrevMI = prior(MII);
Evan Cheng28a1e482010-03-30 05:49:07 +0000992 MII = PrevMI;
993
994 if (PrevMI->isDebugValue())
995 continue; // Skip over dbg_value instructions.
996 ++Count;
997
Lang Hames87e3bca2009-05-06 02:36:21 +0000998 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
999 MachineOperand &MO = PrevMI->getOperand(i);
1000 if (!MO.isReg() || MO.getReg() == 0)
1001 continue;
1002 unsigned Reg = MO.getReg();
1003 if (MO.isDef()) {
1004 Defs.set(Reg);
1005 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1006 Defs.set(*AS);
1007 } else {
1008 LocalUses.push_back(Reg);
1009 if (MO.isKill() && AllocatableRegs[Reg])
1010 Kills.push_back(Reg);
1011 }
1012 }
1013
1014 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1015 unsigned Kill = Kills[i];
1016 if (!Defs[Kill] && !Uses[Kill] &&
Rafael Espindoladb776092010-07-11 16:45:17 +00001017 RC->contains(Kill))
Lang Hames87e3bca2009-05-06 02:36:21 +00001018 return Kill;
1019 }
1020 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1021 unsigned Reg = LocalUses[i];
1022 Uses.set(Reg);
1023 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1024 Uses.set(*AS);
1025 }
Lang Hames87e3bca2009-05-06 02:36:21 +00001026 }
1027
1028 return 0;
1029}
1030
1031static
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001032void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1033 const TargetRegisterInfo &TRI) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001034 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1035 MachineOperand &MO = MI->getOperand(i);
1036 if (MO.isReg() && MO.getReg() == VirtReg)
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001037 substitutePhysReg(MO, PhysReg, TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001038 }
1039}
1040
Evan Chengeca24fb2009-05-12 23:07:00 +00001041namespace {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001042
1043struct RefSorter {
1044 bool operator()(const std::pair<MachineInstr*, int> &A,
1045 const std::pair<MachineInstr*, int> &B) {
1046 return A.second < B.second;
1047 }
1048};
Lang Hames87e3bca2009-05-06 02:36:21 +00001049
1050// ***************************** //
1051// Local Spiller Implementation //
1052// ***************************** //
1053
Nick Lewycky6726b6d2009-10-25 06:33:48 +00001054class LocalRewriter : public VirtRegRewriter {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001055 MachineRegisterInfo *MRI;
Lang Hames87e3bca2009-05-06 02:36:21 +00001056 const TargetRegisterInfo *TRI;
1057 const TargetInstrInfo *TII;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001058 VirtRegMap *VRM;
Lang Hames87e3bca2009-05-06 02:36:21 +00001059 BitVector AllocatableRegs;
1060 DenseMap<MachineInstr*, unsigned> DistanceMap;
Evan Chengbd6cb4b2010-04-29 18:51:00 +00001061 DenseMap<int, SmallVector<MachineInstr*,4> > Slot2DbgValues;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001062
1063 MachineBasicBlock *MBB; // Basic block currently being processed.
1064
Lang Hames87e3bca2009-05-06 02:36:21 +00001065public:
1066
1067 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001068 LiveIntervals* LIs);
Lang Hames87e3bca2009-05-06 02:36:21 +00001069
1070private:
1071
Lang Hames87e3bca2009-05-06 02:36:21 +00001072 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
Lang Hames87e3bca2009-05-06 02:36:21 +00001073 MachineBasicBlock::iterator &MII,
1074 std::vector<MachineInstr*> &MaybeDeadStores,
1075 AvailableSpills &Spills,
1076 BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001077 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001078
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001079 bool OptimizeByUnfold(MachineBasicBlock::iterator &MII,
Lang Hames87e3bca2009-05-06 02:36:21 +00001080 std::vector<MachineInstr*> &MaybeDeadStores,
1081 AvailableSpills &Spills,
1082 BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001083 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001084
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001085 bool CommuteToFoldReload(MachineBasicBlock::iterator &MII,
Lang Hames87e3bca2009-05-06 02:36:21 +00001086 unsigned VirtReg, unsigned SrcReg, int SS,
1087 AvailableSpills &Spills,
1088 BitVector &RegKills,
1089 std::vector<MachineOperand*> &KillOps,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001090 const TargetRegisterInfo *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001091
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001092 void SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
Lang Hames87e3bca2009-05-06 02:36:21 +00001093 int Idx, unsigned PhysReg, int StackSlot,
1094 const TargetRegisterClass *RC,
1095 bool isAvailable, MachineInstr *&LastStore,
1096 AvailableSpills &Spills,
1097 SmallSet<MachineInstr*, 4> &ReMatDefs,
1098 BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001099 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001100
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001101 void TransferDeadness(unsigned Reg, BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001102 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001103
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001104 bool InsertEmergencySpills(MachineInstr *MI);
1105
1106 bool InsertRestores(MachineInstr *MI,
1107 AvailableSpills &Spills,
1108 BitVector &RegKills,
1109 std::vector<MachineOperand*> &KillOps);
1110
1111 bool InsertSpills(MachineInstr *MI);
1112
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00001113 void ProcessUses(MachineInstr &MI, AvailableSpills &Spills,
1114 std::vector<MachineInstr*> &MaybeDeadStores,
1115 BitVector &RegKills,
1116 ReuseInfo &ReusedOperands,
1117 std::vector<MachineOperand*> &KillOps);
1118
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001119 void RewriteMBB(LiveIntervals *LIs,
1120 AvailableSpills &Spills, BitVector &RegKills,
1121 std::vector<MachineOperand*> &KillOps);
1122};
1123}
1124
1125bool LocalRewriter::runOnMachineFunction(MachineFunction &MF, VirtRegMap &vrm,
1126 LiveIntervals* LIs) {
1127 MRI = &MF.getRegInfo();
1128 TRI = MF.getTarget().getRegisterInfo();
1129 TII = MF.getTarget().getInstrInfo();
1130 VRM = &vrm;
1131 AllocatableRegs = TRI->getAllocatableSet(MF);
1132 DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
1133 << MF.getFunction()->getName() << "':\n");
1134 DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
1135 " reloads!) ****\n");
1136 DEBUG(MF.dump());
1137
1138 // Spills - Keep track of which spilled values are available in physregs
1139 // so that we can choose to reuse the physregs instead of emitting
1140 // reloads. This is usually refreshed per basic block.
1141 AvailableSpills Spills(TRI, TII);
1142
1143 // Keep track of kill information.
1144 BitVector RegKills(TRI->getNumRegs());
1145 std::vector<MachineOperand*> KillOps;
1146 KillOps.resize(TRI->getNumRegs(), NULL);
1147
1148 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1149 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1150 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1151
1152 // Traverse the basic blocks depth first.
1153 MachineBasicBlock *Entry = MF.begin();
1154 SmallPtrSet<MachineBasicBlock*,16> Visited;
1155 for (df_ext_iterator<MachineBasicBlock*,
1156 SmallPtrSet<MachineBasicBlock*,16> >
1157 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1158 DFI != E; ++DFI) {
1159 MBB = *DFI;
1160 if (!EarlyVisited.count(MBB))
1161 RewriteMBB(LIs, Spills, RegKills, KillOps);
1162
1163 // If this MBB is the only predecessor of a successor. Keep the
1164 // availability information and visit it next.
1165 do {
1166 // Keep visiting single predecessor successor as long as possible.
1167 SinglePredSuccs.clear();
1168 findSinglePredSuccessor(MBB, SinglePredSuccs);
1169 if (SinglePredSuccs.empty())
1170 MBB = 0;
1171 else {
1172 // FIXME: More than one successors, each of which has MBB has
1173 // the only predecessor.
1174 MBB = SinglePredSuccs[0];
1175 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1176 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1177 RewriteMBB(LIs, Spills, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001178 }
1179 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001180 } while (MBB);
Lang Hames87e3bca2009-05-06 02:36:21 +00001181
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001182 // Clear the availability info.
1183 Spills.clear();
Lang Hames87e3bca2009-05-06 02:36:21 +00001184 }
1185
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001186 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
1187 DEBUG(MF.dump());
1188
1189 // Mark unused spill slots.
1190 MachineFrameInfo *MFI = MF.getFrameInfo();
1191 int SS = VRM->getLowSpillSlot();
Evan Chengbd6cb4b2010-04-29 18:51:00 +00001192 if (SS != VirtRegMap::NO_STACK_SLOT) {
1193 for (int e = VRM->getHighSpillSlot(); SS <= e; ++SS) {
1194 SmallVector<MachineInstr*, 4> &DbgValues = Slot2DbgValues[SS];
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001195 if (!VRM->isSpillSlotUsed(SS)) {
1196 MFI->RemoveStackObject(SS);
Evan Chengbd6cb4b2010-04-29 18:51:00 +00001197 for (unsigned j = 0, ee = DbgValues.size(); j != ee; ++j) {
1198 MachineInstr *DVMI = DbgValues[j];
1199 MachineBasicBlock *DVMBB = DVMI->getParent();
1200 DEBUG(dbgs() << "Removing debug info referencing FI#" << SS << '\n');
1201 VRM->RemoveMachineInstrFromMaps(DVMI);
1202 DVMBB->erase(DVMI);
1203 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001204 ++NumDSS;
1205 }
Evan Chengbd6cb4b2010-04-29 18:51:00 +00001206 DbgValues.clear();
1207 }
1208 }
1209 Slot2DbgValues.clear();
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001210
1211 return true;
1212}
1213
1214/// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1215/// a scratch register is available.
1216/// xorq %r12<kill>, %r13
1217/// addq %rax, -184(%rbp)
1218/// addq %r13, -184(%rbp)
1219/// ==>
1220/// xorq %r12<kill>, %r13
1221/// movq -184(%rbp), %r12
1222/// addq %rax, %r12
1223/// addq %r13, %r12
1224/// movq %r12, -184(%rbp)
1225bool LocalRewriter::
1226OptimizeByUnfold2(unsigned VirtReg, int SS,
1227 MachineBasicBlock::iterator &MII,
1228 std::vector<MachineInstr*> &MaybeDeadStores,
1229 AvailableSpills &Spills,
1230 BitVector &RegKills,
1231 std::vector<MachineOperand*> &KillOps) {
1232
1233 MachineBasicBlock::iterator NextMII = llvm::next(MII);
Evan Cheng28a1e482010-03-30 05:49:07 +00001234 // Skip over dbg_value instructions.
1235 while (NextMII != MBB->end() && NextMII->isDebugValue())
1236 NextMII = llvm::next(NextMII);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001237 if (NextMII == MBB->end())
1238 return false;
1239
1240 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1241 return false;
1242
1243 // Now let's see if the last couple of instructions happens to have freed up
1244 // a register.
1245 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1246 unsigned PhysReg = FindFreeRegister(MII, *MBB, RC, TRI, AllocatableRegs);
1247 if (!PhysReg)
1248 return false;
1249
1250 MachineFunction &MF = *MBB->getParent();
1251 TRI = MF.getTarget().getRegisterInfo();
1252 MachineInstr &MI = *MII;
1253 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, *VRM))
1254 return false;
1255
1256 // If the next instruction also folds the same SS modref and can be unfoled,
1257 // then it's worthwhile to issue a load from SS into the free register and
1258 // then unfold these instructions.
1259 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM))
1260 return false;
1261
1262 // Back-schedule reloads and remats.
1263 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, false, SS, TII, MF);
1264
1265 // Load from SS to the spare physical register.
Evan Cheng746ad692010-05-06 19:06:44 +00001266 TII->loadRegFromStackSlot(*MBB, MII, PhysReg, SS, RC, TRI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001267 // This invalidates Phys.
1268 Spills.ClobberPhysReg(PhysReg);
1269 // Remember it's available.
1270 Spills.addAvailable(SS, PhysReg);
1271 MaybeDeadStores[SS] = NULL;
1272
1273 // Unfold current MI.
1274 SmallVector<MachineInstr*, 4> NewMIs;
1275 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1276 llvm_unreachable("Unable unfold the load / store folding instruction!");
1277 assert(NewMIs.size() == 1);
1278 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1279 VRM->transferRestorePts(&MI, NewMIs[0]);
1280 MII = MBB->insert(MII, NewMIs[0]);
1281 InvalidateKills(MI, TRI, RegKills, KillOps);
1282 VRM->RemoveMachineInstrFromMaps(&MI);
1283 MBB->erase(&MI);
1284 ++NumModRefUnfold;
1285
1286 // Unfold next instructions that fold the same SS.
1287 do {
1288 MachineInstr &NextMI = *NextMII;
1289 NextMII = llvm::next(NextMII);
1290 NewMIs.clear();
1291 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1292 llvm_unreachable("Unable unfold the load / store folding instruction!");
1293 assert(NewMIs.size() == 1);
1294 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1295 VRM->transferRestorePts(&NextMI, NewMIs[0]);
1296 MBB->insert(NextMII, NewMIs[0]);
1297 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1298 VRM->RemoveMachineInstrFromMaps(&NextMI);
1299 MBB->erase(&NextMI);
1300 ++NumModRefUnfold;
Evan Cheng28a1e482010-03-30 05:49:07 +00001301 // Skip over dbg_value instructions.
1302 while (NextMII != MBB->end() && NextMII->isDebugValue())
1303 NextMII = llvm::next(NextMII);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001304 if (NextMII == MBB->end())
1305 break;
1306 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM));
1307
1308 // Store the value back into SS.
Evan Cheng746ad692010-05-06 19:06:44 +00001309 TII->storeRegToStackSlot(*MBB, NextMII, PhysReg, true, SS, RC, TRI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001310 MachineInstr *StoreMI = prior(NextMII);
1311 VRM->addSpillSlotUse(SS, StoreMI);
1312 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1313
1314 return true;
1315}
1316
1317/// OptimizeByUnfold - Turn a store folding instruction into a load folding
1318/// instruction. e.g.
1319/// xorl %edi, %eax
1320/// movl %eax, -32(%ebp)
1321/// movl -36(%ebp), %eax
1322/// orl %eax, -32(%ebp)
1323/// ==>
1324/// xorl %edi, %eax
1325/// orl -36(%ebp), %eax
1326/// mov %eax, -32(%ebp)
1327/// This enables unfolding optimization for a subsequent instruction which will
1328/// also eliminate the newly introduced store instruction.
1329bool LocalRewriter::
1330OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1331 std::vector<MachineInstr*> &MaybeDeadStores,
1332 AvailableSpills &Spills,
1333 BitVector &RegKills,
1334 std::vector<MachineOperand*> &KillOps) {
1335 MachineFunction &MF = *MBB->getParent();
1336 MachineInstr &MI = *MII;
1337 unsigned UnfoldedOpc = 0;
1338 unsigned UnfoldPR = 0;
1339 unsigned UnfoldVR = 0;
1340 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1341 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1342 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
1343 // Only transform a MI that folds a single register.
1344 if (UnfoldedOpc)
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001345 return false;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001346 UnfoldVR = I->second.first;
1347 VirtRegMap::ModRef MR = I->second.second;
1348 // MI2VirtMap be can updated which invalidate the iterator.
1349 // Increment the iterator first.
1350 ++I;
1351 if (VRM->isAssignedReg(UnfoldVR))
1352 continue;
1353 // If this reference is not a use, any previous store is now dead.
1354 // Otherwise, the store to this stack slot is not dead anymore.
1355 FoldedSS = VRM->getStackSlot(UnfoldVR);
1356 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1357 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1358 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1359 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001360 continue;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001361 UnfoldPR = PhysReg;
1362 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1363 false, true);
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001364 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001365 }
1366
1367 if (!UnfoldedOpc) {
1368 if (!UnfoldVR)
1369 return false;
1370
1371 // Look for other unfolding opportunities.
1372 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MII, MaybeDeadStores, Spills,
1373 RegKills, KillOps);
1374 }
1375
1376 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1377 MachineOperand &MO = MI.getOperand(i);
1378 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1379 continue;
1380 unsigned VirtReg = MO.getReg();
1381 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1382 continue;
1383 if (VRM->isAssignedReg(VirtReg)) {
1384 unsigned PhysReg = VRM->getPhys(VirtReg);
1385 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1386 return false;
1387 } else if (VRM->isReMaterialized(VirtReg))
1388 continue;
1389 int SS = VRM->getStackSlot(VirtReg);
1390 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1391 if (PhysReg) {
1392 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1393 return false;
1394 continue;
1395 }
1396 if (VRM->hasPhys(VirtReg)) {
1397 PhysReg = VRM->getPhys(VirtReg);
1398 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1399 continue;
1400 }
1401
1402 // Ok, we'll need to reload the value into a register which makes
1403 // it impossible to perform the store unfolding optimization later.
1404 // Let's see if it is possible to fold the load if the store is
1405 // unfolded. This allows us to perform the store unfolding
1406 // optimization.
1407 SmallVector<MachineInstr*, 4> NewMIs;
1408 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1409 assert(NewMIs.size() == 1);
1410 MachineInstr *NewMI = NewMIs.back();
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001411 MBB->insert(MII, NewMI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001412 NewMIs.clear();
1413 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1414 assert(Idx != -1);
1415 SmallVector<unsigned, 1> Ops;
1416 Ops.push_back(Idx);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001417 MachineInstr *FoldedMI = TII->foldMemoryOperand(NewMI, Ops, SS);
1418 NewMI->eraseFromParent();
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001419 if (FoldedMI) {
1420 VRM->addSpillSlotUse(SS, FoldedMI);
1421 if (!VRM->hasPhys(UnfoldVR))
1422 VRM->assignVirt2Phys(UnfoldVR, UnfoldPR);
1423 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001424 MII = FoldedMI;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001425 InvalidateKills(MI, TRI, RegKills, KillOps);
1426 VRM->RemoveMachineInstrFromMaps(&MI);
1427 MBB->erase(&MI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001428 return true;
1429 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001430 }
1431 }
1432
1433 return false;
1434}
1435
1436/// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1437/// where SrcReg is r1 and it is tied to r0. Return true if after
1438/// commuting this instruction it will be r0 = op r2, r1.
1439static bool CommuteChangesDestination(MachineInstr *DefMI,
1440 const TargetInstrDesc &TID,
1441 unsigned SrcReg,
1442 const TargetInstrInfo *TII,
1443 unsigned &DstIdx) {
1444 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1445 return false;
1446 if (!DefMI->getOperand(1).isReg() ||
1447 DefMI->getOperand(1).getReg() != SrcReg)
1448 return false;
1449 unsigned DefIdx;
1450 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1451 return false;
1452 unsigned SrcIdx1, SrcIdx2;
1453 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1454 return false;
1455 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1456 DstIdx = 2;
1457 return true;
1458 }
1459 return false;
1460}
1461
1462/// CommuteToFoldReload -
1463/// Look for
1464/// r1 = load fi#1
1465/// r1 = op r1, r2<kill>
1466/// store r1, fi#1
1467///
1468/// If op is commutable and r2 is killed, then we can xform these to
1469/// r2 = op r2, fi#1
1470/// store r2, fi#1
1471bool LocalRewriter::
1472CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1473 unsigned VirtReg, unsigned SrcReg, int SS,
1474 AvailableSpills &Spills,
1475 BitVector &RegKills,
1476 std::vector<MachineOperand*> &KillOps,
1477 const TargetRegisterInfo *TRI) {
1478 if (MII == MBB->begin() || !MII->killsRegister(SrcReg))
1479 return false;
1480
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001481 MachineInstr &MI = *MII;
1482 MachineBasicBlock::iterator DefMII = prior(MII);
1483 MachineInstr *DefMI = DefMII;
1484 const TargetInstrDesc &TID = DefMI->getDesc();
1485 unsigned NewDstIdx;
1486 if (DefMII != MBB->begin() &&
1487 TID.isCommutable() &&
1488 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1489 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1490 unsigned NewReg = NewDstMO.getReg();
1491 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1492 return false;
1493 MachineInstr *ReloadMI = prior(DefMII);
1494 int FrameIdx;
1495 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1496 if (DestReg != SrcReg || FrameIdx != SS)
1497 return false;
1498 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1499 if (UseIdx == -1)
1500 return false;
1501 unsigned DefIdx;
1502 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1503 return false;
1504 assert(DefMI->getOperand(DefIdx).isReg() &&
1505 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1506
1507 // Now commute def instruction.
1508 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1509 if (!CommutedMI)
1510 return false;
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001511 MBB->insert(MII, CommutedMI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001512 SmallVector<unsigned, 1> Ops;
1513 Ops.push_back(NewDstIdx);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001514 MachineInstr *FoldedMI = TII->foldMemoryOperand(CommutedMI, Ops, SS);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001515 // Not needed since foldMemoryOperand returns new MI.
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001516 CommutedMI->eraseFromParent();
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001517 if (!FoldedMI)
1518 return false;
1519
1520 VRM->addSpillSlotUse(SS, FoldedMI);
1521 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1522 // Insert new def MI and spill MI.
1523 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
Evan Cheng746ad692010-05-06 19:06:44 +00001524 TII->storeRegToStackSlot(*MBB, &MI, NewReg, true, SS, RC, TRI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001525 MII = prior(MII);
1526 MachineInstr *StoreMI = MII;
1527 VRM->addSpillSlotUse(SS, StoreMI);
1528 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001529 MII = FoldedMI; // Update MII to backtrack.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001530
1531 // Delete all 3 old instructions.
1532 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1533 VRM->RemoveMachineInstrFromMaps(ReloadMI);
1534 MBB->erase(ReloadMI);
1535 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1536 VRM->RemoveMachineInstrFromMaps(DefMI);
1537 MBB->erase(DefMI);
1538 InvalidateKills(MI, TRI, RegKills, KillOps);
1539 VRM->RemoveMachineInstrFromMaps(&MI);
1540 MBB->erase(&MI);
1541
1542 // If NewReg was previously holding value of some SS, it's now clobbered.
1543 // This has to be done now because it's a physical register. When this
1544 // instruction is re-visited, it's ignored.
1545 Spills.ClobberPhysReg(NewReg);
1546
1547 ++NumCommutes;
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001548 return true;
1549 }
1550
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001551 return false;
1552}
Lang Hames87e3bca2009-05-06 02:36:21 +00001553
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001554/// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1555/// the last store to the same slot is now dead. If so, remove the last store.
1556void LocalRewriter::
1557SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1558 int Idx, unsigned PhysReg, int StackSlot,
1559 const TargetRegisterClass *RC,
1560 bool isAvailable, MachineInstr *&LastStore,
1561 AvailableSpills &Spills,
1562 SmallSet<MachineInstr*, 4> &ReMatDefs,
1563 BitVector &RegKills,
1564 std::vector<MachineOperand*> &KillOps) {
Evan Chengeca24fb2009-05-12 23:07:00 +00001565
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001566 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
Evan Cheng746ad692010-05-06 19:06:44 +00001567 TII->storeRegToStackSlot(*MBB, llvm::next(MII), PhysReg, true, StackSlot, RC,
1568 TRI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001569 MachineInstr *StoreMI = prior(oldNextMII);
1570 VRM->addSpillSlotUse(StackSlot, StoreMI);
1571 DEBUG(dbgs() << "Store:\t" << *StoreMI);
Evan Chengeca24fb2009-05-12 23:07:00 +00001572
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001573 // If there is a dead store to this stack slot, nuke it now.
1574 if (LastStore) {
1575 DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
1576 ++NumDSE;
1577 SmallVector<unsigned, 2> KillRegs;
1578 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1579 MachineBasicBlock::iterator PrevMII = LastStore;
1580 bool CheckDef = PrevMII != MBB->begin();
1581 if (CheckDef)
1582 --PrevMII;
1583 VRM->RemoveMachineInstrFromMaps(LastStore);
1584 MBB->erase(LastStore);
1585 if (CheckDef) {
1586 // Look at defs of killed registers on the store. Mark the defs
1587 // as dead since the store has been deleted and they aren't
1588 // being reused.
1589 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1590 bool HasOtherDef = false;
1591 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1592 MachineInstr *DeadDef = PrevMII;
1593 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1594 // FIXME: This assumes a remat def does not have side effects.
1595 VRM->RemoveMachineInstrFromMaps(DeadDef);
1596 MBB->erase(DeadDef);
1597 ++NumDRM;
1598 }
Evan Chengeca24fb2009-05-12 23:07:00 +00001599 }
Lang Hames87e3bca2009-05-06 02:36:21 +00001600 }
1601 }
1602 }
1603
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001604 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1605 // the last of multiple instructions is the actual store.
1606 LastStore = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001607
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001608 // If the stack slot value was previously available in some other
1609 // register, change it now. Otherwise, make the register available,
1610 // in PhysReg.
1611 Spills.ModifyStackSlotOrReMat(StackSlot);
1612 Spills.ClobberPhysReg(PhysReg);
1613 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1614 ++NumStores;
1615}
Lang Hames87e3bca2009-05-06 02:36:21 +00001616
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001617/// isSafeToDelete - Return true if this instruction doesn't produce any side
1618/// effect and all of its defs are dead.
1619static bool isSafeToDelete(MachineInstr &MI) {
1620 const TargetInstrDesc &TID = MI.getDesc();
1621 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1622 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1623 TID.hasUnmodeledSideEffects())
1624 return false;
1625 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1626 MachineOperand &MO = MI.getOperand(i);
1627 if (!MO.isReg() || !MO.getReg())
1628 continue;
1629 if (MO.isDef() && !MO.isDead())
1630 return false;
1631 if (MO.isUse() && MO.isKill())
1632 // FIXME: We can't remove kill markers or else the scavenger will assert.
1633 // An alternative is to add a ADD pseudo instruction to replace kill
1634 // markers.
1635 return false;
1636 }
1637 return true;
1638}
Lang Hames87e3bca2009-05-06 02:36:21 +00001639
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001640/// TransferDeadness - A identity copy definition is dead and it's being
1641/// removed. Find the last def or use and mark it as dead / kill.
1642void LocalRewriter::
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001643TransferDeadness(unsigned Reg, BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001644 std::vector<MachineOperand*> &KillOps) {
1645 SmallPtrSet<MachineInstr*, 4> Seens;
1646 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1647 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
1648 RE = MRI->reg_end(); RI != RE; ++RI) {
1649 MachineInstr *UDMI = &*RI;
Evan Cheng28a1e482010-03-30 05:49:07 +00001650 if (UDMI->isDebugValue() || UDMI->getParent() != MBB)
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001651 continue;
1652 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001653 if (DI == DistanceMap.end())
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001654 continue;
1655 if (Seens.insert(UDMI))
1656 Refs.push_back(std::make_pair(UDMI, DI->second));
1657 }
Lang Hames87e3bca2009-05-06 02:36:21 +00001658
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001659 if (Refs.empty())
1660 return;
1661 std::sort(Refs.begin(), Refs.end(), RefSorter());
Lang Hames87e3bca2009-05-06 02:36:21 +00001662
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001663 while (!Refs.empty()) {
1664 MachineInstr *LastUDMI = Refs.back().first;
1665 Refs.pop_back();
Lang Hames87e3bca2009-05-06 02:36:21 +00001666
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001667 MachineOperand *LastUD = NULL;
1668 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1669 MachineOperand &MO = LastUDMI->getOperand(i);
1670 if (!MO.isReg() || MO.getReg() != Reg)
1671 continue;
1672 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1673 LastUD = &MO;
1674 if (LastUDMI->isRegTiedToDefOperand(i))
1675 break;
1676 }
1677 if (LastUD->isDef()) {
1678 // If the instruction has no side effect, delete it and propagate
1679 // backward further. Otherwise, mark is dead and we are done.
1680 if (!isSafeToDelete(*LastUDMI)) {
1681 LastUD->setIsDead();
1682 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001683 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001684 VRM->RemoveMachineInstrFromMaps(LastUDMI);
1685 MBB->erase(LastUDMI);
1686 } else {
1687 LastUD->setIsKill();
1688 RegKills.set(Reg);
1689 KillOps[Reg] = LastUD;
1690 break;
1691 }
1692 }
1693}
Lang Hames87e3bca2009-05-06 02:36:21 +00001694
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001695/// InsertEmergencySpills - Insert emergency spills before MI if requested by
1696/// VRM. Return true if spills were inserted.
1697bool LocalRewriter::InsertEmergencySpills(MachineInstr *MI) {
1698 if (!VRM->hasEmergencySpills(MI))
1699 return false;
1700 MachineBasicBlock::iterator MII = MI;
1701 SmallSet<int, 4> UsedSS;
1702 std::vector<unsigned> &EmSpills = VRM->getEmergencySpills(MI);
1703 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1704 unsigned PhysReg = EmSpills[i];
Rafael Espindola0bfd0922010-07-12 00:52:33 +00001705 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001706 assert(RC && "Unable to determine register class!");
1707 int SS = VRM->getEmergencySpillSlot(RC);
1708 if (UsedSS.count(SS))
1709 llvm_unreachable("Need to spill more than one physical registers!");
1710 UsedSS.insert(SS);
Evan Cheng746ad692010-05-06 19:06:44 +00001711 TII->storeRegToStackSlot(*MBB, MII, PhysReg, true, SS, RC, TRI);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001712 MachineInstr *StoreMI = prior(MII);
1713 VRM->addSpillSlotUse(SS, StoreMI);
1714
1715 // Back-schedule reloads and remats.
1716 MachineBasicBlock::iterator InsertLoc =
1717 ComputeReloadLoc(llvm::next(MII), MBB->begin(), PhysReg, TRI, false, SS,
1718 TII, *MBB->getParent());
1719
Evan Cheng746ad692010-05-06 19:06:44 +00001720 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SS, RC, TRI);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001721
1722 MachineInstr *LoadMI = prior(InsertLoc);
1723 VRM->addSpillSlotUse(SS, LoadMI);
1724 ++NumPSpills;
1725 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1726 }
1727 return true;
1728}
1729
1730/// InsertRestores - Restore registers before MI is requested by VRM. Return
1731/// true is any instructions were inserted.
1732bool LocalRewriter::InsertRestores(MachineInstr *MI,
1733 AvailableSpills &Spills,
1734 BitVector &RegKills,
1735 std::vector<MachineOperand*> &KillOps) {
1736 if (!VRM->isRestorePt(MI))
1737 return false;
1738 MachineBasicBlock::iterator MII = MI;
1739 std::vector<unsigned> &RestoreRegs = VRM->getRestorePtRestores(MI);
1740 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1741 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1742 if (!VRM->getPreSplitReg(VirtReg))
1743 continue; // Split interval spilled again.
1744 unsigned Phys = VRM->getPhys(VirtReg);
1745 MRI->setPhysRegUsed(Phys);
1746
1747 // Check if the value being restored if available. If so, it must be
1748 // from a predecessor BB that fallthrough into this BB. We do not
1749 // expect:
1750 // BB1:
1751 // r1 = load fi#1
1752 // ...
1753 // = r1<kill>
1754 // ... # r1 not clobbered
1755 // ...
1756 // = load fi#1
1757 bool DoReMat = VRM->isReMaterialized(VirtReg);
1758 int SSorRMId = DoReMat
1759 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001760 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1761 if (InReg == Phys) {
1762 // If the value is already available in the expected register, save
1763 // a reload / remat.
1764 if (SSorRMId)
1765 DEBUG(dbgs() << "Reusing RM#"
1766 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1767 else
1768 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1769 DEBUG(dbgs() << " from physreg "
1770 << TRI->getName(InReg) << " for vreg"
1771 << VirtReg <<" instead of reloading into physreg "
1772 << TRI->getName(Phys) << '\n');
1773 ++NumOmitted;
1774 continue;
1775 } else if (InReg && InReg != Phys) {
1776 if (SSorRMId)
1777 DEBUG(dbgs() << "Reusing RM#"
1778 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1779 else
1780 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1781 DEBUG(dbgs() << " from physreg "
1782 << TRI->getName(InReg) << " for vreg"
1783 << VirtReg <<" by copying it into physreg "
1784 << TRI->getName(Phys) << '\n');
1785
1786 // If the reloaded / remat value is available in another register,
1787 // copy it to the desired register.
1788
1789 // Back-schedule reloads and remats.
1790 MachineBasicBlock::iterator InsertLoc =
1791 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1792 *MBB->getParent());
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001793 MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI->getDebugLoc(),
1794 TII->get(TargetOpcode::COPY), Phys)
1795 .addReg(InReg, RegState::Kill);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001796
1797 // This invalidates Phys.
1798 Spills.ClobberPhysReg(Phys);
1799 // Remember it's available.
1800 Spills.addAvailable(SSorRMId, Phys);
1801
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001802 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001803 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1804
1805 DEBUG(dbgs() << '\t' << *CopyMI);
1806 ++NumCopified;
1807 continue;
1808 }
1809
1810 // Back-schedule reloads and remats.
1811 MachineBasicBlock::iterator InsertLoc =
1812 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1813 *MBB->getParent());
1814
1815 if (VRM->isReMaterialized(VirtReg)) {
1816 ReMaterialize(*MBB, InsertLoc, Phys, VirtReg, TII, TRI, *VRM);
1817 } else {
1818 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
Evan Cheng746ad692010-05-06 19:06:44 +00001819 TII->loadRegFromStackSlot(*MBB, InsertLoc, Phys, SSorRMId, RC, TRI);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001820 MachineInstr *LoadMI = prior(InsertLoc);
1821 VRM->addSpillSlotUse(SSorRMId, LoadMI);
1822 ++NumLoads;
1823 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1824 }
1825
1826 // This invalidates Phys.
1827 Spills.ClobberPhysReg(Phys);
1828 // Remember it's available.
1829 Spills.addAvailable(SSorRMId, Phys);
1830
1831 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1832 DEBUG(dbgs() << '\t' << *prior(MII));
1833 }
1834 return true;
1835}
1836
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00001837/// InsertSpills - Insert spills after MI if requested by VRM. Return
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001838/// true if spills were inserted.
1839bool LocalRewriter::InsertSpills(MachineInstr *MI) {
1840 if (!VRM->isSpillPt(MI))
1841 return false;
1842 MachineBasicBlock::iterator MII = MI;
1843 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1844 VRM->getSpillPtSpills(MI);
1845 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1846 unsigned VirtReg = SpillRegs[i].first;
1847 bool isKill = SpillRegs[i].second;
1848 if (!VRM->getPreSplitReg(VirtReg))
1849 continue; // Split interval spilled again.
1850 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
1851 unsigned Phys = VRM->getPhys(VirtReg);
1852 int StackSlot = VRM->getStackSlot(VirtReg);
1853 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1854 TII->storeRegToStackSlot(*MBB, llvm::next(MII), Phys, isKill, StackSlot,
Evan Cheng746ad692010-05-06 19:06:44 +00001855 RC, TRI);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001856 MachineInstr *StoreMI = prior(oldNextMII);
1857 VRM->addSpillSlotUse(StackSlot, StoreMI);
1858 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1859 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1860 }
1861 return true;
1862}
1863
1864
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00001865/// ProcessUses - Process all of MI's spilled operands and all available
1866/// operands.
1867void LocalRewriter::ProcessUses(MachineInstr &MI, AvailableSpills &Spills,
1868 std::vector<MachineInstr*> &MaybeDeadStores,
1869 BitVector &RegKills,
1870 ReuseInfo &ReusedOperands,
1871 std::vector<MachineOperand*> &KillOps) {
1872 // Clear kill info.
1873 SmallSet<unsigned, 2> KilledMIRegs;
1874 SmallVector<unsigned, 4> VirtUseOps;
1875 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1876 MachineOperand &MO = MI.getOperand(i);
1877 if (!MO.isReg() || MO.getReg() == 0)
1878 continue; // Ignore non-register operands.
1879
1880 unsigned VirtReg = MO.getReg();
1881 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1882 // Ignore physregs for spilling, but remember that it is used by this
1883 // function.
1884 MRI->setPhysRegUsed(VirtReg);
1885 continue;
1886 }
1887
1888 // We want to process implicit virtual register uses first.
1889 if (MO.isImplicit())
1890 // If the virtual register is implicitly defined, emit a implicit_def
1891 // before so scavenger knows it's "defined".
1892 // FIXME: This is a horrible hack done the by register allocator to
1893 // remat a definition with virtual register operand.
1894 VirtUseOps.insert(VirtUseOps.begin(), i);
1895 else
1896 VirtUseOps.push_back(i);
1897 }
1898
1899 // Process all of the spilled uses and all non spilled reg references.
1900 SmallVector<int, 2> PotentialDeadStoreSlots;
1901 KilledMIRegs.clear();
1902 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1903 unsigned i = VirtUseOps[j];
1904 unsigned VirtReg = MI.getOperand(i).getReg();
1905 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1906 "Not a virtual register?");
1907
1908 unsigned SubIdx = MI.getOperand(i).getSubReg();
1909 if (VRM->isAssignedReg(VirtReg)) {
1910 // This virtual register was assigned a physreg!
1911 unsigned Phys = VRM->getPhys(VirtReg);
1912 MRI->setPhysRegUsed(Phys);
1913 if (MI.getOperand(i).isDef())
1914 ReusedOperands.markClobbered(Phys);
1915 substitutePhysReg(MI.getOperand(i), Phys, *TRI);
1916 if (VRM->isImplicitlyDefined(VirtReg))
1917 // FIXME: Is this needed?
1918 BuildMI(*MBB, &MI, MI.getDebugLoc(),
1919 TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
1920 continue;
1921 }
1922
1923 // This virtual register is now known to be a spilled value.
1924 if (!MI.getOperand(i).isUse())
1925 continue; // Handle defs in the loop below (handle use&def here though)
1926
1927 bool AvoidReload = MI.getOperand(i).isUndef();
1928 // Check if it is defined by an implicit def. It should not be spilled.
1929 // Note, this is for correctness reason. e.g.
1930 // 8 %reg1024<def> = IMPLICIT_DEF
1931 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1932 // The live range [12, 14) are not part of the r1024 live interval since
1933 // it's defined by an implicit def. It will not conflicts with live
1934 // interval of r1025. Now suppose both registers are spilled, you can
1935 // easily see a situation where both registers are reloaded before
1936 // the INSERT_SUBREG and both target registers that would overlap.
1937 bool DoReMat = VRM->isReMaterialized(VirtReg);
1938 int SSorRMId = DoReMat
1939 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1940 int ReuseSlot = SSorRMId;
1941
1942 // Check to see if this stack slot is available.
1943 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1944
1945 // If this is a sub-register use, make sure the reuse register is in the
1946 // right register class. For example, for x86 not all of the 32-bit
1947 // registers have accessible sub-registers.
1948 // Similarly so for EXTRACT_SUBREG. Consider this:
1949 // EDI = op
1950 // MOV32_mr fi#1, EDI
1951 // ...
1952 // = EXTRACT_SUBREG fi#1
1953 // fi#1 is available in EDI, but it cannot be reused because it's not in
1954 // the right register file.
1955 if (PhysReg && !AvoidReload && SubIdx) {
1956 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1957 if (!RC->contains(PhysReg))
1958 PhysReg = 0;
1959 }
1960
1961 if (PhysReg && !AvoidReload) {
1962 // This spilled operand might be part of a two-address operand. If this
1963 // is the case, then changing it will necessarily require changing the
1964 // def part of the instruction as well. However, in some cases, we
1965 // aren't allowed to modify the reused register. If none of these cases
1966 // apply, reuse it.
1967 bool CanReuse = true;
1968 bool isTied = MI.isRegTiedToDefOperand(i);
1969 if (isTied) {
1970 // Okay, we have a two address operand. We can reuse this physreg as
1971 // long as we are allowed to clobber the value and there isn't an
1972 // earlier def that has already clobbered the physreg.
1973 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1974 Spills.canClobberPhysReg(PhysReg);
1975 }
1976 // If this is an asm, and a PhysReg alias is used elsewhere as an
1977 // earlyclobber operand, we can't also use it as an input.
1978 if (MI.isInlineAsm()) {
1979 for (unsigned k = 0, e = MI.getNumOperands(); k != e; ++k) {
1980 MachineOperand &MOk = MI.getOperand(k);
1981 if (MOk.isReg() && MOk.isEarlyClobber() &&
1982 TRI->regsOverlap(MOk.getReg(), PhysReg)) {
1983 CanReuse = false;
1984 DEBUG(dbgs() << "Not reusing physreg " << TRI->getName(PhysReg)
1985 << " for vreg" << VirtReg << ": " << MOk << '\n');
1986 break;
1987 }
1988 }
1989 }
1990
1991 if (CanReuse) {
1992 // If this stack slot value is already available, reuse it!
1993 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1994 DEBUG(dbgs() << "Reusing RM#"
1995 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
1996 else
1997 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
1998 DEBUG(dbgs() << " from physreg "
1999 << TRI->getName(PhysReg) << " for vreg"
2000 << VirtReg <<" instead of reloading into physreg "
2001 << TRI->getName(VRM->getPhys(VirtReg)) << '\n');
2002 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2003 MI.getOperand(i).setReg(RReg);
2004 MI.getOperand(i).setSubReg(0);
2005
2006 // The only technical detail we have is that we don't know that
2007 // PhysReg won't be clobbered by a reloaded stack slot that occurs
2008 // later in the instruction. In particular, consider 'op V1, V2'.
2009 // If V1 is available in physreg R0, we would choose to reuse it
2010 // here, instead of reloading it into the register the allocator
2011 // indicated (say R1). However, V2 might have to be reloaded
2012 // later, and it might indicate that it needs to live in R0. When
2013 // this occurs, we need to have information available that
2014 // indicates it is safe to use R1 for the reload instead of R0.
2015 //
2016 // To further complicate matters, we might conflict with an alias,
2017 // or R0 and R1 might not be compatible with each other. In this
2018 // case, we actually insert a reload for V1 in R1, ensuring that
2019 // we can get at R0 or its alias.
2020 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
2021 VRM->getPhys(VirtReg), VirtReg);
2022 if (isTied)
2023 // Only mark it clobbered if this is a use&def operand.
2024 ReusedOperands.markClobbered(PhysReg);
2025 ++NumReused;
2026
2027 if (MI.getOperand(i).isKill() &&
2028 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
2029
2030 // The store of this spilled value is potentially dead, but we
2031 // won't know for certain until we've confirmed that the re-use
2032 // above is valid, which means waiting until the other operands
2033 // are processed. For now we just track the spill slot, we'll
2034 // remove it after the other operands are processed if valid.
2035
2036 PotentialDeadStoreSlots.push_back(ReuseSlot);
2037 }
2038
2039 // Mark is isKill if it's there no other uses of the same virtual
2040 // register and it's not a two-address operand. IsKill will be
2041 // unset if reg is reused.
2042 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
2043 MI.getOperand(i).setIsKill();
2044 KilledMIRegs.insert(VirtReg);
2045 }
2046
2047 continue;
2048 } // CanReuse
2049
2050 // Otherwise we have a situation where we have a two-address instruction
2051 // whose mod/ref operand needs to be reloaded. This reload is already
2052 // available in some register "PhysReg", but if we used PhysReg as the
2053 // operand to our 2-addr instruction, the instruction would modify
2054 // PhysReg. This isn't cool if something later uses PhysReg and expects
2055 // to get its initial value.
2056 //
2057 // To avoid this problem, and to avoid doing a load right after a store,
2058 // we emit a copy from PhysReg into the designated register for this
2059 // operand.
2060 //
2061 // This case also applies to an earlyclobber'd PhysReg.
2062 unsigned DesignatedReg = VRM->getPhys(VirtReg);
2063 assert(DesignatedReg && "Must map virtreg to physreg!");
2064
2065 // Note that, if we reused a register for a previous operand, the
2066 // register we want to reload into might not actually be
2067 // available. If this occurs, use the register indicated by the
2068 // reuser.
2069 if (ReusedOperands.hasReuses())
2070 DesignatedReg = ReusedOperands.
2071 GetRegForReload(VirtReg, DesignatedReg, &MI, Spills,
2072 MaybeDeadStores, RegKills, KillOps, *VRM);
2073
2074 // If the mapped designated register is actually the physreg we have
2075 // incoming, we don't need to inserted a dead copy.
2076 if (DesignatedReg == PhysReg) {
2077 // If this stack slot value is already available, reuse it!
2078 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2079 DEBUG(dbgs() << "Reusing RM#"
2080 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2081 else
2082 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2083 DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
2084 << " for vreg" << VirtReg
2085 << " instead of reloading into same physreg.\n");
2086 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2087 MI.getOperand(i).setReg(RReg);
2088 MI.getOperand(i).setSubReg(0);
2089 ReusedOperands.markClobbered(RReg);
2090 ++NumReused;
2091 continue;
2092 }
2093
2094 MRI->setPhysRegUsed(DesignatedReg);
2095 ReusedOperands.markClobbered(DesignatedReg);
2096
2097 // Back-schedule reloads and remats.
2098 MachineBasicBlock::iterator InsertLoc =
2099 ComputeReloadLoc(&MI, MBB->begin(), PhysReg, TRI, DoReMat,
2100 SSorRMId, TII, *MBB->getParent());
2101 MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI.getDebugLoc(),
2102 TII->get(TargetOpcode::COPY),
2103 DesignatedReg).addReg(PhysReg);
2104 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2105 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2106
2107 // This invalidates DesignatedReg.
2108 Spills.ClobberPhysReg(DesignatedReg);
2109
2110 Spills.addAvailable(ReuseSlot, DesignatedReg);
2111 unsigned RReg =
2112 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2113 MI.getOperand(i).setReg(RReg);
2114 MI.getOperand(i).setSubReg(0);
2115 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2116 ++NumReused;
2117 continue;
2118 } // if (PhysReg)
2119
2120 // Otherwise, reload it and remember that we have it.
2121 PhysReg = VRM->getPhys(VirtReg);
2122 assert(PhysReg && "Must map virtreg to physreg!");
2123
2124 // Note that, if we reused a register for a previous operand, the
2125 // register we want to reload into might not actually be
2126 // available. If this occurs, use the register indicated by the
2127 // reuser.
2128 if (ReusedOperands.hasReuses())
2129 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2130 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2131
2132 MRI->setPhysRegUsed(PhysReg);
2133 ReusedOperands.markClobbered(PhysReg);
2134 if (AvoidReload)
2135 ++NumAvoided;
2136 else {
2137 // Back-schedule reloads and remats.
2138 MachineBasicBlock::iterator InsertLoc =
2139 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI, DoReMat,
2140 SSorRMId, TII, *MBB->getParent());
2141
2142 if (DoReMat) {
2143 ReMaterialize(*MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, *VRM);
2144 } else {
2145 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2146 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SSorRMId, RC,TRI);
2147 MachineInstr *LoadMI = prior(InsertLoc);
2148 VRM->addSpillSlotUse(SSorRMId, LoadMI);
2149 ++NumLoads;
2150 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
2151 }
2152 // This invalidates PhysReg.
2153 Spills.ClobberPhysReg(PhysReg);
2154
2155 // Any stores to this stack slot are not dead anymore.
2156 if (!DoReMat)
2157 MaybeDeadStores[SSorRMId] = NULL;
2158 Spills.addAvailable(SSorRMId, PhysReg);
2159 // Assumes this is the last use. IsKill will be unset if reg is reused
2160 // unless it's a two-address operand.
2161 if (!MI.isRegTiedToDefOperand(i) &&
2162 KilledMIRegs.count(VirtReg) == 0) {
2163 MI.getOperand(i).setIsKill();
2164 KilledMIRegs.insert(VirtReg);
2165 }
2166
2167 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2168 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2169 }
2170 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2171 MI.getOperand(i).setReg(RReg);
2172 MI.getOperand(i).setSubReg(0);
2173 }
2174
2175 // Ok - now we can remove stores that have been confirmed dead.
2176 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2177 // This was the last use and the spilled value is still available
2178 // for reuse. That means the spill was unnecessary!
2179 int PDSSlot = PotentialDeadStoreSlots[j];
2180 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2181 if (DeadStore) {
2182 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2183 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2184 VRM->RemoveMachineInstrFromMaps(DeadStore);
2185 MBB->erase(DeadStore);
2186 MaybeDeadStores[PDSSlot] = NULL;
2187 ++NumDSE;
2188 }
2189 }
2190
2191}
2192
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002193/// rewriteMBB - Keep track of which spills are available even after the
Jim Grosbachae64eed2010-07-27 17:14:29 +00002194/// register allocator is done with them. If possible, avoid reloading vregs.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002195void
2196LocalRewriter::RewriteMBB(LiveIntervals *LIs,
2197 AvailableSpills &Spills, BitVector &RegKills,
2198 std::vector<MachineOperand*> &KillOps) {
Lang Hames87e3bca2009-05-06 02:36:21 +00002199
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002200 DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
2201 << MBB->getName() << "':\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00002202
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002203 MachineFunction &MF = *MBB->getParent();
David Greene2d4e6d32009-07-28 16:49:24 +00002204
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002205 // MaybeDeadStores - When we need to write a value back into a stack slot,
2206 // keep track of the inserted store. If the stack slot value is never read
2207 // (because the value was used from some available register, for example), and
2208 // subsequently stored to, the original store is dead. This map keeps track
2209 // of inserted stores that are not used. If we see a subsequent store to the
2210 // same stack slot, the original store is deleted.
2211 std::vector<MachineInstr*> MaybeDeadStores;
2212 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
David Greene2d4e6d32009-07-28 16:49:24 +00002213
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002214 // ReMatDefs - These are rematerializable def MIs which are not deleted.
2215 SmallSet<MachineInstr*, 4> ReMatDefs;
Lang Hames87e3bca2009-05-06 02:36:21 +00002216
Jakob Stoklund Olesen2afb7502010-05-21 16:36:13 +00002217 // Keep track of the registers we have already spilled in case there are
2218 // multiple defs of the same register in MI.
2219 SmallSet<unsigned, 8> SpilledMIRegs;
2220
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002221 RegKills.reset();
2222 KillOps.clear();
2223 KillOps.resize(TRI->getNumRegs(), NULL);
Lang Hames87e3bca2009-05-06 02:36:21 +00002224
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002225 DistanceMap.clear();
2226 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2227 MII != E; ) {
2228 MachineBasicBlock::iterator NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00002229
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002230 if (OptimizeByUnfold(MII, MaybeDeadStores, Spills, RegKills, KillOps))
2231 NextMII = llvm::next(MII);
2232
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00002233 if (InsertEmergencySpills(MII))
2234 NextMII = llvm::next(MII);
2235
2236 InsertRestores(MII, Spills, RegKills, KillOps);
2237
2238 if (InsertSpills(MII))
2239 NextMII = llvm::next(MII);
2240
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00002241 bool Erased = false;
2242 bool BackTracked = false;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002243 MachineInstr &MI = *MII;
2244
Evan Chengbd6cb4b2010-04-29 18:51:00 +00002245 // Remember DbgValue's which reference stack slots.
2246 if (MI.isDebugValue() && MI.getOperand(0).isFI())
2247 Slot2DbgValues[MI.getOperand(0).getIndex()].push_back(&MI);
2248
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002249 /// ReusedOperands - Keep track of operand reuse in case we need to undo
2250 /// reuse.
2251 ReuseInfo ReusedOperands(MI, TRI);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002252
Jakob Stoklund Olesena32181a2010-10-08 22:14:41 +00002253 ProcessUses(MI, Spills, MaybeDeadStores, RegKills, ReusedOperands, KillOps);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002254
2255 DEBUG(dbgs() << '\t' << MI);
2256
2257
2258 // If we have folded references to memory operands, make sure we clear all
2259 // physical registers that may contain the value of the spilled virtual
2260 // register
Jakob Stoklund Olesena330d4c2010-08-05 18:12:19 +00002261
2262 // Copy the folded virts to a small vector, we may change MI2VirtMap.
2263 SmallVector<std::pair<unsigned, VirtRegMap::ModRef>, 4> FoldedVirts;
2264 // C++0x FTW!
2265 for (std::pair<VirtRegMap::MI2VirtMapTy::const_iterator,
2266 VirtRegMap::MI2VirtMapTy::const_iterator> FVRange =
2267 VRM->getFoldedVirts(&MI);
2268 FVRange.first != FVRange.second; ++FVRange.first)
2269 FoldedVirts.push_back(FVRange.first->second);
2270
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002271 SmallSet<int, 2> FoldedSS;
Jakob Stoklund Olesena330d4c2010-08-05 18:12:19 +00002272 for (unsigned FVI = 0, FVE = FoldedVirts.size(); FVI != FVE; ++FVI) {
2273 unsigned VirtReg = FoldedVirts[FVI].first;
2274 VirtRegMap::ModRef MR = FoldedVirts[FVI].second;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002275 DEBUG(dbgs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2276
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002277 int SS = VRM->getStackSlot(VirtReg);
2278 if (SS == VirtRegMap::NO_STACK_SLOT)
2279 continue;
2280 FoldedSS.insert(SS);
2281 DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
2282
2283 // If this folded instruction is just a use, check to see if it's a
2284 // straight load from the virt reg slot.
2285 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2286 int FrameIdx;
2287 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2288 if (DestReg && FrameIdx == SS) {
2289 // If this spill slot is available, turn it into a copy (or nothing)
2290 // instead of leaving it as a load!
2291 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2292 DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
2293 if (DestReg != InReg) {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002294 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00002295 MachineInstr *CopyMI = BuildMI(*MBB, &MI, MI.getDebugLoc(),
2296 TII->get(TargetOpcode::COPY))
2297 .addReg(DestReg, RegState::Define, DefMO->getSubReg())
2298 .addReg(InReg, RegState::Kill);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002299 // Revisit the copy so we make sure to notice the effects of the
2300 // operation on the destreg (either needing to RA it if it's
2301 // virtual or needing to clobber any values if it's physical).
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00002302 NextMII = CopyMI;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002303 NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002304 BackTracked = true;
2305 } else {
2306 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2307 // Unset last kill since it's being reused.
2308 InvalidateKill(InReg, TRI, RegKills, KillOps);
2309 Spills.disallowClobberPhysReg(InReg);
2310 }
2311
2312 InvalidateKills(MI, TRI, RegKills, KillOps);
2313 VRM->RemoveMachineInstrFromMaps(&MI);
2314 MBB->erase(&MI);
2315 Erased = true;
2316 goto ProcessNextInst;
2317 }
2318 } else {
2319 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2320 SmallVector<MachineInstr*, 4> NewMIs;
2321 if (PhysReg &&
Jim Grosbach57cb4f82010-07-27 17:38:47 +00002322 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)){
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002323 MBB->insert(MII, NewMIs[0]);
2324 InvalidateKills(MI, TRI, RegKills, KillOps);
2325 VRM->RemoveMachineInstrFromMaps(&MI);
2326 MBB->erase(&MI);
2327 Erased = true;
2328 --NextMII; // backtrack to the unfolded instruction.
2329 BackTracked = true;
2330 goto ProcessNextInst;
2331 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002332 }
2333 }
2334
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002335 // If this reference is not a use, any previous store is now dead.
2336 // Otherwise, the store to this stack slot is not dead anymore.
2337 MachineInstr* DeadStore = MaybeDeadStores[SS];
2338 if (DeadStore) {
2339 bool isDead = !(MR & VirtRegMap::isRef);
2340 MachineInstr *NewStore = NULL;
2341 if (MR & VirtRegMap::isModRef) {
2342 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2343 SmallVector<MachineInstr*, 4> NewMIs;
2344 // We can reuse this physreg as long as we are allowed to clobber
2345 // the value and there isn't an earlier def that has already clobbered
2346 // the physreg.
2347 if (PhysReg &&
2348 !ReusedOperands.isClobbered(PhysReg) &&
2349 Spills.canClobberPhysReg(PhysReg) &&
2350 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2351 MachineOperand *KillOpnd =
2352 DeadStore->findRegisterUseOperand(PhysReg, true);
2353 // Note, if the store is storing a sub-register, it's possible the
2354 // super-register is needed below.
2355 if (KillOpnd && !KillOpnd->getSubReg() &&
2356 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2357 MBB->insert(MII, NewMIs[0]);
2358 NewStore = NewMIs[1];
2359 MBB->insert(MII, NewStore);
2360 VRM->addSpillSlotUse(SS, NewStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002361 InvalidateKills(MI, TRI, RegKills, KillOps);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002362 VRM->RemoveMachineInstrFromMaps(&MI);
2363 MBB->erase(&MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002364 Erased = true;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002365 --NextMII;
Lang Hames87e3bca2009-05-06 02:36:21 +00002366 --NextMII; // backtrack to the unfolded instruction.
2367 BackTracked = true;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002368 isDead = true;
2369 ++NumSUnfold;
2370 }
2371 }
2372 }
2373
2374 if (isDead) { // Previous store is dead.
2375 // If we get here, the store is dead, nuke it now.
2376 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2377 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2378 VRM->RemoveMachineInstrFromMaps(DeadStore);
2379 MBB->erase(DeadStore);
2380 if (!NewStore)
2381 ++NumDSE;
2382 }
2383
2384 MaybeDeadStores[SS] = NULL;
2385 if (NewStore) {
2386 // Treat this store as a spill merged into a copy. That makes the
2387 // stack slot value available.
2388 VRM->virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2389 goto ProcessNextInst;
2390 }
2391 }
2392
2393 // If the spill slot value is available, and this is a new definition of
2394 // the value, the value is not available anymore.
2395 if (MR & VirtRegMap::isMod) {
2396 // Notice that the value in this stack slot has been modified.
2397 Spills.ModifyStackSlotOrReMat(SS);
2398
2399 // If this is *just* a mod of the value, check to see if this is just a
2400 // store to the spill slot (i.e. the spill got merged into the copy). If
2401 // so, realize that the vreg is available now, and add the store to the
2402 // MaybeDeadStore info.
2403 int StackSlot;
2404 if (!(MR & VirtRegMap::isRef)) {
2405 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2406 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2407 "Src hasn't been allocated yet?");
2408
2409 if (CommuteToFoldReload(MII, VirtReg, SrcReg, StackSlot,
2410 Spills, RegKills, KillOps, TRI)) {
2411 NextMII = llvm::next(MII);
2412 BackTracked = true;
Lang Hames87e3bca2009-05-06 02:36:21 +00002413 goto ProcessNextInst;
2414 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002415
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002416 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2417 // this as a potentially dead store in case there is a subsequent
2418 // store into the stack slot without a read from it.
2419 MaybeDeadStores[StackSlot] = &MI;
Lang Hames87e3bca2009-05-06 02:36:21 +00002420
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002421 // If the stack slot value was previously available in some other
2422 // register, change it now. Otherwise, make the register
2423 // available in PhysReg.
2424 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
Lang Hames87e3bca2009-05-06 02:36:21 +00002425 }
2426 }
2427 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002428 }
2429
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002430 // Process all of the spilled defs.
Jakob Stoklund Olesen2afb7502010-05-21 16:36:13 +00002431 SpilledMIRegs.clear();
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002432 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2433 MachineOperand &MO = MI.getOperand(i);
2434 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2435 continue;
Lang Hames87e3bca2009-05-06 02:36:21 +00002436
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002437 unsigned VirtReg = MO.getReg();
2438 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2439 // Check to see if this is a noop copy. If so, eliminate the
2440 // instruction before considering the dest reg to be changed.
2441 // Also check if it's copying from an "undef", if so, we can't
2442 // eliminate this or else the undef marker is lost and it will
2443 // confuses the scavenger. This is extremely rare.
Jakob Stoklund Olesen1769ccc2010-07-09 01:27:19 +00002444 if (MI.isIdentityCopy() && !MI.getOperand(1).isUndef() &&
2445 MI.getNumOperands() == 2) {
2446 ++NumDCE;
2447 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2448 SmallVector<unsigned, 2> KillRegs;
2449 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2450 if (MO.isDead() && !KillRegs.empty()) {
2451 // Source register or an implicit super/sub-register use is killed.
2452 assert(TRI->regsOverlap(KillRegs[0], MI.getOperand(0).getReg()));
2453 // Last def is now dead.
2454 TransferDeadness(MI.getOperand(1).getReg(), RegKills, KillOps);
2455 }
2456 VRM->RemoveMachineInstrFromMaps(&MI);
2457 MBB->erase(&MI);
2458 Erased = true;
2459 Spills.disallowClobberPhysReg(VirtReg);
2460 goto ProcessNextInst;
2461 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002462
2463 // If it's not a no-op copy, it clobbers the value in the destreg.
2464 Spills.ClobberPhysReg(VirtReg);
2465 ReusedOperands.markClobbered(VirtReg);
2466
2467 // Check to see if this instruction is a load from a stack slot into
2468 // a register. If so, this provides the stack slot value in the reg.
2469 int FrameIdx;
2470 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2471 assert(DestReg == VirtReg && "Unknown load situation!");
2472
2473 // If it is a folded reference, then it's not safe to clobber.
2474 bool Folded = FoldedSS.count(FrameIdx);
2475 // Otherwise, if it wasn't available, remember that it is now!
2476 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2477 goto ProcessNextInst;
2478 }
2479
2480 continue;
2481 }
2482
2483 unsigned SubIdx = MO.getSubReg();
2484 bool DoReMat = VRM->isReMaterialized(VirtReg);
2485 if (DoReMat)
2486 ReMatDefs.insert(&MI);
2487
2488 // The only vregs left are stack slot definitions.
2489 int StackSlot = VRM->getStackSlot(VirtReg);
2490 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2491
2492 // If this def is part of a two-address operand, make sure to execute
2493 // the store from the correct physical register.
2494 unsigned PhysReg;
2495 unsigned TiedOp;
2496 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2497 PhysReg = MI.getOperand(TiedOp).getReg();
2498 if (SubIdx) {
2499 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2500 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2501 "Can't find corresponding super-register!");
2502 PhysReg = SuperReg;
2503 }
2504 } else {
2505 PhysReg = VRM->getPhys(VirtReg);
2506 if (ReusedOperands.isClobbered(PhysReg)) {
2507 // Another def has taken the assigned physreg. It must have been a
2508 // use&def which got it due to reuse. Undo the reuse!
2509 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2510 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2511 }
2512 }
2513
2514 assert(PhysReg && "VR not assigned a physical register?");
2515 MRI->setPhysRegUsed(PhysReg);
2516 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2517 ReusedOperands.markClobbered(RReg);
2518 MI.getOperand(i).setReg(RReg);
2519 MI.getOperand(i).setSubReg(0);
2520
Jakob Stoklund Olesen2afb7502010-05-21 16:36:13 +00002521 if (!MO.isDead() && SpilledMIRegs.insert(VirtReg)) {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002522 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2523 SpillRegToStackSlot(MII, -1, PhysReg, StackSlot, RC, true,
2524 LastStore, Spills, ReMatDefs, RegKills, KillOps);
2525 NextMII = llvm::next(MII);
2526
2527 // Check to see if this is a noop copy. If so, eliminate the
2528 // instruction before considering the dest reg to be changed.
Jakob Stoklund Olesen1769ccc2010-07-09 01:27:19 +00002529 if (MI.isIdentityCopy()) {
2530 ++NumDCE;
2531 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2532 InvalidateKills(MI, TRI, RegKills, KillOps);
2533 VRM->RemoveMachineInstrFromMaps(&MI);
2534 MBB->erase(&MI);
2535 Erased = true;
2536 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2537 goto ProcessNextInst;
2538 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002539 }
2540 }
2541 ProcessNextInst:
2542 // Delete dead instructions without side effects.
2543 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2544 InvalidateKills(MI, TRI, RegKills, KillOps);
2545 VRM->RemoveMachineInstrFromMaps(&MI);
2546 MBB->erase(&MI);
2547 Erased = true;
2548 }
2549 if (!Erased)
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00002550 DistanceMap.insert(std::make_pair(&MI, DistanceMap.size()));
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002551 if (!Erased && !BackTracked) {
2552 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2553 UpdateKills(*II, TRI, RegKills, KillOps);
2554 }
2555 MII = NextMII;
2556 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002557
Dan Gohman7db949d2009-08-07 01:32:21 +00002558}
2559
Lang Hames87e3bca2009-05-06 02:36:21 +00002560llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2561 switch (RewriterOpt) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002562 default: llvm_unreachable("Unreachable!");
Lang Hames87e3bca2009-05-06 02:36:21 +00002563 case local:
2564 return new LocalRewriter();
Lang Hamesf41538d2009-06-02 16:53:25 +00002565 case trivial:
2566 return new TrivialRewriter();
Lang Hames87e3bca2009-05-06 02:36:21 +00002567 }
2568}