1 //===- RegAllocBigBlock.cpp - A register allocator for large basic blocks -===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Duraid Madina and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the RABigBlock class
12 //===----------------------------------------------------------------------===//
14 // This register allocator is derived from RegAllocLocal.cpp. Like it, this
15 // allocator works on one basic block at a time, oblivious to others.
16 // However, the algorithm used here is suited for long blocks of
17 // instructions - registers are spilled by greedily choosing those holding
18 // values that will not be needed for the longest amount of time. This works
19 // particularly well for blocks with 10 or more times as many instructions
20 // as machine registers, but can be used for general code.
22 //===----------------------------------------------------------------------===//
24 // TODO: - automagically invoke linearscan for (groups of) small BBs?
25 // - break ties when picking regs? (probably not worth it in a
28 //===----------------------------------------------------------------------===//
30 #define DEBUG_TYPE "regalloc"
31 #include "llvm/BasicBlock.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/SSARegMap.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/LiveVariables.h"
38 #include "llvm/CodeGen/RegAllocRegistry.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/ADT/IndexedMap.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/SmallPtrSet.h"
48 #include "llvm/ADT/Statistic.h"
52 STATISTIC(NumStores, "Number of stores added");
53 STATISTIC(NumLoads , "Number of loads added");
54 STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
57 static RegisterRegAlloc
58 bigBlockRegAlloc("bigblock", " Big-block register allocator",
59 createBigBlockRegisterAllocator);
61 /// VRegKeyInfo - Defines magic values required to use VirtRegs as DenseMap
64 static inline unsigned getEmptyKey() { return -1U; }
65 static inline unsigned getTombstoneKey() { return -2U; }
66 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
67 static unsigned getHashValue(const unsigned &Key) { return Key; }
71 /// This register allocator is derived from RegAllocLocal.cpp. Like it, this
72 /// allocator works on one basic block at a time, oblivious to others.
73 /// However, the algorithm used here is suited for long blocks of
74 /// instructions - registers are spilled by greedily choosing those holding
75 /// values that will not be needed for the longest amount of time. This works
76 /// particularly well for blocks with 10 or more times as many instructions
77 /// as machine registers, but can be used for general code.
79 /// TODO: - automagically invoke linearscan for (groups of) small BBs?
80 /// - break ties when picking regs? (probably not worth it in a
83 class VISIBILITY_HIDDEN RABigBlock : public MachineFunctionPass {
86 RABigBlock() : MachineFunctionPass((intptr_t)&ID) {}
88 /// TM - For getting at TargetMachine info
90 const TargetMachine *TM;
92 /// MF - Our generic MachineFunction pointer
96 /// RegInfo - For dealing with machine register info (aliases, folds
98 const MRegisterInfo *RegInfo;
100 /// LV - Our generic LiveVariables pointer
104 typedef SmallVector<unsigned, 2> VRegTimes;
106 /// VRegReadTable - maps VRegs in a BB to the set of times they are read
108 DenseMap<unsigned, VRegTimes*, VRegKeyInfo> VRegReadTable;
110 /// VRegReadIdx - keeps track of the "current time" in terms of
111 /// positions in VRegReadTable
112 DenseMap<unsigned, unsigned , VRegKeyInfo> VRegReadIdx;
114 /// StackSlotForVirtReg - Maps virtual regs to the frame index where these
115 /// values are spilled.
116 IndexedMap<unsigned, VirtReg2IndexFunctor> StackSlotForVirtReg;
118 /// Virt2PhysRegMap - This map contains entries for each virtual register
119 /// that is currently available in a physical register.
120 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
122 /// PhysRegsUsed - This array is effectively a map, containing entries for
123 /// each physical register that currently has a value (ie, it is in
124 /// Virt2PhysRegMap). The value mapped to is the virtual register
125 /// corresponding to the physical register (the inverse of the
126 /// Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
127 /// because it is used by a future instruction, and to -2 if it is not
128 /// allocatable. If the entry for a physical register is -1, then the
129 /// physical register is "not in the map".
131 std::vector<int> PhysRegsUsed;
133 /// VirtRegModified - This bitset contains information about which virtual
134 /// registers need to be spilled back to memory when their registers are
135 /// scavenged. If a virtual register has simply been rematerialized, there
136 /// is no reason to spill it to memory when we need the register back.
138 std::vector<int> VirtRegModified;
140 /// MBBLastInsnTime - the number of the the last instruction in MBB
144 /// MBBCurTime - the number of the the instruction being currently processed
148 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
149 return Virt2PhysRegMap[VirtReg];
152 unsigned &getVirt2StackSlot(unsigned VirtReg) {
153 return StackSlotForVirtReg[VirtReg];
156 /// markVirtRegModified - Lets us flip bits in the VirtRegModified bitset
158 void markVirtRegModified(unsigned Reg, bool Val = true) {
159 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
160 Reg -= MRegisterInfo::FirstVirtualRegister;
161 if (VirtRegModified.size() <= Reg)
162 VirtRegModified.resize(Reg+1);
163 VirtRegModified[Reg] = Val;
166 /// isVirtRegModified - Lets us query the VirtRegModified bitset
168 bool isVirtRegModified(unsigned Reg) const {
169 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
170 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
171 && "Illegal virtual register!");
172 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
176 /// getPassName - returns the BigBlock allocator's name
178 virtual const char *getPassName() const {
179 return "BigBlock Register Allocator";
182 /// getAnalaysisUsage - declares the required analyses
184 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
185 AU.addRequired<LiveVariables>();
186 AU.addRequiredID(PHIEliminationID);
187 AU.addRequiredID(TwoAddressInstructionPassID);
188 MachineFunctionPass::getAnalysisUsage(AU);
192 /// runOnMachineFunction - Register allocate the whole function
194 bool runOnMachineFunction(MachineFunction &Fn);
196 /// AllocateBasicBlock - Register allocate the specified basic block.
198 void AllocateBasicBlock(MachineBasicBlock &MBB);
200 /// FillVRegReadTable - Fill out the table of vreg read times given a BB
202 void FillVRegReadTable(MachineBasicBlock &MBB);
204 /// areRegsEqual - This method returns true if the specified registers are
205 /// related to each other. To do this, it checks to see if they are equal
206 /// or if the first register is in the alias set of the second register.
208 bool areRegsEqual(unsigned R1, unsigned R2) const {
209 if (R1 == R2) return true;
210 for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
211 *AliasSet; ++AliasSet) {
212 if (*AliasSet == R1) return true;
217 /// getStackSpaceFor - This returns the frame index of the specified virtual
218 /// register on the stack, allocating space if necessary.
219 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
221 /// removePhysReg - This method marks the specified physical register as no
222 /// longer being in use.
224 void removePhysReg(unsigned PhysReg);
226 /// spillVirtReg - This method spills the value specified by PhysReg into
227 /// the virtual register slot specified by VirtReg. It then updates the RA
228 /// data structures to indicate the fact that PhysReg is now available.
230 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
231 unsigned VirtReg, unsigned PhysReg);
233 /// spillPhysReg - This method spills the specified physical register into
234 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
235 /// true, then the request is ignored if the physical register does not
236 /// contain a virtual register.
238 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
239 unsigned PhysReg, bool OnlyVirtRegs = false);
241 /// assignVirtToPhysReg - This method updates local state so that we know
242 /// that PhysReg is the proper container for VirtReg now. The physical
243 /// register must not be used for anything else when this is called.
245 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
247 /// isPhysRegAvailable - Return true if the specified physical register is
248 /// free and available for use. This also includes checking to see if
249 /// aliased registers are all free...
251 bool isPhysRegAvailable(unsigned PhysReg) const;
253 /// getFreeReg - Look to see if there is a free register available in the
254 /// specified register class. If not, return 0.
256 unsigned getFreeReg(const TargetRegisterClass *RC);
258 /// chooseReg - Pick a physical register to hold the specified
259 /// virtual register by choosing the one which will be read furthest
262 unsigned chooseReg(MachineBasicBlock &MBB, MachineInstr *MI,
265 /// reloadVirtReg - This method transforms the specified specified virtual
266 /// register use to refer to a physical register. This method may do this
267 /// in one of several ways: if the register is available in a physical
268 /// register already, it uses that physical register. If the value is not
269 /// in a physical register, and if there are physical registers available,
270 /// it loads it into a register. If register pressure is high, and it is
271 /// possible, it tries to fold the load of the virtual register into the
272 /// instruction itself. It avoids doing this if register pressure is low to
273 /// improve the chance that subsequent instructions can use the reloaded
274 /// value. This method returns the modified instruction.
276 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
280 char RABigBlock::ID = 0;
283 /// getStackSpaceFor - This allocates space for the specified virtual register
284 /// to be held on the stack.
285 int RABigBlock::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
286 // Find the location Reg would belong...
287 int FrameIdx = getVirt2StackSlot(VirtReg);
290 return FrameIdx - 1; // Already has space allocated?
292 // Allocate a new stack object for this spill location...
293 FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
296 // Assign the slot...
297 getVirt2StackSlot(VirtReg) = FrameIdx + 1;
302 /// removePhysReg - This method marks the specified physical register as no
303 /// longer being in use.
305 void RABigBlock::removePhysReg(unsigned PhysReg) {
306 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
310 /// spillVirtReg - This method spills the value specified by PhysReg into the
311 /// virtual register slot specified by VirtReg. It then updates the RA data
312 /// structures to indicate the fact that PhysReg is now available.
314 void RABigBlock::spillVirtReg(MachineBasicBlock &MBB,
315 MachineBasicBlock::iterator I,
316 unsigned VirtReg, unsigned PhysReg) {
317 assert(VirtReg && "Spilling a physical register is illegal!"
318 " Must not have appropriate kill for the register or use exists beyond"
319 " the intended one.");
320 DOUT << " Spilling register " << RegInfo->getName(PhysReg)
321 << " containing %reg" << VirtReg;
322 if (!isVirtRegModified(VirtReg))
323 DOUT << " which has not been modified, so no store necessary!";
325 // Otherwise, there is a virtual register corresponding to this physical
326 // register. We only need to spill it into its stack slot if it has been
328 if (isVirtRegModified(VirtReg)) {
329 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
330 int FrameIndex = getStackSpaceFor(VirtReg, RC);
331 DOUT << " to stack slot #" << FrameIndex;
332 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RC);
333 ++NumStores; // Update statistics
336 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
339 removePhysReg(PhysReg);
343 /// spillPhysReg - This method spills the specified physical register into the
344 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
345 /// then the request is ignored if the physical register does not contain a
346 /// virtual register.
348 void RABigBlock::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
349 unsigned PhysReg, bool OnlyVirtRegs) {
350 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
351 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
352 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
353 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
355 // If the selected register aliases any other registers, we must make
356 // sure that one of the aliases isn't alive.
357 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
358 *AliasSet; ++AliasSet)
359 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
360 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
361 if (PhysRegsUsed[*AliasSet])
362 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
367 /// assignVirtToPhysReg - This method updates local state so that we know
368 /// that PhysReg is the proper container for VirtReg now. The physical
369 /// register must not be used for anything else when this is called.
371 void RABigBlock::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
372 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
373 // Update information to note the fact that this register was just used, and
375 PhysRegsUsed[PhysReg] = VirtReg;
376 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
380 /// isPhysRegAvailable - Return true if the specified physical register is free
381 /// and available for use. This also includes checking to see if aliased
382 /// registers are all free...
384 bool RABigBlock::isPhysRegAvailable(unsigned PhysReg) const {
385 if (PhysRegsUsed[PhysReg] != -1) return false;
387 // If the selected register aliases any other allocated registers, it is
389 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
390 *AliasSet; ++AliasSet)
391 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
392 return false; // Can't use this reg then.
397 /// getFreeReg - Look to see if there is a free register available in the
398 /// specified register class. If not, return 0.
400 unsigned RABigBlock::getFreeReg(const TargetRegisterClass *RC) {
401 // Get iterators defining the range of registers that are valid to allocate in
402 // this class, which also specifies the preferred allocation order.
403 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
404 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
406 for (; RI != RE; ++RI)
407 if (isPhysRegAvailable(*RI)) { // Is reg unused?
408 assert(*RI != 0 && "Cannot use register!");
409 return *RI; // Found an unused register!
415 /// chooseReg - Pick a physical register to hold the specified
416 /// virtual register by choosing the one whose value will be read
417 /// furthest in the future.
419 unsigned RABigBlock::chooseReg(MachineBasicBlock &MBB, MachineInstr *I,
421 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
422 // First check to see if we have a free register of the requested type...
423 unsigned PhysReg = getFreeReg(RC);
425 // If we didn't find an unused register, find the one which will be
426 // read at the most distant point in time.
428 unsigned delay=0, longest_delay=0;
429 VRegTimes* ReadTimes;
431 unsigned curTime = MBBCurTime;
433 // for all physical regs in the RC,
434 for(TargetRegisterClass::iterator pReg = RC->begin();
435 pReg != RC->end(); ++pReg) {
436 // how long until they're read?
437 if(PhysRegsUsed[*pReg]>0) { // ignore non-allocatable regs
438 ReadTimes = VRegReadTable[PhysRegsUsed[*pReg]];
439 if(ReadTimes && !ReadTimes->empty()) {
440 unsigned& pt = VRegReadIdx[PhysRegsUsed[*pReg]];
441 while(pt < ReadTimes->size() && (*ReadTimes)[pt] < curTime) {
445 if(pt < ReadTimes->size())
446 delay = (*ReadTimes)[pt] - curTime;
448 delay = MBBLastInsnTime + 1 - curTime;
450 // This register is only defined, but never
451 // read in this MBB. Therefore the next read
452 // happens after the end of this MBB
453 delay = MBBLastInsnTime + 1 - curTime;
457 if(delay > longest_delay) {
458 longest_delay = delay;
464 if(PhysReg == 0) { // ok, now we're desperate. We couldn't choose
465 // a register to spill by looking through the
466 // read timetable, so now we just spill the
467 // first allocatable register we find.
469 // for all physical regs in the RC,
470 for(TargetRegisterClass::iterator pReg = RC->begin();
471 pReg != RC->end(); ++pReg) {
472 // if we find a register we can spill
473 if(PhysRegsUsed[*pReg]>=-1)
474 PhysReg = *pReg; // choose it to be spilled
478 assert(PhysReg && "couldn't choose a register to spill :( ");
479 // TODO: assert that RC->contains(PhysReg) / handle aliased registers?
481 // since we needed to look in the table we need to spill this register.
482 spillPhysReg(MBB, I, PhysReg);
485 // assign the vreg to our chosen physical register
486 assignVirtToPhysReg(VirtReg, PhysReg);
487 return PhysReg; // and return it
491 /// reloadVirtReg - This method transforms an instruction with a virtual
492 /// register use to one that references a physical register. It does this as
495 /// 1) If the register is already in a physical register, it uses it.
496 /// 2) Otherwise, if there is a free physical register, it uses that.
497 /// 3) Otherwise, it calls chooseReg() to get the physical register
498 /// holding the most distantly needed value, generating a spill in
501 /// This method returns the modified instruction.
502 MachineInstr *RABigBlock::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
504 unsigned VirtReg = MI->getOperand(OpNum).getReg();
506 // If the virtual register is already available in a physical register,
507 // just update the instruction and return.
508 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
509 MI->getOperand(OpNum).setReg(PR);
513 // Otherwise, if we have free physical registers available to hold the
515 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
516 unsigned PhysReg = getFreeReg(RC);
517 int FrameIndex = getStackSpaceFor(VirtReg, RC);
519 if (PhysReg) { // we have a free register, so use it.
520 assignVirtToPhysReg(VirtReg, PhysReg);
521 } else { // no free registers available.
522 // try to fold the spill into the instruction
523 if(MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, OpNum, FrameIndex)) {
525 // Since we changed the address of MI, make sure to update live variables
526 // to know that the new instruction has the properties of the old one.
527 LV->instructionChanged(MI, FMI);
528 return MBB.insert(MBB.erase(MI), FMI);
531 // determine which of the physical registers we'll kill off, since we
533 PhysReg = chooseReg(MBB, MI, VirtReg);
536 // this virtual register is now unmodified (since we just reloaded it)
537 markVirtRegModified(VirtReg, false);
539 DOUT << " Reloading %reg" << VirtReg << " into "
540 << RegInfo->getName(PhysReg) << "\n";
542 // Add move instruction(s)
543 RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
544 ++NumLoads; // Update statistics
546 MF->setPhysRegUsed(PhysReg);
547 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
551 /// Fill out the vreg read timetable. Since ReadTime increases
552 /// monotonically, the individual readtime sets will be sorted
553 /// in ascending order.
554 void RABigBlock::FillVRegReadTable(MachineBasicBlock &MBB) {
555 // loop over each instruction
556 MachineBasicBlock::iterator MII;
559 for(ReadTime=0, MII = MBB.begin(); MII != MBB.end(); ++ReadTime, ++MII) {
560 MachineInstr *MI = MII;
562 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
563 MachineOperand& MO = MI->getOperand(i);
564 // look for vreg reads..
565 if (MO.isRegister() && !MO.isDef() && MO.getReg() &&
566 MRegisterInfo::isVirtualRegister(MO.getReg())) {
567 // ..and add them to the read table.
568 VRegTimes* &Times = VRegReadTable[MO.getReg()];
569 if(!VRegReadTable[MO.getReg()]) {
570 Times = new VRegTimes;
571 VRegReadIdx[MO.getReg()] = 0;
573 Times->push_back(ReadTime);
579 MBBLastInsnTime = ReadTime;
581 for(DenseMap<unsigned, VRegTimes*, VRegKeyInfo>::iterator Reads = VRegReadTable.begin();
582 Reads != VRegReadTable.end(); ++Reads) {
584 DOUT << "Reads[" << Reads->first << "]=" << Reads->second->size() << "\n";
589 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
590 /// read/mod/write register, i.e. update partial register.
591 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
592 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
593 MachineOperand& MO = MI->getOperand(i);
594 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
595 MO.isDef() && !MO.isDead())
601 /// isReadModWriteImplicitDef - True if this is an implicit def for a
602 /// read/mod/write register, i.e. update partial register.
603 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
604 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
605 MachineOperand& MO = MI->getOperand(i);
606 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
607 !MO.isDef() && MO.isKill())
614 void RABigBlock::AllocateBasicBlock(MachineBasicBlock &MBB) {
615 // loop over each instruction
616 MachineBasicBlock::iterator MII = MBB.begin();
617 const TargetInstrInfo &TII = *TM->getInstrInfo();
619 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
620 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
622 // If this is the first basic block in the machine function, add live-in
623 // registers as active.
624 if (&MBB == &*MF->begin()) {
625 for (MachineFunction::livein_iterator I = MF->livein_begin(),
626 E = MF->livein_end(); I != E; ++I) {
627 unsigned Reg = I->first;
628 MF->setPhysRegUsed(Reg);
629 PhysRegsUsed[Reg] = 0; // It is free and reserved now
630 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
631 *AliasSet; ++AliasSet) {
632 if (PhysRegsUsed[*AliasSet] != -2) {
633 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
634 MF->setPhysRegUsed(*AliasSet);
640 // Otherwise, sequentially allocate each instruction in the MBB.
642 while (MII != MBB.end()) {
643 MachineInstr *MI = MII++;
645 const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
646 DEBUG(DOUT << "\nTime=" << MBBCurTime << " Starting RegAlloc of: " << *MI;
647 DOUT << " Regs have values: ";
648 for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
649 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
650 DOUT << "[" << RegInfo->getName(i)
651 << ",%reg" << PhysRegsUsed[i] << "] ";
654 SmallVector<unsigned, 8> Kills;
655 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
656 MachineOperand& MO = MI->getOperand(i);
657 if (MO.isRegister() && MO.isKill()) {
658 if (!MO.isImplicit())
659 Kills.push_back(MO.getReg());
660 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
661 // These are extra physical register kills when a sub-register
662 // is defined (def of a sub-register is a read/mod/write of the
663 // larger registers). Ignore.
664 Kills.push_back(MO.getReg());
668 // Get the used operands into registers. This has the potential to spill
669 // incoming values if we are out of registers. Note that we completely
670 // ignore physical register uses here. We assume that if an explicit
671 // physical register is referenced by the instruction, that it is guaranteed
672 // to be live-in, or the input is badly hosed.
674 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
675 MachineOperand& MO = MI->getOperand(i);
676 // here we are looking for only used operands (never def&use)
677 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
678 MRegisterInfo::isVirtualRegister(MO.getReg()))
679 MI = reloadVirtReg(MBB, MI, i);
682 // If this instruction is the last user of this register, kill the
683 // value, freeing the register being used, so it doesn't need to be
684 // spilled to memory.
686 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
687 unsigned VirtReg = Kills[i];
688 unsigned PhysReg = VirtReg;
689 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
690 // If the virtual register was never materialized into a register, it
691 // might not be in the map, but it won't hurt to zero it out anyway.
692 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
693 PhysReg = PhysRegSlot;
695 } else if (PhysRegsUsed[PhysReg] == -2) {
696 // Unallocatable register dead, ignore.
699 assert(!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1 &&
700 "Silently clearing a virtual register?");
704 DOUT << " Last use of " << RegInfo->getName(PhysReg)
705 << "[%reg" << VirtReg <<"], removing it from live set\n";
706 removePhysReg(PhysReg);
707 for (const unsigned *AliasSet = RegInfo->getSubRegisters(PhysReg);
708 *AliasSet; ++AliasSet) {
709 if (PhysRegsUsed[*AliasSet] != -2) {
710 DOUT << " Last use of "
711 << RegInfo->getName(*AliasSet)
712 << "[%reg" << VirtReg <<"], removing it from live set\n";
713 removePhysReg(*AliasSet);
719 // Loop over all of the operands of the instruction, spilling registers that
720 // are defined, and marking explicit destinations in the PhysRegsUsed map.
721 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
722 MachineOperand& MO = MI->getOperand(i);
723 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
724 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
725 unsigned Reg = MO.getReg();
726 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
727 // These are extra physical register defs when a sub-register
728 // is defined (def of a sub-register is a read/mod/write of the
729 // larger registers). Ignore.
730 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
732 MF->setPhysRegUsed(Reg);
733 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
734 PhysRegsUsed[Reg] = 0; // It is free and reserved now
735 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
736 *AliasSet; ++AliasSet) {
737 if (PhysRegsUsed[*AliasSet] != -2) {
738 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
739 MF->setPhysRegUsed(*AliasSet);
745 // Loop over the implicit defs, spilling them as well.
746 if (TID.ImplicitDefs) {
747 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
748 *ImplicitDefs; ++ImplicitDefs) {
749 unsigned Reg = *ImplicitDefs;
750 if (PhysRegsUsed[Reg] != -2) {
751 spillPhysReg(MBB, MI, Reg, true);
752 PhysRegsUsed[Reg] = 0; // It is free and reserved now
754 MF->setPhysRegUsed(Reg);
755 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
756 *AliasSet; ++AliasSet) {
757 if (PhysRegsUsed[*AliasSet] != -2) {
758 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
759 MF->setPhysRegUsed(*AliasSet);
765 SmallVector<unsigned, 8> DeadDefs;
766 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
767 MachineOperand& MO = MI->getOperand(i);
768 if (MO.isRegister() && MO.isDead())
769 DeadDefs.push_back(MO.getReg());
772 // Okay, we have allocated all of the source operands and spilled any values
773 // that would be destroyed by defs of this instruction. Loop over the
774 // explicit defs and assign them to a register, spilling incoming values if
775 // we need to scavenge a register.
777 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
778 MachineOperand& MO = MI->getOperand(i);
779 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
780 MRegisterInfo::isVirtualRegister(MO.getReg())) {
781 unsigned DestVirtReg = MO.getReg();
782 unsigned DestPhysReg;
784 // If DestVirtReg already has a value, use it.
785 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
786 DestPhysReg = chooseReg(MBB, MI, DestVirtReg);
787 MF->setPhysRegUsed(DestPhysReg);
788 markVirtRegModified(DestVirtReg);
789 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
793 // If this instruction defines any registers that are immediately dead,
796 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
797 unsigned VirtReg = DeadDefs[i];
798 unsigned PhysReg = VirtReg;
799 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
800 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
801 PhysReg = PhysRegSlot;
802 assert(PhysReg != 0);
804 } else if (PhysRegsUsed[PhysReg] == -2) {
805 // Unallocatable register dead, ignore.
810 DOUT << " Register " << RegInfo->getName(PhysReg)
811 << " [%reg" << VirtReg
812 << "] is never used, removing it frame live list\n";
813 removePhysReg(PhysReg);
814 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
815 *AliasSet; ++AliasSet) {
816 if (PhysRegsUsed[*AliasSet] != -2) {
817 DOUT << " Register " << RegInfo->getName(*AliasSet)
818 << " [%reg" << *AliasSet
819 << "] is never used, removing it frame live list\n";
820 removePhysReg(*AliasSet);
826 // Finally, if this is a noop copy instruction, zap it.
827 unsigned SrcReg, DstReg;
828 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
829 LV->removeVirtualRegistersKilled(MI);
830 LV->removeVirtualRegistersDead(MI);
835 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
837 // Spill all physical registers holding virtual registers now.
838 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
839 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
840 if (unsigned VirtReg = PhysRegsUsed[i])
841 spillVirtReg(MBB, MI, VirtReg, i);
846 /// runOnMachineFunction - Register allocate the whole function
848 bool RABigBlock::runOnMachineFunction(MachineFunction &Fn) {
849 DOUT << "Machine Function " << "\n";
851 TM = &Fn.getTarget();
852 RegInfo = TM->getRegisterInfo();
853 LV = &getAnalysis<LiveVariables>();
855 PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
857 // At various places we want to efficiently check to see whether a register
858 // is allocatable. To handle this, we mark all unallocatable registers as
859 // being pinned down, permanently.
861 BitVector Allocable = RegInfo->getAllocatableSet(Fn);
862 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
864 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
867 // initialize the virtual->physical register map to have a 'null'
868 // mapping for all virtual registers
869 Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
870 StackSlotForVirtReg.grow(MF->getSSARegMap()->getLastVirtReg());
871 VirtRegModified.resize(MF->getSSARegMap()->getLastVirtReg() - MRegisterInfo::FirstVirtualRegister + 1,0);
873 // Loop over all of the basic blocks, eliminating virtual register references
874 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
875 MBB != MBBe; ++MBB) {
876 // fill out the read timetable
877 FillVRegReadTable(*MBB);
878 // use it to allocate the BB
879 AllocateBasicBlock(*MBB);
881 VRegReadTable.clear();
884 StackSlotForVirtReg.clear();
885 PhysRegsUsed.clear();
886 VirtRegModified.clear();
887 Virt2PhysRegMap.clear();
891 FunctionPass *llvm::createBigBlockRegisterAllocator() {
892 return new RABigBlock();