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/LiveVariables.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegAllocRegistry.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/ADT/IndexedMap.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
36 STATISTIC(NumStores, "Number of stores added");
37 STATISTIC(NumLoads , "Number of loads added");
38 STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
41 static RegisterRegAlloc
42 localRegAlloc("local", " local register allocator",
43 createLocalRegisterAllocator);
46 class VISIBILITY_HIDDEN RALocal : public MachineFunctionPass {
49 RALocal() : MachineFunctionPass((intptr_t)&ID) {}
51 const TargetMachine *TM;
53 const MRegisterInfo *MRI;
54 const TargetInstrInfo *TII;
56 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
57 // values are spilled.
58 std::map<unsigned, int> 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(MRegisterInfo::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 void markVirtRegModified(unsigned Reg, bool Val = true) {
107 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
108 Reg -= MRegisterInfo::FirstVirtualRegister;
110 VirtRegModified.set(Reg);
112 VirtRegModified.reset(Reg);
115 bool isVirtRegModified(unsigned Reg) const {
116 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
117 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
118 && "Illegal virtual register!");
119 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
122 void AddToPhysRegsUseOrder(unsigned Reg) {
123 std::vector<unsigned>::iterator It =
124 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg);
125 if (It != PhysRegsUseOrder.end())
126 PhysRegsUseOrder.erase(It);
127 PhysRegsUseOrder.push_back(Reg);
130 void MarkPhysRegRecentlyUsed(unsigned Reg) {
131 if (PhysRegsUseOrder.empty() ||
132 PhysRegsUseOrder.back() == Reg) return; // Already most recently used
134 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
135 if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
136 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
137 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
138 // Add it to the end of the list
139 PhysRegsUseOrder.push_back(RegMatch);
141 return; // Found an exact match, exit early
146 virtual const char *getPassName() const {
147 return "Local Register Allocator";
150 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
151 AU.addRequired<LiveVariables>();
152 AU.addRequiredID(PHIEliminationID);
153 AU.addRequiredID(TwoAddressInstructionPassID);
154 MachineFunctionPass::getAnalysisUsage(AU);
158 /// runOnMachineFunction - Register allocate the whole function
159 bool runOnMachineFunction(MachineFunction &Fn);
161 /// AllocateBasicBlock - Register allocate the specified basic block.
162 void AllocateBasicBlock(MachineBasicBlock &MBB);
165 /// areRegsEqual - This method returns true if the specified registers are
166 /// related to each other. To do this, it checks to see if they are equal
167 /// or if the first register is in the alias set of the second register.
169 bool areRegsEqual(unsigned R1, unsigned R2) const {
170 if (R1 == R2) return true;
171 for (const unsigned *AliasSet = MRI->getAliasSet(R2);
172 *AliasSet; ++AliasSet) {
173 if (*AliasSet == R1) return true;
178 /// getStackSpaceFor - This returns the frame index of the specified virtual
179 /// register on the stack, allocating space if necessary.
180 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
182 /// removePhysReg - This method marks the specified physical register as no
183 /// longer being in use.
185 void removePhysReg(unsigned PhysReg);
187 /// spillVirtReg - This method spills the value specified by PhysReg into
188 /// the virtual register slot specified by VirtReg. It then updates the RA
189 /// data structures to indicate the fact that PhysReg is now available.
191 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
192 unsigned VirtReg, unsigned PhysReg);
194 /// spillPhysReg - This method spills the specified physical register into
195 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
196 /// true, then the request is ignored if the physical register does not
197 /// contain a virtual register.
199 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
200 unsigned PhysReg, bool OnlyVirtRegs = false);
202 /// assignVirtToPhysReg - This method updates local state so that we know
203 /// that PhysReg is the proper container for VirtReg now. The physical
204 /// register must not be used for anything else when this is called.
206 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
208 /// isPhysRegAvailable - Return true if the specified physical register is
209 /// free and available for use. This also includes checking to see if
210 /// aliased registers are all free...
212 bool isPhysRegAvailable(unsigned PhysReg) const;
214 /// getFreeReg - Look to see if there is a free register available in the
215 /// specified register class. If not, return 0.
217 unsigned getFreeReg(const TargetRegisterClass *RC);
219 /// getReg - Find a physical register to hold the specified virtual
220 /// register. If all compatible physical registers are used, this method
221 /// spills the last used virtual register to the stack, and uses that
224 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
227 /// reloadVirtReg - This method transforms the specified specified virtual
228 /// register use to refer to a physical register. This method may do this
229 /// in one of several ways: if the register is available in a physical
230 /// register already, it uses that physical register. If the value is not
231 /// in a physical register, and if there are physical registers available,
232 /// it loads it into a register. If register pressure is high, and it is
233 /// possible, it tries to fold the load of the virtual register into the
234 /// instruction itself. It avoids doing this if register pressure is low to
235 /// improve the chance that subsequent instructions can use the reloaded
236 /// value. This method returns the modified instruction.
238 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
242 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
245 char RALocal::ID = 0;
248 /// getStackSpaceFor - This allocates space for the specified virtual register
249 /// to be held on the stack.
250 int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
251 // Find the location Reg would belong...
252 std::map<unsigned, int>::iterator I =StackSlotForVirtReg.lower_bound(VirtReg);
254 if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
255 return I->second; // Already has space allocated?
257 // Allocate a new stack object for this spill location...
258 int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
261 // Assign the slot...
262 StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
267 /// removePhysReg - This method marks the specified physical register as no
268 /// longer being in use.
270 void RALocal::removePhysReg(unsigned PhysReg) {
271 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
273 std::vector<unsigned>::iterator It =
274 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
275 if (It != PhysRegsUseOrder.end())
276 PhysRegsUseOrder.erase(It);
280 /// spillVirtReg - This method spills the value specified by PhysReg into the
281 /// virtual register slot specified by VirtReg. It then updates the RA data
282 /// structures to indicate the fact that PhysReg is now available.
284 void RALocal::spillVirtReg(MachineBasicBlock &MBB,
285 MachineBasicBlock::iterator I,
286 unsigned VirtReg, unsigned PhysReg) {
287 assert(VirtReg && "Spilling a physical register is illegal!"
288 " Must not have appropriate kill for the register or use exists beyond"
289 " the intended one.");
290 DOUT << " Spilling register " << MRI->getName(PhysReg)
291 << " containing %reg" << VirtReg;
293 const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
295 if (!isVirtRegModified(VirtReg)) {
296 DOUT << " which has not been modified, so no store necessary!";
297 std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
299 LastUse.first->getOperand(LastUse.second).setIsKill();
301 // Otherwise, there is a virtual register corresponding to this physical
302 // register. We only need to spill it into its stack slot if it has been
304 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
305 int FrameIndex = getStackSpaceFor(VirtReg, RC);
306 DOUT << " to stack slot #" << FrameIndex;
307 TII->storeRegToStackSlot(MBB, I, PhysReg, true, FrameIndex, RC);
309 // If the instruction reads the register that's spilled, (e.g. this can
310 // happen if it is a move to a physical register), then the spill
311 // instruction is not a kill.
312 if (I != MBB.end() && I->findRegisterUseOperandIdx(PhysReg) != -1) {
313 MachineBasicBlock::iterator StoreMI = prior(I);
314 int Idx = StoreMI->findRegisterUseOperandIdx(PhysReg, true);
315 assert(Idx != -1 && "Unrecognized spill instruction!");
316 StoreMI->getOperand(Idx).setIsKill(false);
318 ++NumStores; // Update statistics
321 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
324 removePhysReg(PhysReg);
328 /// spillPhysReg - This method spills the specified physical register into the
329 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
330 /// then the request is ignored if the physical register does not contain a
331 /// virtual register.
333 void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
334 unsigned PhysReg, bool OnlyVirtRegs) {
335 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
336 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
337 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
338 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
340 // If the selected register aliases any other registers, we must make
341 // sure that one of the aliases isn't alive.
342 for (const unsigned *AliasSet = MRI->getAliasSet(PhysReg);
343 *AliasSet; ++AliasSet)
344 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
345 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
346 if (PhysRegsUsed[*AliasSet])
347 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
352 /// assignVirtToPhysReg - This method updates local state so that we know
353 /// that PhysReg is the proper container for VirtReg now. The physical
354 /// register must not be used for anything else when this is called.
356 void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
357 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
358 // Update information to note the fact that this register was just used, and
360 PhysRegsUsed[PhysReg] = VirtReg;
361 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
362 AddToPhysRegsUseOrder(PhysReg); // New use of PhysReg
366 /// isPhysRegAvailable - Return true if the specified physical register is free
367 /// and available for use. This also includes checking to see if aliased
368 /// registers are all free...
370 bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
371 if (PhysRegsUsed[PhysReg] != -1) return false;
373 // If the selected register aliases any other allocated registers, it is
375 for (const unsigned *AliasSet = MRI->getAliasSet(PhysReg);
376 *AliasSet; ++AliasSet)
377 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
378 return false; // Can't use this reg then.
383 /// getFreeReg - Look to see if there is a free register available in the
384 /// specified register class. If not, return 0.
386 unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
387 // Get iterators defining the range of registers that are valid to allocate in
388 // this class, which also specifies the preferred allocation order.
389 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
390 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
392 for (; RI != RE; ++RI)
393 if (isPhysRegAvailable(*RI)) { // Is reg unused?
394 assert(*RI != 0 && "Cannot use register!");
395 return *RI; // Found an unused register!
401 /// getReg - Find a physical register to hold the specified virtual
402 /// register. If all compatible physical registers are used, this method spills
403 /// the last used virtual register to the stack, and uses that register.
405 unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
407 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
409 // First check to see if we have a free register of the requested type...
410 unsigned PhysReg = getFreeReg(RC);
412 // If we didn't find an unused register, scavenge one now!
414 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
416 // Loop over all of the preallocated registers from the least recently used
417 // to the most recently used. When we find one that is capable of holding
418 // our register, use it.
419 for (unsigned i = 0; PhysReg == 0; ++i) {
420 assert(i != PhysRegsUseOrder.size() &&
421 "Couldn't find a register of the appropriate class!");
423 unsigned R = PhysRegsUseOrder[i];
425 // We can only use this register if it holds a virtual register (ie, it
426 // can be spilled). Do not use it if it is an explicitly allocated
427 // physical register!
428 assert(PhysRegsUsed[R] != -1 &&
429 "PhysReg in PhysRegsUseOrder, but is not allocated?");
430 if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
431 // If the current register is compatible, use it.
432 if (RC->contains(R)) {
436 // If one of the registers aliased to the current register is
437 // compatible, use it.
438 for (const unsigned *AliasIt = MRI->getAliasSet(R);
439 *AliasIt; ++AliasIt) {
440 if (RC->contains(*AliasIt) &&
441 // If this is pinned down for some reason, don't use it. For
442 // example, if CL is pinned, and we run across CH, don't use
443 // CH as justification for using scavenging ECX (which will
445 PhysRegsUsed[*AliasIt] != 0 &&
447 // Make sure the register is allocatable. Don't allocate SIL on
449 PhysRegsUsed[*AliasIt] != -2) {
450 PhysReg = *AliasIt; // Take an aliased register
458 assert(PhysReg && "Physical register not assigned!?!?");
460 // At this point PhysRegsUseOrder[i] is the least recently used register of
461 // compatible register class. Spill it to memory and reap its remains.
462 spillPhysReg(MBB, I, PhysReg);
465 // Now that we know which register we need to assign this to, do it now!
466 assignVirtToPhysReg(VirtReg, PhysReg);
471 /// reloadVirtReg - This method transforms the specified specified virtual
472 /// register use to refer to a physical register. This method may do this in
473 /// one of several ways: if the register is available in a physical register
474 /// already, it uses that physical register. If the value is not in a physical
475 /// register, and if there are physical registers available, it loads it into a
476 /// register. If register pressure is high, and it is possible, it tries to
477 /// fold the load of the virtual register into the instruction itself. It
478 /// avoids doing this if register pressure is low to improve the chance that
479 /// subsequent instructions can use the reloaded value. This method returns the
480 /// modified instruction.
482 MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
484 unsigned VirtReg = MI->getOperand(OpNum).getReg();
486 // If the virtual register is already available, just update the instruction
488 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
489 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
490 MI->getOperand(OpNum).setReg(PR); // Assign the input register
494 // Otherwise, we need to fold it into the current instruction, or reload it.
495 // If we have registers available to hold the value, use them.
496 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
497 unsigned PhysReg = getFreeReg(RC);
498 int FrameIndex = getStackSpaceFor(VirtReg, RC);
500 if (PhysReg) { // Register is available, allocate it!
501 assignVirtToPhysReg(VirtReg, PhysReg);
502 } else { // No registers available.
503 // If we can fold this spill into this instruction, do so now.
504 SmallVector<unsigned, 2> Ops;
505 Ops.push_back(OpNum);
507 // It looks like we can't fold this virtual register load into this
508 // instruction. Force some poor hapless value out of the register file to
509 // make room for the new register, and reload it.
510 PhysReg = getReg(MBB, MI, VirtReg);
513 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
515 DOUT << " Reloading %reg" << VirtReg << " into "
516 << MRI->getName(PhysReg) << "\n";
518 // Add move instruction(s)
519 const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
520 TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
521 ++NumLoads; // Update statistics
523 MF->getRegInfo().setPhysRegUsed(PhysReg);
524 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
525 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
529 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
530 /// read/mod/write register, i.e. update partial register.
531 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
532 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
533 MachineOperand& MO = MI->getOperand(i);
534 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
535 MO.isDef() && !MO.isDead())
541 /// isReadModWriteImplicitDef - True if this is an implicit def for a
542 /// read/mod/write register, i.e. update partial register.
543 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
544 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
545 MachineOperand& MO = MI->getOperand(i);
546 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
547 !MO.isDef() && MO.isKill())
553 void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
554 // loop over each instruction
555 MachineBasicBlock::iterator MII = MBB.begin();
556 const TargetInstrInfo &TII = *TM->getInstrInfo();
558 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
559 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
561 // If this is the first basic block in the machine function, add live-in
562 // registers as active.
563 if (&MBB == &*MF->begin()) {
564 for (MachineRegisterInfo::livein_iterator I=MF->getRegInfo().livein_begin(),
565 E = MF->getRegInfo().livein_end(); I != E; ++I) {
566 unsigned Reg = I->first;
567 MF->getRegInfo().setPhysRegUsed(Reg);
568 PhysRegsUsed[Reg] = 0; // It is free and reserved now
569 AddToPhysRegsUseOrder(Reg);
570 for (const unsigned *AliasSet = MRI->getSubRegisters(Reg);
571 *AliasSet; ++AliasSet) {
572 if (PhysRegsUsed[*AliasSet] != -2) {
573 AddToPhysRegsUseOrder(*AliasSet);
574 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
575 MF->getRegInfo().setPhysRegUsed(*AliasSet);
581 // Otherwise, sequentially allocate each instruction in the MBB.
582 while (MII != MBB.end()) {
583 MachineInstr *MI = MII++;
584 const TargetInstrDesc &TID = MI->getDesc();
585 DEBUG(DOUT << "\nStarting RegAlloc of: " << *MI;
586 DOUT << " Regs have values: ";
587 for (unsigned i = 0; i != MRI->getNumRegs(); ++i)
588 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
589 DOUT << "[" << MRI->getName(i)
590 << ",%reg" << PhysRegsUsed[i] << "] ";
593 // Loop over the implicit uses, making sure that they are at the head of the
594 // use order list, so they don't get reallocated.
595 if (TID.ImplicitUses) {
596 for (const unsigned *ImplicitUses = TID.ImplicitUses;
597 *ImplicitUses; ++ImplicitUses)
598 MarkPhysRegRecentlyUsed(*ImplicitUses);
601 SmallVector<unsigned, 8> Kills;
602 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
603 MachineOperand& MO = MI->getOperand(i);
604 if (MO.isRegister() && MO.isKill()) {
605 if (!MO.isImplicit())
606 Kills.push_back(MO.getReg());
607 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
608 // These are extra physical register kills when a sub-register
609 // is defined (def of a sub-register is a read/mod/write of the
610 // larger registers). Ignore.
611 Kills.push_back(MO.getReg());
615 // Get the used operands into registers. This has the potential to spill
616 // incoming values if we are out of registers. Note that we completely
617 // ignore physical register uses here. We assume that if an explicit
618 // physical register is referenced by the instruction, that it is guaranteed
619 // to be live-in, or the input is badly hosed.
621 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
622 MachineOperand& MO = MI->getOperand(i);
623 // here we are looking for only used operands (never def&use)
624 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
625 MRegisterInfo::isVirtualRegister(MO.getReg()))
626 MI = reloadVirtReg(MBB, MI, i);
629 // If this instruction is the last user of this register, kill the
630 // value, freeing the register being used, so it doesn't need to be
631 // spilled to memory.
633 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
634 unsigned VirtReg = Kills[i];
635 unsigned PhysReg = VirtReg;
636 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
637 // If the virtual register was never materialized into a register, it
638 // might not be in the map, but it won't hurt to zero it out anyway.
639 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
640 PhysReg = PhysRegSlot;
642 } else if (PhysRegsUsed[PhysReg] == -2) {
643 // Unallocatable register dead, ignore.
646 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
647 "Silently clearing a virtual register?");
651 DOUT << " Last use of " << MRI->getName(PhysReg)
652 << "[%reg" << VirtReg <<"], removing it from live set\n";
653 removePhysReg(PhysReg);
654 for (const unsigned *AliasSet = MRI->getSubRegisters(PhysReg);
655 *AliasSet; ++AliasSet) {
656 if (PhysRegsUsed[*AliasSet] != -2) {
657 DOUT << " Last use of "
658 << MRI->getName(*AliasSet)
659 << "[%reg" << VirtReg <<"], removing it from live set\n";
660 removePhysReg(*AliasSet);
666 // Loop over all of the operands of the instruction, spilling registers that
667 // are defined, and marking explicit destinations in the PhysRegsUsed map.
668 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
669 MachineOperand& MO = MI->getOperand(i);
670 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
671 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
672 unsigned Reg = MO.getReg();
673 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
674 // These are extra physical register defs when a sub-register
675 // is defined (def of a sub-register is a read/mod/write of the
676 // larger registers). Ignore.
677 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
679 MF->getRegInfo().setPhysRegUsed(Reg);
680 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
681 PhysRegsUsed[Reg] = 0; // It is free and reserved now
682 AddToPhysRegsUseOrder(Reg);
684 for (const unsigned *AliasSet = MRI->getSubRegisters(Reg);
685 *AliasSet; ++AliasSet) {
686 if (PhysRegsUsed[*AliasSet] != -2) {
687 MF->getRegInfo().setPhysRegUsed(*AliasSet);
688 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
689 AddToPhysRegsUseOrder(*AliasSet);
695 // Loop over the implicit defs, spilling them as well.
696 if (TID.ImplicitDefs) {
697 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
698 *ImplicitDefs; ++ImplicitDefs) {
699 unsigned Reg = *ImplicitDefs;
700 if (PhysRegsUsed[Reg] != -2) {
701 spillPhysReg(MBB, MI, Reg, true);
702 AddToPhysRegsUseOrder(Reg);
703 PhysRegsUsed[Reg] = 0; // It is free and reserved now
705 MF->getRegInfo().setPhysRegUsed(Reg);
706 for (const unsigned *AliasSet = MRI->getSubRegisters(Reg);
707 *AliasSet; ++AliasSet) {
708 if (PhysRegsUsed[*AliasSet] != -2) {
709 AddToPhysRegsUseOrder(*AliasSet);
710 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
711 MF->getRegInfo().setPhysRegUsed(*AliasSet);
717 SmallVector<unsigned, 8> DeadDefs;
718 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
719 MachineOperand& MO = MI->getOperand(i);
720 if (MO.isRegister() && MO.isDead())
721 DeadDefs.push_back(MO.getReg());
724 // Okay, we have allocated all of the source operands and spilled any values
725 // that would be destroyed by defs of this instruction. Loop over the
726 // explicit defs and assign them to a register, spilling incoming values if
727 // we need to scavenge a register.
729 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
730 MachineOperand& MO = MI->getOperand(i);
731 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
732 MRegisterInfo::isVirtualRegister(MO.getReg())) {
733 unsigned DestVirtReg = MO.getReg();
734 unsigned DestPhysReg;
736 // If DestVirtReg already has a value, use it.
737 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
738 DestPhysReg = getReg(MBB, MI, DestVirtReg);
739 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
740 markVirtRegModified(DestVirtReg);
741 getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
742 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
746 // If this instruction defines any registers that are immediately dead,
749 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
750 unsigned VirtReg = DeadDefs[i];
751 unsigned PhysReg = VirtReg;
752 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
753 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
754 PhysReg = PhysRegSlot;
755 assert(PhysReg != 0);
757 } else if (PhysRegsUsed[PhysReg] == -2) {
758 // Unallocatable register dead, ignore.
763 DOUT << " Register " << MRI->getName(PhysReg)
764 << " [%reg" << VirtReg
765 << "] is never used, removing it frame live list\n";
766 removePhysReg(PhysReg);
767 for (const unsigned *AliasSet = MRI->getAliasSet(PhysReg);
768 *AliasSet; ++AliasSet) {
769 if (PhysRegsUsed[*AliasSet] != -2) {
770 DOUT << " Register " << MRI->getName(*AliasSet)
771 << " [%reg" << *AliasSet
772 << "] is never used, removing it frame live list\n";
773 removePhysReg(*AliasSet);
779 // Finally, if this is a noop copy instruction, zap it.
780 unsigned SrcReg, DstReg;
781 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg)
785 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
787 // Spill all physical registers holding virtual registers now.
788 for (unsigned i = 0, e = MRI->getNumRegs(); i != e; ++i)
789 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
790 if (unsigned VirtReg = PhysRegsUsed[i])
791 spillVirtReg(MBB, MI, VirtReg, i);
796 // This checking code is very expensive.
798 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
799 e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
800 if (unsigned PR = Virt2PhysRegMap[i]) {
801 cerr << "Register still mapped: " << i << " -> " << PR << "\n";
804 assert(AllOk && "Virtual registers still in phys regs?");
807 // Clear any physical register which appear live at the end of the basic
808 // block, but which do not hold any virtual registers. e.g., the stack
810 PhysRegsUseOrder.clear();
814 /// runOnMachineFunction - Register allocate the whole function
816 bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
817 DOUT << "Machine Function " << "\n";
819 TM = &Fn.getTarget();
820 MRI = TM->getRegisterInfo();
821 TII = TM->getInstrInfo();
823 PhysRegsUsed.assign(MRI->getNumRegs(), -1);
825 // At various places we want to efficiently check to see whether a register
826 // is allocatable. To handle this, we mark all unallocatable registers as
827 // being pinned down, permanently.
829 BitVector Allocable = MRI->getAllocatableSet(Fn);
830 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
832 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
835 // initialize the virtual->physical register map to have a 'null'
836 // mapping for all virtual registers
837 unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
838 Virt2PhysRegMap.grow(LastVirtReg);
839 Virt2LastUseMap.grow(LastVirtReg);
840 VirtRegModified.resize(LastVirtReg+1-MRegisterInfo::FirstVirtualRegister);
842 // Loop over all of the basic blocks, eliminating virtual register references
843 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
845 AllocateBasicBlock(*MBB);
847 StackSlotForVirtReg.clear();
848 PhysRegsUsed.clear();
849 VirtRegModified.clear();
850 Virt2PhysRegMap.clear();
851 Virt2LastUseMap.clear();
855 FunctionPass *llvm::createLocalRegisterAllocator() {
856 return new RALocal();