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/Passes.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/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/Compiler.h"
28 #include "llvm/ADT/IndexedMap.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
34 STATISTIC(NumStores, "Number of stores added");
35 STATISTIC(NumLoads , "Number of loads added");
36 STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
39 static RegisterRegAlloc
40 localRegAlloc("local", " local register allocator",
41 createLocalRegisterAllocator);
44 class VISIBILITY_HIDDEN RALocal : public MachineFunctionPass {
47 RALocal() : MachineFunctionPass((intptr_t)&ID) {}
49 const TargetMachine *TM;
51 const MRegisterInfo *MRI;
52 const TargetInstrInfo *TII;
54 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
55 // values are spilled.
56 std::map<unsigned, int> StackSlotForVirtReg;
58 // Virt2PhysRegMap - This map contains entries for each virtual register
59 // that is currently available in a physical register.
60 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
62 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
63 return Virt2PhysRegMap[VirtReg];
66 // PhysRegsUsed - This array is effectively a map, containing entries for
67 // each physical register that currently has a value (ie, it is in
68 // Virt2PhysRegMap). The value mapped to is the virtual register
69 // corresponding to the physical register (the inverse of the
70 // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
71 // because it is used by a future instruction, and to -2 if it is not
72 // allocatable. If the entry for a physical register is -1, then the
73 // physical register is "not in the map".
75 std::vector<int> PhysRegsUsed;
77 // PhysRegsUseOrder - This contains a list of the physical registers that
78 // currently have a virtual register value in them. This list provides an
79 // ordering of registers, imposing a reallocation order. This list is only
80 // used if all registers are allocated and we have to spill one, in which
81 // case we spill the least recently used register. Entries at the front of
82 // the list are the least recently used registers, entries at the back are
83 // the most recently used.
85 std::vector<unsigned> PhysRegsUseOrder;
87 // Virt2LastUseMap - This maps each virtual register to its last use
88 // (MachineInstr*, operand index pair).
89 IndexedMap<std::pair<MachineInstr*, unsigned>, VirtReg2IndexFunctor>
92 std::pair<MachineInstr*,unsigned>& getVirtRegLastUse(unsigned Reg) {
93 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
94 return Virt2LastUseMap[Reg];
97 // VirtRegModified - This bitset contains information about which virtual
98 // registers need to be spilled back to memory when their registers are
99 // scavenged. If a virtual register has simply been rematerialized, there
100 // is no reason to spill it to memory when we need the register back.
102 BitVector VirtRegModified;
104 void markVirtRegModified(unsigned Reg, bool Val = true) {
105 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
106 Reg -= MRegisterInfo::FirstVirtualRegister;
108 VirtRegModified.set(Reg);
110 VirtRegModified.reset(Reg);
113 bool isVirtRegModified(unsigned Reg) const {
114 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
115 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
116 && "Illegal virtual register!");
117 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
120 void AddToPhysRegsUseOrder(unsigned Reg) {
121 std::vector<unsigned>::iterator It =
122 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg);
123 if (It != PhysRegsUseOrder.end())
124 PhysRegsUseOrder.erase(It);
125 PhysRegsUseOrder.push_back(Reg);
128 void MarkPhysRegRecentlyUsed(unsigned Reg) {
129 if (PhysRegsUseOrder.empty() ||
130 PhysRegsUseOrder.back() == Reg) return; // Already most recently used
132 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
133 if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
134 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
135 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
136 // Add it to the end of the list
137 PhysRegsUseOrder.push_back(RegMatch);
139 return; // Found an exact match, exit early
144 virtual const char *getPassName() const {
145 return "Local Register Allocator";
148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
149 AU.addRequiredID(PHIEliminationID);
150 AU.addRequiredID(TwoAddressInstructionPassID);
151 MachineFunctionPass::getAnalysisUsage(AU);
155 /// runOnMachineFunction - Register allocate the whole function
156 bool runOnMachineFunction(MachineFunction &Fn);
158 /// AllocateBasicBlock - Register allocate the specified basic block.
159 void AllocateBasicBlock(MachineBasicBlock &MBB);
162 /// areRegsEqual - This method returns true if the specified registers are
163 /// related to each other. To do this, it checks to see if they are equal
164 /// or if the first register is in the alias set of the second register.
166 bool areRegsEqual(unsigned R1, unsigned R2) const {
167 if (R1 == R2) return true;
168 for (const unsigned *AliasSet = MRI->getAliasSet(R2);
169 *AliasSet; ++AliasSet) {
170 if (*AliasSet == R1) return true;
175 /// getStackSpaceFor - This returns the frame index of the specified virtual
176 /// register on the stack, allocating space if necessary.
177 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
179 /// removePhysReg - This method marks the specified physical register as no
180 /// longer being in use.
182 void removePhysReg(unsigned PhysReg);
184 /// spillVirtReg - This method spills the value specified by PhysReg into
185 /// the virtual register slot specified by VirtReg. It then updates the RA
186 /// data structures to indicate the fact that PhysReg is now available.
188 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
189 unsigned VirtReg, unsigned PhysReg);
191 /// spillPhysReg - This method spills the specified physical register into
192 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
193 /// true, then the request is ignored if the physical register does not
194 /// contain a virtual register.
196 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
197 unsigned PhysReg, bool OnlyVirtRegs = false);
199 /// assignVirtToPhysReg - This method updates local state so that we know
200 /// that PhysReg is the proper container for VirtReg now. The physical
201 /// register must not be used for anything else when this is called.
203 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
205 /// isPhysRegAvailable - Return true if the specified physical register is
206 /// free and available for use. This also includes checking to see if
207 /// aliased registers are all free...
209 bool isPhysRegAvailable(unsigned PhysReg) const;
211 /// getFreeReg - Look to see if there is a free register available in the
212 /// specified register class. If not, return 0.
214 unsigned getFreeReg(const TargetRegisterClass *RC);
216 /// getReg - Find a physical register to hold the specified virtual
217 /// register. If all compatible physical registers are used, this method
218 /// spills the last used virtual register to the stack, and uses that
221 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
224 /// reloadVirtReg - This method transforms the specified specified virtual
225 /// register use to refer to a physical register. This method may do this
226 /// in one of several ways: if the register is available in a physical
227 /// register already, it uses that physical register. If the value is not
228 /// in a physical register, and if there are physical registers available,
229 /// it loads it into a register. If register pressure is high, and it is
230 /// possible, it tries to fold the load of the virtual register into the
231 /// instruction itself. It avoids doing this if register pressure is low to
232 /// improve the chance that subsequent instructions can use the reloaded
233 /// value. This method returns the modified instruction.
235 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
239 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
242 char RALocal::ID = 0;
245 /// getStackSpaceFor - This allocates space for the specified virtual register
246 /// to be held on the stack.
247 int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
248 // Find the location Reg would belong...
249 std::map<unsigned, int>::iterator I =StackSlotForVirtReg.lower_bound(VirtReg);
251 if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
252 return I->second; // Already has space allocated?
254 // Allocate a new stack object for this spill location...
255 int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
258 // Assign the slot...
259 StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
264 /// removePhysReg - This method marks the specified physical register as no
265 /// longer being in use.
267 void RALocal::removePhysReg(unsigned PhysReg) {
268 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
270 std::vector<unsigned>::iterator It =
271 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
272 if (It != PhysRegsUseOrder.end())
273 PhysRegsUseOrder.erase(It);
277 /// spillVirtReg - This method spills the value specified by PhysReg into the
278 /// virtual register slot specified by VirtReg. It then updates the RA data
279 /// structures to indicate the fact that PhysReg is now available.
281 void RALocal::spillVirtReg(MachineBasicBlock &MBB,
282 MachineBasicBlock::iterator I,
283 unsigned VirtReg, unsigned PhysReg) {
284 assert(VirtReg && "Spilling a physical register is illegal!"
285 " Must not have appropriate kill for the register or use exists beyond"
286 " the intended one.");
287 DOUT << " Spilling register " << MRI->getName(PhysReg)
288 << " containing %reg" << VirtReg;
290 const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
292 if (!isVirtRegModified(VirtReg)) {
293 DOUT << " which has not been modified, so no store necessary!";
294 std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
296 LastUse.first->getOperand(LastUse.second).setIsKill();
299 // Otherwise, there is a virtual register corresponding to this physical
300 // register. We only need to spill it into its stack slot if it has been
302 if (isVirtRegModified(VirtReg)) {
303 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
304 int FrameIndex = getStackSpaceFor(VirtReg, RC);
305 DOUT << " to stack slot #" << FrameIndex;
306 TII->storeRegToStackSlot(MBB, I, PhysReg, true, FrameIndex, RC);
307 ++NumStores; // Update statistics
310 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
313 removePhysReg(PhysReg);
317 /// spillPhysReg - This method spills the specified physical register into the
318 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
319 /// then the request is ignored if the physical register does not contain a
320 /// virtual register.
322 void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
323 unsigned PhysReg, bool OnlyVirtRegs) {
324 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
325 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
326 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
327 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
329 // If the selected register aliases any other registers, we must make
330 // sure that one of the aliases isn't alive.
331 for (const unsigned *AliasSet = MRI->getAliasSet(PhysReg);
332 *AliasSet; ++AliasSet)
333 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
334 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
335 if (PhysRegsUsed[*AliasSet])
336 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
341 /// assignVirtToPhysReg - This method updates local state so that we know
342 /// that PhysReg is the proper container for VirtReg now. The physical
343 /// register must not be used for anything else when this is called.
345 void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
346 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
347 // Update information to note the fact that this register was just used, and
349 PhysRegsUsed[PhysReg] = VirtReg;
350 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
351 AddToPhysRegsUseOrder(PhysReg); // New use of PhysReg
355 /// isPhysRegAvailable - Return true if the specified physical register is free
356 /// and available for use. This also includes checking to see if aliased
357 /// registers are all free...
359 bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
360 if (PhysRegsUsed[PhysReg] != -1) return false;
362 // If the selected register aliases any other allocated registers, it is
364 for (const unsigned *AliasSet = MRI->getAliasSet(PhysReg);
365 *AliasSet; ++AliasSet)
366 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
367 return false; // Can't use this reg then.
372 /// getFreeReg - Look to see if there is a free register available in the
373 /// specified register class. If not, return 0.
375 unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
376 // Get iterators defining the range of registers that are valid to allocate in
377 // this class, which also specifies the preferred allocation order.
378 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
379 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
381 for (; RI != RE; ++RI)
382 if (isPhysRegAvailable(*RI)) { // Is reg unused?
383 assert(*RI != 0 && "Cannot use register!");
384 return *RI; // Found an unused register!
390 /// getReg - Find a physical register to hold the specified virtual
391 /// register. If all compatible physical registers are used, this method spills
392 /// the last used virtual register to the stack, and uses that register.
394 unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
396 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
398 // First check to see if we have a free register of the requested type...
399 unsigned PhysReg = getFreeReg(RC);
401 // If we didn't find an unused register, scavenge one now!
403 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
405 // Loop over all of the preallocated registers from the least recently used
406 // to the most recently used. When we find one that is capable of holding
407 // our register, use it.
408 for (unsigned i = 0; PhysReg == 0; ++i) {
409 assert(i != PhysRegsUseOrder.size() &&
410 "Couldn't find a register of the appropriate class!");
412 unsigned R = PhysRegsUseOrder[i];
414 // We can only use this register if it holds a virtual register (ie, it
415 // can be spilled). Do not use it if it is an explicitly allocated
416 // physical register!
417 assert(PhysRegsUsed[R] != -1 &&
418 "PhysReg in PhysRegsUseOrder, but is not allocated?");
419 if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
420 // If the current register is compatible, use it.
421 if (RC->contains(R)) {
425 // If one of the registers aliased to the current register is
426 // compatible, use it.
427 for (const unsigned *AliasIt = MRI->getAliasSet(R);
428 *AliasIt; ++AliasIt) {
429 if (RC->contains(*AliasIt) &&
430 // If this is pinned down for some reason, don't use it. For
431 // example, if CL is pinned, and we run across CH, don't use
432 // CH as justification for using scavenging ECX (which will
434 PhysRegsUsed[*AliasIt] != 0 &&
436 // Make sure the register is allocatable. Don't allocate SIL on
438 PhysRegsUsed[*AliasIt] != -2) {
439 PhysReg = *AliasIt; // Take an aliased register
447 assert(PhysReg && "Physical register not assigned!?!?");
449 // At this point PhysRegsUseOrder[i] is the least recently used register of
450 // compatible register class. Spill it to memory and reap its remains.
451 spillPhysReg(MBB, I, PhysReg);
454 // Now that we know which register we need to assign this to, do it now!
455 assignVirtToPhysReg(VirtReg, PhysReg);
460 /// reloadVirtReg - This method transforms the specified specified virtual
461 /// register use to refer to a physical register. This method may do this in
462 /// one of several ways: if the register is available in a physical register
463 /// already, it uses that physical register. If the value is not in a physical
464 /// register, and if there are physical registers available, it loads it into a
465 /// register. If register pressure is high, and it is possible, it tries to
466 /// fold the load of the virtual register into the instruction itself. It
467 /// avoids doing this if register pressure is low to improve the chance that
468 /// subsequent instructions can use the reloaded value. This method returns the
469 /// modified instruction.
471 MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
473 unsigned VirtReg = MI->getOperand(OpNum).getReg();
475 // If the virtual register is already available, just update the instruction
477 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
478 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
479 MI->getOperand(OpNum).setReg(PR); // Assign the input register
483 // Otherwise, we need to fold it into the current instruction, or reload it.
484 // If we have registers available to hold the value, use them.
485 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
486 unsigned PhysReg = getFreeReg(RC);
487 int FrameIndex = getStackSpaceFor(VirtReg, RC);
489 if (PhysReg) { // Register is available, allocate it!
490 assignVirtToPhysReg(VirtReg, PhysReg);
491 } else { // No registers available.
492 // If we can fold this spill into this instruction, do so now.
493 SmallVector<unsigned, 2> Ops;
494 Ops.push_back(OpNum);
495 if (MachineInstr* FMI = TII->foldMemoryOperand(MI, Ops, FrameIndex)) {
497 // Update kill/dead flags.
498 FMI->copyKillDeadInfo(MI);
499 return MBB.insert(MBB.erase(MI), FMI);
502 // It looks like we can't fold this virtual register load into this
503 // instruction. Force some poor hapless value out of the register file to
504 // make room for the new register, and reload it.
505 PhysReg = getReg(MBB, MI, VirtReg);
508 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
510 DOUT << " Reloading %reg" << VirtReg << " into "
511 << MRI->getName(PhysReg) << "\n";
513 // Add move instruction(s)
514 const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
515 TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
516 ++NumLoads; // Update statistics
518 MF->getRegInfo().setPhysRegUsed(PhysReg);
519 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
520 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
524 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
525 /// read/mod/write register, i.e. update partial register.
526 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
527 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
528 MachineOperand& MO = MI->getOperand(i);
529 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
530 MO.isDef() && !MO.isDead())
536 /// isReadModWriteImplicitDef - True if this is an implicit def for a
537 /// read/mod/write register, i.e. update partial register.
538 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
539 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
540 MachineOperand& MO = MI->getOperand(i);
541 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
542 !MO.isDef() && MO.isKill())
548 void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
549 // loop over each instruction
550 MachineBasicBlock::iterator MII = MBB.begin();
551 const TargetInstrInfo &TII = *TM->getInstrInfo();
553 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
554 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
556 // If this is the first basic block in the machine function, add live-in
557 // registers as active.
558 if (&MBB == &*MF->begin()) {
559 for (MachineRegisterInfo::livein_iterator I=MF->getRegInfo().livein_begin(),
560 E = MF->getRegInfo().livein_end(); I != E; ++I) {
561 unsigned Reg = I->first;
562 MF->getRegInfo().setPhysRegUsed(Reg);
563 PhysRegsUsed[Reg] = 0; // It is free and reserved now
564 AddToPhysRegsUseOrder(Reg);
565 for (const unsigned *AliasSet = MRI->getSubRegisters(Reg);
566 *AliasSet; ++AliasSet) {
567 if (PhysRegsUsed[*AliasSet] != -2) {
568 AddToPhysRegsUseOrder(*AliasSet);
569 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
570 MF->getRegInfo().setPhysRegUsed(*AliasSet);
576 // Otherwise, sequentially allocate each instruction in the MBB.
577 while (MII != MBB.end()) {
578 MachineInstr *MI = MII++;
579 const TargetInstrDesc &TID = MI->getDesc();
580 DEBUG(DOUT << "\nStarting RegAlloc of: " << *MI;
581 DOUT << " Regs have values: ";
582 for (unsigned i = 0; i != MRI->getNumRegs(); ++i)
583 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
584 DOUT << "[" << MRI->getName(i)
585 << ",%reg" << PhysRegsUsed[i] << "] ";
588 // Loop over the implicit uses, making sure that they are at the head of the
589 // use order list, so they don't get reallocated.
590 if (TID.ImplicitUses) {
591 for (const unsigned *ImplicitUses = TID.ImplicitUses;
592 *ImplicitUses; ++ImplicitUses)
593 MarkPhysRegRecentlyUsed(*ImplicitUses);
596 SmallVector<unsigned, 8> Kills;
597 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
598 MachineOperand& MO = MI->getOperand(i);
599 if (MO.isRegister() && MO.isKill()) {
600 if (!MO.isImplicit())
601 Kills.push_back(MO.getReg());
602 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
603 // These are extra physical register kills when a sub-register
604 // is defined (def of a sub-register is a read/mod/write of the
605 // larger registers). Ignore.
606 Kills.push_back(MO.getReg());
610 // Get the used operands into registers. This has the potential to spill
611 // incoming values if we are out of registers. Note that we completely
612 // ignore physical register uses here. We assume that if an explicit
613 // physical register is referenced by the instruction, that it is guaranteed
614 // to be live-in, or the input is badly hosed.
616 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
617 MachineOperand& MO = MI->getOperand(i);
618 // here we are looking for only used operands (never def&use)
619 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
620 MRegisterInfo::isVirtualRegister(MO.getReg()))
621 MI = reloadVirtReg(MBB, MI, i);
624 // If this instruction is the last user of this register, kill the
625 // value, freeing the register being used, so it doesn't need to be
626 // spilled to memory.
628 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
629 unsigned VirtReg = Kills[i];
630 unsigned PhysReg = VirtReg;
631 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
632 // If the virtual register was never materialized into a register, it
633 // might not be in the map, but it won't hurt to zero it out anyway.
634 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
635 PhysReg = PhysRegSlot;
637 } else if (PhysRegsUsed[PhysReg] == -2) {
638 // Unallocatable register dead, ignore.
641 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
642 "Silently clearing a virtual register?");
646 DOUT << " Last use of " << MRI->getName(PhysReg)
647 << "[%reg" << VirtReg <<"], removing it from live set\n";
648 removePhysReg(PhysReg);
649 for (const unsigned *AliasSet = MRI->getSubRegisters(PhysReg);
650 *AliasSet; ++AliasSet) {
651 if (PhysRegsUsed[*AliasSet] != -2) {
652 DOUT << " Last use of "
653 << MRI->getName(*AliasSet)
654 << "[%reg" << VirtReg <<"], removing it from live set\n";
655 removePhysReg(*AliasSet);
661 // Loop over all of the operands of the instruction, spilling registers that
662 // are defined, and marking explicit destinations in the PhysRegsUsed map.
663 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
664 MachineOperand& MO = MI->getOperand(i);
665 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
666 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
667 unsigned Reg = MO.getReg();
668 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
669 // These are extra physical register defs when a sub-register
670 // is defined (def of a sub-register is a read/mod/write of the
671 // larger registers). Ignore.
672 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
674 MF->getRegInfo().setPhysRegUsed(Reg);
675 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
676 PhysRegsUsed[Reg] = 0; // It is free and reserved now
677 AddToPhysRegsUseOrder(Reg);
679 for (const unsigned *AliasSet = MRI->getSubRegisters(Reg);
680 *AliasSet; ++AliasSet) {
681 if (PhysRegsUsed[*AliasSet] != -2) {
682 MF->getRegInfo().setPhysRegUsed(*AliasSet);
683 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
684 AddToPhysRegsUseOrder(*AliasSet);
690 // Loop over the implicit defs, spilling them as well.
691 if (TID.ImplicitDefs) {
692 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
693 *ImplicitDefs; ++ImplicitDefs) {
694 unsigned Reg = *ImplicitDefs;
695 if (PhysRegsUsed[Reg] != -2) {
696 spillPhysReg(MBB, MI, Reg, true);
697 AddToPhysRegsUseOrder(Reg);
698 PhysRegsUsed[Reg] = 0; // It is free and reserved now
700 MF->getRegInfo().setPhysRegUsed(Reg);
701 for (const unsigned *AliasSet = MRI->getSubRegisters(Reg);
702 *AliasSet; ++AliasSet) {
703 if (PhysRegsUsed[*AliasSet] != -2) {
704 AddToPhysRegsUseOrder(*AliasSet);
705 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
706 MF->getRegInfo().setPhysRegUsed(*AliasSet);
712 SmallVector<unsigned, 8> DeadDefs;
713 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
714 MachineOperand& MO = MI->getOperand(i);
715 if (MO.isRegister() && MO.isDead())
716 DeadDefs.push_back(MO.getReg());
719 // Okay, we have allocated all of the source operands and spilled any values
720 // that would be destroyed by defs of this instruction. Loop over the
721 // explicit defs and assign them to a register, spilling incoming values if
722 // we need to scavenge a register.
724 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
725 MachineOperand& MO = MI->getOperand(i);
726 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
727 MRegisterInfo::isVirtualRegister(MO.getReg())) {
728 unsigned DestVirtReg = MO.getReg();
729 unsigned DestPhysReg;
731 // If DestVirtReg already has a value, use it.
732 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
733 DestPhysReg = getReg(MBB, MI, DestVirtReg);
734 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
735 markVirtRegModified(DestVirtReg);
736 getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
737 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
741 // If this instruction defines any registers that are immediately dead,
744 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
745 unsigned VirtReg = DeadDefs[i];
746 unsigned PhysReg = VirtReg;
747 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
748 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
749 PhysReg = PhysRegSlot;
750 assert(PhysReg != 0);
752 } else if (PhysRegsUsed[PhysReg] == -2) {
753 // Unallocatable register dead, ignore.
758 DOUT << " Register " << MRI->getName(PhysReg)
759 << " [%reg" << VirtReg
760 << "] is never used, removing it frame live list\n";
761 removePhysReg(PhysReg);
762 for (const unsigned *AliasSet = MRI->getAliasSet(PhysReg);
763 *AliasSet; ++AliasSet) {
764 if (PhysRegsUsed[*AliasSet] != -2) {
765 DOUT << " Register " << MRI->getName(*AliasSet)
766 << " [%reg" << *AliasSet
767 << "] is never used, removing it frame live list\n";
768 removePhysReg(*AliasSet);
774 // Finally, if this is a noop copy instruction, zap it.
775 unsigned SrcReg, DstReg;
776 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
781 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
783 // Spill all physical registers holding virtual registers now.
784 for (unsigned i = 0, e = MRI->getNumRegs(); i != e; ++i)
785 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
786 if (unsigned VirtReg = PhysRegsUsed[i])
787 spillVirtReg(MBB, MI, VirtReg, i);
792 // This checking code is very expensive.
794 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
795 e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
796 if (unsigned PR = Virt2PhysRegMap[i]) {
797 cerr << "Register still mapped: " << i << " -> " << PR << "\n";
800 assert(AllOk && "Virtual registers still in phys regs?");
803 // Clear any physical register which appear live at the end of the basic
804 // block, but which do not hold any virtual registers. e.g., the stack
806 PhysRegsUseOrder.clear();
810 /// runOnMachineFunction - Register allocate the whole function
812 bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
813 DOUT << "Machine Function " << "\n";
815 TM = &Fn.getTarget();
816 MRI = TM->getRegisterInfo();
817 TII = TM->getInstrInfo();
819 PhysRegsUsed.assign(MRI->getNumRegs(), -1);
821 // At various places we want to efficiently check to see whether a register
822 // is allocatable. To handle this, we mark all unallocatable registers as
823 // being pinned down, permanently.
825 BitVector Allocable = MRI->getAllocatableSet(Fn);
826 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
828 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
831 // initialize the virtual->physical register map to have a 'null'
832 // mapping for all virtual registers
833 unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
834 Virt2PhysRegMap.grow(LastVirtReg);
835 Virt2LastUseMap.grow(LastVirtReg);
836 VirtRegModified.resize(LastVirtReg+1-MRegisterInfo::FirstVirtualRegister);
838 // Loop over all of the basic blocks, eliminating virtual register references
839 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
841 AllocateBasicBlock(*MBB);
843 StackSlotForVirtReg.clear();
844 PhysRegsUsed.clear();
845 VirtRegModified.clear();
846 Virt2PhysRegMap.clear();
847 Virt2LastUseMap.clear();
851 FunctionPass *llvm::createLocalRegisterAllocator() {
852 return new RALocal();