1 //===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the machine register scavenger. It can provide
11 // information, such as unused registers, at any point in a machine basic block.
12 // It also provides a mechanism to make registers available by evicting them to
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "reg-scavenging"
18 #include "llvm/CodeGen/RegisterScavenging.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/STLExtras.h"
36 /// setUsed - Set the register and its sub-registers as being used.
37 void RegScavenger::setUsed(unsigned Reg
) {
38 RegsAvailable
.reset(Reg
);
40 for (const unsigned *SubRegs
= TRI
->getSubRegisters(Reg
);
41 unsigned SubReg
= *SubRegs
; ++SubRegs
)
42 RegsAvailable
.reset(SubReg
);
45 bool RegScavenger::isAliasUsed(unsigned Reg
) const {
48 for (const unsigned *R
= TRI
->getAliasSet(Reg
); *R
; ++R
)
54 void RegScavenger::initRegState() {
57 ScavengeRestore
= NULL
;
59 // All registers started out unused.
62 // Reserved registers are always used.
63 RegsAvailable
^= ReservedRegs
;
68 // Live-in registers are in use.
69 for (MachineBasicBlock::livein_iterator I
= MBB
->livein_begin(),
70 E
= MBB
->livein_end(); I
!= E
; ++I
)
73 // Pristine CSRs are also unavailable.
74 BitVector PR
= MBB
->getParent()->getFrameInfo()->getPristineRegs(MBB
);
75 for (int I
= PR
.find_first(); I
>0; I
= PR
.find_next(I
))
79 void RegScavenger::enterBasicBlock(MachineBasicBlock
*mbb
) {
80 MachineFunction
&MF
= *mbb
->getParent();
81 const TargetMachine
&TM
= MF
.getTarget();
82 TII
= TM
.getInstrInfo();
83 TRI
= TM
.getRegisterInfo();
84 MRI
= &MF
.getRegInfo();
86 assert((NumPhysRegs
== 0 || NumPhysRegs
== TRI
->getNumRegs()) &&
91 NumPhysRegs
= TRI
->getNumRegs();
92 RegsAvailable
.resize(NumPhysRegs
);
94 // Create reserved registers bitvector.
95 ReservedRegs
= TRI
->getReservedRegs(MF
);
97 // Create callee-saved registers bitvector.
98 CalleeSavedRegs
.resize(NumPhysRegs
);
99 const unsigned *CSRegs
= TRI
->getCalleeSavedRegs();
101 for (unsigned i
= 0; CSRegs
[i
]; ++i
)
102 CalleeSavedRegs
.set(CSRegs
[i
]);
111 void RegScavenger::addRegWithSubRegs(BitVector
&BV
, unsigned Reg
) {
113 for (const unsigned *R
= TRI
->getSubRegisters(Reg
); *R
; R
++)
117 void RegScavenger::addRegWithAliases(BitVector
&BV
, unsigned Reg
) {
119 for (const unsigned *R
= TRI
->getAliasSet(Reg
); *R
; R
++)
123 void RegScavenger::forward() {
129 assert(MBBI
!= MBB
->end() && "Already past the end of the basic block!");
130 MBBI
= llvm::next(MBBI
);
132 assert(MBBI
!= MBB
->end() && "Already at the end of the basic block!");
134 MachineInstr
*MI
= MBBI
;
136 if (MI
== ScavengeRestore
) {
139 ScavengeRestore
= NULL
;
142 if (MI
->isDebugValue())
145 // Find out which registers are early clobbered, killed, defined, and marked
146 // def-dead in this instruction.
147 // FIXME: The scavenger is not predication aware. If the instruction is
148 // predicated, conservatively assume "kill" markers do not actually kill the
149 // register. Similarly ignores "dead" markers.
150 bool isPred
= TII
->isPredicated(MI
);
151 BitVector
EarlyClobberRegs(NumPhysRegs
);
152 BitVector
KillRegs(NumPhysRegs
);
153 BitVector
DefRegs(NumPhysRegs
);
154 BitVector
DeadRegs(NumPhysRegs
);
155 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
156 const MachineOperand
&MO
= MI
->getOperand(i
);
159 unsigned Reg
= MO
.getReg();
160 if (!Reg
|| isReserved(Reg
))
164 // Ignore undef uses.
167 // Two-address operands implicitly kill.
168 if (!isPred
&& (MO
.isKill() || MI
->isRegTiedToDefOperand(i
)))
169 addRegWithSubRegs(KillRegs
, Reg
);
172 if (!isPred
&& MO
.isDead())
173 addRegWithSubRegs(DeadRegs
, Reg
);
175 addRegWithSubRegs(DefRegs
, Reg
);
176 if (MO
.isEarlyClobber())
177 addRegWithAliases(EarlyClobberRegs
, Reg
);
181 // Verify uses and defs.
182 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
183 const MachineOperand
&MO
= MI
->getOperand(i
);
186 unsigned Reg
= MO
.getReg();
187 if (!Reg
|| isReserved(Reg
))
193 // Check if it's partial live: e.g.
194 // D0 = insert_subreg D0<undef>, S0
196 // The problem is the insert_subreg could be eliminated. The use of
197 // D0 is using a partially undef value. This is not *incorrect* since
198 // S1 is can be freely clobbered.
199 // Ideally we would like a way to model this, but leaving the
200 // insert_subreg around causes both correctness and performance issues.
201 bool SubUsed
= false;
202 for (const unsigned *SubRegs
= TRI
->getSubRegisters(Reg
);
203 unsigned SubReg
= *SubRegs
; ++SubRegs
)
204 if (isUsed(SubReg
)) {
208 assert(SubUsed
&& "Using an undefined register!");
210 assert((!EarlyClobberRegs
.test(Reg
) || MI
->isRegTiedToDefOperand(i
)) &&
211 "Using an early clobbered register!");
215 // FIXME: Enable this once we've figured out how to correctly transfer
216 // implicit kills during codegen passes like the coalescer.
217 assert((KillRegs
.test(Reg
) || isUnused(Reg
) ||
218 isLiveInButUnusedBefore(Reg
, MI
, MBB
, TRI
, MRI
)) &&
219 "Re-defining a live register!");
224 // Commit the changes.
230 void RegScavenger::getRegsUsed(BitVector
&used
, bool includeReserved
) {
232 used
= ~RegsAvailable
;
234 used
= ~RegsAvailable
& ~ReservedRegs
;
237 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass
*RC
) const {
238 for (TargetRegisterClass::iterator I
= RC
->begin(), E
= RC
->end();
240 if (!isAliasUsed(*I
)) {
241 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI
->getName(*I
) <<
248 /// getRegsAvailable - Return all available registers in the register class
250 BitVector
RegScavenger::getRegsAvailable(const TargetRegisterClass
*RC
) {
251 BitVector
Mask(TRI
->getNumRegs());
252 for (TargetRegisterClass::iterator I
= RC
->begin(), E
= RC
->end();
254 if (!isAliasUsed(*I
))
259 /// findSurvivorReg - Return the candidate register that is unused for the
260 /// longest after StargMII. UseMI is set to the instruction where the search
263 /// No more than InstrLimit instructions are inspected.
265 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI
,
266 BitVector
&Candidates
,
268 MachineBasicBlock::iterator
&UseMI
) {
269 int Survivor
= Candidates
.find_first();
270 assert(Survivor
> 0 && "No candidates for scavenging");
272 MachineBasicBlock::iterator ME
= MBB
->getFirstTerminator();
273 assert(StartMI
!= ME
&& "MI already at terminator");
274 MachineBasicBlock::iterator RestorePointMI
= StartMI
;
275 MachineBasicBlock::iterator MI
= StartMI
;
277 bool inVirtLiveRange
= false;
278 for (++MI
; InstrLimit
> 0 && MI
!= ME
; ++MI
, --InstrLimit
) {
279 if (MI
->isDebugValue()) {
280 ++InstrLimit
; // Don't count debug instructions
283 bool isVirtKillInsn
= false;
284 bool isVirtDefInsn
= false;
285 // Remove any candidates touched by instruction.
286 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
287 const MachineOperand
&MO
= MI
->getOperand(i
);
288 if (!MO
.isReg() || MO
.isUndef() || !MO
.getReg())
290 if (TargetRegisterInfo::isVirtualRegister(MO
.getReg())) {
292 isVirtDefInsn
= true;
293 else if (MO
.isKill())
294 isVirtKillInsn
= true;
297 Candidates
.reset(MO
.getReg());
298 for (const unsigned *R
= TRI
->getAliasSet(MO
.getReg()); *R
; R
++)
299 Candidates
.reset(*R
);
301 // If we're not in a virtual reg's live range, this is a valid
303 if (!inVirtLiveRange
) RestorePointMI
= MI
;
305 // Update whether we're in the live range of a virtual register
306 if (isVirtKillInsn
) inVirtLiveRange
= false;
307 if (isVirtDefInsn
) inVirtLiveRange
= true;
309 // Was our survivor untouched by this instruction?
310 if (Candidates
.test(Survivor
))
313 // All candidates gone?
314 if (Candidates
.none())
317 Survivor
= Candidates
.find_first();
319 // If we ran off the end, that's where we want to restore.
320 if (MI
== ME
) RestorePointMI
= ME
;
321 assert (RestorePointMI
!= StartMI
&&
322 "No available scavenger restore location!");
324 // We ran out of candidates, so stop the search.
325 UseMI
= RestorePointMI
;
329 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass
*RC
,
330 MachineBasicBlock::iterator I
,
332 // Consider all allocatable registers in the register class initially
333 BitVector Candidates
=
334 TRI
->getAllocatableSet(*I
->getParent()->getParent(), RC
);
336 // Exclude all the registers being used by the instruction.
337 for (unsigned i
= 0, e
= I
->getNumOperands(); i
!= e
; ++i
) {
338 MachineOperand
&MO
= I
->getOperand(i
);
339 if (MO
.isReg() && MO
.getReg() != 0 &&
340 !TargetRegisterInfo::isVirtualRegister(MO
.getReg()))
341 Candidates
.reset(MO
.getReg());
344 // Try to find a register that's unused if there is one, as then we won't
345 // have to spill. Search explicitly rather than masking out based on
346 // RegsAvailable, as RegsAvailable does not take aliases into account.
347 // That's what getRegsAvailable() is for.
348 BitVector Available
= getRegsAvailable(RC
);
350 if ((Candidates
& Available
).any())
351 Candidates
&= Available
;
353 // Find the register whose use is furthest away.
354 MachineBasicBlock::iterator UseMI
;
355 unsigned SReg
= findSurvivorReg(I
, Candidates
, 25, UseMI
);
357 // If we found an unused register there is no reason to spill it.
358 if (!isAliasUsed(SReg
)) {
359 DEBUG(dbgs() << "Scavenged register: " << TRI
->getName(SReg
) << "\n");
363 assert(ScavengedReg
== 0 &&
364 "Scavenger slot is live, unable to scavenge another register!");
366 // Avoid infinite regress
369 // If the target knows how to save/restore the register, let it do so;
370 // otherwise, use the emergency stack spill slot.
371 if (!TRI
->saveScavengerRegister(*MBB
, I
, UseMI
, RC
, SReg
)) {
372 // Spill the scavenged register before I.
373 assert(ScavengingFrameIndex
>= 0 &&
374 "Cannot scavenge register without an emergency spill slot!");
375 TII
->storeRegToStackSlot(*MBB
, I
, SReg
, true, ScavengingFrameIndex
, RC
,TRI
);
376 MachineBasicBlock::iterator II
= prior(I
);
377 TRI
->eliminateFrameIndex(II
, SPAdj
, this);
379 // Restore the scavenged register before its use (or first terminator).
380 TII
->loadRegFromStackSlot(*MBB
, UseMI
, SReg
, ScavengingFrameIndex
, RC
, TRI
);
382 TRI
->eliminateFrameIndex(II
, SPAdj
, this);
385 ScavengeRestore
= prior(UseMI
);
387 // Doing this here leads to infinite regress.
388 // ScavengedReg = SReg;
391 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI
->getName(SReg
) <<