blob: 401bcb618e429e5c96552ea85346cfb4563da6c0 [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"
Benjamin Kramercfa6ec92009-08-23 11:37:21 +000012#include "llvm/Function.h"
13#include "llvm/CodeGen/MachineFrameInfo.h"
14#include "llvm/CodeGen/MachineInstrBuilder.h"
15#include "llvm/CodeGen/MachineRegisterInfo.h"
Lang Hames87e3bca2009-05-06 02:36:21 +000016#include "llvm/Support/Compiler.h"
Benjamin Kramercfa6ec92009-08-23 11:37:21 +000017#include "llvm/Support/CommandLine.h"
18#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000019#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000020#include "llvm/Support/raw_ostream.h"
Benjamin Kramercfa6ec92009-08-23 11:37:21 +000021#include "llvm/Target/TargetInstrInfo.h"
David Greene2d4e6d32009-07-28 16:49:24 +000022#include "llvm/Target/TargetLowering.h"
Lang Hames87e3bca2009-05-06 02:36:21 +000023#include "llvm/ADT/DepthFirstIterator.h"
24#include "llvm/ADT/Statistic.h"
Lang Hames87e3bca2009-05-06 02:36:21 +000025#include <algorithm>
26using namespace llvm;
27
28STATISTIC(NumDSE , "Number of dead stores elided");
29STATISTIC(NumDSS , "Number of dead spill slots removed");
30STATISTIC(NumCommutes, "Number of instructions commuted");
31STATISTIC(NumDRM , "Number of re-materializable defs elided");
32STATISTIC(NumStores , "Number of stores added");
33STATISTIC(NumPSpills , "Number of physical register spills");
34STATISTIC(NumOmitted , "Number of reloads omited");
35STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
36STATISTIC(NumCopified, "Number of available reloads turned into copies");
37STATISTIC(NumReMats , "Number of re-materialization");
38STATISTIC(NumLoads , "Number of loads added");
39STATISTIC(NumReused , "Number of values reused");
40STATISTIC(NumDCE , "Number of copies elided");
41STATISTIC(NumSUnfold , "Number of stores unfolded");
42STATISTIC(NumModRefUnfold, "Number of modref unfolded");
43
44namespace {
Lang Hamesac276402009-06-04 18:45:36 +000045 enum RewriterName { local, trivial };
Lang Hames87e3bca2009-05-06 02:36:21 +000046}
47
48static cl::opt<RewriterName>
49RewriterOpt("rewriter",
50 cl::desc("Rewriter to use: (default: local)"),
51 cl::Prefix,
Lang Hamesac276402009-06-04 18:45:36 +000052 cl::values(clEnumVal(local, "local rewriter"),
Lang Hamesf41538d2009-06-02 16:53:25 +000053 clEnumVal(trivial, "trivial rewriter"),
Lang Hames87e3bca2009-05-06 02:36:21 +000054 clEnumValEnd),
55 cl::init(local));
56
Dan Gohman7db949d2009-08-07 01:32:21 +000057static cl::opt<bool>
David Greene2d4e6d32009-07-28 16:49:24 +000058ScheduleSpills("schedule-spills",
59 cl::desc("Schedule spill code"),
60 cl::init(false));
61
Lang Hames87e3bca2009-05-06 02:36:21 +000062VirtRegRewriter::~VirtRegRewriter() {}
63
Dan Gohman7db949d2009-08-07 01:32:21 +000064namespace {
Lang Hames87e3bca2009-05-06 02:36:21 +000065
Lang Hamesf41538d2009-06-02 16:53:25 +000066/// This class is intended for use with the new spilling framework only. It
67/// rewrites vreg def/uses to use the assigned preg, but does not insert any
68/// spill code.
69struct VISIBILITY_HIDDEN TrivialRewriter : public VirtRegRewriter {
70
71 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
72 LiveIntervals* LIs) {
Chris Lattner6456d382009-08-23 03:20:44 +000073 DEBUG(errs() << "********** REWRITE MACHINE CODE **********\n");
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000074 DEBUG(errs() << "********** Function: "
75 << MF.getFunction()->getName() << '\n');
Chris Lattner6456d382009-08-23 03:20:44 +000076 DEBUG(errs() << "**** Machine Instrs"
77 << "(NOTE! Does not include spills and reloads!) ****\n");
David Greene2d4e6d32009-07-28 16:49:24 +000078 DEBUG(MF.dump());
79
Lang Hamesf41538d2009-06-02 16:53:25 +000080 MachineRegisterInfo *mri = &MF.getRegInfo();
81
82 bool changed = false;
83
84 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
85 liItr != liEnd; ++liItr) {
86
87 if (TargetRegisterInfo::isVirtualRegister(liItr->first)) {
88 if (VRM.hasPhys(liItr->first)) {
89 unsigned preg = VRM.getPhys(liItr->first);
90 mri->replaceRegWith(liItr->first, preg);
91 mri->setPhysRegUsed(preg);
92 changed = true;
93 }
94 }
95 else {
96 if (!liItr->second->empty()) {
97 mri->setPhysRegUsed(liItr->first);
98 }
99 }
100 }
David Greene2d4e6d32009-07-28 16:49:24 +0000101
102
Chris Lattner6456d382009-08-23 03:20:44 +0000103 DEBUG(errs() << "**** Post Machine Instrs ****\n");
David Greene2d4e6d32009-07-28 16:49:24 +0000104 DEBUG(MF.dump());
Lang Hamesf41538d2009-06-02 16:53:25 +0000105
106 return changed;
107 }
108
109};
110
Dan Gohman7db949d2009-08-07 01:32:21 +0000111}
112
Lang Hames87e3bca2009-05-06 02:36:21 +0000113// ************************************************************************ //
114
Dan Gohman7db949d2009-08-07 01:32:21 +0000115namespace {
116
Lang Hames87e3bca2009-05-06 02:36:21 +0000117/// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
118/// from top down, keep track of which spill slots or remat are available in
119/// each register.
120///
121/// Note that not all physregs are created equal here. In particular, some
122/// physregs are reloads that we are allowed to clobber or ignore at any time.
123/// Other physregs are values that the register allocated program is using
124/// that we cannot CHANGE, but we can read if we like. We keep track of this
125/// on a per-stack-slot / remat id basis as the low bit in the value of the
126/// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
127/// this bit and addAvailable sets it if.
128class VISIBILITY_HIDDEN AvailableSpills {
129 const TargetRegisterInfo *TRI;
130 const TargetInstrInfo *TII;
131
132 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
133 // or remat'ed virtual register values that are still available, due to
134 // being loaded or stored to, but not invalidated yet.
135 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
136
137 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
138 // indicating which stack slot values are currently held by a physreg. This
139 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
140 // physreg is modified.
141 std::multimap<unsigned, int> PhysRegsAvailable;
142
143 void disallowClobberPhysRegOnly(unsigned PhysReg);
144
145 void ClobberPhysRegOnly(unsigned PhysReg);
146public:
147 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
148 : TRI(tri), TII(tii) {
149 }
150
151 /// clear - Reset the state.
152 void clear() {
153 SpillSlotsOrReMatsAvailable.clear();
154 PhysRegsAvailable.clear();
155 }
156
157 const TargetRegisterInfo *getRegInfo() const { return TRI; }
158
159 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
160 /// available in a physical register, return that PhysReg, otherwise
161 /// return 0.
162 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
163 std::map<int, unsigned>::const_iterator I =
164 SpillSlotsOrReMatsAvailable.find(Slot);
165 if (I != SpillSlotsOrReMatsAvailable.end()) {
166 return I->second >> 1; // Remove the CanClobber bit.
167 }
168 return 0;
169 }
170
171 /// addAvailable - Mark that the specified stack slot / remat is available
172 /// in the specified physreg. If CanClobber is true, the physreg can be
173 /// modified at any time without changing the semantics of the program.
174 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
175 // If this stack slot is thought to be available in some other physreg,
176 // remove its record.
177 ModifyStackSlotOrReMat(SlotOrReMat);
178
179 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
180 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
181 (unsigned)CanClobber;
182
183 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
Chris Lattner6456d382009-08-23 03:20:44 +0000184 DEBUG(errs() << "Remembering RM#"
185 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +0000186 else
Chris Lattner6456d382009-08-23 03:20:44 +0000187 DEBUG(errs() << "Remembering SS#" << SlotOrReMat);
188 DEBUG(errs() << " in physreg " << TRI->getName(Reg) << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000189 }
190
191 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
192 /// the value of the specified stackslot register if it desires. The
193 /// specified stack slot must be available in a physreg for this query to
194 /// make sense.
195 bool canClobberPhysRegForSS(int SlotOrReMat) const {
196 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
197 "Value not available!");
198 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
199 }
200
201 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
202 /// physical register where values for some stack slot(s) might be
203 /// available.
204 bool canClobberPhysReg(unsigned PhysReg) const {
205 std::multimap<unsigned, int>::const_iterator I =
206 PhysRegsAvailable.lower_bound(PhysReg);
207 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
208 int SlotOrReMat = I->second;
209 I++;
210 if (!canClobberPhysRegForSS(SlotOrReMat))
211 return false;
212 }
213 return true;
214 }
215
216 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
217 /// stackslot register. The register is still available but is no longer
218 /// allowed to be modifed.
219 void disallowClobberPhysReg(unsigned PhysReg);
220
221 /// ClobberPhysReg - This is called when the specified physreg changes
222 /// value. We use this to invalidate any info about stuff that lives in
223 /// it and any of its aliases.
224 void ClobberPhysReg(unsigned PhysReg);
225
226 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
227 /// slot changes. This removes information about which register the
228 /// previous value for this slot lives in (as the previous value is dead
229 /// now).
230 void ModifyStackSlotOrReMat(int SlotOrReMat);
231
232 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
233 /// into the specified MBB. Add available physical registers as potential
234 /// live-in's. If they are reused in the MBB, they will be added to the
235 /// live-in set to make register scavenger and post-allocation scheduler.
236 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
237 std::vector<MachineOperand*> &KillOps);
238};
239
Dan Gohman7db949d2009-08-07 01:32:21 +0000240}
241
Lang Hames87e3bca2009-05-06 02:36:21 +0000242// ************************************************************************ //
243
David Greene2d4e6d32009-07-28 16:49:24 +0000244// Given a location where a reload of a spilled register or a remat of
245// a constant is to be inserted, attempt to find a safe location to
246// insert the load at an earlier point in the basic-block, to hide
247// latency of the load and to avoid address-generation interlock
248// issues.
249static MachineBasicBlock::iterator
250ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
251 MachineBasicBlock::iterator const Begin,
252 unsigned PhysReg,
253 const TargetRegisterInfo *TRI,
254 bool DoReMat,
255 int SSorRMId,
256 const TargetInstrInfo *TII,
257 const MachineFunction &MF)
258{
259 if (!ScheduleSpills)
260 return InsertLoc;
261
262 // Spill backscheduling is of primary interest to addresses, so
263 // don't do anything if the register isn't in the register class
264 // used for pointers.
265
266 const TargetLowering *TL = MF.getTarget().getTargetLowering();
267
268 if (!TL->isTypeLegal(TL->getPointerTy()))
269 // Believe it or not, this is true on PIC16.
270 return InsertLoc;
271
272 const TargetRegisterClass *ptrRegClass =
273 TL->getRegClassFor(TL->getPointerTy());
274 if (!ptrRegClass->contains(PhysReg))
275 return InsertLoc;
276
277 // Scan upwards through the preceding instructions. If an instruction doesn't
278 // reference the stack slot or the register we're loading, we can
279 // backschedule the reload up past it.
280 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
281 while (NewInsertLoc != Begin) {
282 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
283 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
284 MachineOperand &Op = Prev->getOperand(i);
285 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
286 goto stop;
287 }
288 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
289 Prev->findRegisterDefOperand(PhysReg))
290 goto stop;
291 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
292 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
293 Prev->findRegisterDefOperand(*Alias))
294 goto stop;
295 NewInsertLoc = Prev;
296 }
297stop:;
298
299 // If we made it to the beginning of the block, turn around and move back
300 // down just past any existing reloads. They're likely to be reloads/remats
301 // for instructions earlier than what our current reload/remat is for, so
302 // they should be scheduled earlier.
303 if (NewInsertLoc == Begin) {
304 int FrameIdx;
305 while (InsertLoc != NewInsertLoc &&
306 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
307 TII->isTriviallyReMaterializable(NewInsertLoc)))
308 ++NewInsertLoc;
309 }
310
311 return NewInsertLoc;
312}
Dan Gohman7db949d2009-08-07 01:32:21 +0000313
314namespace {
315
Lang Hames87e3bca2009-05-06 02:36:21 +0000316// ReusedOp - For each reused operand, we keep track of a bit of information,
317// in case we need to rollback upon processing a new operand. See comments
318// below.
319struct ReusedOp {
320 // The MachineInstr operand that reused an available value.
321 unsigned Operand;
322
323 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
324 unsigned StackSlotOrReMat;
325
326 // PhysRegReused - The physical register the value was available in.
327 unsigned PhysRegReused;
328
329 // AssignedPhysReg - The physreg that was assigned for use by the reload.
330 unsigned AssignedPhysReg;
331
332 // VirtReg - The virtual register itself.
333 unsigned VirtReg;
334
335 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
336 unsigned vreg)
337 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
338 AssignedPhysReg(apr), VirtReg(vreg) {}
339};
340
341/// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
342/// is reused instead of reloaded.
343class VISIBILITY_HIDDEN ReuseInfo {
344 MachineInstr &MI;
345 std::vector<ReusedOp> Reuses;
346 BitVector PhysRegsClobbered;
347public:
348 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
349 PhysRegsClobbered.resize(tri->getNumRegs());
350 }
351
352 bool hasReuses() const {
353 return !Reuses.empty();
354 }
355
356 /// addReuse - If we choose to reuse a virtual register that is already
357 /// available instead of reloading it, remember that we did so.
358 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
359 unsigned PhysRegReused, unsigned AssignedPhysReg,
360 unsigned VirtReg) {
361 // If the reload is to the assigned register anyway, no undo will be
362 // required.
363 if (PhysRegReused == AssignedPhysReg) return;
364
365 // Otherwise, remember this.
366 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
367 AssignedPhysReg, VirtReg));
368 }
369
370 void markClobbered(unsigned PhysReg) {
371 PhysRegsClobbered.set(PhysReg);
372 }
373
374 bool isClobbered(unsigned PhysReg) const {
375 return PhysRegsClobbered.test(PhysReg);
376 }
377
378 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
379 /// is some other operand that is using the specified register, either pick
380 /// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000381 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
382 MachineFunction &MF, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000383 AvailableSpills &Spills,
384 std::vector<MachineInstr*> &MaybeDeadStores,
385 SmallSet<unsigned, 8> &Rejected,
386 BitVector &RegKills,
387 std::vector<MachineOperand*> &KillOps,
388 VirtRegMap &VRM);
389
390 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
391 /// 'Rejected' set to remember which registers have been considered and
392 /// rejected for the reload. This avoids infinite looping in case like
393 /// this:
394 /// t1 := op t2, t3
395 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
396 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
397 /// t1 <- desires r1
398 /// sees r1 is taken by t2, tries t2's reload register r0
399 /// sees r0 is taken by t3, tries t3's reload register r1
400 /// sees r1 is taken by t2, tries t2's reload register r0 ...
Evan Cheng5d885022009-07-21 09:15:00 +0000401 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000402 AvailableSpills &Spills,
403 std::vector<MachineInstr*> &MaybeDeadStores,
404 BitVector &RegKills,
405 std::vector<MachineOperand*> &KillOps,
406 VirtRegMap &VRM) {
407 SmallSet<unsigned, 8> Rejected;
Evan Cheng5d885022009-07-21 09:15:00 +0000408 MachineFunction &MF = *MI->getParent()->getParent();
409 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
410 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
411 Rejected, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +0000412 }
413};
414
Dan Gohman7db949d2009-08-07 01:32:21 +0000415}
Lang Hames87e3bca2009-05-06 02:36:21 +0000416
417// ****************** //
418// Utility Functions //
419// ****************** //
420
Lang Hames87e3bca2009-05-06 02:36:21 +0000421/// findSinglePredSuccessor - Return via reference a vector of machine basic
422/// blocks each of which is a successor of the specified BB and has no other
423/// predecessor.
424static void findSinglePredSuccessor(MachineBasicBlock *MBB,
425 SmallVectorImpl<MachineBasicBlock *> &Succs) {
426 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
427 SE = MBB->succ_end(); SI != SE; ++SI) {
428 MachineBasicBlock *SuccMBB = *SI;
429 if (SuccMBB->pred_size() == 1)
430 Succs.push_back(SuccMBB);
431 }
432}
433
Evan Cheng427a6b62009-05-15 06:48:19 +0000434/// InvalidateKill - Invalidate register kill information for a specific
435/// register. This also unsets the kills marker on the last kill operand.
436static void InvalidateKill(unsigned Reg,
437 const TargetRegisterInfo* TRI,
438 BitVector &RegKills,
439 std::vector<MachineOperand*> &KillOps) {
440 if (RegKills[Reg]) {
441 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000442 // KillOps[Reg] might be a def of a super-register.
443 unsigned KReg = KillOps[Reg]->getReg();
444 KillOps[KReg] = NULL;
445 RegKills.reset(KReg);
446 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
Evan Cheng427a6b62009-05-15 06:48:19 +0000447 if (RegKills[*SR]) {
448 KillOps[*SR]->setIsKill(false);
449 KillOps[*SR] = NULL;
450 RegKills.reset(*SR);
451 }
452 }
453 }
454}
455
Lang Hames87e3bca2009-05-06 02:36:21 +0000456/// InvalidateKills - MI is going to be deleted. If any of its operands are
457/// marked kill, then invalidate the information.
Evan Cheng427a6b62009-05-15 06:48:19 +0000458static void InvalidateKills(MachineInstr &MI,
459 const TargetRegisterInfo* TRI,
460 BitVector &RegKills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000461 std::vector<MachineOperand*> &KillOps,
462 SmallVector<unsigned, 2> *KillRegs = NULL) {
463 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
464 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000465 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000466 continue;
467 unsigned Reg = MO.getReg();
468 if (TargetRegisterInfo::isVirtualRegister(Reg))
469 continue;
470 if (KillRegs)
471 KillRegs->push_back(Reg);
472 assert(Reg < KillOps.size());
473 if (KillOps[Reg] == &MO) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000474 KillOps[Reg] = NULL;
Evan Cheng427a6b62009-05-15 06:48:19 +0000475 RegKills.reset(Reg);
476 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
477 if (RegKills[*SR]) {
478 KillOps[*SR] = NULL;
479 RegKills.reset(*SR);
480 }
481 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000482 }
483 }
484}
485
486/// InvalidateRegDef - If the def operand of the specified def MI is now dead
487/// (since it's spill instruction is removed), mark it isDead. Also checks if
488/// the def MI has other definition operands that are not dead. Returns it by
489/// reference.
490static bool InvalidateRegDef(MachineBasicBlock::iterator I,
491 MachineInstr &NewDef, unsigned Reg,
492 bool &HasLiveDef) {
493 // Due to remat, it's possible this reg isn't being reused. That is,
494 // the def of this reg (by prev MI) is now dead.
495 MachineInstr *DefMI = I;
496 MachineOperand *DefOp = NULL;
497 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
498 MachineOperand &MO = DefMI->getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000499 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
500 continue;
501 if (MO.getReg() == Reg)
502 DefOp = &MO;
503 else if (!MO.isDead())
504 HasLiveDef = true;
Lang Hames87e3bca2009-05-06 02:36:21 +0000505 }
506 if (!DefOp)
507 return false;
508
509 bool FoundUse = false, Done = false;
510 MachineBasicBlock::iterator E = &NewDef;
511 ++I; ++E;
512 for (; !Done && I != E; ++I) {
513 MachineInstr *NMI = I;
514 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
515 MachineOperand &MO = NMI->getOperand(j);
516 if (!MO.isReg() || MO.getReg() != Reg)
517 continue;
518 if (MO.isUse())
519 FoundUse = true;
520 Done = true; // Stop after scanning all the operands of this MI.
521 }
522 }
523 if (!FoundUse) {
524 // Def is dead!
525 DefOp->setIsDead();
526 return true;
527 }
528 return false;
529}
530
531/// UpdateKills - Track and update kill info. If a MI reads a register that is
532/// marked kill, then it must be due to register reuse. Transfer the kill info
533/// over.
Evan Cheng427a6b62009-05-15 06:48:19 +0000534static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
535 BitVector &RegKills,
536 std::vector<MachineOperand*> &KillOps) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000537 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
538 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000539 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000540 continue;
541 unsigned Reg = MO.getReg();
542 if (Reg == 0)
543 continue;
544
545 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
546 // That can't be right. Register is killed but not re-defined and it's
547 // being reused. Let's fix that.
548 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000549 // KillOps[Reg] might be a def of a super-register.
550 unsigned KReg = KillOps[Reg]->getReg();
551 KillOps[KReg] = NULL;
552 RegKills.reset(KReg);
553
554 // Must be a def of a super-register. Its other sub-regsters are no
555 // longer killed as well.
556 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
557 KillOps[*SR] = NULL;
558 RegKills.reset(*SR);
559 }
560
Lang Hames87e3bca2009-05-06 02:36:21 +0000561 if (!MI.isRegTiedToDefOperand(i))
562 // Unless it's a two-address operand, this is the new kill.
563 MO.setIsKill();
564 }
565 if (MO.isKill()) {
566 RegKills.set(Reg);
567 KillOps[Reg] = &MO;
Evan Cheng427a6b62009-05-15 06:48:19 +0000568 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
569 RegKills.set(*SR);
570 KillOps[*SR] = &MO;
571 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000572 }
573 }
574
575 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
576 const MachineOperand &MO = MI.getOperand(i);
577 if (!MO.isReg() || !MO.isDef())
578 continue;
579 unsigned Reg = MO.getReg();
580 RegKills.reset(Reg);
581 KillOps[Reg] = NULL;
582 // It also defines (or partially define) aliases.
Evan Cheng427a6b62009-05-15 06:48:19 +0000583 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
584 RegKills.reset(*SR);
585 KillOps[*SR] = NULL;
Lang Hames87e3bca2009-05-06 02:36:21 +0000586 }
587 }
588}
589
590/// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
591///
592static void ReMaterialize(MachineBasicBlock &MBB,
593 MachineBasicBlock::iterator &MII,
594 unsigned DestReg, unsigned Reg,
595 const TargetInstrInfo *TII,
596 const TargetRegisterInfo *TRI,
597 VirtRegMap &VRM) {
Evan Cheng5f159922009-07-16 20:15:00 +0000598 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
Daniel Dunbar24cd3c42009-07-16 22:08:25 +0000599#ifndef NDEBUG
Evan Cheng5f159922009-07-16 20:15:00 +0000600 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
Evan Chengc1b46f92009-07-17 00:32:06 +0000601 assert(TID.getNumDefs() == 1 &&
Evan Cheng5f159922009-07-16 20:15:00 +0000602 "Don't know how to remat instructions that define > 1 values!");
603#endif
604 TII->reMaterialize(MBB, MII, DestReg,
605 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000606 MachineInstr *NewMI = prior(MII);
607 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
608 MachineOperand &MO = NewMI->getOperand(i);
609 if (!MO.isReg() || MO.getReg() == 0)
610 continue;
611 unsigned VirtReg = MO.getReg();
612 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
613 continue;
614 assert(MO.isUse());
615 unsigned SubIdx = MO.getSubReg();
616 unsigned Phys = VRM.getPhys(VirtReg);
617 assert(Phys);
618 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
619 MO.setReg(RReg);
620 MO.setSubReg(0);
621 }
622 ++NumReMats;
623}
624
625/// findSuperReg - Find the SubReg's super-register of given register class
626/// where its SubIdx sub-register is SubReg.
627static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
628 unsigned SubIdx, const TargetRegisterInfo *TRI) {
629 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
630 I != E; ++I) {
631 unsigned Reg = *I;
632 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
633 return Reg;
634 }
635 return 0;
636}
637
638// ******************************** //
639// Available Spills Implementation //
640// ******************************** //
641
642/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
643/// stackslot register. The register is still available but is no longer
644/// allowed to be modifed.
645void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
646 std::multimap<unsigned, int>::iterator I =
647 PhysRegsAvailable.lower_bound(PhysReg);
648 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
649 int SlotOrReMat = I->second;
650 I++;
651 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
652 "Bidirectional map mismatch!");
653 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
Chris Lattner6456d382009-08-23 03:20:44 +0000654 DEBUG(errs() << "PhysReg " << TRI->getName(PhysReg)
655 << " copied, it is available for use but can no longer be modified\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000656 }
657}
658
659/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
660/// stackslot register and its aliases. The register and its aliases may
661/// still available but is no longer allowed to be modifed.
662void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
663 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
664 disallowClobberPhysRegOnly(*AS);
665 disallowClobberPhysRegOnly(PhysReg);
666}
667
668/// ClobberPhysRegOnly - This is called when the specified physreg changes
669/// value. We use this to invalidate any info about stuff we thing lives in it.
670void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
671 std::multimap<unsigned, int>::iterator I =
672 PhysRegsAvailable.lower_bound(PhysReg);
673 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
674 int SlotOrReMat = I->second;
675 PhysRegsAvailable.erase(I++);
676 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
677 "Bidirectional map mismatch!");
678 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
Chris Lattner6456d382009-08-23 03:20:44 +0000679 DEBUG(errs() << "PhysReg " << TRI->getName(PhysReg)
680 << " clobbered, invalidating ");
Lang Hames87e3bca2009-05-06 02:36:21 +0000681 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
Chris Lattner6456d382009-08-23 03:20:44 +0000682 DEBUG(errs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000683 else
Chris Lattner6456d382009-08-23 03:20:44 +0000684 DEBUG(errs() << "SS#" << SlotOrReMat << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000685 }
686}
687
688/// ClobberPhysReg - This is called when the specified physreg changes
689/// value. We use this to invalidate any info about stuff we thing lives in
690/// it and any of its aliases.
691void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
692 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
693 ClobberPhysRegOnly(*AS);
694 ClobberPhysRegOnly(PhysReg);
695}
696
697/// AddAvailableRegsToLiveIn - Availability information is being kept coming
698/// into the specified MBB. Add available physical registers as potential
699/// live-in's. If they are reused in the MBB, they will be added to the
700/// live-in set to make register scavenger and post-allocation scheduler.
701void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
702 BitVector &RegKills,
703 std::vector<MachineOperand*> &KillOps) {
704 std::set<unsigned> NotAvailable;
705 for (std::multimap<unsigned, int>::iterator
706 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
707 I != E; ++I) {
708 unsigned Reg = I->first;
709 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
710 // FIXME: A temporary workaround. We can't reuse available value if it's
711 // not safe to move the def of the virtual register's class. e.g.
712 // X86::RFP* register classes. Do not add it as a live-in.
713 if (!TII->isSafeToMoveRegClassDefs(RC))
714 // This is no longer available.
715 NotAvailable.insert(Reg);
716 else {
717 MBB.addLiveIn(Reg);
Evan Cheng427a6b62009-05-15 06:48:19 +0000718 InvalidateKill(Reg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +0000719 }
720
721 // Skip over the same register.
722 std::multimap<unsigned, int>::iterator NI = next(I);
723 while (NI != E && NI->first == Reg) {
724 ++I;
725 ++NI;
726 }
727 }
728
729 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
730 E = NotAvailable.end(); I != E; ++I) {
731 ClobberPhysReg(*I);
732 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
733 *SubRegs; ++SubRegs)
734 ClobberPhysReg(*SubRegs);
735 }
736}
737
738/// ModifyStackSlotOrReMat - This method is called when the value in a stack
739/// slot changes. This removes information about which register the previous
740/// value for this slot lives in (as the previous value is dead now).
741void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
742 std::map<int, unsigned>::iterator It =
743 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
744 if (It == SpillSlotsOrReMatsAvailable.end()) return;
745 unsigned Reg = It->second >> 1;
746 SpillSlotsOrReMatsAvailable.erase(It);
747
748 // This register may hold the value of multiple stack slots, only remove this
749 // stack slot from the set of values the register contains.
750 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
751 for (; ; ++I) {
752 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
753 "Map inverse broken!");
754 if (I->second == SlotOrReMat) break;
755 }
756 PhysRegsAvailable.erase(I);
757}
758
759// ************************** //
760// Reuse Info Implementation //
761// ************************** //
762
763/// GetRegForReload - We are about to emit a reload into PhysReg. If there
764/// is some other operand that is using the specified register, either pick
765/// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000766unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
767 unsigned PhysReg,
768 MachineFunction &MF,
769 MachineInstr *MI, AvailableSpills &Spills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000770 std::vector<MachineInstr*> &MaybeDeadStores,
771 SmallSet<unsigned, 8> &Rejected,
772 BitVector &RegKills,
773 std::vector<MachineOperand*> &KillOps,
774 VirtRegMap &VRM) {
Evan Cheng5d885022009-07-21 09:15:00 +0000775 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
776 const TargetRegisterInfo *TRI = Spills.getRegInfo();
Lang Hames87e3bca2009-05-06 02:36:21 +0000777
778 if (Reuses.empty()) return PhysReg; // This is most often empty.
779
780 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
781 ReusedOp &Op = Reuses[ro];
782 // If we find some other reuse that was supposed to use this register
783 // exactly for its reload, we can change this reload to use ITS reload
784 // register. That is, unless its reload register has already been
785 // considered and subsequently rejected because it has also been reused
786 // by another operand.
787 if (Op.PhysRegReused == PhysReg &&
Evan Cheng5d885022009-07-21 09:15:00 +0000788 Rejected.count(Op.AssignedPhysReg) == 0 &&
789 RC->contains(Op.AssignedPhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000790 // Yup, use the reload register that we didn't use before.
791 unsigned NewReg = Op.AssignedPhysReg;
792 Rejected.insert(PhysReg);
Evan Cheng5d885022009-07-21 09:15:00 +0000793 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
Lang Hames87e3bca2009-05-06 02:36:21 +0000794 RegKills, KillOps, VRM);
795 } else {
796 // Otherwise, we might also have a problem if a previously reused
Evan Cheng5d885022009-07-21 09:15:00 +0000797 // value aliases the new register. If so, codegen the previous reload
Lang Hames87e3bca2009-05-06 02:36:21 +0000798 // and use this one.
799 unsigned PRRU = Op.PhysRegReused;
Lang Hames3f2f3f52009-09-03 02:52:02 +0000800 if (TRI->regsOverlap(PRRU, PhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000801 // Okay, we found out that an alias of a reused register
802 // was used. This isn't good because it means we have
803 // to undo a previous reuse.
804 MachineBasicBlock *MBB = MI->getParent();
805 const TargetRegisterClass *AliasRC =
806 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
807
808 // Copy Op out of the vector and remove it, we're going to insert an
809 // explicit load for it.
810 ReusedOp NewOp = Op;
811 Reuses.erase(Reuses.begin()+ro);
812
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000813 // MI may be using only a sub-register of PhysRegUsed.
814 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
815 unsigned SubIdx = 0;
816 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
817 "A reuse cannot be a virtual register");
818 if (PRRU != RealPhysRegUsed) {
819 // What was the sub-register index?
820 unsigned SubReg;
821 for (SubIdx = 1; (SubReg = TRI->getSubReg(PRRU, SubIdx)); SubIdx++)
822 if (SubReg == RealPhysRegUsed)
823 break;
824 assert(SubReg == RealPhysRegUsed &&
825 "Operand physreg is not a sub-register of PhysRegUsed");
826 }
827
Lang Hames87e3bca2009-05-06 02:36:21 +0000828 // Ok, we're going to try to reload the assigned physreg into the
829 // slot that we were supposed to in the first place. However, that
830 // register could hold a reuse. Check to see if it conflicts or
831 // would prefer us to use a different register.
Evan Cheng5d885022009-07-21 09:15:00 +0000832 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
833 MF, MI, Spills, MaybeDeadStores,
834 Rejected, RegKills, KillOps, VRM);
David Greene2d4e6d32009-07-28 16:49:24 +0000835
836 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
837 int SSorRMId = DoReMat
838 ? VRM.getReMatId(NewOp.VirtReg) : NewOp.StackSlotOrReMat;
839
840 // Back-schedule reloads and remats.
841 MachineBasicBlock::iterator InsertLoc =
842 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
843 DoReMat, SSorRMId, TII, MF);
844
845 if (DoReMat) {
846 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
847 TRI, VRM);
848 } else {
849 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
Lang Hames87e3bca2009-05-06 02:36:21 +0000850 NewOp.StackSlotOrReMat, AliasRC);
David Greene2d4e6d32009-07-28 16:49:24 +0000851 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +0000852 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
853 // Any stores to this stack slot are not dead anymore.
854 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
855 ++NumLoads;
856 }
857 Spills.ClobberPhysReg(NewPhysReg);
858 Spills.ClobberPhysReg(NewOp.PhysRegReused);
859
Lang Hames87e3bca2009-05-06 02:36:21 +0000860 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
861 MI->getOperand(NewOp.Operand).setReg(RReg);
862 MI->getOperand(NewOp.Operand).setSubReg(0);
863
864 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
David Greene2d4e6d32009-07-28 16:49:24 +0000865 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
Chris Lattner6456d382009-08-23 03:20:44 +0000866 DEBUG(errs() << '\t' << *prior(InsertLoc));
Lang Hames87e3bca2009-05-06 02:36:21 +0000867
Chris Lattner6456d382009-08-23 03:20:44 +0000868 DEBUG(errs() << "Reuse undone!\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000869 --NumReused;
870
871 // Finally, PhysReg is now available, go ahead and use it.
872 return PhysReg;
873 }
874 }
875 }
876 return PhysReg;
877}
878
879// ************************************************************************ //
880
881/// FoldsStackSlotModRef - Return true if the specified MI folds the specified
882/// stack slot mod/ref. It also checks if it's possible to unfold the
883/// instruction by having it define a specified physical register instead.
884static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
885 const TargetInstrInfo *TII,
886 const TargetRegisterInfo *TRI,
887 VirtRegMap &VRM) {
888 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
889 return false;
890
891 bool Found = false;
892 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
893 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
894 unsigned VirtReg = I->second.first;
895 VirtRegMap::ModRef MR = I->second.second;
896 if (MR & VirtRegMap::isModRef)
897 if (VRM.getStackSlot(VirtReg) == SS) {
898 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
899 break;
900 }
901 }
902 if (!Found)
903 return false;
904
905 // Does the instruction uses a register that overlaps the scratch register?
906 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
907 MachineOperand &MO = MI.getOperand(i);
908 if (!MO.isReg() || MO.getReg() == 0)
909 continue;
910 unsigned Reg = MO.getReg();
911 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
912 if (!VRM.hasPhys(Reg))
913 continue;
914 Reg = VRM.getPhys(Reg);
915 }
916 if (TRI->regsOverlap(PhysReg, Reg))
917 return false;
918 }
919 return true;
920}
921
922/// FindFreeRegister - Find a free register of a given register class by looking
923/// at (at most) the last two machine instructions.
924static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
925 MachineBasicBlock &MBB,
926 const TargetRegisterClass *RC,
927 const TargetRegisterInfo *TRI,
928 BitVector &AllocatableRegs) {
929 BitVector Defs(TRI->getNumRegs());
930 BitVector Uses(TRI->getNumRegs());
931 SmallVector<unsigned, 4> LocalUses;
932 SmallVector<unsigned, 4> Kills;
933
934 // Take a look at 2 instructions at most.
935 for (unsigned Count = 0; Count < 2; ++Count) {
936 if (MII == MBB.begin())
937 break;
938 MachineInstr *PrevMI = prior(MII);
939 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
940 MachineOperand &MO = PrevMI->getOperand(i);
941 if (!MO.isReg() || MO.getReg() == 0)
942 continue;
943 unsigned Reg = MO.getReg();
944 if (MO.isDef()) {
945 Defs.set(Reg);
946 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
947 Defs.set(*AS);
948 } else {
949 LocalUses.push_back(Reg);
950 if (MO.isKill() && AllocatableRegs[Reg])
951 Kills.push_back(Reg);
952 }
953 }
954
955 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
956 unsigned Kill = Kills[i];
957 if (!Defs[Kill] && !Uses[Kill] &&
958 TRI->getPhysicalRegisterRegClass(Kill) == RC)
959 return Kill;
960 }
961 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
962 unsigned Reg = LocalUses[i];
963 Uses.set(Reg);
964 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
965 Uses.set(*AS);
966 }
967
968 MII = PrevMI;
969 }
970
971 return 0;
972}
973
974static
975void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
976 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
977 MachineOperand &MO = MI->getOperand(i);
978 if (MO.isReg() && MO.getReg() == VirtReg)
979 MO.setReg(PhysReg);
980 }
981}
982
Evan Chengeca24fb2009-05-12 23:07:00 +0000983namespace {
984 struct RefSorter {
985 bool operator()(const std::pair<MachineInstr*, int> &A,
986 const std::pair<MachineInstr*, int> &B) {
987 return A.second < B.second;
988 }
989 };
990}
Lang Hames87e3bca2009-05-06 02:36:21 +0000991
992// ***************************** //
993// Local Spiller Implementation //
994// ***************************** //
995
Dan Gohman7db949d2009-08-07 01:32:21 +0000996namespace {
997
Lang Hames87e3bca2009-05-06 02:36:21 +0000998class VISIBILITY_HIDDEN LocalRewriter : public VirtRegRewriter {
999 MachineRegisterInfo *RegInfo;
1000 const TargetRegisterInfo *TRI;
1001 const TargetInstrInfo *TII;
1002 BitVector AllocatableRegs;
1003 DenseMap<MachineInstr*, unsigned> DistanceMap;
1004public:
1005
1006 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1007 LiveIntervals* LIs) {
1008 RegInfo = &MF.getRegInfo();
1009 TRI = MF.getTarget().getRegisterInfo();
1010 TII = MF.getTarget().getInstrInfo();
1011 AllocatableRegs = TRI->getAllocatableSet(MF);
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001012 DEBUG(errs() << "\n**** Local spiller rewriting function '"
1013 << MF.getFunction()->getName() << "':\n");
Chris Lattner6456d382009-08-23 03:20:44 +00001014 DEBUG(errs() << "**** Machine Instrs (NOTE! Does not include spills and"
1015 " reloads!) ****\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001016 DEBUG(MF.dump());
1017
1018 // Spills - Keep track of which spilled values are available in physregs
1019 // so that we can choose to reuse the physregs instead of emitting
1020 // reloads. This is usually refreshed per basic block.
1021 AvailableSpills Spills(TRI, TII);
1022
1023 // Keep track of kill information.
1024 BitVector RegKills(TRI->getNumRegs());
1025 std::vector<MachineOperand*> KillOps;
1026 KillOps.resize(TRI->getNumRegs(), NULL);
1027
1028 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1029 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1030 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1031
1032 // Traverse the basic blocks depth first.
1033 MachineBasicBlock *Entry = MF.begin();
1034 SmallPtrSet<MachineBasicBlock*,16> Visited;
1035 for (df_ext_iterator<MachineBasicBlock*,
1036 SmallPtrSet<MachineBasicBlock*,16> >
1037 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1038 DFI != E; ++DFI) {
1039 MachineBasicBlock *MBB = *DFI;
1040 if (!EarlyVisited.count(MBB))
1041 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1042
1043 // If this MBB is the only predecessor of a successor. Keep the
1044 // availability information and visit it next.
1045 do {
1046 // Keep visiting single predecessor successor as long as possible.
1047 SinglePredSuccs.clear();
1048 findSinglePredSuccessor(MBB, SinglePredSuccs);
1049 if (SinglePredSuccs.empty())
1050 MBB = 0;
1051 else {
1052 // FIXME: More than one successors, each of which has MBB has
1053 // the only predecessor.
1054 MBB = SinglePredSuccs[0];
1055 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1056 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1057 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1058 }
1059 }
1060 } while (MBB);
1061
1062 // Clear the availability info.
1063 Spills.clear();
1064 }
1065
Chris Lattner6456d382009-08-23 03:20:44 +00001066 DEBUG(errs() << "**** Post Machine Instrs ****\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001067 DEBUG(MF.dump());
1068
1069 // Mark unused spill slots.
1070 MachineFrameInfo *MFI = MF.getFrameInfo();
1071 int SS = VRM.getLowSpillSlot();
1072 if (SS != VirtRegMap::NO_STACK_SLOT)
1073 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
1074 if (!VRM.isSpillSlotUsed(SS)) {
1075 MFI->RemoveStackObject(SS);
1076 ++NumDSS;
1077 }
1078
1079 return true;
1080 }
1081
1082private:
1083
1084 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1085 /// a scratch register is available.
1086 /// xorq %r12<kill>, %r13
1087 /// addq %rax, -184(%rbp)
1088 /// addq %r13, -184(%rbp)
1089 /// ==>
1090 /// xorq %r12<kill>, %r13
1091 /// movq -184(%rbp), %r12
1092 /// addq %rax, %r12
1093 /// addq %r13, %r12
1094 /// movq %r12, -184(%rbp)
1095 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1096 MachineBasicBlock &MBB,
1097 MachineBasicBlock::iterator &MII,
1098 std::vector<MachineInstr*> &MaybeDeadStores,
1099 AvailableSpills &Spills,
1100 BitVector &RegKills,
1101 std::vector<MachineOperand*> &KillOps,
1102 VirtRegMap &VRM) {
1103
1104 MachineBasicBlock::iterator NextMII = next(MII);
1105 if (NextMII == MBB.end())
1106 return false;
1107
1108 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1109 return false;
1110
1111 // Now let's see if the last couple of instructions happens to have freed up
1112 // a register.
1113 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1114 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
1115 if (!PhysReg)
1116 return false;
1117
1118 MachineFunction &MF = *MBB.getParent();
1119 TRI = MF.getTarget().getRegisterInfo();
1120 MachineInstr &MI = *MII;
1121 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
1122 return false;
1123
1124 // If the next instruction also folds the same SS modref and can be unfoled,
1125 // then it's worthwhile to issue a load from SS into the free register and
1126 // then unfold these instructions.
1127 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
1128 return false;
1129
David Greene2d4e6d32009-07-28 16:49:24 +00001130 // Back-schedule reloads and remats.
Duncan Sandsb7c5bdf2009-09-06 08:33:48 +00001131 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, false, SS, TII, MF);
David Greene2d4e6d32009-07-28 16:49:24 +00001132
Lang Hames87e3bca2009-05-06 02:36:21 +00001133 // Load from SS to the spare physical register.
1134 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1135 // This invalidates Phys.
1136 Spills.ClobberPhysReg(PhysReg);
1137 // Remember it's available.
1138 Spills.addAvailable(SS, PhysReg);
1139 MaybeDeadStores[SS] = NULL;
1140
1141 // Unfold current MI.
1142 SmallVector<MachineInstr*, 4> NewMIs;
1143 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
Torok Edwinc23197a2009-07-14 16:55:14 +00001144 llvm_unreachable("Unable unfold the load / store folding instruction!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001145 assert(NewMIs.size() == 1);
1146 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1147 VRM.transferRestorePts(&MI, NewMIs[0]);
1148 MII = MBB.insert(MII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001149 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001150 VRM.RemoveMachineInstrFromMaps(&MI);
1151 MBB.erase(&MI);
1152 ++NumModRefUnfold;
1153
1154 // Unfold next instructions that fold the same SS.
1155 do {
1156 MachineInstr &NextMI = *NextMII;
1157 NextMII = next(NextMII);
1158 NewMIs.clear();
1159 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
Torok Edwinc23197a2009-07-14 16:55:14 +00001160 llvm_unreachable("Unable unfold the load / store folding instruction!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001161 assert(NewMIs.size() == 1);
1162 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1163 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1164 MBB.insert(NextMII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001165 InvalidateKills(NextMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001166 VRM.RemoveMachineInstrFromMaps(&NextMI);
1167 MBB.erase(&NextMI);
1168 ++NumModRefUnfold;
Evan Cheng2c48fe62009-06-03 09:00:27 +00001169 if (NextMII == MBB.end())
1170 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001171 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1172
1173 // Store the value back into SS.
1174 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1175 MachineInstr *StoreMI = prior(NextMII);
1176 VRM.addSpillSlotUse(SS, StoreMI);
1177 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1178
1179 return true;
1180 }
1181
1182 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1183 /// instruction. e.g.
1184 /// xorl %edi, %eax
1185 /// movl %eax, -32(%ebp)
1186 /// movl -36(%ebp), %eax
1187 /// orl %eax, -32(%ebp)
1188 /// ==>
1189 /// xorl %edi, %eax
1190 /// orl -36(%ebp), %eax
1191 /// mov %eax, -32(%ebp)
1192 /// This enables unfolding optimization for a subsequent instruction which will
1193 /// also eliminate the newly introduced store instruction.
1194 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1195 MachineBasicBlock::iterator &MII,
1196 std::vector<MachineInstr*> &MaybeDeadStores,
1197 AvailableSpills &Spills,
1198 BitVector &RegKills,
1199 std::vector<MachineOperand*> &KillOps,
1200 VirtRegMap &VRM) {
1201 MachineFunction &MF = *MBB.getParent();
1202 MachineInstr &MI = *MII;
1203 unsigned UnfoldedOpc = 0;
1204 unsigned UnfoldPR = 0;
1205 unsigned UnfoldVR = 0;
1206 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1207 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1208 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1209 // Only transform a MI that folds a single register.
1210 if (UnfoldedOpc)
1211 return false;
1212 UnfoldVR = I->second.first;
1213 VirtRegMap::ModRef MR = I->second.second;
1214 // MI2VirtMap be can updated which invalidate the iterator.
1215 // Increment the iterator first.
1216 ++I;
1217 if (VRM.isAssignedReg(UnfoldVR))
1218 continue;
1219 // If this reference is not a use, any previous store is now dead.
1220 // Otherwise, the store to this stack slot is not dead anymore.
1221 FoldedSS = VRM.getStackSlot(UnfoldVR);
1222 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1223 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1224 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1225 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1226 continue;
1227 UnfoldPR = PhysReg;
1228 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1229 false, true);
1230 }
1231 }
1232
1233 if (!UnfoldedOpc) {
1234 if (!UnfoldVR)
1235 return false;
1236
1237 // Look for other unfolding opportunities.
1238 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1239 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1240 }
1241
1242 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1243 MachineOperand &MO = MI.getOperand(i);
1244 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1245 continue;
1246 unsigned VirtReg = MO.getReg();
1247 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1248 continue;
1249 if (VRM.isAssignedReg(VirtReg)) {
1250 unsigned PhysReg = VRM.getPhys(VirtReg);
1251 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1252 return false;
1253 } else if (VRM.isReMaterialized(VirtReg))
1254 continue;
1255 int SS = VRM.getStackSlot(VirtReg);
1256 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1257 if (PhysReg) {
1258 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1259 return false;
1260 continue;
1261 }
1262 if (VRM.hasPhys(VirtReg)) {
1263 PhysReg = VRM.getPhys(VirtReg);
1264 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1265 continue;
1266 }
1267
1268 // Ok, we'll need to reload the value into a register which makes
1269 // it impossible to perform the store unfolding optimization later.
1270 // Let's see if it is possible to fold the load if the store is
1271 // unfolded. This allows us to perform the store unfolding
1272 // optimization.
1273 SmallVector<MachineInstr*, 4> NewMIs;
1274 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1275 assert(NewMIs.size() == 1);
1276 MachineInstr *NewMI = NewMIs.back();
1277 NewMIs.clear();
1278 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1279 assert(Idx != -1);
1280 SmallVector<unsigned, 1> Ops;
1281 Ops.push_back(Idx);
1282 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1283 if (FoldedMI) {
1284 VRM.addSpillSlotUse(SS, FoldedMI);
1285 if (!VRM.hasPhys(UnfoldVR))
1286 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1287 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1288 MII = MBB.insert(MII, FoldedMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001289 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001290 VRM.RemoveMachineInstrFromMaps(&MI);
1291 MBB.erase(&MI);
1292 MF.DeleteMachineInstr(NewMI);
1293 return true;
1294 }
1295 MF.DeleteMachineInstr(NewMI);
1296 }
1297 }
1298
1299 return false;
1300 }
1301
Evan Cheng261ce1d2009-07-10 19:15:51 +00001302 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1303 /// where SrcReg is r1 and it is tied to r0. Return true if after
1304 /// commuting this instruction it will be r0 = op r2, r1.
1305 static bool CommuteChangesDestination(MachineInstr *DefMI,
1306 const TargetInstrDesc &TID,
1307 unsigned SrcReg,
1308 const TargetInstrInfo *TII,
1309 unsigned &DstIdx) {
1310 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1311 return false;
1312 if (!DefMI->getOperand(1).isReg() ||
1313 DefMI->getOperand(1).getReg() != SrcReg)
1314 return false;
1315 unsigned DefIdx;
1316 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1317 return false;
1318 unsigned SrcIdx1, SrcIdx2;
1319 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1320 return false;
1321 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1322 DstIdx = 2;
1323 return true;
1324 }
1325 return false;
1326 }
1327
Lang Hames87e3bca2009-05-06 02:36:21 +00001328 /// CommuteToFoldReload -
1329 /// Look for
1330 /// r1 = load fi#1
1331 /// r1 = op r1, r2<kill>
1332 /// store r1, fi#1
1333 ///
1334 /// If op is commutable and r2 is killed, then we can xform these to
1335 /// r2 = op r2, fi#1
1336 /// store r2, fi#1
1337 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1338 MachineBasicBlock::iterator &MII,
1339 unsigned VirtReg, unsigned SrcReg, int SS,
1340 AvailableSpills &Spills,
1341 BitVector &RegKills,
1342 std::vector<MachineOperand*> &KillOps,
1343 const TargetRegisterInfo *TRI,
1344 VirtRegMap &VRM) {
1345 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1346 return false;
1347
1348 MachineFunction &MF = *MBB.getParent();
1349 MachineInstr &MI = *MII;
1350 MachineBasicBlock::iterator DefMII = prior(MII);
1351 MachineInstr *DefMI = DefMII;
1352 const TargetInstrDesc &TID = DefMI->getDesc();
1353 unsigned NewDstIdx;
1354 if (DefMII != MBB.begin() &&
1355 TID.isCommutable() &&
Evan Cheng261ce1d2009-07-10 19:15:51 +00001356 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001357 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1358 unsigned NewReg = NewDstMO.getReg();
1359 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1360 return false;
1361 MachineInstr *ReloadMI = prior(DefMII);
1362 int FrameIdx;
1363 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1364 if (DestReg != SrcReg || FrameIdx != SS)
1365 return false;
1366 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1367 if (UseIdx == -1)
1368 return false;
1369 unsigned DefIdx;
1370 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1371 return false;
1372 assert(DefMI->getOperand(DefIdx).isReg() &&
1373 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1374
1375 // Now commute def instruction.
1376 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1377 if (!CommutedMI)
1378 return false;
1379 SmallVector<unsigned, 1> Ops;
1380 Ops.push_back(NewDstIdx);
1381 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1382 // Not needed since foldMemoryOperand returns new MI.
1383 MF.DeleteMachineInstr(CommutedMI);
1384 if (!FoldedMI)
1385 return false;
1386
1387 VRM.addSpillSlotUse(SS, FoldedMI);
1388 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1389 // Insert new def MI and spill MI.
1390 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1391 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1392 MII = prior(MII);
1393 MachineInstr *StoreMI = MII;
1394 VRM.addSpillSlotUse(SS, StoreMI);
1395 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1396 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1397
1398 // Delete all 3 old instructions.
Evan Cheng427a6b62009-05-15 06:48:19 +00001399 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001400 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1401 MBB.erase(ReloadMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001402 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001403 VRM.RemoveMachineInstrFromMaps(DefMI);
1404 MBB.erase(DefMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001405 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001406 VRM.RemoveMachineInstrFromMaps(&MI);
1407 MBB.erase(&MI);
1408
1409 // If NewReg was previously holding value of some SS, it's now clobbered.
1410 // This has to be done now because it's a physical register. When this
1411 // instruction is re-visited, it's ignored.
1412 Spills.ClobberPhysReg(NewReg);
1413
1414 ++NumCommutes;
1415 return true;
1416 }
1417
1418 return false;
1419 }
1420
1421 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1422 /// the last store to the same slot is now dead. If so, remove the last store.
1423 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1424 MachineBasicBlock::iterator &MII,
1425 int Idx, unsigned PhysReg, int StackSlot,
1426 const TargetRegisterClass *RC,
1427 bool isAvailable, MachineInstr *&LastStore,
1428 AvailableSpills &Spills,
1429 SmallSet<MachineInstr*, 4> &ReMatDefs,
1430 BitVector &RegKills,
1431 std::vector<MachineOperand*> &KillOps,
1432 VirtRegMap &VRM) {
1433
1434 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1435 MachineInstr *StoreMI = next(MII);
1436 VRM.addSpillSlotUse(StackSlot, StoreMI);
Chris Lattner6456d382009-08-23 03:20:44 +00001437 DEBUG(errs() << "Store:\t" << *StoreMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001438
1439 // If there is a dead store to this stack slot, nuke it now.
1440 if (LastStore) {
Chris Lattner6456d382009-08-23 03:20:44 +00001441 DEBUG(errs() << "Removed dead store:\t" << *LastStore);
Lang Hames87e3bca2009-05-06 02:36:21 +00001442 ++NumDSE;
1443 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00001444 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00001445 MachineBasicBlock::iterator PrevMII = LastStore;
1446 bool CheckDef = PrevMII != MBB.begin();
1447 if (CheckDef)
1448 --PrevMII;
1449 VRM.RemoveMachineInstrFromMaps(LastStore);
1450 MBB.erase(LastStore);
1451 if (CheckDef) {
1452 // Look at defs of killed registers on the store. Mark the defs
1453 // as dead since the store has been deleted and they aren't
1454 // being reused.
1455 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1456 bool HasOtherDef = false;
1457 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1458 MachineInstr *DeadDef = PrevMII;
1459 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
Evan Cheng4784f1f2009-06-30 08:49:04 +00001460 // FIXME: This assumes a remat def does not have side effects.
Lang Hames87e3bca2009-05-06 02:36:21 +00001461 VRM.RemoveMachineInstrFromMaps(DeadDef);
1462 MBB.erase(DeadDef);
1463 ++NumDRM;
1464 }
1465 }
1466 }
1467 }
1468 }
1469
1470 LastStore = next(MII);
1471
1472 // If the stack slot value was previously available in some other
1473 // register, change it now. Otherwise, make the register available,
1474 // in PhysReg.
1475 Spills.ModifyStackSlotOrReMat(StackSlot);
1476 Spills.ClobberPhysReg(PhysReg);
1477 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1478 ++NumStores;
1479 }
1480
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001481 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1482 /// effect and all of its defs are dead.
1483 static bool isSafeToDelete(MachineInstr &MI) {
1484 const TargetInstrDesc &TID = MI.getDesc();
1485 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1486 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1487 TID.hasUnmodeledSideEffects())
1488 return false;
1489 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1490 MachineOperand &MO = MI.getOperand(i);
1491 if (!MO.isReg() || !MO.getReg())
1492 continue;
1493 if (MO.isDef() && !MO.isDead())
1494 return false;
1495 if (MO.isUse() && MO.isKill())
1496 // FIXME: We can't remove kill markers or else the scavenger will assert.
1497 // An alternative is to add a ADD pseudo instruction to replace kill
1498 // markers.
1499 return false;
1500 }
1501 return true;
1502 }
1503
Lang Hames87e3bca2009-05-06 02:36:21 +00001504 /// TransferDeadness - A identity copy definition is dead and it's being
1505 /// removed. Find the last def or use and mark it as dead / kill.
1506 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1507 unsigned Reg, BitVector &RegKills,
Evan Chengeca24fb2009-05-12 23:07:00 +00001508 std::vector<MachineOperand*> &KillOps,
1509 VirtRegMap &VRM) {
1510 SmallPtrSet<MachineInstr*, 4> Seens;
1511 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
Lang Hames87e3bca2009-05-06 02:36:21 +00001512 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1513 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1514 MachineInstr *UDMI = &*RI;
1515 if (UDMI->getParent() != MBB)
1516 continue;
1517 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1518 if (DI == DistanceMap.end() || DI->second > CurDist)
1519 continue;
Evan Chengeca24fb2009-05-12 23:07:00 +00001520 if (Seens.insert(UDMI))
1521 Refs.push_back(std::make_pair(UDMI, DI->second));
Lang Hames87e3bca2009-05-06 02:36:21 +00001522 }
1523
Evan Chengeca24fb2009-05-12 23:07:00 +00001524 if (Refs.empty())
1525 return;
1526 std::sort(Refs.begin(), Refs.end(), RefSorter());
1527
1528 while (!Refs.empty()) {
1529 MachineInstr *LastUDMI = Refs.back().first;
1530 Refs.pop_back();
1531
Lang Hames87e3bca2009-05-06 02:36:21 +00001532 MachineOperand *LastUD = NULL;
1533 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1534 MachineOperand &MO = LastUDMI->getOperand(i);
1535 if (!MO.isReg() || MO.getReg() != Reg)
1536 continue;
1537 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1538 LastUD = &MO;
1539 if (LastUDMI->isRegTiedToDefOperand(i))
Evan Chengeca24fb2009-05-12 23:07:00 +00001540 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001541 }
Evan Chengeca24fb2009-05-12 23:07:00 +00001542 if (LastUD->isDef()) {
1543 // If the instruction has no side effect, delete it and propagate
1544 // backward further. Otherwise, mark is dead and we are done.
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001545 if (!isSafeToDelete(*LastUDMI)) {
Evan Chengeca24fb2009-05-12 23:07:00 +00001546 LastUD->setIsDead();
1547 break;
1548 }
1549 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1550 MBB->erase(LastUDMI);
1551 } else {
Lang Hames87e3bca2009-05-06 02:36:21 +00001552 LastUD->setIsKill();
1553 RegKills.set(Reg);
1554 KillOps[Reg] = LastUD;
Evan Chengeca24fb2009-05-12 23:07:00 +00001555 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001556 }
1557 }
1558 }
1559
1560 /// rewriteMBB - Keep track of which spills are available even after the
1561 /// register allocator is done with them. If possible, avid reloading vregs.
1562 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1563 LiveIntervals *LIs,
1564 AvailableSpills &Spills, BitVector &RegKills,
1565 std::vector<MachineOperand*> &KillOps) {
1566
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001567 DEBUG(errs() << "\n**** Local spiller rewriting MBB '"
1568 << MBB.getBasicBlock()->getName() << "':\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001569
1570 MachineFunction &MF = *MBB.getParent();
1571
1572 // MaybeDeadStores - When we need to write a value back into a stack slot,
1573 // keep track of the inserted store. If the stack slot value is never read
1574 // (because the value was used from some available register, for example), and
1575 // subsequently stored to, the original store is dead. This map keeps track
1576 // of inserted stores that are not used. If we see a subsequent store to the
1577 // same stack slot, the original store is deleted.
1578 std::vector<MachineInstr*> MaybeDeadStores;
1579 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1580
1581 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1582 SmallSet<MachineInstr*, 4> ReMatDefs;
1583
1584 // Clear kill info.
1585 SmallSet<unsigned, 2> KilledMIRegs;
1586 RegKills.reset();
1587 KillOps.clear();
1588 KillOps.resize(TRI->getNumRegs(), NULL);
1589
1590 unsigned Dist = 0;
1591 DistanceMap.clear();
1592 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1593 MII != E; ) {
1594 MachineBasicBlock::iterator NextMII = next(MII);
1595
1596 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1597 bool Erased = false;
1598 bool BackTracked = false;
1599 if (OptimizeByUnfold(MBB, MII,
1600 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1601 NextMII = next(MII);
1602
1603 MachineInstr &MI = *MII;
1604
1605 if (VRM.hasEmergencySpills(&MI)) {
1606 // Spill physical register(s) in the rare case the allocator has run out
1607 // of registers to allocate.
1608 SmallSet<int, 4> UsedSS;
1609 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1610 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1611 unsigned PhysReg = EmSpills[i];
1612 const TargetRegisterClass *RC =
1613 TRI->getPhysicalRegisterRegClass(PhysReg);
1614 assert(RC && "Unable to determine register class!");
1615 int SS = VRM.getEmergencySpillSlot(RC);
1616 if (UsedSS.count(SS))
Torok Edwinc23197a2009-07-14 16:55:14 +00001617 llvm_unreachable("Need to spill more than one physical registers!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001618 UsedSS.insert(SS);
1619 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1620 MachineInstr *StoreMI = prior(MII);
1621 VRM.addSpillSlotUse(SS, StoreMI);
David Greene2d4e6d32009-07-28 16:49:24 +00001622
1623 // Back-schedule reloads and remats.
1624 MachineBasicBlock::iterator InsertLoc =
1625 ComputeReloadLoc(next(MII), MBB.begin(), PhysReg, TRI, false,
1626 SS, TII, MF);
1627
1628 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SS, RC);
1629
1630 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00001631 VRM.addSpillSlotUse(SS, LoadMI);
1632 ++NumPSpills;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00001633 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00001634 }
1635 NextMII = next(MII);
1636 }
1637
1638 // Insert restores here if asked to.
1639 if (VRM.isRestorePt(&MI)) {
1640 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1641 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1642 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1643 if (!VRM.getPreSplitReg(VirtReg))
1644 continue; // Split interval spilled again.
1645 unsigned Phys = VRM.getPhys(VirtReg);
1646 RegInfo->setPhysRegUsed(Phys);
1647
1648 // Check if the value being restored if available. If so, it must be
1649 // from a predecessor BB that fallthrough into this BB. We do not
1650 // expect:
1651 // BB1:
1652 // r1 = load fi#1
1653 // ...
1654 // = r1<kill>
1655 // ... # r1 not clobbered
1656 // ...
1657 // = load fi#1
1658 bool DoReMat = VRM.isReMaterialized(VirtReg);
1659 int SSorRMId = DoReMat
1660 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1661 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1662 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1663 if (InReg == Phys) {
1664 // If the value is already available in the expected register, save
1665 // a reload / remat.
1666 if (SSorRMId)
Chris Lattner6456d382009-08-23 03:20:44 +00001667 DEBUG(errs() << "Reusing RM#"
1668 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001669 else
Chris Lattner6456d382009-08-23 03:20:44 +00001670 DEBUG(errs() << "Reusing SS#" << SSorRMId);
1671 DEBUG(errs() << " from physreg "
1672 << TRI->getName(InReg) << " for vreg"
1673 << VirtReg <<" instead of reloading into physreg "
1674 << TRI->getName(Phys) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001675 ++NumOmitted;
1676 continue;
1677 } else if (InReg && InReg != Phys) {
1678 if (SSorRMId)
Chris Lattner6456d382009-08-23 03:20:44 +00001679 DEBUG(errs() << "Reusing RM#"
1680 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001681 else
Chris Lattner6456d382009-08-23 03:20:44 +00001682 DEBUG(errs() << "Reusing SS#" << SSorRMId);
1683 DEBUG(errs() << " from physreg "
1684 << TRI->getName(InReg) << " for vreg"
1685 << VirtReg <<" by copying it into physreg "
1686 << TRI->getName(Phys) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001687
1688 // If the reloaded / remat value is available in another register,
1689 // copy it to the desired register.
David Greene2d4e6d32009-07-28 16:49:24 +00001690
1691 // Back-schedule reloads and remats.
1692 MachineBasicBlock::iterator InsertLoc =
1693 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1694 SSorRMId, TII, MF);
1695
1696 TII->copyRegToReg(MBB, InsertLoc, Phys, InReg, RC, RC);
Lang Hames87e3bca2009-05-06 02:36:21 +00001697
1698 // This invalidates Phys.
1699 Spills.ClobberPhysReg(Phys);
1700 // Remember it's available.
1701 Spills.addAvailable(SSorRMId, Phys);
1702
1703 // Mark is killed.
David Greene2d4e6d32009-07-28 16:49:24 +00001704 MachineInstr *CopyMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00001705 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1706 KillOpnd->setIsKill();
Evan Cheng427a6b62009-05-15 06:48:19 +00001707 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001708
Chris Lattner6456d382009-08-23 03:20:44 +00001709 DEBUG(errs() << '\t' << *CopyMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001710 ++NumCopified;
1711 continue;
1712 }
1713
David Greene2d4e6d32009-07-28 16:49:24 +00001714 // Back-schedule reloads and remats.
1715 MachineBasicBlock::iterator InsertLoc =
1716 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1717 SSorRMId, TII, MF);
1718
Lang Hames87e3bca2009-05-06 02:36:21 +00001719 if (VRM.isReMaterialized(VirtReg)) {
David Greene2d4e6d32009-07-28 16:49:24 +00001720 ReMaterialize(MBB, InsertLoc, Phys, VirtReg, TII, TRI, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00001721 } else {
1722 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
David Greene2d4e6d32009-07-28 16:49:24 +00001723 TII->loadRegFromStackSlot(MBB, InsertLoc, Phys, SSorRMId, RC);
1724 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00001725 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1726 ++NumLoads;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00001727 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00001728 }
1729
1730 // This invalidates Phys.
1731 Spills.ClobberPhysReg(Phys);
1732 // Remember it's available.
1733 Spills.addAvailable(SSorRMId, Phys);
1734
David Greene2d4e6d32009-07-28 16:49:24 +00001735 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
Chris Lattner6456d382009-08-23 03:20:44 +00001736 DEBUG(errs() << '\t' << *prior(MII));
Lang Hames87e3bca2009-05-06 02:36:21 +00001737 }
1738 }
1739
1740 // Insert spills here if asked to.
1741 if (VRM.isSpillPt(&MI)) {
1742 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1743 VRM.getSpillPtSpills(&MI);
1744 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1745 unsigned VirtReg = SpillRegs[i].first;
1746 bool isKill = SpillRegs[i].second;
1747 if (!VRM.getPreSplitReg(VirtReg))
1748 continue; // Split interval spilled again.
1749 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1750 unsigned Phys = VRM.getPhys(VirtReg);
1751 int StackSlot = VRM.getStackSlot(VirtReg);
1752 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1753 MachineInstr *StoreMI = next(MII);
1754 VRM.addSpillSlotUse(StackSlot, StoreMI);
Chris Lattner6456d382009-08-23 03:20:44 +00001755 DEBUG(errs() << "Store:\t" << *StoreMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001756 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1757 }
1758 NextMII = next(MII);
1759 }
1760
1761 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1762 /// reuse.
1763 ReuseInfo ReusedOperands(MI, TRI);
1764 SmallVector<unsigned, 4> VirtUseOps;
1765 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1766 MachineOperand &MO = MI.getOperand(i);
1767 if (!MO.isReg() || MO.getReg() == 0)
1768 continue; // Ignore non-register operands.
1769
1770 unsigned VirtReg = MO.getReg();
1771 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1772 // Ignore physregs for spilling, but remember that it is used by this
1773 // function.
1774 RegInfo->setPhysRegUsed(VirtReg);
1775 continue;
1776 }
1777
1778 // We want to process implicit virtual register uses first.
1779 if (MO.isImplicit())
1780 // If the virtual register is implicitly defined, emit a implicit_def
1781 // before so scavenger knows it's "defined".
Evan Cheng4784f1f2009-06-30 08:49:04 +00001782 // FIXME: This is a horrible hack done the by register allocator to
1783 // remat a definition with virtual register operand.
Lang Hames87e3bca2009-05-06 02:36:21 +00001784 VirtUseOps.insert(VirtUseOps.begin(), i);
1785 else
1786 VirtUseOps.push_back(i);
1787 }
1788
1789 // Process all of the spilled uses and all non spilled reg references.
1790 SmallVector<int, 2> PotentialDeadStoreSlots;
1791 KilledMIRegs.clear();
1792 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1793 unsigned i = VirtUseOps[j];
1794 MachineOperand &MO = MI.getOperand(i);
1795 unsigned VirtReg = MO.getReg();
1796 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1797 "Not a virtual register?");
1798
1799 unsigned SubIdx = MO.getSubReg();
1800 if (VRM.isAssignedReg(VirtReg)) {
1801 // This virtual register was assigned a physreg!
1802 unsigned Phys = VRM.getPhys(VirtReg);
1803 RegInfo->setPhysRegUsed(Phys);
1804 if (MO.isDef())
1805 ReusedOperands.markClobbered(Phys);
1806 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1807 MI.getOperand(i).setReg(RReg);
1808 MI.getOperand(i).setSubReg(0);
1809 if (VRM.isImplicitlyDefined(VirtReg))
Evan Cheng4784f1f2009-06-30 08:49:04 +00001810 // FIXME: Is this needed?
Lang Hames87e3bca2009-05-06 02:36:21 +00001811 BuildMI(MBB, &MI, MI.getDebugLoc(),
1812 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1813 continue;
1814 }
1815
1816 // This virtual register is now known to be a spilled value.
1817 if (!MO.isUse())
1818 continue; // Handle defs in the loop below (handle use&def here though)
1819
Evan Cheng4784f1f2009-06-30 08:49:04 +00001820 bool AvoidReload = MO.isUndef();
1821 // Check if it is defined by an implicit def. It should not be spilled.
1822 // Note, this is for correctness reason. e.g.
1823 // 8 %reg1024<def> = IMPLICIT_DEF
1824 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1825 // The live range [12, 14) are not part of the r1024 live interval since
1826 // it's defined by an implicit def. It will not conflicts with live
1827 // interval of r1025. Now suppose both registers are spilled, you can
1828 // easily see a situation where both registers are reloaded before
1829 // the INSERT_SUBREG and both target registers that would overlap.
Lang Hames87e3bca2009-05-06 02:36:21 +00001830 bool DoReMat = VRM.isReMaterialized(VirtReg);
1831 int SSorRMId = DoReMat
1832 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1833 int ReuseSlot = SSorRMId;
1834
1835 // Check to see if this stack slot is available.
1836 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1837
1838 // If this is a sub-register use, make sure the reuse register is in the
1839 // right register class. For example, for x86 not all of the 32-bit
1840 // registers have accessible sub-registers.
1841 // Similarly so for EXTRACT_SUBREG. Consider this:
1842 // EDI = op
1843 // MOV32_mr fi#1, EDI
1844 // ...
1845 // = EXTRACT_SUBREG fi#1
1846 // fi#1 is available in EDI, but it cannot be reused because it's not in
1847 // the right register file.
1848 if (PhysReg && !AvoidReload &&
1849 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1850 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1851 if (!RC->contains(PhysReg))
1852 PhysReg = 0;
1853 }
1854
1855 if (PhysReg && !AvoidReload) {
1856 // This spilled operand might be part of a two-address operand. If this
1857 // is the case, then changing it will necessarily require changing the
1858 // def part of the instruction as well. However, in some cases, we
1859 // aren't allowed to modify the reused register. If none of these cases
1860 // apply, reuse it.
1861 bool CanReuse = true;
1862 bool isTied = MI.isRegTiedToDefOperand(i);
1863 if (isTied) {
1864 // Okay, we have a two address operand. We can reuse this physreg as
1865 // long as we are allowed to clobber the value and there isn't an
1866 // earlier def that has already clobbered the physreg.
1867 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1868 Spills.canClobberPhysReg(PhysReg);
1869 }
1870
1871 if (CanReuse) {
1872 // If this stack slot value is already available, reuse it!
1873 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
Chris Lattner6456d382009-08-23 03:20:44 +00001874 DEBUG(errs() << "Reusing RM#"
1875 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001876 else
Chris Lattner6456d382009-08-23 03:20:44 +00001877 DEBUG(errs() << "Reusing SS#" << ReuseSlot);
1878 DEBUG(errs() << " from physreg "
1879 << TRI->getName(PhysReg) << " for vreg"
1880 << VirtReg <<" instead of reloading into physreg "
1881 << TRI->getName(VRM.getPhys(VirtReg)) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001882 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1883 MI.getOperand(i).setReg(RReg);
1884 MI.getOperand(i).setSubReg(0);
1885
1886 // The only technical detail we have is that we don't know that
1887 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1888 // later in the instruction. In particular, consider 'op V1, V2'.
1889 // If V1 is available in physreg R0, we would choose to reuse it
1890 // here, instead of reloading it into the register the allocator
1891 // indicated (say R1). However, V2 might have to be reloaded
1892 // later, and it might indicate that it needs to live in R0. When
1893 // this occurs, we need to have information available that
1894 // indicates it is safe to use R1 for the reload instead of R0.
1895 //
1896 // To further complicate matters, we might conflict with an alias,
1897 // or R0 and R1 might not be compatible with each other. In this
1898 // case, we actually insert a reload for V1 in R1, ensuring that
1899 // we can get at R0 or its alias.
1900 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1901 VRM.getPhys(VirtReg), VirtReg);
1902 if (isTied)
1903 // Only mark it clobbered if this is a use&def operand.
1904 ReusedOperands.markClobbered(PhysReg);
1905 ++NumReused;
1906
1907 if (MI.getOperand(i).isKill() &&
1908 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1909
1910 // The store of this spilled value is potentially dead, but we
1911 // won't know for certain until we've confirmed that the re-use
1912 // above is valid, which means waiting until the other operands
1913 // are processed. For now we just track the spill slot, we'll
1914 // remove it after the other operands are processed if valid.
1915
1916 PotentialDeadStoreSlots.push_back(ReuseSlot);
1917 }
1918
1919 // Mark is isKill if it's there no other uses of the same virtual
1920 // register and it's not a two-address operand. IsKill will be
1921 // unset if reg is reused.
1922 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1923 MI.getOperand(i).setIsKill();
1924 KilledMIRegs.insert(VirtReg);
1925 }
1926
1927 continue;
1928 } // CanReuse
1929
1930 // Otherwise we have a situation where we have a two-address instruction
1931 // whose mod/ref operand needs to be reloaded. This reload is already
1932 // available in some register "PhysReg", but if we used PhysReg as the
1933 // operand to our 2-addr instruction, the instruction would modify
1934 // PhysReg. This isn't cool if something later uses PhysReg and expects
1935 // to get its initial value.
1936 //
1937 // To avoid this problem, and to avoid doing a load right after a store,
1938 // we emit a copy from PhysReg into the designated register for this
1939 // operand.
1940 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1941 assert(DesignatedReg && "Must map virtreg to physreg!");
1942
1943 // Note that, if we reused a register for a previous operand, the
1944 // register we want to reload into might not actually be
1945 // available. If this occurs, use the register indicated by the
1946 // reuser.
1947 if (ReusedOperands.hasReuses())
Evan Cheng5d885022009-07-21 09:15:00 +00001948 DesignatedReg = ReusedOperands.GetRegForReload(VirtReg,
1949 DesignatedReg, &MI,
1950 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00001951
1952 // If the mapped designated register is actually the physreg we have
1953 // incoming, we don't need to inserted a dead copy.
1954 if (DesignatedReg == PhysReg) {
1955 // If this stack slot value is already available, reuse it!
1956 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
Chris Lattner6456d382009-08-23 03:20:44 +00001957 DEBUG(errs() << "Reusing RM#"
1958 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001959 else
Chris Lattner6456d382009-08-23 03:20:44 +00001960 DEBUG(errs() << "Reusing SS#" << ReuseSlot);
1961 DEBUG(errs() << " from physreg " << TRI->getName(PhysReg)
1962 << " for vreg" << VirtReg
1963 << " instead of reloading into same physreg.\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001964 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1965 MI.getOperand(i).setReg(RReg);
1966 MI.getOperand(i).setSubReg(0);
1967 ReusedOperands.markClobbered(RReg);
1968 ++NumReused;
1969 continue;
1970 }
1971
1972 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1973 RegInfo->setPhysRegUsed(DesignatedReg);
1974 ReusedOperands.markClobbered(DesignatedReg);
Lang Hames87e3bca2009-05-06 02:36:21 +00001975
David Greene2d4e6d32009-07-28 16:49:24 +00001976 // Back-schedule reloads and remats.
1977 MachineBasicBlock::iterator InsertLoc =
1978 ComputeReloadLoc(&MI, MBB.begin(), PhysReg, TRI, DoReMat,
1979 SSorRMId, TII, MF);
1980
1981 TII->copyRegToReg(MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC);
1982
1983 MachineInstr *CopyMI = prior(InsertLoc);
Evan Cheng427a6b62009-05-15 06:48:19 +00001984 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001985
1986 // This invalidates DesignatedReg.
1987 Spills.ClobberPhysReg(DesignatedReg);
1988
1989 Spills.addAvailable(ReuseSlot, DesignatedReg);
1990 unsigned RReg =
1991 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1992 MI.getOperand(i).setReg(RReg);
1993 MI.getOperand(i).setSubReg(0);
Chris Lattner6456d382009-08-23 03:20:44 +00001994 DEBUG(errs() << '\t' << *prior(MII));
Lang Hames87e3bca2009-05-06 02:36:21 +00001995 ++NumReused;
1996 continue;
1997 } // if (PhysReg)
1998
1999 // Otherwise, reload it and remember that we have it.
2000 PhysReg = VRM.getPhys(VirtReg);
2001 assert(PhysReg && "Must map virtreg to physreg!");
2002
2003 // Note that, if we reused a register for a previous operand, the
2004 // register we want to reload into might not actually be
2005 // available. If this occurs, use the register indicated by the
2006 // reuser.
2007 if (ReusedOperands.hasReuses())
Evan Cheng5d885022009-07-21 09:15:00 +00002008 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2009 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002010
2011 RegInfo->setPhysRegUsed(PhysReg);
2012 ReusedOperands.markClobbered(PhysReg);
2013 if (AvoidReload)
2014 ++NumAvoided;
2015 else {
David Greene2d4e6d32009-07-28 16:49:24 +00002016 // Back-schedule reloads and remats.
2017 MachineBasicBlock::iterator InsertLoc =
2018 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, DoReMat,
2019 SSorRMId, TII, MF);
2020
Lang Hames87e3bca2009-05-06 02:36:21 +00002021 if (DoReMat) {
David Greene2d4e6d32009-07-28 16:49:24 +00002022 ReMaterialize(MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002023 } else {
2024 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
David Greene2d4e6d32009-07-28 16:49:24 +00002025 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SSorRMId, RC);
2026 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00002027 VRM.addSpillSlotUse(SSorRMId, LoadMI);
2028 ++NumLoads;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00002029 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00002030 }
2031 // This invalidates PhysReg.
2032 Spills.ClobberPhysReg(PhysReg);
2033
2034 // Any stores to this stack slot are not dead anymore.
2035 if (!DoReMat)
2036 MaybeDeadStores[SSorRMId] = NULL;
2037 Spills.addAvailable(SSorRMId, PhysReg);
2038 // Assumes this is the last use. IsKill will be unset if reg is reused
2039 // unless it's a two-address operand.
2040 if (!MI.isRegTiedToDefOperand(i) &&
2041 KilledMIRegs.count(VirtReg) == 0) {
2042 MI.getOperand(i).setIsKill();
2043 KilledMIRegs.insert(VirtReg);
2044 }
2045
David Greene2d4e6d32009-07-28 16:49:24 +00002046 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
Chris Lattner6456d382009-08-23 03:20:44 +00002047 DEBUG(errs() << '\t' << *prior(InsertLoc));
Lang Hames87e3bca2009-05-06 02:36:21 +00002048 }
2049 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2050 MI.getOperand(i).setReg(RReg);
2051 MI.getOperand(i).setSubReg(0);
2052 }
2053
2054 // Ok - now we can remove stores that have been confirmed dead.
2055 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2056 // This was the last use and the spilled value is still available
2057 // for reuse. That means the spill was unnecessary!
2058 int PDSSlot = PotentialDeadStoreSlots[j];
2059 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2060 if (DeadStore) {
Chris Lattner6456d382009-08-23 03:20:44 +00002061 DEBUG(errs() << "Removed dead store:\t" << *DeadStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002062 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002063 VRM.RemoveMachineInstrFromMaps(DeadStore);
2064 MBB.erase(DeadStore);
2065 MaybeDeadStores[PDSSlot] = NULL;
2066 ++NumDSE;
2067 }
2068 }
2069
2070
Chris Lattner6456d382009-08-23 03:20:44 +00002071 DEBUG(errs() << '\t' << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002072
2073
2074 // If we have folded references to memory operands, make sure we clear all
2075 // physical registers that may contain the value of the spilled virtual
2076 // register
2077 SmallSet<int, 2> FoldedSS;
2078 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
2079 unsigned VirtReg = I->second.first;
2080 VirtRegMap::ModRef MR = I->second.second;
Chris Lattner6456d382009-08-23 03:20:44 +00002081 DEBUG(errs() << "Folded vreg: " << VirtReg << " MR: " << MR);
Lang Hames87e3bca2009-05-06 02:36:21 +00002082
2083 // MI2VirtMap be can updated which invalidate the iterator.
2084 // Increment the iterator first.
2085 ++I;
2086 int SS = VRM.getStackSlot(VirtReg);
2087 if (SS == VirtRegMap::NO_STACK_SLOT)
2088 continue;
2089 FoldedSS.insert(SS);
Chris Lattner6456d382009-08-23 03:20:44 +00002090 DEBUG(errs() << " - StackSlot: " << SS << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00002091
2092 // If this folded instruction is just a use, check to see if it's a
2093 // straight load from the virt reg slot.
2094 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2095 int FrameIdx;
2096 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2097 if (DestReg && FrameIdx == SS) {
2098 // If this spill slot is available, turn it into a copy (or nothing)
2099 // instead of leaving it as a load!
2100 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
Chris Lattner6456d382009-08-23 03:20:44 +00002101 DEBUG(errs() << "Promoted Load To Copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002102 if (DestReg != InReg) {
2103 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2104 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
2105 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2106 unsigned SubIdx = DefMO->getSubReg();
2107 // Revisit the copy so we make sure to notice the effects of the
2108 // operation on the destreg (either needing to RA it if it's
2109 // virtual or needing to clobber any values if it's physical).
2110 NextMII = &MI;
2111 --NextMII; // backtrack to the copy.
2112 // Propagate the sub-register index over.
2113 if (SubIdx) {
2114 DefMO = NextMII->findRegisterDefOperand(DestReg);
2115 DefMO->setSubReg(SubIdx);
2116 }
2117
2118 // Mark is killed.
2119 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2120 KillOpnd->setIsKill();
2121
2122 BackTracked = true;
2123 } else {
Chris Lattner6456d382009-08-23 03:20:44 +00002124 DEBUG(errs() << "Removing now-noop copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002125 // Unset last kill since it's being reused.
Evan Cheng427a6b62009-05-15 06:48:19 +00002126 InvalidateKill(InReg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002127 Spills.disallowClobberPhysReg(InReg);
2128 }
2129
Evan Cheng427a6b62009-05-15 06:48:19 +00002130 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002131 VRM.RemoveMachineInstrFromMaps(&MI);
2132 MBB.erase(&MI);
2133 Erased = true;
2134 goto ProcessNextInst;
2135 }
2136 } else {
2137 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2138 SmallVector<MachineInstr*, 4> NewMIs;
2139 if (PhysReg &&
2140 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2141 MBB.insert(MII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00002142 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002143 VRM.RemoveMachineInstrFromMaps(&MI);
2144 MBB.erase(&MI);
2145 Erased = true;
2146 --NextMII; // backtrack to the unfolded instruction.
2147 BackTracked = true;
2148 goto ProcessNextInst;
2149 }
2150 }
2151 }
2152
2153 // If this reference is not a use, any previous store is now dead.
2154 // Otherwise, the store to this stack slot is not dead anymore.
2155 MachineInstr* DeadStore = MaybeDeadStores[SS];
2156 if (DeadStore) {
2157 bool isDead = !(MR & VirtRegMap::isRef);
2158 MachineInstr *NewStore = NULL;
2159 if (MR & VirtRegMap::isModRef) {
2160 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2161 SmallVector<MachineInstr*, 4> NewMIs;
2162 // We can reuse this physreg as long as we are allowed to clobber
2163 // the value and there isn't an earlier def that has already clobbered
2164 // the physreg.
2165 if (PhysReg &&
2166 !ReusedOperands.isClobbered(PhysReg) &&
2167 Spills.canClobberPhysReg(PhysReg) &&
2168 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2169 MachineOperand *KillOpnd =
2170 DeadStore->findRegisterUseOperand(PhysReg, true);
2171 // Note, if the store is storing a sub-register, it's possible the
2172 // super-register is needed below.
2173 if (KillOpnd && !KillOpnd->getSubReg() &&
2174 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2175 MBB.insert(MII, NewMIs[0]);
2176 NewStore = NewMIs[1];
2177 MBB.insert(MII, NewStore);
2178 VRM.addSpillSlotUse(SS, NewStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002179 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002180 VRM.RemoveMachineInstrFromMaps(&MI);
2181 MBB.erase(&MI);
2182 Erased = true;
2183 --NextMII;
2184 --NextMII; // backtrack to the unfolded instruction.
2185 BackTracked = true;
2186 isDead = true;
2187 ++NumSUnfold;
2188 }
2189 }
2190 }
2191
2192 if (isDead) { // Previous store is dead.
2193 // If we get here, the store is dead, nuke it now.
Chris Lattner6456d382009-08-23 03:20:44 +00002194 DEBUG(errs() << "Removed dead store:\t" << *DeadStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002195 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002196 VRM.RemoveMachineInstrFromMaps(DeadStore);
2197 MBB.erase(DeadStore);
2198 if (!NewStore)
2199 ++NumDSE;
2200 }
2201
2202 MaybeDeadStores[SS] = NULL;
2203 if (NewStore) {
2204 // Treat this store as a spill merged into a copy. That makes the
2205 // stack slot value available.
2206 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2207 goto ProcessNextInst;
2208 }
2209 }
2210
2211 // If the spill slot value is available, and this is a new definition of
2212 // the value, the value is not available anymore.
2213 if (MR & VirtRegMap::isMod) {
2214 // Notice that the value in this stack slot has been modified.
2215 Spills.ModifyStackSlotOrReMat(SS);
2216
2217 // If this is *just* a mod of the value, check to see if this is just a
2218 // store to the spill slot (i.e. the spill got merged into the copy). If
2219 // so, realize that the vreg is available now, and add the store to the
2220 // MaybeDeadStore info.
2221 int StackSlot;
2222 if (!(MR & VirtRegMap::isRef)) {
2223 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2224 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2225 "Src hasn't been allocated yet?");
2226
2227 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2228 Spills, RegKills, KillOps, TRI, VRM)) {
2229 NextMII = next(MII);
2230 BackTracked = true;
2231 goto ProcessNextInst;
2232 }
2233
2234 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2235 // this as a potentially dead store in case there is a subsequent
2236 // store into the stack slot without a read from it.
2237 MaybeDeadStores[StackSlot] = &MI;
2238
2239 // If the stack slot value was previously available in some other
2240 // register, change it now. Otherwise, make the register
2241 // available in PhysReg.
2242 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2243 }
2244 }
2245 }
2246 }
2247
2248 // Process all of the spilled defs.
2249 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2250 MachineOperand &MO = MI.getOperand(i);
2251 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2252 continue;
2253
2254 unsigned VirtReg = MO.getReg();
2255 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2256 // Check to see if this is a noop copy. If so, eliminate the
2257 // instruction before considering the dest reg to be changed.
Evan Cheng2578ba22009-07-01 01:59:31 +00002258 // Also check if it's copying from an "undef", if so, we can't
2259 // eliminate this or else the undef marker is lost and it will
2260 // confuses the scavenger. This is extremely rare.
Lang Hames87e3bca2009-05-06 02:36:21 +00002261 unsigned Src, Dst, SrcSR, DstSR;
Evan Cheng2578ba22009-07-01 01:59:31 +00002262 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2263 !MI.findRegisterUseOperand(Src)->isUndef()) {
Lang Hames87e3bca2009-05-06 02:36:21 +00002264 ++NumDCE;
Chris Lattner6456d382009-08-23 03:20:44 +00002265 DEBUG(errs() << "Removing now-noop copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002266 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00002267 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00002268 if (MO.isDead() && !KillRegs.empty()) {
2269 // Source register or an implicit super/sub-register use is killed.
2270 assert(KillRegs[0] == Dst ||
2271 TRI->isSubRegister(KillRegs[0], Dst) ||
2272 TRI->isSuperRegister(KillRegs[0], Dst));
2273 // Last def is now dead.
Evan Chengeca24fb2009-05-12 23:07:00 +00002274 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002275 }
2276 VRM.RemoveMachineInstrFromMaps(&MI);
2277 MBB.erase(&MI);
2278 Erased = true;
2279 Spills.disallowClobberPhysReg(VirtReg);
2280 goto ProcessNextInst;
2281 }
Evan Cheng2578ba22009-07-01 01:59:31 +00002282
Lang Hames87e3bca2009-05-06 02:36:21 +00002283 // If it's not a no-op copy, it clobbers the value in the destreg.
2284 Spills.ClobberPhysReg(VirtReg);
2285 ReusedOperands.markClobbered(VirtReg);
2286
2287 // Check to see if this instruction is a load from a stack slot into
2288 // a register. If so, this provides the stack slot value in the reg.
2289 int FrameIdx;
2290 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2291 assert(DestReg == VirtReg && "Unknown load situation!");
2292
2293 // If it is a folded reference, then it's not safe to clobber.
2294 bool Folded = FoldedSS.count(FrameIdx);
2295 // Otherwise, if it wasn't available, remember that it is now!
2296 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2297 goto ProcessNextInst;
2298 }
2299
2300 continue;
2301 }
2302
2303 unsigned SubIdx = MO.getSubReg();
2304 bool DoReMat = VRM.isReMaterialized(VirtReg);
2305 if (DoReMat)
2306 ReMatDefs.insert(&MI);
2307
2308 // The only vregs left are stack slot definitions.
2309 int StackSlot = VRM.getStackSlot(VirtReg);
2310 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2311
2312 // If this def is part of a two-address operand, make sure to execute
2313 // the store from the correct physical register.
2314 unsigned PhysReg;
2315 unsigned TiedOp;
2316 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2317 PhysReg = MI.getOperand(TiedOp).getReg();
2318 if (SubIdx) {
2319 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2320 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2321 "Can't find corresponding super-register!");
2322 PhysReg = SuperReg;
2323 }
2324 } else {
2325 PhysReg = VRM.getPhys(VirtReg);
2326 if (ReusedOperands.isClobbered(PhysReg)) {
2327 // Another def has taken the assigned physreg. It must have been a
2328 // use&def which got it due to reuse. Undo the reuse!
Evan Cheng5d885022009-07-21 09:15:00 +00002329 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2330 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002331 }
2332 }
2333
2334 assert(PhysReg && "VR not assigned a physical register?");
2335 RegInfo->setPhysRegUsed(PhysReg);
2336 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2337 ReusedOperands.markClobbered(RReg);
2338 MI.getOperand(i).setReg(RReg);
2339 MI.getOperand(i).setSubReg(0);
2340
2341 if (!MO.isDead()) {
2342 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2343 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2344 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2345 NextMII = next(MII);
2346
2347 // Check to see if this is a noop copy. If so, eliminate the
2348 // instruction before considering the dest reg to be changed.
2349 {
2350 unsigned Src, Dst, SrcSR, DstSR;
2351 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2352 ++NumDCE;
Chris Lattner6456d382009-08-23 03:20:44 +00002353 DEBUG(errs() << "Removing now-noop copy: " << MI);
Evan Cheng427a6b62009-05-15 06:48:19 +00002354 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002355 VRM.RemoveMachineInstrFromMaps(&MI);
2356 MBB.erase(&MI);
2357 Erased = true;
Evan Cheng427a6b62009-05-15 06:48:19 +00002358 UpdateKills(*LastStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002359 goto ProcessNextInst;
2360 }
2361 }
2362 }
2363 }
2364 ProcessNextInst:
Evan Cheng52484682009-07-18 02:10:10 +00002365 // Delete dead instructions without side effects.
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00002366 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
Evan Cheng52484682009-07-18 02:10:10 +00002367 InvalidateKills(MI, TRI, RegKills, KillOps);
2368 VRM.RemoveMachineInstrFromMaps(&MI);
2369 MBB.erase(&MI);
2370 Erased = true;
2371 }
2372 if (!Erased)
2373 DistanceMap.insert(std::make_pair(&MI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00002374 if (!Erased && !BackTracked) {
2375 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
Evan Cheng427a6b62009-05-15 06:48:19 +00002376 UpdateKills(*II, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002377 }
2378 MII = NextMII;
2379 }
2380
2381 }
2382
2383};
2384
Dan Gohman7db949d2009-08-07 01:32:21 +00002385}
2386
Lang Hames87e3bca2009-05-06 02:36:21 +00002387llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2388 switch (RewriterOpt) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002389 default: llvm_unreachable("Unreachable!");
Lang Hames87e3bca2009-05-06 02:36:21 +00002390 case local:
2391 return new LocalRewriter();
Lang Hamesf41538d2009-06-02 16:53:25 +00002392 case trivial:
2393 return new TrivialRewriter();
Lang Hames87e3bca2009-05-06 02:36:21 +00002394 }
2395}