1 //===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
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 register allocator allocates registers to a basic block at a time,
11 // attempting to keep values in registers and reusing registers as appropriate.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/IndexedMap.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
38 STATISTIC(NumStores, "Number of stores added");
39 STATISTIC(NumLoads , "Number of loads added");
41 static RegisterRegAlloc
42 localRegAlloc("local", "local register allocator",
43 createLocalRegisterAllocator);
46 class RALocal : public MachineFunctionPass {
49 RALocal() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1) {}
51 const TargetMachine *TM;
53 const TargetRegisterInfo *TRI;
54 const TargetInstrInfo *TII;
56 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
57 // values are spilled.
58 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
60 // Virt2PhysRegMap - This map contains entries for each virtual register
61 // that is currently available in a physical register.
62 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
64 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
65 return Virt2PhysRegMap[VirtReg];
68 // PhysRegsUsed - This array is effectively a map, containing entries for
69 // each physical register that currently has a value (ie, it is in
70 // Virt2PhysRegMap). The value mapped to is the virtual register
71 // corresponding to the physical register (the inverse of the
72 // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
73 // because it is used by a future instruction, and to -2 if it is not
74 // allocatable. If the entry for a physical register is -1, then the
75 // physical register is "not in the map".
77 std::vector<int> PhysRegsUsed;
79 // PhysRegsUseOrder - This contains a list of the physical registers that
80 // currently have a virtual register value in them. This list provides an
81 // ordering of registers, imposing a reallocation order. This list is only
82 // used if all registers are allocated and we have to spill one, in which
83 // case we spill the least recently used register. Entries at the front of
84 // the list are the least recently used registers, entries at the back are
85 // the most recently used.
87 std::vector<unsigned> PhysRegsUseOrder;
89 // Virt2LastUseMap - This maps each virtual register to its last use
90 // (MachineInstr*, operand index pair).
91 IndexedMap<std::pair<MachineInstr*, unsigned>, VirtReg2IndexFunctor>
94 std::pair<MachineInstr*,unsigned>& getVirtRegLastUse(unsigned Reg) {
95 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
96 return Virt2LastUseMap[Reg];
99 // VirtRegModified - This bitset contains information about which virtual
100 // registers need to be spilled back to memory when their registers are
101 // scavenged. If a virtual register has simply been rematerialized, there
102 // is no reason to spill it to memory when we need the register back.
104 BitVector VirtRegModified;
106 // UsedInMultipleBlocks - Tracks whether a particular register is used in
107 // more than one block.
108 BitVector UsedInMultipleBlocks;
110 void markVirtRegModified(unsigned Reg, bool Val = true) {
111 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
112 Reg -= TargetRegisterInfo::FirstVirtualRegister;
114 VirtRegModified.set(Reg);
116 VirtRegModified.reset(Reg);
119 bool isVirtRegModified(unsigned Reg) const {
120 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
121 assert(Reg - TargetRegisterInfo::FirstVirtualRegister <
122 VirtRegModified.size() && "Illegal virtual register!");
123 return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
126 void AddToPhysRegsUseOrder(unsigned Reg) {
127 std::vector<unsigned>::iterator It =
128 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg);
129 if (It != PhysRegsUseOrder.end())
130 PhysRegsUseOrder.erase(It);
131 PhysRegsUseOrder.push_back(Reg);
134 void MarkPhysRegRecentlyUsed(unsigned Reg) {
135 if (PhysRegsUseOrder.empty() ||
136 PhysRegsUseOrder.back() == Reg) return; // Already most recently used
138 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i) {
139 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
140 if (!areRegsEqual(Reg, RegMatch)) continue;
142 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
143 // Add it to the end of the list
144 PhysRegsUseOrder.push_back(RegMatch);
146 return; // Found an exact match, exit early
151 virtual const char *getPassName() const {
152 return "Local Register Allocator";
155 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
156 AU.setPreservesCFG();
157 AU.addRequiredID(PHIEliminationID);
158 AU.addRequiredID(TwoAddressInstructionPassID);
159 MachineFunctionPass::getAnalysisUsage(AU);
163 /// runOnMachineFunction - Register allocate the whole function
164 bool runOnMachineFunction(MachineFunction &Fn);
166 /// AllocateBasicBlock - Register allocate the specified basic block.
167 void AllocateBasicBlock(MachineBasicBlock &MBB);
170 /// areRegsEqual - This method returns true if the specified registers are
171 /// related to each other. To do this, it checks to see if they are equal
172 /// or if the first register is in the alias set of the second register.
174 bool areRegsEqual(unsigned R1, unsigned R2) const {
175 if (R1 == R2) return true;
176 for (const unsigned *AliasSet = TRI->getAliasSet(R2);
177 *AliasSet; ++AliasSet) {
178 if (*AliasSet == R1) return true;
183 /// getStackSpaceFor - This returns the frame index of the specified virtual
184 /// register on the stack, allocating space if necessary.
185 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
187 /// removePhysReg - This method marks the specified physical register as no
188 /// longer being in use.
190 void removePhysReg(unsigned PhysReg);
192 /// spillVirtReg - This method spills the value specified by PhysReg into
193 /// the virtual register slot specified by VirtReg. It then updates the RA
194 /// data structures to indicate the fact that PhysReg is now available.
196 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
197 unsigned VirtReg, unsigned PhysReg);
199 /// spillPhysReg - This method spills the specified physical register into
200 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
201 /// true, then the request is ignored if the physical register does not
202 /// contain a virtual register.
204 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
205 unsigned PhysReg, bool OnlyVirtRegs = false);
207 /// assignVirtToPhysReg - This method updates local state so that we know
208 /// that PhysReg is the proper container for VirtReg now. The physical
209 /// register must not be used for anything else when this is called.
211 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
213 /// isPhysRegAvailable - Return true if the specified physical register is
214 /// free and available for use. This also includes checking to see if
215 /// aliased registers are all free...
217 bool isPhysRegAvailable(unsigned PhysReg) const;
219 /// getFreeReg - Look to see if there is a free register available in the
220 /// specified register class. If not, return 0.
222 unsigned getFreeReg(const TargetRegisterClass *RC);
224 /// getReg - Find a physical register to hold the specified virtual
225 /// register. If all compatible physical registers are used, this method
226 /// spills the last used virtual register to the stack, and uses that
227 /// register. If NoFree is true, that means the caller knows there isn't
228 /// a free register, do not call getFreeReg().
229 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
230 unsigned VirtReg, bool NoFree = false);
232 /// reloadVirtReg - This method transforms the specified virtual
233 /// register use to refer to a physical register. This method may do this
234 /// in one of several ways: if the register is available in a physical
235 /// register already, it uses that physical register. If the value is not
236 /// in a physical register, and if there are physical registers available,
237 /// it loads it into a register: PhysReg if that is an available physical
238 /// register, otherwise any physical register of the right class.
239 /// If register pressure is high, and it is possible, it tries to fold the
240 /// load of the virtual register into the instruction itself. It avoids
241 /// doing this if register pressure is low to improve the chance that
242 /// subsequent instructions can use the reloaded value. This method
243 /// returns the modified instruction.
245 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
246 unsigned OpNum, SmallSet<unsigned, 4> &RRegs,
249 /// ComputeLocalLiveness - Computes liveness of registers within a basic
250 /// block, setting the killed/dead flags as appropriate.
251 void ComputeLocalLiveness(MachineBasicBlock& MBB);
253 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
256 char RALocal::ID = 0;
259 /// getStackSpaceFor - This allocates space for the specified virtual register
260 /// to be held on the stack.
261 int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
262 // Find the location Reg would belong...
263 int SS = StackSlotForVirtReg[VirtReg];
265 return SS; // Already has space allocated?
267 // Allocate a new stack object for this spill location...
268 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
272 StackSlotForVirtReg[VirtReg] = FrameIdx;
277 /// removePhysReg - This method marks the specified physical register as no
278 /// longer being in use.
280 void RALocal::removePhysReg(unsigned PhysReg) {
281 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
283 std::vector<unsigned>::iterator It =
284 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
285 if (It != PhysRegsUseOrder.end())
286 PhysRegsUseOrder.erase(It);
290 /// spillVirtReg - This method spills the value specified by PhysReg into the
291 /// virtual register slot specified by VirtReg. It then updates the RA data
292 /// structures to indicate the fact that PhysReg is now available.
294 void RALocal::spillVirtReg(MachineBasicBlock &MBB,
295 MachineBasicBlock::iterator I,
296 unsigned VirtReg, unsigned PhysReg) {
297 assert(VirtReg && "Spilling a physical register is illegal!"
298 " Must not have appropriate kill for the register or use exists beyond"
299 " the intended one.");
300 DEBUG(dbgs() << " Spilling register " << TRI->getName(PhysReg)
301 << " containing %reg" << VirtReg);
303 if (!isVirtRegModified(VirtReg)) {
304 DEBUG(dbgs() << " which has not been modified, so no store necessary!");
305 std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
307 LastUse.first->getOperand(LastUse.second).setIsKill();
309 // Otherwise, there is a virtual register corresponding to this physical
310 // register. We only need to spill it into its stack slot if it has been
312 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
313 int FrameIndex = getStackSpaceFor(VirtReg, RC);
314 DEBUG(dbgs() << " to stack slot #" << FrameIndex);
315 // If the instruction reads the register that's spilled, (e.g. this can
316 // happen if it is a move to a physical register), then the spill
317 // instruction is not a kill.
318 bool isKill = !(I != MBB.end() && I->readsRegister(PhysReg));
319 TII->storeRegToStackSlot(MBB, I, PhysReg, isKill, FrameIndex, RC);
320 ++NumStores; // Update statistics
323 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
325 DEBUG(dbgs() << '\n');
326 removePhysReg(PhysReg);
330 /// spillPhysReg - This method spills the specified physical register into the
331 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
332 /// then the request is ignored if the physical register does not contain a
333 /// virtual register.
335 void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
336 unsigned PhysReg, bool OnlyVirtRegs) {
337 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
338 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
339 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
340 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
344 // If the selected register aliases any other registers, we must make
345 // sure that one of the aliases isn't alive.
346 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
347 *AliasSet; ++AliasSet) {
348 if (PhysRegsUsed[*AliasSet] == -1 || // Spill aliased register.
349 PhysRegsUsed[*AliasSet] == -2) // If allocatable.
352 if (PhysRegsUsed[*AliasSet])
353 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
358 /// assignVirtToPhysReg - This method updates local state so that we know
359 /// that PhysReg is the proper container for VirtReg now. The physical
360 /// register must not be used for anything else when this is called.
362 void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
363 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
364 // Update information to note the fact that this register was just used, and
366 PhysRegsUsed[PhysReg] = VirtReg;
367 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
368 AddToPhysRegsUseOrder(PhysReg); // New use of PhysReg
372 /// isPhysRegAvailable - Return true if the specified physical register is free
373 /// and available for use. This also includes checking to see if aliased
374 /// registers are all free...
376 bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
377 if (PhysRegsUsed[PhysReg] != -1) return false;
379 // If the selected register aliases any other allocated registers, it is
381 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
382 *AliasSet; ++AliasSet)
383 if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
384 return false; // Can't use this reg then.
389 /// getFreeReg - Look to see if there is a free register available in the
390 /// specified register class. If not, return 0.
392 unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
393 // Get iterators defining the range of registers that are valid to allocate in
394 // this class, which also specifies the preferred allocation order.
395 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
396 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
398 for (; RI != RE; ++RI)
399 if (isPhysRegAvailable(*RI)) { // Is reg unused?
400 assert(*RI != 0 && "Cannot use register!");
401 return *RI; // Found an unused register!
407 /// getReg - Find a physical register to hold the specified virtual
408 /// register. If all compatible physical registers are used, this method spills
409 /// the last used virtual register to the stack, and uses that register.
411 unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
412 unsigned VirtReg, bool NoFree) {
413 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
415 // First check to see if we have a free register of the requested type...
416 unsigned PhysReg = NoFree ? 0 : getFreeReg(RC);
419 // Assign the register.
420 assignVirtToPhysReg(VirtReg, PhysReg);
424 // If we didn't find an unused register, scavenge one now!
425 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
427 // Loop over all of the preallocated registers from the least recently used
428 // to the most recently used. When we find one that is capable of holding
429 // our register, use it.
430 for (unsigned i = 0; PhysReg == 0; ++i) {
431 assert(i != PhysRegsUseOrder.size() &&
432 "Couldn't find a register of the appropriate class!");
434 unsigned R = PhysRegsUseOrder[i];
436 // We can only use this register if it holds a virtual register (ie, it
437 // can be spilled). Do not use it if it is an explicitly allocated
438 // physical register!
439 assert(PhysRegsUsed[R] != -1 &&
440 "PhysReg in PhysRegsUseOrder, but is not allocated?");
441 if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
442 // If the current register is compatible, use it.
443 if (RC->contains(R)) {
448 // If one of the registers aliased to the current register is
449 // compatible, use it.
450 for (const unsigned *AliasIt = TRI->getAliasSet(R);
451 *AliasIt; ++AliasIt) {
452 if (!RC->contains(*AliasIt)) continue;
454 // If this is pinned down for some reason, don't use it. For
455 // example, if CL is pinned, and we run across CH, don't use
456 // CH as justification for using scavenging ECX (which will
458 if (PhysRegsUsed[*AliasIt] == 0) continue;
460 // Make sure the register is allocatable. Don't allocate SIL on
462 if (PhysRegsUsed[*AliasIt] == -2) continue;
464 PhysReg = *AliasIt; // Take an aliased register
470 assert(PhysReg && "Physical register not assigned!?!?");
472 // At this point PhysRegsUseOrder[i] is the least recently used register of
473 // compatible register class. Spill it to memory and reap its remains.
474 spillPhysReg(MBB, I, PhysReg);
476 // Now that we know which register we need to assign this to, do it now!
477 assignVirtToPhysReg(VirtReg, PhysReg);
482 /// reloadVirtReg - This method transforms the specified virtual
483 /// register use to refer to a physical register. This method may do this in
484 /// one of several ways: if the register is available in a physical register
485 /// already, it uses that physical register. If the value is not in a physical
486 /// register, and if there are physical registers available, it loads it into a
487 /// register: PhysReg if that is an available physical register, otherwise any
488 /// register. If register pressure is high, and it is possible, it tries to
489 /// fold the load of the virtual register into the instruction itself. It
490 /// avoids doing this if register pressure is low to improve the chance that
491 /// subsequent instructions can use the reloaded value. This method returns
492 /// the modified instruction.
494 MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
496 SmallSet<unsigned, 4> &ReloadedRegs,
498 unsigned VirtReg = MI->getOperand(OpNum).getReg();
500 // If the virtual register is already available, just update the instruction
502 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
503 MI->getOperand(OpNum).setReg(PR); // Assign the input register
504 if (!MI->isDebugValue()) {
505 // Do not do these for DBG_VALUE as they can affect codegen.
506 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
507 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
512 // Otherwise, we need to fold it into the current instruction, or reload it.
513 // If we have registers available to hold the value, use them.
514 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
515 // If we already have a PhysReg (this happens when the instruction is a
516 // reg-to-reg copy with a PhysReg destination) use that.
517 if (!PhysReg || !TargetRegisterInfo::isPhysicalRegister(PhysReg) ||
518 !isPhysRegAvailable(PhysReg))
519 PhysReg = getFreeReg(RC);
520 int FrameIndex = getStackSpaceFor(VirtReg, RC);
522 if (PhysReg) { // Register is available, allocate it!
523 assignVirtToPhysReg(VirtReg, PhysReg);
524 } else { // No registers available.
525 // Force some poor hapless value out of the register file to
526 // make room for the new register, and reload it.
527 PhysReg = getReg(MBB, MI, VirtReg, true);
530 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
532 DEBUG(dbgs() << " Reloading %reg" << VirtReg << " into "
533 << TRI->getName(PhysReg) << "\n");
535 // Add move instruction(s)
536 TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
537 ++NumLoads; // Update statistics
539 MF->getRegInfo().setPhysRegUsed(PhysReg);
540 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
541 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
543 if (!ReloadedRegs.insert(PhysReg)) {
545 raw_string_ostream Msg(msg);
546 Msg << "Ran out of registers during register allocation!";
547 if (MI->isInlineAsm()) {
548 Msg << "\nPlease check your inline asm statement for invalid "
552 llvm_report_error(Msg.str());
554 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
555 *SubRegs; ++SubRegs) {
556 if (ReloadedRegs.insert(*SubRegs)) continue;
559 raw_string_ostream Msg(msg);
560 Msg << "Ran out of registers during register allocation!";
561 if (MI->isInlineAsm()) {
562 Msg << "\nPlease check your inline asm statement for invalid "
566 llvm_report_error(Msg.str());
572 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
573 /// read/mod/write register, i.e. update partial register.
574 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
575 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
576 MachineOperand &MO = MI->getOperand(i);
577 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
578 MO.isDef() && !MO.isDead())
584 /// isReadModWriteImplicitDef - True if this is an implicit def for a
585 /// read/mod/write register, i.e. update partial register.
586 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
587 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
588 MachineOperand &MO = MI->getOperand(i);
589 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
590 !MO.isDef() && MO.isKill())
596 // precedes - Helper function to determine with MachineInstr A
597 // precedes MachineInstr B within the same MBB.
598 static bool precedes(MachineBasicBlock::iterator A,
599 MachineBasicBlock::iterator B) {
603 MachineBasicBlock::iterator I = A->getParent()->begin();
604 while (I != A->getParent()->end()) {
616 /// ComputeLocalLiveness - Computes liveness of registers within a basic
617 /// block, setting the killed/dead flags as appropriate.
618 void RALocal::ComputeLocalLiveness(MachineBasicBlock& MBB) {
619 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
620 // Keep track of the most recently seen previous use or def of each reg,
621 // so that we can update them with dead/kill markers.
622 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> > LastUseDef;
623 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
625 if (I->isDebugValue())
628 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
629 MachineOperand &MO = I->getOperand(i);
630 // Uses don't trigger any flags, but we need to save
631 // them for later. Also, we have to process these
632 // _before_ processing the defs, since an instr
633 // uses regs before it defs them.
634 if (!MO.isReg() || !MO.getReg() || !MO.isUse())
637 LastUseDef[MO.getReg()] = std::make_pair(I, i);
639 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) continue;
641 const unsigned *Aliases = TRI->getAliasSet(MO.getReg());
646 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
647 alias = LastUseDef.find(*Aliases);
649 if (alias != LastUseDef.end() && alias->second.first != I)
650 LastUseDef[*Aliases] = std::make_pair(I, i);
656 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
657 MachineOperand &MO = I->getOperand(i);
658 // Defs others than 2-addr redefs _do_ trigger flag changes:
659 // - A def followed by a def is dead
660 // - A use followed by a def is a kill
661 if (!MO.isReg() || !MO.getReg() || !MO.isDef()) continue;
663 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
664 last = LastUseDef.find(MO.getReg());
665 if (last != LastUseDef.end()) {
666 // Check if this is a two address instruction. If so, then
667 // the def does not kill the use.
668 if (last->second.first == I &&
669 I->isRegTiedToUseOperand(i))
672 MachineOperand &lastUD =
673 last->second.first->getOperand(last->second.second);
675 lastUD.setIsDead(true);
677 lastUD.setIsKill(true);
680 LastUseDef[MO.getReg()] = std::make_pair(I, i);
684 // Live-out (of the function) registers contain return values of the function,
685 // so we need to make sure they are alive at return time.
686 MachineBasicBlock::iterator Ret = MBB.getFirstTerminator();
687 bool BBEndsInReturn = (Ret != MBB.end() && Ret->getDesc().isReturn());
690 for (MachineRegisterInfo::liveout_iterator
691 I = MF->getRegInfo().liveout_begin(),
692 E = MF->getRegInfo().liveout_end(); I != E; ++I)
693 if (!Ret->readsRegister(*I)) {
694 Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
695 LastUseDef[*I] = std::make_pair(Ret, Ret->getNumOperands()-1);
698 // Finally, loop over the final use/def of each reg
699 // in the block and determine if it is dead.
700 for (DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
701 I = LastUseDef.begin(), E = LastUseDef.end(); I != E; ++I) {
702 MachineInstr *MI = I->second.first;
703 unsigned idx = I->second.second;
704 MachineOperand &MO = MI->getOperand(idx);
706 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(MO.getReg());
708 // A crude approximation of "live-out" calculation
709 bool usedOutsideBlock = isPhysReg ? false :
710 UsedInMultipleBlocks.test(MO.getReg() -
711 TargetRegisterInfo::FirstVirtualRegister);
713 // If the machine BB ends in a return instruction, then the value isn't used
714 // outside of the BB.
715 if (!isPhysReg && (!usedOutsideBlock || BBEndsInReturn)) {
716 // DBG_VALUE complicates this: if the only refs of a register outside
717 // this block are DBG_VALUE, we can't keep the reg live just for that,
718 // as it will cause the reg to be spilled at the end of this block when
719 // it wouldn't have been otherwise. Nullify the DBG_VALUEs when that
721 bool UsedByDebugValueOnly = false;
722 for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
723 UE = MRI.reg_end(); UI != UE; ++UI) {
725 // - used in another block
726 // - used in the same block before it is defined (loop)
727 if (UI->getParent() == &MBB &&
728 !(MO.isDef() && UI.getOperand().isUse() && precedes(&*UI, MI)))
731 if (UI->isDebugValue()) {
732 UsedByDebugValueOnly = true;
736 // A non-DBG_VALUE use means we can leave DBG_VALUE uses alone.
737 UsedInMultipleBlocks.set(MO.getReg() -
738 TargetRegisterInfo::FirstVirtualRegister);
739 usedOutsideBlock = true;
740 UsedByDebugValueOnly = false;
744 if (UsedByDebugValueOnly)
745 for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
746 UE = MRI.reg_end(); UI != UE; ++UI)
747 if (UI->isDebugValue() &&
748 (UI->getParent() != &MBB ||
749 (MO.isDef() && precedes(&*UI, MI))))
750 UI.getOperand().setReg(0U);
753 // Physical registers and those that are not live-out of the block are
754 // killed/dead at their last use/def within this block.
755 if (isPhysReg || !usedOutsideBlock || BBEndsInReturn) {
757 // Don't mark uses that are tied to defs as kills.
758 if (!MI->isRegTiedToDefOperand(idx))
767 void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
768 // loop over each instruction
769 MachineBasicBlock::iterator MII = MBB.begin();
772 const BasicBlock *LBB = MBB.getBasicBlock();
774 dbgs() << "\nStarting RegAlloc of BB: " << LBB->getName();
777 // Add live-in registers as active.
778 for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
779 E = MBB.livein_end(); I != E; ++I) {
781 MF->getRegInfo().setPhysRegUsed(Reg);
782 PhysRegsUsed[Reg] = 0; // It is free and reserved now
783 AddToPhysRegsUseOrder(Reg);
784 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
785 *SubRegs; ++SubRegs) {
786 if (PhysRegsUsed[*SubRegs] == -2) continue;
788 AddToPhysRegsUseOrder(*SubRegs);
789 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
790 MF->getRegInfo().setPhysRegUsed(*SubRegs);
794 ComputeLocalLiveness(MBB);
796 // Otherwise, sequentially allocate each instruction in the MBB.
797 while (MII != MBB.end()) {
798 MachineInstr *MI = MII++;
799 const TargetInstrDesc &TID = MI->getDesc();
801 dbgs() << "\nStarting RegAlloc of: " << *MI;
802 dbgs() << " Regs have values: ";
803 for (unsigned i = 0; i != TRI->getNumRegs(); ++i)
804 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
805 dbgs() << "[" << TRI->getName(i)
806 << ",%reg" << PhysRegsUsed[i] << "] ";
810 // Determine whether this is a copy instruction. The cases where the
811 // source or destination are phys regs are handled specially.
812 unsigned SrcCopyReg, DstCopyReg, SrcCopySubReg, DstCopySubReg;
813 unsigned SrcCopyPhysReg = 0U;
814 bool isCopy = TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
815 SrcCopySubReg, DstCopySubReg);
816 if (isCopy && TargetRegisterInfo::isVirtualRegister(SrcCopyReg))
817 SrcCopyPhysReg = getVirt2PhysRegMapSlot(SrcCopyReg);
819 // Loop over the implicit uses, making sure that they are at the head of the
820 // use order list, so they don't get reallocated.
821 if (TID.ImplicitUses) {
822 for (const unsigned *ImplicitUses = TID.ImplicitUses;
823 *ImplicitUses; ++ImplicitUses)
824 MarkPhysRegRecentlyUsed(*ImplicitUses);
827 SmallVector<unsigned, 8> Kills;
828 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
829 MachineOperand &MO = MI->getOperand(i);
830 if (!MO.isReg() || !MO.isKill()) continue;
832 if (!MO.isImplicit())
833 Kills.push_back(MO.getReg());
834 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
835 // These are extra physical register kills when a sub-register
836 // is defined (def of a sub-register is a read/mod/write of the
837 // larger registers). Ignore.
838 Kills.push_back(MO.getReg());
841 // If any physical regs are earlyclobber, spill any value they might
842 // have in them, then mark them unallocatable.
843 // If any virtual regs are earlyclobber, allocate them now (before
844 // freeing inputs that are killed).
845 if (MI->isInlineAsm()) {
846 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
847 MachineOperand &MO = MI->getOperand(i);
848 if (!MO.isReg() || !MO.isDef() || !MO.isEarlyClobber() ||
852 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
853 unsigned DestVirtReg = MO.getReg();
854 unsigned DestPhysReg;
856 // If DestVirtReg already has a value, use it.
857 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
858 DestPhysReg = getReg(MBB, MI, DestVirtReg);
859 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
860 markVirtRegModified(DestVirtReg);
861 getVirtRegLastUse(DestVirtReg) =
862 std::make_pair((MachineInstr*)0, 0);
863 DEBUG(dbgs() << " Assigning " << TRI->getName(DestPhysReg)
864 << " to %reg" << DestVirtReg << "\n");
865 MO.setReg(DestPhysReg); // Assign the earlyclobber register
867 unsigned Reg = MO.getReg();
868 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
869 // These are extra physical register defs when a sub-register
870 // is defined (def of a sub-register is a read/mod/write of the
871 // larger registers). Ignore.
872 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
874 MF->getRegInfo().setPhysRegUsed(Reg);
875 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
876 PhysRegsUsed[Reg] = 0; // It is free and reserved now
877 AddToPhysRegsUseOrder(Reg);
879 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
880 *SubRegs; ++SubRegs) {
881 if (PhysRegsUsed[*SubRegs] == -2) continue;
882 MF->getRegInfo().setPhysRegUsed(*SubRegs);
883 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
884 AddToPhysRegsUseOrder(*SubRegs);
890 // If a DBG_VALUE says something is located in a spilled register,
891 // change the DBG_VALUE to be undef, which prevents the register
892 // from being reloaded here. Doing that would change the generated
893 // code, unless another use immediately follows this instruction.
894 if (MI->isDebugValue() &&
895 MI->getNumOperands()==3 && MI->getOperand(0).isReg()) {
896 unsigned VirtReg = MI->getOperand(0).getReg();
897 if (VirtReg && TargetRegisterInfo::isVirtualRegister(VirtReg) &&
898 !getVirt2PhysRegMapSlot(VirtReg))
899 MI->getOperand(0).setReg(0U);
902 // Get the used operands into registers. This has the potential to spill
903 // incoming values if we are out of registers. Note that we completely
904 // ignore physical register uses here. We assume that if an explicit
905 // physical register is referenced by the instruction, that it is guaranteed
906 // to be live-in, or the input is badly hosed.
908 SmallSet<unsigned, 4> ReloadedRegs;
909 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
910 MachineOperand &MO = MI->getOperand(i);
911 // here we are looking for only used operands (never def&use)
912 if (MO.isReg() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
913 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
914 MI = reloadVirtReg(MBB, MI, i, ReloadedRegs,
915 isCopy ? DstCopyReg : 0);
918 // If this instruction is the last user of this register, kill the
919 // value, freeing the register being used, so it doesn't need to be
920 // spilled to memory.
922 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
923 unsigned VirtReg = Kills[i];
924 unsigned PhysReg = VirtReg;
925 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
926 // If the virtual register was never materialized into a register, it
927 // might not be in the map, but it won't hurt to zero it out anyway.
928 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
929 PhysReg = PhysRegSlot;
931 } else if (PhysRegsUsed[PhysReg] == -2) {
932 // Unallocatable register dead, ignore.
935 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
936 "Silently clearing a virtual register?");
939 if (!PhysReg) continue;
941 DEBUG(dbgs() << " Last use of " << TRI->getName(PhysReg)
942 << "[%reg" << VirtReg <<"], removing it from live set\n");
943 removePhysReg(PhysReg);
944 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
945 *SubRegs; ++SubRegs) {
946 if (PhysRegsUsed[*SubRegs] != -2) {
947 DEBUG(dbgs() << " Last use of "
948 << TRI->getName(*SubRegs) << "[%reg" << VirtReg
949 <<"], removing it from live set\n");
950 removePhysReg(*SubRegs);
955 // Loop over all of the operands of the instruction, spilling registers that
956 // are defined, and marking explicit destinations in the PhysRegsUsed map.
957 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
958 MachineOperand &MO = MI->getOperand(i);
959 if (!MO.isReg() || !MO.isDef() || MO.isImplicit() || !MO.getReg() ||
960 MO.isEarlyClobber() ||
961 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
964 unsigned Reg = MO.getReg();
965 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
966 // These are extra physical register defs when a sub-register
967 // is defined (def of a sub-register is a read/mod/write of the
968 // larger registers). Ignore.
969 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
971 MF->getRegInfo().setPhysRegUsed(Reg);
972 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
973 PhysRegsUsed[Reg] = 0; // It is free and reserved now
974 AddToPhysRegsUseOrder(Reg);
976 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
977 *SubRegs; ++SubRegs) {
978 if (PhysRegsUsed[*SubRegs] == -2) continue;
980 MF->getRegInfo().setPhysRegUsed(*SubRegs);
981 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
982 AddToPhysRegsUseOrder(*SubRegs);
986 // Loop over the implicit defs, spilling them as well.
987 if (TID.ImplicitDefs) {
988 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
989 *ImplicitDefs; ++ImplicitDefs) {
990 unsigned Reg = *ImplicitDefs;
991 if (PhysRegsUsed[Reg] != -2) {
992 spillPhysReg(MBB, MI, Reg, true);
993 AddToPhysRegsUseOrder(Reg);
994 PhysRegsUsed[Reg] = 0; // It is free and reserved now
996 MF->getRegInfo().setPhysRegUsed(Reg);
997 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
998 *SubRegs; ++SubRegs) {
999 if (PhysRegsUsed[*SubRegs] == -2) continue;
1001 AddToPhysRegsUseOrder(*SubRegs);
1002 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
1003 MF->getRegInfo().setPhysRegUsed(*SubRegs);
1008 SmallVector<unsigned, 8> DeadDefs;
1009 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1010 MachineOperand &MO = MI->getOperand(i);
1011 if (MO.isReg() && MO.isDead())
1012 DeadDefs.push_back(MO.getReg());
1015 // Okay, we have allocated all of the source operands and spilled any values
1016 // that would be destroyed by defs of this instruction. Loop over the
1017 // explicit defs and assign them to a register, spilling incoming values if
1018 // we need to scavenge a register.
1020 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1021 MachineOperand &MO = MI->getOperand(i);
1022 if (!MO.isReg() || !MO.isDef() || !MO.getReg() ||
1023 MO.isEarlyClobber() ||
1024 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1027 unsigned DestVirtReg = MO.getReg();
1028 unsigned DestPhysReg;
1030 // If DestVirtReg already has a value, use it.
1031 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg))) {
1032 // If this is a copy try to reuse the input as the output;
1033 // that will make the copy go away.
1034 // If this is a copy, the source reg is a phys reg, and
1035 // that reg is available, use that phys reg for DestPhysReg.
1036 // If this is a copy, the source reg is a virtual reg, and
1037 // the phys reg that was assigned to that virtual reg is now
1038 // available, use that phys reg for DestPhysReg. (If it's now
1039 // available that means this was the last use of the source.)
1041 TargetRegisterInfo::isPhysicalRegister(SrcCopyReg) &&
1042 isPhysRegAvailable(SrcCopyReg)) {
1043 DestPhysReg = SrcCopyReg;
1044 assignVirtToPhysReg(DestVirtReg, DestPhysReg);
1045 } else if (isCopy &&
1046 TargetRegisterInfo::isVirtualRegister(SrcCopyReg) &&
1047 SrcCopyPhysReg && isPhysRegAvailable(SrcCopyPhysReg) &&
1048 MF->getRegInfo().getRegClass(DestVirtReg)->
1049 contains(SrcCopyPhysReg)) {
1050 DestPhysReg = SrcCopyPhysReg;
1051 assignVirtToPhysReg(DestVirtReg, DestPhysReg);
1053 DestPhysReg = getReg(MBB, MI, DestVirtReg);
1055 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
1056 markVirtRegModified(DestVirtReg);
1057 getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
1058 DEBUG(dbgs() << " Assigning " << TRI->getName(DestPhysReg)
1059 << " to %reg" << DestVirtReg << "\n");
1060 MO.setReg(DestPhysReg); // Assign the output register
1063 // If this instruction defines any registers that are immediately dead,
1066 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
1067 unsigned VirtReg = DeadDefs[i];
1068 unsigned PhysReg = VirtReg;
1069 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
1070 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
1071 PhysReg = PhysRegSlot;
1072 assert(PhysReg != 0);
1074 } else if (PhysRegsUsed[PhysReg] == -2) {
1075 // Unallocatable register dead, ignore.
1077 } else if (!PhysReg)
1080 DEBUG(dbgs() << " Register " << TRI->getName(PhysReg)
1081 << " [%reg" << VirtReg
1082 << "] is never used, removing it from live set\n");
1083 removePhysReg(PhysReg);
1084 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
1085 *AliasSet; ++AliasSet) {
1086 if (PhysRegsUsed[*AliasSet] != -2) {
1087 DEBUG(dbgs() << " Register " << TRI->getName(*AliasSet)
1088 << " [%reg" << *AliasSet
1089 << "] is never used, removing it from live set\n");
1090 removePhysReg(*AliasSet);
1095 // Finally, if this is a noop copy instruction, zap it. (Except that if
1096 // the copy is dead, it must be kept to avoid messing up liveness info for
1097 // the register scavenger. See pr4100.)
1098 if (TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
1099 SrcCopySubReg, DstCopySubReg) &&
1100 SrcCopyReg == DstCopyReg && DeadDefs.empty())
1104 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1106 // Spill all physical registers holding virtual registers now.
1107 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
1108 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
1109 if (unsigned VirtReg = PhysRegsUsed[i])
1110 spillVirtReg(MBB, MI, VirtReg, i);
1116 // This checking code is very expensive.
1118 for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
1119 e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
1120 if (unsigned PR = Virt2PhysRegMap[i]) {
1121 cerr << "Register still mapped: " << i << " -> " << PR << "\n";
1124 assert(AllOk && "Virtual registers still in phys regs?");
1127 // Clear any physical register which appear live at the end of the basic
1128 // block, but which do not hold any virtual registers. e.g., the stack
1130 PhysRegsUseOrder.clear();
1133 /// runOnMachineFunction - Register allocate the whole function
1135 bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
1136 DEBUG(dbgs() << "Machine Function\n");
1138 TM = &Fn.getTarget();
1139 TRI = TM->getRegisterInfo();
1140 TII = TM->getInstrInfo();
1142 PhysRegsUsed.assign(TRI->getNumRegs(), -1);
1144 // At various places we want to efficiently check to see whether a register
1145 // is allocatable. To handle this, we mark all unallocatable registers as
1146 // being pinned down, permanently.
1148 BitVector Allocable = TRI->getAllocatableSet(Fn);
1149 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
1151 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
1154 // initialize the virtual->physical register map to have a 'null'
1155 // mapping for all virtual registers
1156 unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
1157 StackSlotForVirtReg.grow(LastVirtReg);
1158 Virt2PhysRegMap.grow(LastVirtReg);
1159 Virt2LastUseMap.grow(LastVirtReg);
1160 VirtRegModified.resize(LastVirtReg+1 -
1161 TargetRegisterInfo::FirstVirtualRegister);
1162 UsedInMultipleBlocks.resize(LastVirtReg+1 -
1163 TargetRegisterInfo::FirstVirtualRegister);
1165 // Loop over all of the basic blocks, eliminating virtual register references
1166 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
1168 AllocateBasicBlock(*MBB);
1170 StackSlotForVirtReg.clear();
1171 PhysRegsUsed.clear();
1172 VirtRegModified.clear();
1173 UsedInMultipleBlocks.clear();
1174 Virt2PhysRegMap.clear();
1175 Virt2LastUseMap.clear();
1179 FunctionPass *llvm::createLocalRegisterAllocator() {
1180 return new RALocal();