blob: fe4f7b7a1ac9c949c9b5c7f6107e37071a74de4d [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the VirtRegMap class.
11//
12// It also contains implementations of the the Spiller interface, which, given a
13// virtual register map and a machine function, eliminates all virtual
14// references by replacing them with physical register references - adding spill
15// code as necessary.
16//
17//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "spiller"
20#include "VirtRegMap.h"
21#include "llvm/Function.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/SSARegMap.h"
25#include "llvm/Target/TargetMachine.h"
26#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/ADT/BitVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallSet.h"
34#include <algorithm>
35using namespace llvm;
36
37STATISTIC(NumSpills, "Number of register spills");
38STATISTIC(NumReMats, "Number of re-materialization");
Evan Cheng498949b2007-08-14 23:25:37 +000039STATISTIC(NumDRM , "Number of re-materializable defs elided");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040STATISTIC(NumStores, "Number of stores added");
41STATISTIC(NumLoads , "Number of loads added");
42STATISTIC(NumReused, "Number of values reused");
43STATISTIC(NumDSE , "Number of dead stores elided");
44STATISTIC(NumDCE , "Number of copies elided");
45
46namespace {
47 enum SpillerName { simple, local };
48
49 static cl::opt<SpillerName>
50 SpillerOpt("spiller",
51 cl::desc("Spiller to use: (default: local)"),
52 cl::Prefix,
53 cl::values(clEnumVal(simple, " simple spiller"),
54 clEnumVal(local, " local spiller"),
55 clEnumValEnd),
56 cl::init(local));
57}
58
59//===----------------------------------------------------------------------===//
60// VirtRegMap implementation
61//===----------------------------------------------------------------------===//
62
63VirtRegMap::VirtRegMap(MachineFunction &mf)
64 : TII(*mf.getTarget().getInstrInfo()), MF(mf),
65 Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT),
Evan Chengcecc8222007-11-17 00:40:40 +000066 Virt2ReMatIdMap(NO_STACK_SLOT), Virt2SplitMap(0),
67 ReMatMap(NULL), ReMatId(MAX_STACK_SLOT+1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000068 grow();
69}
70
71void VirtRegMap::grow() {
Evan Cheng1204d172007-08-13 23:45:17 +000072 unsigned LastVirtReg = MF.getSSARegMap()->getLastVirtReg();
73 Virt2PhysMap.grow(LastVirtReg);
74 Virt2StackSlotMap.grow(LastVirtReg);
75 Virt2ReMatIdMap.grow(LastVirtReg);
Evan Chengcecc8222007-11-17 00:40:40 +000076 Virt2SplitMap.grow(LastVirtReg);
77 Virt2SpillPtsMap.grow(LastVirtReg);
Evan Cheng1204d172007-08-13 23:45:17 +000078 ReMatMap.grow(LastVirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079}
80
81int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
82 assert(MRegisterInfo::isVirtualRegister(virtReg));
83 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
84 "attempt to assign stack slot to already spilled register");
85 const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
86 int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
87 RC->getAlignment());
88 Virt2StackSlotMap[virtReg] = frameIndex;
89 ++NumSpills;
90 return frameIndex;
91}
92
93void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
94 assert(MRegisterInfo::isVirtualRegister(virtReg));
95 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
96 "attempt to assign stack slot to already spilled register");
97 assert((frameIndex >= 0 ||
98 (frameIndex >= MF.getFrameInfo()->getObjectIndexBegin())) &&
99 "illegal fixed frame index");
100 Virt2StackSlotMap[virtReg] = frameIndex;
101}
102
103int VirtRegMap::assignVirtReMatId(unsigned virtReg) {
104 assert(MRegisterInfo::isVirtualRegister(virtReg));
Evan Cheng1204d172007-08-13 23:45:17 +0000105 assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106 "attempt to assign re-mat id to already spilled register");
Evan Cheng1204d172007-08-13 23:45:17 +0000107 Virt2ReMatIdMap[virtReg] = ReMatId;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 return ReMatId++;
109}
110
Evan Cheng1204d172007-08-13 23:45:17 +0000111void VirtRegMap::assignVirtReMatId(unsigned virtReg, int id) {
112 assert(MRegisterInfo::isVirtualRegister(virtReg));
113 assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
114 "attempt to assign re-mat id to already spilled register");
115 Virt2ReMatIdMap[virtReg] = id;
116}
117
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
119 unsigned OpNo, MachineInstr *NewMI) {
120 // Move previous memory references folded to new instruction.
121 MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
122 for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
123 E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
124 MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
125 MI2VirtMap.erase(I++);
126 }
127
128 ModRef MRInfo;
129 const TargetInstrDescriptor *TID = OldMI->getInstrDescriptor();
130 if (TID->getOperandConstraint(OpNo, TOI::TIED_TO) != -1 ||
131 TID->findTiedToSrcOperand(OpNo) != -1) {
132 // Folded a two-address operand.
133 MRInfo = isModRef;
134 } else if (OldMI->getOperand(OpNo).isDef()) {
135 MRInfo = isMod;
136 } else {
137 MRInfo = isRef;
138 }
139
140 // add new memory reference
141 MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
142}
143
Evan Chengf3255842007-10-13 02:50:24 +0000144void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *MI, ModRef MRInfo) {
145 MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(MI);
146 MI2VirtMap.insert(IP, std::make_pair(MI, std::make_pair(VirtReg, MRInfo)));
147}
148
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149void VirtRegMap::print(std::ostream &OS) const {
150 const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
151
152 OS << "********** REGISTER MAP **********\n";
153 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
154 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
155 if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
156 OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
157
158 }
159
160 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
161 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
162 if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
163 OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
164 OS << '\n';
165}
166
167void VirtRegMap::dump() const {
168 print(DOUT);
169}
170
171
172//===----------------------------------------------------------------------===//
173// Simple Spiller Implementation
174//===----------------------------------------------------------------------===//
175
176Spiller::~Spiller() {}
177
178namespace {
179 struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
180 bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
181 };
182}
183
184bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
185 DOUT << "********** REWRITE MACHINE CODE **********\n";
186 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
187 const TargetMachine &TM = MF.getTarget();
188 const MRegisterInfo &MRI = *TM.getRegisterInfo();
189
190 // LoadedRegs - Keep track of which vregs are loaded, so that we only load
191 // each vreg once (in the case where a spilled vreg is used by multiple
192 // operands). This is always smaller than the number of operands to the
193 // current machine instr, so it should be small.
194 std::vector<unsigned> LoadedRegs;
195
196 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
197 MBBI != E; ++MBBI) {
198 DOUT << MBBI->getBasicBlock()->getName() << ":\n";
199 MachineBasicBlock &MBB = *MBBI;
200 for (MachineBasicBlock::iterator MII = MBB.begin(),
201 E = MBB.end(); MII != E; ++MII) {
202 MachineInstr &MI = *MII;
203 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
204 MachineOperand &MO = MI.getOperand(i);
205 if (MO.isRegister() && MO.getReg())
206 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
207 unsigned VirtReg = MO.getReg();
208 unsigned PhysReg = VRM.getPhys(VirtReg);
Evan Cheng1204d172007-08-13 23:45:17 +0000209 if (!VRM.isAssignedReg(VirtReg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 int StackSlot = VRM.getStackSlot(VirtReg);
211 const TargetRegisterClass* RC =
212 MF.getSSARegMap()->getRegClass(VirtReg);
213
214 if (MO.isUse() &&
215 std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
216 == LoadedRegs.end()) {
217 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
218 LoadedRegs.push_back(VirtReg);
219 ++NumLoads;
220 DOUT << '\t' << *prior(MII);
221 }
222
223 if (MO.isDef()) {
224 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
225 ++NumStores;
226 }
227 }
228 MF.setPhysRegUsed(PhysReg);
229 MI.getOperand(i).setReg(PhysReg);
230 } else {
231 MF.setPhysRegUsed(MO.getReg());
232 }
233 }
234
235 DOUT << '\t' << MI;
236 LoadedRegs.clear();
237 }
238 }
239 return true;
240}
241
242//===----------------------------------------------------------------------===//
243// Local Spiller Implementation
244//===----------------------------------------------------------------------===//
245
246namespace {
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000247 class AvailableSpills;
248
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 /// LocalSpiller - This spiller does a simple pass over the machine basic
250 /// block to attempt to keep spills in registers as much as possible for
251 /// blocks that have low register pressure (the vreg may be spilled due to
252 /// register pressure in other blocks).
253 class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
Evan Cheng687d1082007-10-12 08:50:34 +0000254 SSARegMap *RegMap;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 const MRegisterInfo *MRI;
256 const TargetInstrInfo *TII;
257 public:
258 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
Evan Cheng687d1082007-10-12 08:50:34 +0000259 RegMap = MF.getSSARegMap();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 MRI = MF.getTarget().getRegisterInfo();
261 TII = MF.getTarget().getInstrInfo();
262 DOUT << "\n**** Local spiller rewriting function '"
263 << MF.getFunction()->getName() << "':\n";
David Greenea1c1e782007-09-06 16:36:39 +0000264 DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!) ****\n";
265 DEBUG(MF.dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
268 MBB != E; ++MBB)
Evan Cheng1204d172007-08-13 23:45:17 +0000269 RewriteMBB(*MBB, VRM);
David Greenea1c1e782007-09-06 16:36:39 +0000270
271 DOUT << "**** Post Machine Instrs ****\n";
272 DEBUG(MF.dump());
273
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 return true;
275 }
276 private:
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000277 bool PrepForUnfoldOpti(MachineBasicBlock &MBB,
278 MachineBasicBlock::iterator &MII,
279 std::vector<MachineInstr*> &MaybeDeadStores,
280 AvailableSpills &Spills, BitVector &RegKills,
281 std::vector<MachineOperand*> &KillOps,
282 VirtRegMap &VRM);
Evan Chengcecc8222007-11-17 00:40:40 +0000283 void SpillRegToStackSlot(MachineBasicBlock &MBB,
284 MachineBasicBlock::iterator &MII,
285 int Idx, unsigned PhysReg, int StackSlot,
286 const TargetRegisterClass *RC,
287 MachineInstr *&LastStore,
288 AvailableSpills &Spills,
289 SmallSet<MachineInstr*, 4> &ReMatDefs,
290 BitVector &RegKills,
291 std::vector<MachineOperand*> &KillOps,
292 VirtRegMap &VRM);
Evan Cheng1204d172007-08-13 23:45:17 +0000293 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 };
295}
296
297/// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
Evan Cheng1204d172007-08-13 23:45:17 +0000298/// top down, keep track of which spills slots or remat are available in each
299/// register.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300///
301/// Note that not all physregs are created equal here. In particular, some
302/// physregs are reloads that we are allowed to clobber or ignore at any time.
303/// Other physregs are values that the register allocated program is using that
304/// we cannot CHANGE, but we can read if we like. We keep track of this on a
Evan Cheng1204d172007-08-13 23:45:17 +0000305/// per-stack-slot / remat id basis as the low bit in the value of the
306/// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
307/// this bit and addAvailable sets it if.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308namespace {
309class VISIBILITY_HIDDEN AvailableSpills {
310 const MRegisterInfo *MRI;
311 const TargetInstrInfo *TII;
312
Evan Cheng1204d172007-08-13 23:45:17 +0000313 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
314 // or remat'ed virtual register values that are still available, due to being
315 // loaded or stored to, but not invalidated yet.
316 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317
Evan Cheng1204d172007-08-13 23:45:17 +0000318 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
319 // indicating which stack slot values are currently held by a physreg. This
320 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
321 // physreg is modified.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 std::multimap<unsigned, int> PhysRegsAvailable;
323
324 void disallowClobberPhysRegOnly(unsigned PhysReg);
325
326 void ClobberPhysRegOnly(unsigned PhysReg);
327public:
328 AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
329 : MRI(mri), TII(tii) {
330 }
331
332 const MRegisterInfo *getRegInfo() const { return MRI; }
333
Evan Cheng1204d172007-08-13 23:45:17 +0000334 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
335 /// available in a physical register, return that PhysReg, otherwise
336 /// return 0.
337 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
338 std::map<int, unsigned>::const_iterator I =
339 SpillSlotsOrReMatsAvailable.find(Slot);
340 if (I != SpillSlotsOrReMatsAvailable.end()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 return I->second >> 1; // Remove the CanClobber bit.
342 }
343 return 0;
344 }
345
Evan Cheng1204d172007-08-13 23:45:17 +0000346 /// addAvailable - Mark that the specified stack slot / remat is available in
347 /// the specified physreg. If CanClobber is true, the physreg can be modified
348 /// at any time without changing the semantics of the program.
349 void addAvailable(int SlotOrReMat, MachineInstr *MI, unsigned Reg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 bool CanClobber = true) {
351 // If this stack slot is thought to be available in some other physreg,
352 // remove its record.
Evan Cheng1204d172007-08-13 23:45:17 +0000353 ModifyStackSlotOrReMat(SlotOrReMat);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354
Evan Cheng1204d172007-08-13 23:45:17 +0000355 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
Evan Cheng7efc9422007-08-15 20:20:34 +0000356 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) | (unsigned)CanClobber;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357
Evan Cheng1204d172007-08-13 23:45:17 +0000358 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
359 DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 else
Evan Cheng1204d172007-08-13 23:45:17 +0000361 DOUT << "Remembering SS#" << SlotOrReMat;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362 DOUT << " in physreg " << MRI->getName(Reg) << "\n";
363 }
364
365 /// canClobberPhysReg - Return true if the spiller is allowed to change the
366 /// value of the specified stackslot register if it desires. The specified
367 /// stack slot must be available in a physreg for this query to make sense.
Evan Cheng1204d172007-08-13 23:45:17 +0000368 bool canClobberPhysReg(int SlotOrReMat) const {
Evan Cheng7efc9422007-08-15 20:20:34 +0000369 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
370 "Value not available!");
Evan Cheng1204d172007-08-13 23:45:17 +0000371 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372 }
373
374 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
375 /// stackslot register. The register is still available but is no longer
376 /// allowed to be modifed.
377 void disallowClobberPhysReg(unsigned PhysReg);
378
379 /// ClobberPhysReg - This is called when the specified physreg changes
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000380 /// value. We use this to invalidate any info about stuff that lives in
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 /// it and any of its aliases.
382 void ClobberPhysReg(unsigned PhysReg);
383
Evan Cheng7efc9422007-08-15 20:20:34 +0000384 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
385 /// slot changes. This removes information about which register the previous
386 /// value for this slot lives in (as the previous value is dead now).
Evan Cheng1204d172007-08-13 23:45:17 +0000387 void ModifyStackSlotOrReMat(int SlotOrReMat);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000388};
389}
390
391/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
392/// stackslot register. The register is still available but is no longer
393/// allowed to be modifed.
394void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
395 std::multimap<unsigned, int>::iterator I =
396 PhysRegsAvailable.lower_bound(PhysReg);
397 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
Evan Cheng1204d172007-08-13 23:45:17 +0000398 int SlotOrReMat = I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 I++;
Evan Cheng1204d172007-08-13 23:45:17 +0000400 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401 "Bidirectional map mismatch!");
Evan Cheng1204d172007-08-13 23:45:17 +0000402 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 DOUT << "PhysReg " << MRI->getName(PhysReg)
404 << " copied, it is available for use but can no longer be modified\n";
405 }
406}
407
408/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
409/// stackslot register and its aliases. The register and its aliases may
410/// still available but is no longer allowed to be modifed.
411void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
412 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
413 disallowClobberPhysRegOnly(*AS);
414 disallowClobberPhysRegOnly(PhysReg);
415}
416
417/// ClobberPhysRegOnly - This is called when the specified physreg changes
418/// value. We use this to invalidate any info about stuff we thing lives in it.
419void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
420 std::multimap<unsigned, int>::iterator I =
421 PhysRegsAvailable.lower_bound(PhysReg);
422 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
Evan Cheng1204d172007-08-13 23:45:17 +0000423 int SlotOrReMat = I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 PhysRegsAvailable.erase(I++);
Evan Cheng1204d172007-08-13 23:45:17 +0000425 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 "Bidirectional map mismatch!");
Evan Cheng1204d172007-08-13 23:45:17 +0000427 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428 DOUT << "PhysReg " << MRI->getName(PhysReg)
429 << " clobbered, invalidating ";
Evan Cheng1204d172007-08-13 23:45:17 +0000430 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
431 DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 else
Evan Cheng1204d172007-08-13 23:45:17 +0000433 DOUT << "SS#" << SlotOrReMat << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434 }
435}
436
437/// ClobberPhysReg - This is called when the specified physreg changes
438/// value. We use this to invalidate any info about stuff we thing lives in
439/// it and any of its aliases.
440void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
441 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
442 ClobberPhysRegOnly(*AS);
443 ClobberPhysRegOnly(PhysReg);
444}
445
Evan Cheng7efc9422007-08-15 20:20:34 +0000446/// ModifyStackSlotOrReMat - This method is called when the value in a stack
447/// slot changes. This removes information about which register the previous
448/// value for this slot lives in (as the previous value is dead now).
Evan Cheng1204d172007-08-13 23:45:17 +0000449void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
Evan Cheng7efc9422007-08-15 20:20:34 +0000450 std::map<int, unsigned>::iterator It =
451 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
Evan Cheng1204d172007-08-13 23:45:17 +0000452 if (It == SpillSlotsOrReMatsAvailable.end()) return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453 unsigned Reg = It->second >> 1;
Evan Cheng1204d172007-08-13 23:45:17 +0000454 SpillSlotsOrReMatsAvailable.erase(It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000455
456 // This register may hold the value of multiple stack slots, only remove this
457 // stack slot from the set of values the register contains.
458 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
459 for (; ; ++I) {
460 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
461 "Map inverse broken!");
Evan Cheng1204d172007-08-13 23:45:17 +0000462 if (I->second == SlotOrReMat) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000463 }
464 PhysRegsAvailable.erase(I);
465}
466
467
468
469/// InvalidateKills - MI is going to be deleted. If any of its operands are
470/// marked kill, then invalidate the information.
471static void InvalidateKills(MachineInstr &MI, BitVector &RegKills,
Evan Chengeec85c52007-08-14 20:23:13 +0000472 std::vector<MachineOperand*> &KillOps,
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000473 SmallVector<unsigned, 2> *KillRegs = NULL) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
475 MachineOperand &MO = MI.getOperand(i);
Dan Gohman38a9a9f2007-09-14 20:33:02 +0000476 if (!MO.isRegister() || !MO.isUse() || !MO.isKill())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477 continue;
478 unsigned Reg = MO.getReg();
Evan Cheng498949b2007-08-14 23:25:37 +0000479 if (KillRegs)
480 KillRegs->push_back(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481 if (KillOps[Reg] == &MO) {
482 RegKills.reset(Reg);
483 KillOps[Reg] = NULL;
484 }
485 }
486}
487
Evan Cheng498949b2007-08-14 23:25:37 +0000488/// InvalidateRegDef - If the def operand of the specified def MI is now dead
489/// (since it's spill instruction is removed), mark it isDead. Also checks if
490/// the def MI has other definition operands that are not dead. Returns it by
491/// reference.
492static bool InvalidateRegDef(MachineBasicBlock::iterator I,
493 MachineInstr &NewDef, unsigned Reg,
494 bool &HasLiveDef) {
495 // Due to remat, it's possible this reg isn't being reused. That is,
496 // the def of this reg (by prev MI) is now dead.
497 MachineInstr *DefMI = I;
498 MachineOperand *DefOp = NULL;
499 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
500 MachineOperand &MO = DefMI->getOperand(i);
Dan Gohman38a9a9f2007-09-14 20:33:02 +0000501 if (MO.isRegister() && MO.isDef()) {
Evan Cheng498949b2007-08-14 23:25:37 +0000502 if (MO.getReg() == Reg)
503 DefOp = &MO;
504 else if (!MO.isDead())
505 HasLiveDef = true;
506 }
507 }
508 if (!DefOp)
509 return false;
510
511 bool FoundUse = false, Done = false;
512 MachineBasicBlock::iterator E = NewDef;
513 ++I; ++E;
514 for (; !Done && I != E; ++I) {
515 MachineInstr *NMI = I;
516 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
517 MachineOperand &MO = NMI->getOperand(j);
Dan Gohman38a9a9f2007-09-14 20:33:02 +0000518 if (!MO.isRegister() || MO.getReg() != Reg)
Evan Cheng498949b2007-08-14 23:25:37 +0000519 continue;
520 if (MO.isUse())
521 FoundUse = true;
522 Done = true; // Stop after scanning all the operands of this MI.
523 }
524 }
525 if (!FoundUse) {
526 // Def is dead!
527 DefOp->setIsDead();
528 return true;
529 }
530 return false;
531}
532
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000533/// UpdateKills - Track and update kill info. If a MI reads a register that is
534/// marked kill, then it must be due to register reuse. Transfer the kill info
535/// over.
536static void UpdateKills(MachineInstr &MI, BitVector &RegKills,
537 std::vector<MachineOperand*> &KillOps) {
538 const TargetInstrDescriptor *TID = MI.getInstrDescriptor();
539 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
540 MachineOperand &MO = MI.getOperand(i);
Dan Gohman38a9a9f2007-09-14 20:33:02 +0000541 if (!MO.isRegister() || !MO.isUse())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000542 continue;
543 unsigned Reg = MO.getReg();
544 if (Reg == 0)
545 continue;
546
547 if (RegKills[Reg]) {
548 // That can't be right. Register is killed but not re-defined and it's
549 // being reused. Let's fix that.
550 KillOps[Reg]->unsetIsKill();
551 if (i < TID->numOperands &&
552 TID->getOperandConstraint(i, TOI::TIED_TO) == -1)
553 // Unless it's a two-address operand, this is the new kill.
554 MO.setIsKill();
555 }
556
557 if (MO.isKill()) {
558 RegKills.set(Reg);
559 KillOps[Reg] = &MO;
560 }
561 }
562
563 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
564 const MachineOperand &MO = MI.getOperand(i);
Dan Gohman38a9a9f2007-09-14 20:33:02 +0000565 if (!MO.isRegister() || !MO.isDef())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 continue;
567 unsigned Reg = MO.getReg();
568 RegKills.reset(Reg);
569 KillOps[Reg] = NULL;
570 }
571}
572
573
574// ReusedOp - For each reused operand, we keep track of a bit of information, in
575// case we need to rollback upon processing a new operand. See comments below.
576namespace {
577 struct ReusedOp {
578 // The MachineInstr operand that reused an available value.
579 unsigned Operand;
580
Evan Cheng1204d172007-08-13 23:45:17 +0000581 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
582 unsigned StackSlotOrReMat;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583
584 // PhysRegReused - The physical register the value was available in.
585 unsigned PhysRegReused;
586
587 // AssignedPhysReg - The physreg that was assigned for use by the reload.
588 unsigned AssignedPhysReg;
589
590 // VirtReg - The virtual register itself.
591 unsigned VirtReg;
592
593 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
594 unsigned vreg)
Evan Cheng7efc9422007-08-15 20:20:34 +0000595 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
596 AssignedPhysReg(apr), VirtReg(vreg) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000597 };
598
599 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
600 /// is reused instead of reloaded.
601 class VISIBILITY_HIDDEN ReuseInfo {
602 MachineInstr &MI;
603 std::vector<ReusedOp> Reuses;
604 BitVector PhysRegsClobbered;
605 public:
606 ReuseInfo(MachineInstr &mi, const MRegisterInfo *mri) : MI(mi) {
607 PhysRegsClobbered.resize(mri->getNumRegs());
608 }
609
610 bool hasReuses() const {
611 return !Reuses.empty();
612 }
613
614 /// addReuse - If we choose to reuse a virtual register that is already
615 /// available instead of reloading it, remember that we did so.
Evan Cheng1204d172007-08-13 23:45:17 +0000616 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617 unsigned PhysRegReused, unsigned AssignedPhysReg,
618 unsigned VirtReg) {
619 // If the reload is to the assigned register anyway, no undo will be
620 // required.
621 if (PhysRegReused == AssignedPhysReg) return;
622
623 // Otherwise, remember this.
Evan Cheng1204d172007-08-13 23:45:17 +0000624 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625 AssignedPhysReg, VirtReg));
626 }
627
628 void markClobbered(unsigned PhysReg) {
629 PhysRegsClobbered.set(PhysReg);
630 }
631
632 bool isClobbered(unsigned PhysReg) const {
633 return PhysRegsClobbered.test(PhysReg);
634 }
635
636 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
637 /// is some other operand that is using the specified register, either pick
638 /// a new register to use, or evict the previous reload and use this reg.
639 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
640 AvailableSpills &Spills,
Evan Chengd368d822007-08-14 09:11:18 +0000641 std::vector<MachineInstr*> &MaybeDeadStores,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 SmallSet<unsigned, 8> &Rejected,
643 BitVector &RegKills,
Evan Cheng1204d172007-08-13 23:45:17 +0000644 std::vector<MachineOperand*> &KillOps,
645 VirtRegMap &VRM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646 if (Reuses.empty()) return PhysReg; // This is most often empty.
647
648 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
649 ReusedOp &Op = Reuses[ro];
650 // If we find some other reuse that was supposed to use this register
651 // exactly for its reload, we can change this reload to use ITS reload
652 // register. That is, unless its reload register has already been
653 // considered and subsequently rejected because it has also been reused
654 // by another operand.
655 if (Op.PhysRegReused == PhysReg &&
656 Rejected.count(Op.AssignedPhysReg) == 0) {
657 // Yup, use the reload register that we didn't use before.
658 unsigned NewReg = Op.AssignedPhysReg;
659 Rejected.insert(PhysReg);
660 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
Evan Cheng1204d172007-08-13 23:45:17 +0000661 RegKills, KillOps, VRM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662 } else {
663 // Otherwise, we might also have a problem if a previously reused
664 // value aliases the new register. If so, codegen the previous reload
665 // and use this one.
666 unsigned PRRU = Op.PhysRegReused;
667 const MRegisterInfo *MRI = Spills.getRegInfo();
668 if (MRI->areAliases(PRRU, PhysReg)) {
669 // Okay, we found out that an alias of a reused register
670 // was used. This isn't good because it means we have
671 // to undo a previous reuse.
672 MachineBasicBlock *MBB = MI->getParent();
673 const TargetRegisterClass *AliasRC =
674 MBB->getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
675
676 // Copy Op out of the vector and remove it, we're going to insert an
677 // explicit load for it.
678 ReusedOp NewOp = Op;
679 Reuses.erase(Reuses.begin()+ro);
680
681 // Ok, we're going to try to reload the assigned physreg into the
682 // slot that we were supposed to in the first place. However, that
683 // register could hold a reuse. Check to see if it conflicts or
684 // would prefer us to use a different register.
685 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
686 MI, Spills, MaybeDeadStores,
Evan Cheng1204d172007-08-13 23:45:17 +0000687 Rejected, RegKills, KillOps, VRM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688
Evan Cheng1204d172007-08-13 23:45:17 +0000689 if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
690 MRI->reMaterialize(*MBB, MI, NewPhysReg,
691 VRM.getReMaterializedMI(NewOp.VirtReg));
692 ++NumReMats;
693 } else {
694 MRI->loadRegFromStackSlot(*MBB, MI, NewPhysReg,
695 NewOp.StackSlotOrReMat, AliasRC);
Evan Chengd368d822007-08-14 09:11:18 +0000696 // Any stores to this stack slot are not dead anymore.
697 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
Evan Cheng1204d172007-08-13 23:45:17 +0000698 ++NumLoads;
699 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 Spills.ClobberPhysReg(NewPhysReg);
701 Spills.ClobberPhysReg(NewOp.PhysRegReused);
702
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000703 MI->getOperand(NewOp.Operand).setReg(NewPhysReg);
704
Evan Cheng1204d172007-08-13 23:45:17 +0000705 Spills.addAvailable(NewOp.StackSlotOrReMat, MI, NewPhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 MachineBasicBlock::iterator MII = MI;
707 --MII;
708 UpdateKills(*MII, RegKills, KillOps);
709 DOUT << '\t' << *MII;
710
711 DOUT << "Reuse undone!\n";
712 --NumReused;
713
714 // Finally, PhysReg is now available, go ahead and use it.
715 return PhysReg;
716 }
717 }
718 }
719 return PhysReg;
720 }
721
722 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
723 /// 'Rejected' set to remember which registers have been considered and
724 /// rejected for the reload. This avoids infinite looping in case like
725 /// this:
726 /// t1 := op t2, t3
727 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
728 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
729 /// t1 <- desires r1
730 /// sees r1 is taken by t2, tries t2's reload register r0
731 /// sees r0 is taken by t3, tries t3's reload register r1
732 /// sees r1 is taken by t2, tries t2's reload register r0 ...
733 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
734 AvailableSpills &Spills,
Evan Chengd368d822007-08-14 09:11:18 +0000735 std::vector<MachineInstr*> &MaybeDeadStores,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 BitVector &RegKills,
Evan Cheng1204d172007-08-13 23:45:17 +0000737 std::vector<MachineOperand*> &KillOps,
738 VirtRegMap &VRM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 SmallSet<unsigned, 8> Rejected;
740 return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
Evan Cheng1204d172007-08-13 23:45:17 +0000741 RegKills, KillOps, VRM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742 }
743 };
744}
745
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000746/// PrepForUnfoldOpti - Turn a store folding instruction into a load folding
747/// instruction. e.g.
748/// xorl %edi, %eax
749/// movl %eax, -32(%ebp)
750/// movl -36(%ebp), %eax
751/// orl %eax, -32(%ebp)
752/// ==>
753/// xorl %edi, %eax
754/// orl -36(%ebp), %eax
755/// mov %eax, -32(%ebp)
756/// This enables unfolding optimization for a subsequent instruction which will
757/// also eliminate the newly introduced store instruction.
758bool LocalSpiller::PrepForUnfoldOpti(MachineBasicBlock &MBB,
759 MachineBasicBlock::iterator &MII,
760 std::vector<MachineInstr*> &MaybeDeadStores,
761 AvailableSpills &Spills,
762 BitVector &RegKills,
763 std::vector<MachineOperand*> &KillOps,
764 VirtRegMap &VRM) {
765 MachineFunction &MF = *MBB.getParent();
766 MachineInstr &MI = *MII;
767 unsigned UnfoldedOpc = 0;
768 unsigned UnfoldPR = 0;
769 unsigned UnfoldVR = 0;
770 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
771 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
772 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
773 // Only transform a MI that folds a single register.
774 if (UnfoldedOpc)
775 return false;
776 UnfoldVR = I->second.first;
777 VirtRegMap::ModRef MR = I->second.second;
778 if (VRM.isAssignedReg(UnfoldVR))
779 continue;
780 // If this reference is not a use, any previous store is now dead.
781 // Otherwise, the store to this stack slot is not dead anymore.
782 FoldedSS = VRM.getStackSlot(UnfoldVR);
783 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
784 if (DeadStore && (MR & VirtRegMap::isModRef)) {
785 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
786 if (!PhysReg ||
787 DeadStore->findRegisterUseOperandIdx(PhysReg, true) == -1)
788 continue;
789 UnfoldPR = PhysReg;
790 UnfoldedOpc = MRI->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
791 false, true);
792 }
793 }
794
795 if (!UnfoldedOpc)
796 return false;
797
798 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
799 MachineOperand &MO = MI.getOperand(i);
800 if (!MO.isRegister() || MO.getReg() == 0 || !MO.isUse())
801 continue;
802 unsigned VirtReg = MO.getReg();
Evan Cheng4d0fbf32007-11-14 07:59:08 +0000803 if (MRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000804 continue;
805 if (VRM.isAssignedReg(VirtReg)) {
806 unsigned PhysReg = VRM.getPhys(VirtReg);
807 if (PhysReg && MRI->regsOverlap(PhysReg, UnfoldPR))
808 return false;
809 } else if (VRM.isReMaterialized(VirtReg))
810 continue;
811 int SS = VRM.getStackSlot(VirtReg);
812 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
813 if (PhysReg) {
814 if (MRI->regsOverlap(PhysReg, UnfoldPR))
815 return false;
816 continue;
817 }
818 PhysReg = VRM.getPhys(VirtReg);
819 if (!MRI->regsOverlap(PhysReg, UnfoldPR))
820 continue;
821
822 // Ok, we'll need to reload the value into a register which makes
823 // it impossible to perform the store unfolding optimization later.
824 // Let's see if it is possible to fold the load if the store is
825 // unfolded. This allows us to perform the store unfolding
826 // optimization.
827 SmallVector<MachineInstr*, 4> NewMIs;
828 if (MRI->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
829 assert(NewMIs.size() == 1);
830 MachineInstr *NewMI = NewMIs.back();
831 NewMIs.clear();
Evan Chengcecc8222007-11-17 00:40:40 +0000832 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg);
833 assert(Idx != -1);
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000834 MachineInstr *FoldedMI = MRI->foldMemoryOperand(NewMI, Idx, SS);
835 if (FoldedMI) {
Evan Cheng3b94f752007-10-22 03:01:44 +0000836 if (!VRM.hasPhys(UnfoldVR))
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000837 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000838 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
839 MII = MBB.insert(MII, FoldedMI);
840 VRM.RemoveFromFoldedVirtMap(&MI);
841 MBB.erase(&MI);
842 return true;
843 }
844 delete NewMI;
845 }
846 }
847 return false;
848}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849
Evan Chenga1b89c22007-11-02 17:35:08 +0000850/// findSuperReg - Find the SubReg's super-register of given register class
851/// where its SubIdx sub-register is SubReg.
852static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
853 unsigned SubIdx, const MRegisterInfo *MRI) {
854 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
855 I != E; ++I) {
856 unsigned Reg = *I;
857 if (MRI->getSubReg(Reg, SubIdx) == SubReg)
858 return Reg;
859 }
860 return 0;
861}
862
Evan Chengcecc8222007-11-17 00:40:40 +0000863/// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
864/// the last store to the same slot is now dead. If so, remove the last store.
865void LocalSpiller::SpillRegToStackSlot(MachineBasicBlock &MBB,
866 MachineBasicBlock::iterator &MII,
867 int Idx, unsigned PhysReg, int StackSlot,
868 const TargetRegisterClass *RC,
869 MachineInstr *&LastStore,
870 AvailableSpills &Spills,
871 SmallSet<MachineInstr*, 4> &ReMatDefs,
872 BitVector &RegKills,
873 std::vector<MachineOperand*> &KillOps,
874 VirtRegMap &VRM) {
875 MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
876 DOUT << "Store:\t" << *next(MII);
877
878 // If there is a dead store to this stack slot, nuke it now.
879 if (LastStore) {
880 DOUT << "Removed dead store:\t" << *LastStore;
881 ++NumDSE;
882 SmallVector<unsigned, 2> KillRegs;
883 InvalidateKills(*LastStore, RegKills, KillOps, &KillRegs);
884 MachineBasicBlock::iterator PrevMII = LastStore;
885 bool CheckDef = PrevMII != MBB.begin();
886 if (CheckDef)
887 --PrevMII;
888 MBB.erase(LastStore);
889 VRM.RemoveFromFoldedVirtMap(LastStore);
890 if (CheckDef) {
891 // Look at defs of killed registers on the store. Mark the defs
892 // as dead since the store has been deleted and they aren't
893 // being reused.
894 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
895 bool HasOtherDef = false;
896 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
897 MachineInstr *DeadDef = PrevMII;
898 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
899 // FIXME: This assumes a remat def does not have side
900 // effects.
901 MBB.erase(DeadDef);
902 VRM.RemoveFromFoldedVirtMap(DeadDef);
903 ++NumDRM;
904 }
905 }
906 }
907 }
908 }
909
910 LastStore = next(MII);
911
912 // If the stack slot value was previously available in some other
913 // register, change it now. Otherwise, make the register available,
914 // in PhysReg.
915 Spills.ModifyStackSlotOrReMat(StackSlot);
916 Spills.ClobberPhysReg(PhysReg);
917 Spills.addAvailable(StackSlot, LastStore, PhysReg);
918 ++NumStores;
919}
920
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921/// rewriteMBB - Keep track of which spills are available even after the
Evan Chengcecc8222007-11-17 00:40:40 +0000922/// register allocator is done with them. If possible, avid reloading vregs.
Evan Cheng1204d172007-08-13 23:45:17 +0000923void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924 DOUT << MBB.getBasicBlock()->getName() << ":\n";
925
Evan Chengd368d822007-08-14 09:11:18 +0000926 MachineFunction &MF = *MBB.getParent();
927
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928 // Spills - Keep track of which spilled values are available in physregs so
929 // that we can choose to reuse the physregs instead of emitting reloads.
930 AvailableSpills Spills(MRI, TII);
931
932 // MaybeDeadStores - When we need to write a value back into a stack slot,
933 // keep track of the inserted store. If the stack slot value is never read
934 // (because the value was used from some available register, for example), and
935 // subsequently stored to, the original store is dead. This map keeps track
936 // of inserted stores that are not used. If we see a subsequent store to the
937 // same stack slot, the original store is deleted.
Evan Chengd368d822007-08-14 09:11:18 +0000938 std::vector<MachineInstr*> MaybeDeadStores;
939 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000940
Evan Cheng498949b2007-08-14 23:25:37 +0000941 // ReMatDefs - These are rematerializable def MIs which are not deleted.
942 SmallSet<MachineInstr*, 4> ReMatDefs;
943
Evan Chengcecc8222007-11-17 00:40:40 +0000944 // ReloadedSplits - Splits must be reloaded once per MBB. This keeps track
945 // which have been reloaded.
946 SmallSet<unsigned, 8> ReloadedSplits;
947
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948 // Keep track of kill information.
949 BitVector RegKills(MRI->getNumRegs());
950 std::vector<MachineOperand*> KillOps;
951 KillOps.resize(MRI->getNumRegs(), NULL);
952
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
954 MII != E; ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000955 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000957 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958 bool Erased = false;
959 bool BackTracked = false;
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000960 if (PrepForUnfoldOpti(MBB, MII,
961 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
962 NextMII = next(MII);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963
Evan Cheng4a7e72f2007-10-19 21:23:22 +0000964 MachineInstr &MI = *MII;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965 const TargetInstrDescriptor *TID = MI.getInstrDescriptor();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966
Evan Chengcecc8222007-11-17 00:40:40 +0000967 // Insert spills here if asked to.
968 std::vector<unsigned> SpillRegs = VRM.getSpillPtSpills(&MI);
969 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
970 unsigned VirtReg = SpillRegs[i];
971 const TargetRegisterClass *RC = RegMap->getRegClass(VirtReg);
972 unsigned Phys = VRM.getPhys(VirtReg);
973 int StackSlot = VRM.getStackSlot(VirtReg);
974 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
975 SpillRegToStackSlot(MBB, MII, i, Phys, StackSlot, RC,
976 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
977 }
978
979 /// ReusedOperands - Keep track of operand reuse in case we need to undo
980 /// reuse.
981 ReuseInfo ReusedOperands(MI, MRI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 // Process all of the spilled uses and all non spilled reg references.
983 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
984 MachineOperand &MO = MI.getOperand(i);
985 if (!MO.isRegister() || MO.getReg() == 0)
986 continue; // Ignore non-register operands.
987
Evan Cheng687d1082007-10-12 08:50:34 +0000988 unsigned VirtReg = MO.getReg();
989 if (MRegisterInfo::isPhysicalRegister(VirtReg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 // Ignore physregs for spilling, but remember that it is used by this
991 // function.
Evan Cheng687d1082007-10-12 08:50:34 +0000992 MF.setPhysRegUsed(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993 continue;
994 }
995
Evan Cheng687d1082007-10-12 08:50:34 +0000996 assert(MRegisterInfo::isVirtualRegister(VirtReg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997 "Not a virtual or a physical register?");
998
Evan Cheng4d0fbf32007-11-14 07:59:08 +0000999 unsigned SubIdx = MO.getSubReg();
Evan Cheng1204d172007-08-13 23:45:17 +00001000 if (VRM.isAssignedReg(VirtReg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 // This virtual register was assigned a physreg!
1002 unsigned Phys = VRM.getPhys(VirtReg);
1003 MF.setPhysRegUsed(Phys);
1004 if (MO.isDef())
1005 ReusedOperands.markClobbered(Phys);
Evan Chengcecc8222007-11-17 00:40:40 +00001006
1007 // If it's a split live interval, insert a reload for the first use
1008 // unless it's previously defined in the MBB.
1009 unsigned SplitReg = VRM.getPreSplitReg(VirtReg);
1010 if (SplitReg) {
1011 if (ReloadedSplits.insert(VirtReg)) {
1012 bool HasUse = MO.isUse();
1013 // If it's a def, we don't need to reload the value unless it's
1014 // a two-address code.
1015 if (!HasUse) {
1016 for (unsigned j = i+1; j != e; ++j) {
1017 MachineOperand &MOJ = MI.getOperand(j);
1018 if (MOJ.isRegister() && MOJ.getReg() == VirtReg) {
1019 HasUse = true;
1020 break;
1021 }
1022 }
1023 }
1024
1025 if (HasUse) {
1026 if (VRM.isReMaterialized(VirtReg)) {
1027 MRI->reMaterialize(MBB, &MI, Phys,
1028 VRM.getReMaterializedMI(VirtReg));
1029 ++NumReMats;
1030 } else {
1031 const TargetRegisterClass* RC = RegMap->getRegClass(VirtReg);
1032 MRI->loadRegFromStackSlot(MBB, &MI, Phys, VRM.getStackSlot(VirtReg), RC);
1033 ++NumLoads;
1034 }
1035 // This invalidates Phys.
1036 Spills.ClobberPhysReg(Phys);
1037 UpdateKills(*prior(MII), RegKills, KillOps);
1038 DOUT << '\t' << *prior(MII);
1039 }
1040 }
1041 }
1042
Evan Cheng4d0fbf32007-11-14 07:59:08 +00001043 unsigned RReg = SubIdx ? MRI->getSubReg(Phys, SubIdx) : Phys;
Evan Cheng687d1082007-10-12 08:50:34 +00001044 MI.getOperand(i).setReg(RReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 continue;
1046 }
1047
1048 // This virtual register is now known to be a spilled value.
1049 if (!MO.isUse())
1050 continue; // Handle defs in the loop below (handle use&def here though)
1051
Evan Cheng1204d172007-08-13 23:45:17 +00001052 bool DoReMat = VRM.isReMaterialized(VirtReg);
1053 int SSorRMId = DoReMat
1054 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
Evan Cheng67cf11c2007-08-14 05:42:54 +00001055 int ReuseSlot = SSorRMId;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001056
1057 // Check to see if this stack slot is available.
Evan Cheng67cf11c2007-08-14 05:42:54 +00001058 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1059 if (!PhysReg && DoReMat) {
1060 // This use is rematerializable. But perhaps the value is available in
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001061 // a register if the definition is not deleted. If so, check if we can
Evan Cheng67cf11c2007-08-14 05:42:54 +00001062 // reuse the value.
1063 ReuseSlot = VRM.getStackSlot(VirtReg);
1064 if (ReuseSlot != VirtRegMap::NO_STACK_SLOT)
1065 PhysReg = Spills.getSpillSlotOrReMatPhysReg(ReuseSlot);
1066 }
Evan Cheng687d1082007-10-12 08:50:34 +00001067
1068 // If this is a sub-register use, make sure the reuse register is in the
1069 // right register class. For example, for x86 not all of the 32-bit
1070 // registers have accessible sub-registers.
1071 // Similarly so for EXTRACT_SUBREG. Consider this:
1072 // EDI = op
1073 // MOV32_mr fi#1, EDI
1074 // ...
1075 // = EXTRACT_SUBREG fi#1
1076 // fi#1 is available in EDI, but it cannot be reused because it's not in
1077 // the right register file.
1078 if (PhysReg &&
Evan Cheng4d0fbf32007-11-14 07:59:08 +00001079 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
Evan Cheng687d1082007-10-12 08:50:34 +00001080 const TargetRegisterClass* RC = RegMap->getRegClass(VirtReg);
1081 if (!RC->contains(PhysReg))
1082 PhysReg = 0;
1083 }
1084
Evan Cheng67cf11c2007-08-14 05:42:54 +00001085 if (PhysReg) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086 // This spilled operand might be part of a two-address operand. If this
1087 // is the case, then changing it will necessarily require changing the
1088 // def part of the instruction as well. However, in some cases, we
1089 // aren't allowed to modify the reused register. If none of these cases
1090 // apply, reuse it.
1091 bool CanReuse = true;
1092 int ti = TID->getOperandConstraint(i, TOI::TIED_TO);
1093 if (ti != -1 &&
Dan Gohman38a9a9f2007-09-14 20:33:02 +00001094 MI.getOperand(ti).isRegister() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095 MI.getOperand(ti).getReg() == VirtReg) {
1096 // Okay, we have a two address operand. We can reuse this physreg as
1097 // long as we are allowed to clobber the value and there isn't an
1098 // earlier def that has already clobbered the physreg.
Evan Cheng67cf11c2007-08-14 05:42:54 +00001099 CanReuse = Spills.canClobberPhysReg(ReuseSlot) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 !ReusedOperands.isClobbered(PhysReg);
1101 }
1102
1103 if (CanReuse) {
1104 // If this stack slot value is already available, reuse it!
Evan Cheng67cf11c2007-08-14 05:42:54 +00001105 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1106 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107 else
Evan Cheng67cf11c2007-08-14 05:42:54 +00001108 DOUT << "Reusing SS#" << ReuseSlot;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109 DOUT << " from physreg "
1110 << MRI->getName(PhysReg) << " for vreg"
1111 << VirtReg <<" instead of reloading into physreg "
1112 << MRI->getName(VRM.getPhys(VirtReg)) << "\n";
Evan Cheng4d0fbf32007-11-14 07:59:08 +00001113 unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
Evan Cheng687d1082007-10-12 08:50:34 +00001114 MI.getOperand(i).setReg(RReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115
1116 // The only technical detail we have is that we don't know that
1117 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1118 // later in the instruction. In particular, consider 'op V1, V2'.
1119 // If V1 is available in physreg R0, we would choose to reuse it
1120 // here, instead of reloading it into the register the allocator
1121 // indicated (say R1). However, V2 might have to be reloaded
1122 // later, and it might indicate that it needs to live in R0. When
1123 // this occurs, we need to have information available that
1124 // indicates it is safe to use R1 for the reload instead of R0.
1125 //
1126 // To further complicate matters, we might conflict with an alias,
1127 // or R0 and R1 might not be compatible with each other. In this
1128 // case, we actually insert a reload for V1 in R1, ensuring that
1129 // we can get at R0 or its alias.
Evan Cheng67cf11c2007-08-14 05:42:54 +00001130 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131 VRM.getPhys(VirtReg), VirtReg);
1132 if (ti != -1)
1133 // Only mark it clobbered if this is a use&def operand.
1134 ReusedOperands.markClobbered(PhysReg);
1135 ++NumReused;
Evan Chengd368d822007-08-14 09:11:18 +00001136
1137 if (MI.getOperand(i).isKill() &&
1138 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1139 // This was the last use and the spilled value is still available
1140 // for reuse. That means the spill was unnecessary!
1141 MachineInstr* DeadStore = MaybeDeadStores[ReuseSlot];
1142 if (DeadStore) {
1143 DOUT << "Removed dead store:\t" << *DeadStore;
1144 InvalidateKills(*DeadStore, RegKills, KillOps);
Evan Chengd368d822007-08-14 09:11:18 +00001145 VRM.RemoveFromFoldedVirtMap(DeadStore);
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001146 MBB.erase(DeadStore);
Evan Chengd368d822007-08-14 09:11:18 +00001147 MaybeDeadStores[ReuseSlot] = NULL;
1148 ++NumDSE;
1149 }
1150 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151 continue;
Evan Cheng687d1082007-10-12 08:50:34 +00001152 } // CanReuse
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153
1154 // Otherwise we have a situation where we have a two-address instruction
1155 // whose mod/ref operand needs to be reloaded. This reload is already
1156 // available in some register "PhysReg", but if we used PhysReg as the
1157 // operand to our 2-addr instruction, the instruction would modify
1158 // PhysReg. This isn't cool if something later uses PhysReg and expects
1159 // to get its initial value.
1160 //
1161 // To avoid this problem, and to avoid doing a load right after a store,
1162 // we emit a copy from PhysReg into the designated register for this
1163 // operand.
1164 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1165 assert(DesignatedReg && "Must map virtreg to physreg!");
1166
1167 // Note that, if we reused a register for a previous operand, the
1168 // register we want to reload into might not actually be
1169 // available. If this occurs, use the register indicated by the
1170 // reuser.
1171 if (ReusedOperands.hasReuses())
1172 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
Evan Cheng1204d172007-08-13 23:45:17 +00001173 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001174
1175 // If the mapped designated register is actually the physreg we have
1176 // incoming, we don't need to inserted a dead copy.
1177 if (DesignatedReg == PhysReg) {
1178 // If this stack slot value is already available, reuse it!
Evan Cheng67cf11c2007-08-14 05:42:54 +00001179 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1180 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001181 else
Evan Cheng67cf11c2007-08-14 05:42:54 +00001182 DOUT << "Reusing SS#" << ReuseSlot;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001183 DOUT << " from physreg " << MRI->getName(PhysReg) << " for vreg"
1184 << VirtReg
1185 << " instead of reloading into same physreg.\n";
Evan Cheng4d0fbf32007-11-14 07:59:08 +00001186 unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
Evan Cheng687d1082007-10-12 08:50:34 +00001187 MI.getOperand(i).setReg(RReg);
Evan Chenga1b89c22007-11-02 17:35:08 +00001188 ReusedOperands.markClobbered(RReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001189 ++NumReused;
1190 continue;
1191 }
1192
Evan Cheng687d1082007-10-12 08:50:34 +00001193 const TargetRegisterClass* RC = RegMap->getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 MF.setPhysRegUsed(DesignatedReg);
1195 ReusedOperands.markClobbered(DesignatedReg);
Evan Chengb3d91cf2007-09-26 06:25:56 +00001196 MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001197
1198 MachineInstr *CopyMI = prior(MII);
1199 UpdateKills(*CopyMI, RegKills, KillOps);
1200
1201 // This invalidates DesignatedReg.
1202 Spills.ClobberPhysReg(DesignatedReg);
1203
Evan Cheng67cf11c2007-08-14 05:42:54 +00001204 Spills.addAvailable(ReuseSlot, &MI, DesignatedReg);
Evan Cheng687d1082007-10-12 08:50:34 +00001205 unsigned RReg =
Evan Cheng4d0fbf32007-11-14 07:59:08 +00001206 SubIdx ? MRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
Evan Cheng687d1082007-10-12 08:50:34 +00001207 MI.getOperand(i).setReg(RReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208 DOUT << '\t' << *prior(MII);
1209 ++NumReused;
1210 continue;
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001211 } // if (PhysReg)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001212
1213 // Otherwise, reload it and remember that we have it.
1214 PhysReg = VRM.getPhys(VirtReg);
1215 assert(PhysReg && "Must map virtreg to physreg!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001216
1217 // Note that, if we reused a register for a previous operand, the
1218 // register we want to reload into might not actually be
1219 // available. If this occurs, use the register indicated by the
1220 // reuser.
1221 if (ReusedOperands.hasReuses())
1222 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
Evan Cheng1204d172007-08-13 23:45:17 +00001223 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224
1225 MF.setPhysRegUsed(PhysReg);
1226 ReusedOperands.markClobbered(PhysReg);
Evan Cheng1204d172007-08-13 23:45:17 +00001227 if (DoReMat) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 MRI->reMaterialize(MBB, &MI, PhysReg, VRM.getReMaterializedMI(VirtReg));
1229 ++NumReMats;
1230 } else {
Evan Cheng687d1082007-10-12 08:50:34 +00001231 const TargetRegisterClass* RC = RegMap->getRegClass(VirtReg);
Evan Cheng1204d172007-08-13 23:45:17 +00001232 MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001233 ++NumLoads;
1234 }
1235 // This invalidates PhysReg.
1236 Spills.ClobberPhysReg(PhysReg);
1237
1238 // Any stores to this stack slot are not dead anymore.
Evan Cheng1204d172007-08-13 23:45:17 +00001239 if (!DoReMat)
Evan Chengd368d822007-08-14 09:11:18 +00001240 MaybeDeadStores[SSorRMId] = NULL;
Evan Cheng1204d172007-08-13 23:45:17 +00001241 Spills.addAvailable(SSorRMId, &MI, PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 // Assumes this is the last use. IsKill will be unset if reg is reused
1243 // unless it's a two-address operand.
1244 if (TID->getOperandConstraint(i, TOI::TIED_TO) == -1)
1245 MI.getOperand(i).setIsKill();
Evan Cheng4d0fbf32007-11-14 07:59:08 +00001246 unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
Evan Cheng687d1082007-10-12 08:50:34 +00001247 MI.getOperand(i).setReg(RReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248 UpdateKills(*prior(MII), RegKills, KillOps);
1249 DOUT << '\t' << *prior(MII);
1250 }
1251
1252 DOUT << '\t' << MI;
1253
Evan Chengcecc8222007-11-17 00:40:40 +00001254
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001255 // If we have folded references to memory operands, make sure we clear all
1256 // physical registers that may contain the value of the spilled virtual
1257 // register
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001258 SmallSet<int, 2> FoldedSS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260 unsigned VirtReg = I->second.first;
1261 VirtRegMap::ModRef MR = I->second.second;
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001262 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
Evan Chengcecc8222007-11-17 00:40:40 +00001263
1264 // If this is a split live interval, remember we have seen this so
1265 // we do not need to reload it for later uses.
1266 unsigned SplitReg = VRM.getPreSplitReg(VirtReg);
1267 if (SplitReg)
1268 ReloadedSplits.insert(VirtReg);
1269
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 int SS = VRM.getStackSlot(VirtReg);
Evan Chengcecc8222007-11-17 00:40:40 +00001271 if (SS == VirtRegMap::NO_STACK_SLOT)
1272 continue;
Evan Cheng7efc9422007-08-15 20:20:34 +00001273 FoldedSS.insert(SS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 DOUT << " - StackSlot: " << SS << "\n";
1275
1276 // If this folded instruction is just a use, check to see if it's a
1277 // straight load from the virt reg slot.
1278 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1279 int FrameIdx;
Evan Cheng687d1082007-10-12 08:50:34 +00001280 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1281 if (DestReg && FrameIdx == SS) {
1282 // If this spill slot is available, turn it into a copy (or nothing)
1283 // instead of leaving it as a load!
1284 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1285 DOUT << "Promoted Load To Copy: " << MI;
1286 if (DestReg != InReg) {
1287 const TargetRegisterClass *RC = RegMap->getRegClass(VirtReg);
1288 MRI->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1289 // Revisit the copy so we make sure to notice the effects of the
1290 // operation on the destreg (either needing to RA it if it's
1291 // virtual or needing to clobber any values if it's physical).
1292 NextMII = &MI;
1293 --NextMII; // backtrack to the copy.
1294 BackTracked = true;
1295 } else
1296 DOUT << "Removing now-noop copy: " << MI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297
Evan Cheng687d1082007-10-12 08:50:34 +00001298 VRM.RemoveFromFoldedVirtMap(&MI);
1299 MBB.erase(&MI);
1300 Erased = true;
1301 goto ProcessNextInst;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 }
Evan Chengf3255842007-10-13 02:50:24 +00001303 } else {
1304 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1305 SmallVector<MachineInstr*, 4> NewMIs;
1306 if (PhysReg &&
1307 MRI->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1308 MBB.insert(MII, NewMIs[0]);
1309 VRM.RemoveFromFoldedVirtMap(&MI);
1310 MBB.erase(&MI);
1311 Erased = true;
1312 --NextMII; // backtrack to the unfolded instruction.
1313 BackTracked = true;
1314 goto ProcessNextInst;
1315 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316 }
1317 }
1318
1319 // If this reference is not a use, any previous store is now dead.
1320 // Otherwise, the store to this stack slot is not dead anymore.
Evan Chengd368d822007-08-14 09:11:18 +00001321 MachineInstr* DeadStore = MaybeDeadStores[SS];
1322 if (DeadStore) {
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001323 bool isDead = !(MR & VirtRegMap::isRef);
Evan Chengf3255842007-10-13 02:50:24 +00001324 MachineInstr *NewStore = NULL;
Evan Cheng3b94f752007-10-22 03:01:44 +00001325 if (MR & VirtRegMap::isModRef) {
Evan Chengf3255842007-10-13 02:50:24 +00001326 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1327 SmallVector<MachineInstr*, 4> NewMIs;
1328 if (PhysReg &&
1329 DeadStore->findRegisterUseOperandIdx(PhysReg, true) != -1 &&
1330 MRI->unfoldMemoryOperand(MF, &MI, PhysReg, false, true, NewMIs)) {
1331 MBB.insert(MII, NewMIs[0]);
1332 NewStore = NewMIs[1];
1333 MBB.insert(MII, NewStore);
1334 VRM.RemoveFromFoldedVirtMap(&MI);
1335 MBB.erase(&MI);
1336 Erased = true;
1337 --NextMII;
1338 --NextMII; // backtrack to the unfolded instruction.
1339 BackTracked = true;
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001340 isDead = true;
1341 }
Evan Chengf3255842007-10-13 02:50:24 +00001342 }
1343
1344 if (isDead) { // Previous store is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 // If we get here, the store is dead, nuke it now.
Evan Chengd368d822007-08-14 09:11:18 +00001346 DOUT << "Removed dead store:\t" << *DeadStore;
1347 InvalidateKills(*DeadStore, RegKills, KillOps);
Evan Chengd368d822007-08-14 09:11:18 +00001348 VRM.RemoveFromFoldedVirtMap(DeadStore);
Evan Chengf3255842007-10-13 02:50:24 +00001349 MBB.erase(DeadStore);
1350 if (!NewStore)
1351 ++NumDSE;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352 }
Evan Chengf3255842007-10-13 02:50:24 +00001353
Evan Chengd368d822007-08-14 09:11:18 +00001354 MaybeDeadStores[SS] = NULL;
Evan Chengf3255842007-10-13 02:50:24 +00001355 if (NewStore) {
1356 // Treat this store as a spill merged into a copy. That makes the
1357 // stack slot value available.
1358 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
1359 goto ProcessNextInst;
1360 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 }
1362
1363 // If the spill slot value is available, and this is a new definition of
1364 // the value, the value is not available anymore.
1365 if (MR & VirtRegMap::isMod) {
1366 // Notice that the value in this stack slot has been modified.
Evan Cheng1204d172007-08-13 23:45:17 +00001367 Spills.ModifyStackSlotOrReMat(SS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368
1369 // If this is *just* a mod of the value, check to see if this is just a
1370 // store to the spill slot (i.e. the spill got merged into the copy). If
1371 // so, realize that the vreg is available now, and add the store to the
1372 // MaybeDeadStore info.
1373 int StackSlot;
1374 if (!(MR & VirtRegMap::isRef)) {
1375 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1376 assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
1377 "Src hasn't been allocated yet?");
1378 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
1379 // this as a potentially dead store in case there is a subsequent
1380 // store into the stack slot without a read from it.
1381 MaybeDeadStores[StackSlot] = &MI;
1382
1383 // If the stack slot value was previously available in some other
1384 // register, change it now. Otherwise, make the register available,
1385 // in PhysReg.
1386 Spills.addAvailable(StackSlot, &MI, SrcReg, false/*don't clobber*/);
1387 }
1388 }
1389 }
1390 }
1391
1392 // Process all of the spilled defs.
1393 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1394 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001395 if (!(MO.isRegister() && MO.getReg() && MO.isDef()))
1396 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001398 unsigned VirtReg = MO.getReg();
1399 if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
1400 // Check to see if this is a noop copy. If so, eliminate the
1401 // instruction before considering the dest reg to be changed.
1402 unsigned Src, Dst;
1403 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1404 ++NumDCE;
1405 DOUT << "Removing now-noop copy: " << MI;
1406 MBB.erase(&MI);
1407 Erased = true;
1408 VRM.RemoveFromFoldedVirtMap(&MI);
1409 Spills.disallowClobberPhysReg(VirtReg);
1410 goto ProcessNextInst;
1411 }
1412
1413 // If it's not a no-op copy, it clobbers the value in the destreg.
1414 Spills.ClobberPhysReg(VirtReg);
1415 ReusedOperands.markClobbered(VirtReg);
1416
1417 // Check to see if this instruction is a load from a stack slot into
1418 // a register. If so, this provides the stack slot value in the reg.
1419 int FrameIdx;
1420 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
1421 assert(DestReg == VirtReg && "Unknown load situation!");
1422
1423 // If it is a folded reference, then it's not safe to clobber.
1424 bool Folded = FoldedSS.count(FrameIdx);
1425 // Otherwise, if it wasn't available, remember that it is now!
1426 Spills.addAvailable(FrameIdx, &MI, DestReg, !Folded);
1427 goto ProcessNextInst;
1428 }
1429
1430 continue;
1431 }
1432
Evan Cheng4d0fbf32007-11-14 07:59:08 +00001433 unsigned SubIdx = MO.getSubReg();
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001434 bool DoReMat = VRM.isReMaterialized(VirtReg);
1435 if (DoReMat)
1436 ReMatDefs.insert(&MI);
1437
1438 // The only vregs left are stack slot definitions.
1439 int StackSlot = VRM.getStackSlot(VirtReg);
1440 const TargetRegisterClass *RC = RegMap->getRegClass(VirtReg);
1441
1442 // If this def is part of a two-address operand, make sure to execute
1443 // the store from the correct physical register.
1444 unsigned PhysReg;
1445 int TiedOp = MI.getInstrDescriptor()->findTiedToSrcOperand(i);
Evan Chenga1b89c22007-11-02 17:35:08 +00001446 if (TiedOp != -1) {
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001447 PhysReg = MI.getOperand(TiedOp).getReg();
Evan Cheng4d0fbf32007-11-14 07:59:08 +00001448 if (SubIdx) {
Evan Chenga1b89c22007-11-02 17:35:08 +00001449 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, MRI);
1450 assert(SuperReg && MRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
1451 "Can't find corresponding super-register!");
1452 PhysReg = SuperReg;
1453 }
1454 } else {
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001455 PhysReg = VRM.getPhys(VirtReg);
1456 if (ReusedOperands.isClobbered(PhysReg)) {
1457 // Another def has taken the assigned physreg. It must have been a
1458 // use&def which got it due to reuse. Undo the reuse!
1459 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1460 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1461 }
1462 }
1463
1464 MF.setPhysRegUsed(PhysReg);
Evan Cheng4d0fbf32007-11-14 07:59:08 +00001465 unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
Evan Chenga1b89c22007-11-02 17:35:08 +00001466 ReusedOperands.markClobbered(RReg);
1467 MI.getOperand(i).setReg(RReg);
1468
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001469 if (!MO.isDead()) {
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001470 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
Evan Chengcecc8222007-11-17 00:40:40 +00001471 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, LastStore,
1472 Spills, ReMatDefs, RegKills, KillOps, VRM);
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001473
1474 // Check to see if this is a noop copy. If so, eliminate the
1475 // instruction before considering the dest reg to be changed.
1476 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477 unsigned Src, Dst;
1478 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1479 ++NumDCE;
1480 DOUT << "Removing now-noop copy: " << MI;
1481 MBB.erase(&MI);
1482 Erased = true;
1483 VRM.RemoveFromFoldedVirtMap(&MI);
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001484 UpdateKills(*LastStore, RegKills, KillOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001485 goto ProcessNextInst;
1486 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001487 }
Evan Cheng4a7e72f2007-10-19 21:23:22 +00001488 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001489 }
1490 ProcessNextInst:
1491 if (!Erased && !BackTracked)
1492 for (MachineBasicBlock::iterator II = MI; II != NextMII; ++II)
1493 UpdateKills(*II, RegKills, KillOps);
1494 MII = NextMII;
1495 }
1496}
1497
1498
1499llvm::Spiller* llvm::createSpiller() {
1500 switch (SpillerOpt) {
1501 default: assert(0 && "Unreachable!");
1502 case local:
1503 return new LocalSpiller();
1504 case simple:
1505 return new SimpleSpiller();
1506 }
1507}