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) {
61 RegsAvailable.reset(Reg);
63 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
64 unsigned SubReg = *SubRegs; ++SubRegs)
65 RegsAvailable.reset(SubReg);
68 /// setUnused - Set the register and its sub-registers as being unused.
69 void RegScavenger::setUnused(unsigned Reg, const MachineInstr *MI) {
70 RegsAvailable.set(Reg);
72 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
73 unsigned SubReg = *SubRegs; ++SubRegs)
74 if (!RedefinesSuperRegPart(MI, Reg, TRI))
75 RegsAvailable.set(SubReg);
78 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
79 MachineFunction &MF = *mbb->getParent();
80 const TargetMachine &TM = MF.getTarget();
81 TII = TM.getInstrInfo();
82 TRI = TM.getRegisterInfo();
83 MRI = &MF.getRegInfo();
85 assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
89 NumPhysRegs = TRI->getNumRegs();
90 RegsAvailable.resize(NumPhysRegs);
92 // Create reserved registers bitvector.
93 ReservedRegs = TRI->getReservedRegs(MF);
95 // Create callee-saved registers bitvector.
96 CalleeSavedRegs.resize(NumPhysRegs);
97 const unsigned *CSRegs = TRI->getCalleeSavedRegs();
99 for (unsigned i = 0; CSRegs[i]; ++i)
100 CalleeSavedRegs.set(CSRegs[i]);
106 ScavengeRestore = NULL;
110 // All registers started out unused.
113 // Reserved registers are always used.
114 RegsAvailable ^= ReservedRegs;
116 // Live-in registers are in use.
117 if (!MBB->livein_empty())
118 for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
119 E = MBB->livein_end(); I != E; ++I)
125 void RegScavenger::restoreScavengedReg() {
126 TII->loadRegFromStackSlot(*MBB, MBBI, ScavengedReg,
127 ScavengingFrameIndex, ScavengedRC);
128 MachineBasicBlock::iterator II = prior(MBBI);
129 TRI->eliminateFrameIndex(II, 0, this);
130 setUsed(ScavengedReg);
136 /// isLiveInButUnusedBefore - Return true if register is livein the MBB not
137 /// not used before it reaches the MI that defines register.
138 static bool isLiveInButUnusedBefore(unsigned Reg, MachineInstr *MI,
139 MachineBasicBlock *MBB,
140 const TargetRegisterInfo *TRI,
141 MachineRegisterInfo* MRI) {
142 // First check if register is livein.
143 bool isLiveIn = false;
144 for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
145 E = MBB->livein_end(); I != E; ++I)
146 if (Reg == *I || TRI->isSuperRegister(Reg, *I)) {
153 // Is there any use of it before the specified MI?
154 SmallPtrSet<MachineInstr*, 4> UsesInMBB;
155 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
156 UE = MRI->use_end(); UI != UE; ++UI) {
157 MachineInstr *UseMI = &*UI;
158 if (UseMI->getParent() == MBB)
159 UsesInMBB.insert(UseMI);
161 if (UsesInMBB.empty())
164 for (MachineBasicBlock::iterator I = MBB->begin(), E = MI; I != E; ++I)
165 if (UsesInMBB.count(&*I))
171 void RegScavenger::forward() {
177 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
181 MachineInstr *MI = MBBI;
182 DistanceMap.insert(std::make_pair(MI, CurrDist++));
184 if (MI == ScavengeRestore) {
187 ScavengeRestore = NULL;
190 // Separate register operands into 3 classes: uses, defs, earlyclobbers.
191 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> UseMOs;
192 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> DefMOs;
193 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> EarlyClobberMOs;
194 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
195 const MachineOperand &MO = MI->getOperand(i);
196 if (!MO.isReg() || MO.getReg() == 0 || MO.isUndef())
199 UseMOs.push_back(std::make_pair(&MO,i));
200 else if (MO.isEarlyClobber())
201 EarlyClobberMOs.push_back(std::make_pair(&MO,i));
203 DefMOs.push_back(std::make_pair(&MO,i));
206 // Process uses first.
207 BitVector KillRegs(NumPhysRegs);
208 for (unsigned i = 0, e = UseMOs.size(); i != e; ++i) {
209 const MachineOperand MO = *UseMOs[i].first;
210 unsigned Reg = MO.getReg();
212 assert(isUsed(Reg) && "Using an undefined register!");
214 if (MO.isKill() && !isReserved(Reg)) {
217 // Mark sub-registers as used.
218 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
219 unsigned SubReg = *SubRegs; ++SubRegs)
220 KillRegs.set(SubReg);
224 // Change states of all registers after all the uses are processed to guard
225 // against multiple uses.
228 // Process early clobber defs then process defs. We can have a early clobber
229 // that is dead, it should not conflict with a def that happens one "slot"
230 // (see InstrSlots in LiveIntervalAnalysis.h) later.
231 unsigned NumECs = EarlyClobberMOs.size();
232 unsigned NumDefs = DefMOs.size();
234 for (unsigned i = 0, e = NumECs + NumDefs; i != e; ++i) {
235 const MachineOperand &MO = (i < NumECs)
236 ? *EarlyClobberMOs[i].first : *DefMOs[i-NumECs].first;
237 unsigned Idx = (i < NumECs)
238 ? EarlyClobberMOs[i].second : DefMOs[i-NumECs].second;
239 unsigned Reg = MO.getReg();
241 // If it's dead upon def, then it is now free.
247 // Skip two-address destination operand.
248 if (MI->isRegTiedToUseOperand(Idx)) {
249 assert(isUsed(Reg) && "Using an undefined register!");
253 // Skip if this is merely redefining part of a super-register.
254 if (RedefinesSuperRegPart(MI, MO, TRI))
257 // Implicit def is allowed to "re-define" any register. Similarly,
258 // implicitly defined registers can be clobbered.
259 assert((isReserved(Reg) || isUnused(Reg) ||
260 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
261 "Re-defining a live register!");
266 void RegScavenger::backward() {
267 assert(Tracking && "Not tracking states!");
268 assert(MBBI != MBB->begin() && "Already at start of basic block!");
269 // Move ptr backward.
272 MachineInstr *MI = MBBI;
273 DistanceMap.erase(MI);
276 // Separate register operands into 3 classes: uses, defs, earlyclobbers.
277 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> UseMOs;
278 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> DefMOs;
279 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> EarlyClobberMOs;
280 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
281 const MachineOperand &MO = MI->getOperand(i);
282 if (!MO.isReg() || MO.getReg() == 0 || MO.isUndef())
285 UseMOs.push_back(std::make_pair(&MO,i));
286 else if (MO.isEarlyClobber())
287 EarlyClobberMOs.push_back(std::make_pair(&MO,i));
289 DefMOs.push_back(std::make_pair(&MO,i));
293 // Process defs first.
294 unsigned NumECs = EarlyClobberMOs.size();
295 unsigned NumDefs = DefMOs.size();
296 for (unsigned i = 0, e = NumECs + NumDefs; i != e; ++i) {
297 const MachineOperand &MO = (i < NumDefs)
298 ? *DefMOs[i].first : *EarlyClobberMOs[i-NumDefs].first;
299 unsigned Idx = (i < NumECs)
300 ? DefMOs[i].second : EarlyClobberMOs[i-NumDefs].second;
302 // Skip two-address destination operand.
303 if (MI->isRegTiedToUseOperand(Idx))
306 unsigned Reg = MO.getReg();
308 if (!isReserved(Reg))
313 BitVector UseRegs(NumPhysRegs);
314 for (unsigned i = 0, e = UseMOs.size(); i != e; ++i) {
315 const MachineOperand MO = *UseMOs[i].first;
316 unsigned Reg = MO.getReg();
317 assert(isUnused(Reg) || isReserved(Reg));
320 // Set the sub-registers as "used".
321 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
322 unsigned SubReg = *SubRegs; ++SubRegs)
328 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
330 used = ~RegsAvailable;
332 used = ~RegsAvailable & ~ReservedRegs;
335 /// CreateRegClassMask - Set the bits that represent the registers in the
336 /// TargetRegisterClass.
337 static void CreateRegClassMask(const TargetRegisterClass *RC, BitVector &Mask) {
338 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E;
343 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
344 const BitVector &Candidates) const {
345 // Mask off the registers which are not in the TargetRegisterClass.
346 BitVector RegsAvailableCopy(NumPhysRegs, false);
347 CreateRegClassMask(RegClass, RegsAvailableCopy);
348 RegsAvailableCopy &= RegsAvailable;
350 // Restrict the search to candidates.
351 RegsAvailableCopy &= Candidates;
353 // Returns the first unused (bit is set) register, or 0 is none is found.
354 int Reg = RegsAvailableCopy.find_first();
355 return (Reg == -1) ? 0 : Reg;
358 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
359 bool ExCalleeSaved) const {
360 // Mask off the registers which are not in the TargetRegisterClass.
361 BitVector RegsAvailableCopy(NumPhysRegs, false);
362 CreateRegClassMask(RegClass, RegsAvailableCopy);
363 RegsAvailableCopy &= RegsAvailable;
365 // If looking for a non-callee-saved register, mask off all the callee-saved
368 RegsAvailableCopy &= ~CalleeSavedRegs;
370 // Returns the first unused (bit is set) register, or 0 is none is found.
371 int Reg = RegsAvailableCopy.find_first();
372 return (Reg == -1) ? 0 : Reg;
375 /// findFirstUse - Calculate the distance to the first use of the
376 /// specified register.
378 RegScavenger::findFirstUse(MachineBasicBlock *MBB,
379 MachineBasicBlock::iterator I, unsigned Reg,
381 MachineInstr *UseMI = 0;
383 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
384 RE = MRI->reg_end(); RI != RE; ++RI) {
385 MachineInstr *UDMI = &*RI;
386 if (UDMI->getParent() != MBB)
388 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
389 if (DI == DistanceMap.end()) {
390 // If it's not in map, it's below current MI, let's initialize the
393 unsigned Dist = CurrDist + 1;
394 while (I != MBB->end()) {
395 DistanceMap.insert(std::make_pair(I, Dist++));
399 DI = DistanceMap.find(UDMI);
400 if (DI->second > CurrDist && DI->second < Dist) {
408 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
409 MachineBasicBlock::iterator I,
411 assert(ScavengingFrameIndex >= 0 &&
412 "Cannot scavenge a register without an emergency spill slot!");
414 // Mask off the registers which are not in the TargetRegisterClass.
415 BitVector Candidates(NumPhysRegs, false);
416 CreateRegClassMask(RC, Candidates);
417 Candidates ^= ReservedRegs; // Do not include reserved registers.
419 // Exclude all the registers being used by the instruction.
420 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
421 MachineOperand &MO = I->getOperand(i);
423 Candidates.reset(MO.getReg());
426 // Find the register whose use is furthest away.
428 unsigned MaxDist = 0;
429 MachineInstr *MaxUseMI = 0;
430 int Reg = Candidates.find_first();
433 MachineInstr *UseMI = findFirstUse(MBB, I, Reg, Dist);
434 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
436 MachineInstr *AsUseMI = findFirstUse(MBB, I, *AS, AsDist);
442 if (Dist >= MaxDist) {
447 Reg = Candidates.find_next(Reg);
450 if (ScavengedReg != 0) {
451 assert(0 && "Scavenger slot is live, unable to scavenge another register!");
455 // Spill the scavenged register before I.
456 TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC);
457 MachineBasicBlock::iterator II = prior(I);
458 TRI->eliminateFrameIndex(II, SPAdj, this);
460 // Restore the scavenged register before its use (or first terminator).
462 ? MachineBasicBlock::iterator(MaxUseMI) : MBB->getFirstTerminator();
463 TII->loadRegFromStackSlot(*MBB, II, SReg, ScavengingFrameIndex, RC);
464 ScavengeRestore = prior(II);