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/MachineFunction.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/STLExtras.h"
31 /// RedefinesSuperRegPart - Return true if the specified register is redefining
32 /// part of a super-register.
33 static bool RedefinesSuperRegPart(const MachineInstr *MI, unsigned SubReg,
34 const TargetRegisterInfo *TRI) {
35 bool SeenSuperUse = false;
36 bool SeenSuperDef = false;
37 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
38 const MachineOperand &MO = MI->getOperand(i);
39 if (!MO.isReg() || MO.isUndef())
41 if (TRI->isSuperRegister(SubReg, MO.getReg())) {
44 else if (MO.isImplicit())
49 return SeenSuperDef && SeenSuperUse;
52 static bool RedefinesSuperRegPart(const MachineInstr *MI,
53 const MachineOperand &MO,
54 const TargetRegisterInfo *TRI) {
55 assert(MO.isReg() && MO.isDef() && "Not a register def!");
56 return RedefinesSuperRegPart(MI, MO.getReg(), TRI);
59 /// setUsed - Set the register and its sub-registers as being used.
60 void RegScavenger::setUsed(unsigned Reg, bool ImpDef) {
61 RegsAvailable.reset(Reg);
62 ImplicitDefed[Reg] = ImpDef;
64 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
65 unsigned SubReg = *SubRegs; ++SubRegs) {
66 RegsAvailable.reset(SubReg);
67 ImplicitDefed[SubReg] = ImpDef;
71 /// setUnused - Set the register and its sub-registers as being unused.
72 void RegScavenger::setUnused(unsigned Reg, const MachineInstr *MI) {
73 RegsAvailable.set(Reg);
74 ImplicitDefed.reset(Reg);
76 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
77 unsigned SubReg = *SubRegs; ++SubRegs)
78 if (!RedefinesSuperRegPart(MI, Reg, TRI)) {
79 RegsAvailable.set(SubReg);
80 ImplicitDefed.reset(SubReg);
84 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
85 MachineFunction &MF = *mbb->getParent();
86 const TargetMachine &TM = MF.getTarget();
87 TII = TM.getInstrInfo();
88 TRI = TM.getRegisterInfo();
89 MRI = &MF.getRegInfo();
91 assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
95 NumPhysRegs = TRI->getNumRegs();
96 RegsAvailable.resize(NumPhysRegs);
97 ImplicitDefed.resize(NumPhysRegs);
99 // Create reserved registers bitvector.
100 ReservedRegs = TRI->getReservedRegs(MF);
102 // Create callee-saved registers bitvector.
103 CalleeSavedRegs.resize(NumPhysRegs);
104 const unsigned *CSRegs = TRI->getCalleeSavedRegs();
106 for (unsigned i = 0; CSRegs[i]; ++i)
107 CalleeSavedRegs.set(CSRegs[i]);
113 ScavengeRestore = NULL;
116 ImplicitDefed.reset();
118 // All registers started out unused.
121 // Reserved registers are always used.
122 RegsAvailable ^= ReservedRegs;
124 // Live-in registers are in use.
125 if (!MBB->livein_empty())
126 for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
127 E = MBB->livein_end(); I != E; ++I)
133 void RegScavenger::restoreScavengedReg() {
134 TII->loadRegFromStackSlot(*MBB, MBBI, ScavengedReg,
135 ScavengingFrameIndex, ScavengedRC);
136 MachineBasicBlock::iterator II = prior(MBBI);
137 TRI->eliminateFrameIndex(II, 0, this);
138 setUsed(ScavengedReg);
144 /// isLiveInButUnusedBefore - Return true if register is livein the MBB not
145 /// not used before it reaches the MI that defines register.
146 static bool isLiveInButUnusedBefore(unsigned Reg, MachineInstr *MI,
147 MachineBasicBlock *MBB,
148 const TargetRegisterInfo *TRI,
149 MachineRegisterInfo* MRI) {
150 // First check if register is livein.
151 bool isLiveIn = false;
152 for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
153 E = MBB->livein_end(); I != E; ++I)
154 if (Reg == *I || TRI->isSuperRegister(Reg, *I)) {
161 // Is there any use of it before the specified MI?
162 SmallPtrSet<MachineInstr*, 4> UsesInMBB;
163 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
164 UE = MRI->use_end(); UI != UE; ++UI) {
165 MachineInstr *UseMI = &*UI;
166 if (UseMI->getParent() == MBB)
167 UsesInMBB.insert(UseMI);
169 if (UsesInMBB.empty())
172 for (MachineBasicBlock::iterator I = MBB->begin(), E = MI; I != E; ++I)
173 if (UsesInMBB.count(&*I))
179 void RegScavenger::forward() {
185 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
189 MachineInstr *MI = MBBI;
190 DistanceMap.insert(std::make_pair(MI, CurrDist++));
192 if (MI == ScavengeRestore) {
195 ScavengeRestore = NULL;
198 bool IsImpDef = MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF;
200 // Separate register operands into 3 classes: uses, defs, earlyclobbers.
201 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> UseMOs;
202 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> DefMOs;
203 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> EarlyClobberMOs;
204 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
205 const MachineOperand &MO = MI->getOperand(i);
206 if (!MO.isReg() || MO.getReg() == 0 || MO.isUndef())
209 UseMOs.push_back(std::make_pair(&MO,i));
210 else if (MO.isEarlyClobber())
211 EarlyClobberMOs.push_back(std::make_pair(&MO,i));
213 DefMOs.push_back(std::make_pair(&MO,i));
216 // Process uses first.
217 BitVector KillRegs(NumPhysRegs);
218 for (unsigned i = 0, e = UseMOs.size(); i != e; ++i) {
219 const MachineOperand MO = *UseMOs[i].first;
220 unsigned Reg = MO.getReg();
222 assert(isUsed(Reg) && "Using an undefined register!");
224 // Kill of implicit_def defined registers are ignored. e.g.
225 // entry: 0x2029ab8, LLVM BB @0x1b06080, ID#0:
227 // %R0<def> = IMPLICIT_DEF
228 // %R0<def> = IMPLICIT_DEF
229 // STR %R0<kill>, %R0, %reg0, 0, 14, %reg0, Mem:ST(4,4) [0x1b06510 + 0]
230 // %R1<def> = LDR %R0, %reg0, 24, 14, %reg0, Mem:LD(4,4) [0x1b065bc + 0]
231 if (MO.isKill() && !isReserved(Reg) && !isImplicitlyDefined(Reg)) {
234 // Mark sub-registers as used.
235 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
236 unsigned SubReg = *SubRegs; ++SubRegs)
237 KillRegs.set(SubReg);
241 // Change states of all registers after all the uses are processed to guard
242 // against multiple uses.
245 // Process early clobber defs then process defs. We can have a early clobber
246 // that is dead, it should not conflict with a def that happens one "slot"
247 // (see InstrSlots in LiveIntervalAnalysis.h) later.
248 unsigned NumECs = EarlyClobberMOs.size();
249 unsigned NumDefs = DefMOs.size();
251 for (unsigned i = 0, e = NumECs + NumDefs; i != e; ++i) {
252 const MachineOperand &MO = (i < NumECs)
253 ? *EarlyClobberMOs[i].first : *DefMOs[i-NumECs].first;
254 unsigned Idx = (i < NumECs)
255 ? EarlyClobberMOs[i].second : DefMOs[i-NumECs].second;
256 unsigned Reg = MO.getReg();
258 // If it's dead upon def, then it is now free.
264 // Skip two-address destination operand.
265 if (MI->isRegTiedToUseOperand(Idx)) {
266 assert(isUsed(Reg) && "Using an undefined register!");
270 // Skip if this is merely redefining part of a super-register.
271 if (RedefinesSuperRegPart(MI, MO, TRI))
274 // Implicit def is allowed to "re-define" any register. Similarly,
275 // implicitly defined registers can be clobbered.
276 assert((isReserved(Reg) || isUnused(Reg) ||
277 IsImpDef || isImplicitlyDefined(Reg) ||
278 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
279 "Re-defining a live register!");
280 setUsed(Reg, IsImpDef);
284 void RegScavenger::backward() {
285 assert(Tracking && "Not tracking states!");
286 assert(MBBI != MBB->begin() && "Already at start of basic block!");
287 // Move ptr backward.
290 MachineInstr *MI = MBBI;
291 DistanceMap.erase(MI);
294 // Separate register operands into 3 classes: uses, defs, earlyclobbers.
295 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> UseMOs;
296 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> DefMOs;
297 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> EarlyClobberMOs;
298 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
299 const MachineOperand &MO = MI->getOperand(i);
300 if (!MO.isReg() || MO.getReg() == 0 || MO.isUndef())
303 UseMOs.push_back(std::make_pair(&MO,i));
304 else if (MO.isEarlyClobber())
305 EarlyClobberMOs.push_back(std::make_pair(&MO,i));
307 DefMOs.push_back(std::make_pair(&MO,i));
311 // Process defs first.
312 unsigned NumECs = EarlyClobberMOs.size();
313 unsigned NumDefs = DefMOs.size();
314 for (unsigned i = 0, e = NumECs + NumDefs; i != e; ++i) {
315 const MachineOperand &MO = (i < NumDefs)
316 ? *DefMOs[i].first : *EarlyClobberMOs[i-NumDefs].first;
317 unsigned Idx = (i < NumECs)
318 ? DefMOs[i].second : EarlyClobberMOs[i-NumDefs].second;
320 // Skip two-address destination operand.
321 if (MI->isRegTiedToUseOperand(Idx))
324 unsigned Reg = MO.getReg();
326 if (!isReserved(Reg))
331 BitVector UseRegs(NumPhysRegs);
332 for (unsigned i = 0, e = UseMOs.size(); i != e; ++i) {
333 const MachineOperand MO = *UseMOs[i].first;
334 unsigned Reg = MO.getReg();
335 assert(isUnused(Reg) || isReserved(Reg));
338 // Set the sub-registers as "used".
339 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
340 unsigned SubReg = *SubRegs; ++SubRegs)
346 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
348 used = ~RegsAvailable;
350 used = ~RegsAvailable & ~ReservedRegs;
353 /// CreateRegClassMask - Set the bits that represent the registers in the
354 /// TargetRegisterClass.
355 static void CreateRegClassMask(const TargetRegisterClass *RC, BitVector &Mask) {
356 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E;
361 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
362 const BitVector &Candidates) const {
363 // Mask off the registers which are not in the TargetRegisterClass.
364 BitVector RegsAvailableCopy(NumPhysRegs, false);
365 CreateRegClassMask(RegClass, RegsAvailableCopy);
366 RegsAvailableCopy &= RegsAvailable;
368 // Restrict the search to candidates.
369 RegsAvailableCopy &= Candidates;
371 // Returns the first unused (bit is set) register, or 0 is none is found.
372 int Reg = RegsAvailableCopy.find_first();
373 return (Reg == -1) ? 0 : Reg;
376 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
377 bool ExCalleeSaved) const {
378 // Mask off the registers which are not in the TargetRegisterClass.
379 BitVector RegsAvailableCopy(NumPhysRegs, false);
380 CreateRegClassMask(RegClass, RegsAvailableCopy);
381 RegsAvailableCopy &= RegsAvailable;
383 // If looking for a non-callee-saved register, mask off all the callee-saved
386 RegsAvailableCopy &= ~CalleeSavedRegs;
388 // Returns the first unused (bit is set) register, or 0 is none is found.
389 int Reg = RegsAvailableCopy.find_first();
390 return (Reg == -1) ? 0 : Reg;
393 /// findFirstUse - Calculate the distance to the first use of the
394 /// specified register.
396 RegScavenger::findFirstUse(MachineBasicBlock *MBB,
397 MachineBasicBlock::iterator I, unsigned Reg,
399 MachineInstr *UseMI = 0;
401 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
402 RE = MRI->reg_end(); RI != RE; ++RI) {
403 MachineInstr *UDMI = &*RI;
404 if (UDMI->getParent() != MBB)
406 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
407 if (DI == DistanceMap.end()) {
408 // If it's not in map, it's below current MI, let's initialize the
411 unsigned Dist = CurrDist + 1;
412 while (I != MBB->end()) {
413 DistanceMap.insert(std::make_pair(I, Dist++));
417 DI = DistanceMap.find(UDMI);
418 if (DI->second > CurrDist && DI->second < Dist) {
426 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
427 MachineBasicBlock::iterator I,
429 assert(ScavengingFrameIndex >= 0 &&
430 "Cannot scavenge a register without an emergency spill slot!");
432 // Mask off the registers which are not in the TargetRegisterClass.
433 BitVector Candidates(NumPhysRegs, false);
434 CreateRegClassMask(RC, Candidates);
435 Candidates ^= ReservedRegs; // Do not include reserved registers.
437 // Exclude all the registers being used by the instruction.
438 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
439 MachineOperand &MO = I->getOperand(i);
441 Candidates.reset(MO.getReg());
444 // Find the register whose use is furthest away.
446 unsigned MaxDist = 0;
447 MachineInstr *MaxUseMI = 0;
448 int Reg = Candidates.find_first();
451 MachineInstr *UseMI = findFirstUse(MBB, I, Reg, Dist);
452 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
454 MachineInstr *AsUseMI = findFirstUse(MBB, I, *AS, AsDist);
460 if (Dist >= MaxDist) {
465 Reg = Candidates.find_next(Reg);
468 if (ScavengedReg != 0) {
469 assert(0 && "Scavenger slot is live, unable to scavenge another register!");
473 // Spill the scavenged register before I.
474 TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC);
475 MachineBasicBlock::iterator II = prior(I);
476 TRI->eliminateFrameIndex(II, SPAdj, this);
478 // Restore the scavenged register before its use (or first terminator).
480 ? MachineBasicBlock::iterator(MaxUseMI) : MBB->getFirstTerminator();
481 TII->loadRegFromStackSlot(*MBB, II, SReg, ScavengingFrameIndex, RC);
482 ScavengeRestore = prior(II);