Update comments.
[llvm/msp430.git] / lib / CodeGen / RegAllocBigBlock.cpp
blob91e4099d0c45761fea7ca9849b6d062d2984104b
1 //===- RegAllocBigBlock.cpp - A register allocator for large basic blocks -===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
26 // JIT context)
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/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.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/Statistic.h"
48 #include <algorithm>
49 using namespace llvm;
51 STATISTIC(NumStores, "Number of stores added");
52 STATISTIC(NumLoads , "Number of loads added");
53 STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
55 static RegisterRegAlloc
56 bigBlockRegAlloc("bigblock", "Big-block register allocator",
57 createBigBlockRegisterAllocator);
59 namespace {
60 /// VRegKeyInfo - Defines magic values required to use VirtRegs as DenseMap
61 /// keys.
62 struct VRegKeyInfo {
63 static inline unsigned getEmptyKey() { return -1U; }
64 static inline unsigned getTombstoneKey() { return -2U; }
65 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
66 static unsigned getHashValue(const unsigned &Key) { return Key; }
70 /// This register allocator is derived from RegAllocLocal.cpp. Like it, this
71 /// allocator works on one basic block at a time, oblivious to others.
72 /// However, the algorithm used here is suited for long blocks of
73 /// instructions - registers are spilled by greedily choosing those holding
74 /// values that will not be needed for the longest amount of time. This works
75 /// particularly well for blocks with 10 or more times as many instructions
76 /// as machine registers, but can be used for general code.
77 ///
78 /// TODO: - automagically invoke linearscan for (groups of) small BBs?
79 /// - break ties when picking regs? (probably not worth it in a
80 /// JIT context)
81 ///
82 class VISIBILITY_HIDDEN RABigBlock : public MachineFunctionPass {
83 public:
84 static char ID;
85 RABigBlock() : MachineFunctionPass(&ID) {}
86 private:
87 /// TM - For getting at TargetMachine info
88 ///
89 const TargetMachine *TM;
91 /// MF - Our generic MachineFunction pointer
92 ///
93 MachineFunction *MF;
95 /// RegInfo - For dealing with machine register info (aliases, folds
96 /// etc)
97 const TargetRegisterInfo *RegInfo;
99 typedef SmallVector<unsigned, 2> VRegTimes;
101 /// VRegReadTable - maps VRegs in a BB to the set of times they are read
103 DenseMap<unsigned, VRegTimes*, VRegKeyInfo> VRegReadTable;
105 /// VRegReadIdx - keeps track of the "current time" in terms of
106 /// positions in VRegReadTable
107 DenseMap<unsigned, unsigned , VRegKeyInfo> VRegReadIdx;
109 /// StackSlotForVirtReg - Maps virtual regs to the frame index where these
110 /// values are spilled.
111 IndexedMap<unsigned, VirtReg2IndexFunctor> StackSlotForVirtReg;
113 /// Virt2PhysRegMap - This map contains entries for each virtual register
114 /// that is currently available in a physical register.
115 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
117 /// PhysRegsUsed - This array is effectively a map, containing entries for
118 /// each physical register that currently has a value (ie, it is in
119 /// Virt2PhysRegMap). The value mapped to is the virtual register
120 /// corresponding to the physical register (the inverse of the
121 /// Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
122 /// because it is used by a future instruction, and to -2 if it is not
123 /// allocatable. If the entry for a physical register is -1, then the
124 /// physical register is "not in the map".
126 std::vector<int> PhysRegsUsed;
128 /// VirtRegModified - This bitset contains information about which virtual
129 /// registers need to be spilled back to memory when their registers are
130 /// scavenged. If a virtual register has simply been rematerialized, there
131 /// is no reason to spill it to memory when we need the register back.
133 std::vector<int> VirtRegModified;
135 /// MBBLastInsnTime - the number of the the last instruction in MBB
137 int MBBLastInsnTime;
139 /// MBBCurTime - the number of the the instruction being currently processed
141 int MBBCurTime;
143 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
144 return Virt2PhysRegMap[VirtReg];
147 unsigned &getVirt2StackSlot(unsigned VirtReg) {
148 return StackSlotForVirtReg[VirtReg];
151 /// markVirtRegModified - Lets us flip bits in the VirtRegModified bitset
153 void markVirtRegModified(unsigned Reg, bool Val = true) {
154 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
155 Reg -= TargetRegisterInfo::FirstVirtualRegister;
156 if (VirtRegModified.size() <= Reg)
157 VirtRegModified.resize(Reg+1);
158 VirtRegModified[Reg] = Val;
161 /// isVirtRegModified - Lets us query the VirtRegModified bitset
163 bool isVirtRegModified(unsigned Reg) const {
164 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
165 assert(Reg - TargetRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
166 && "Illegal virtual register!");
167 return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
170 public:
171 /// getPassName - returns the BigBlock allocator's name
173 virtual const char *getPassName() const {
174 return "BigBlock Register Allocator";
177 /// getAnalaysisUsage - declares the required analyses
179 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
180 AU.addRequiredID(PHIEliminationID);
181 AU.addRequiredID(TwoAddressInstructionPassID);
182 MachineFunctionPass::getAnalysisUsage(AU);
185 private:
186 /// runOnMachineFunction - Register allocate the whole function
188 bool runOnMachineFunction(MachineFunction &Fn);
190 /// AllocateBasicBlock - Register allocate the specified basic block.
192 void AllocateBasicBlock(MachineBasicBlock &MBB);
194 /// FillVRegReadTable - Fill out the table of vreg read times given a BB
196 void FillVRegReadTable(MachineBasicBlock &MBB);
198 /// areRegsEqual - This method returns true if the specified registers are
199 /// related to each other. To do this, it checks to see if they are equal
200 /// or if the first register is in the alias set of the second register.
202 bool areRegsEqual(unsigned R1, unsigned R2) const {
203 if (R1 == R2) return true;
204 for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
205 *AliasSet; ++AliasSet) {
206 if (*AliasSet == R1) return true;
208 return false;
211 /// getStackSpaceFor - This returns the frame index of the specified virtual
212 /// register on the stack, allocating space if necessary.
213 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
215 /// removePhysReg - This method marks the specified physical register as no
216 /// longer being in use.
218 void removePhysReg(unsigned PhysReg);
220 /// spillVirtReg - This method spills the value specified by PhysReg into
221 /// the virtual register slot specified by VirtReg. It then updates the RA
222 /// data structures to indicate the fact that PhysReg is now available.
224 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
225 unsigned VirtReg, unsigned PhysReg);
227 /// spillPhysReg - This method spills the specified physical register into
228 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
229 /// true, then the request is ignored if the physical register does not
230 /// contain a virtual register.
232 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
233 unsigned PhysReg, bool OnlyVirtRegs = false);
235 /// assignVirtToPhysReg - This method updates local state so that we know
236 /// that PhysReg is the proper container for VirtReg now. The physical
237 /// register must not be used for anything else when this is called.
239 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
241 /// isPhysRegAvailable - Return true if the specified physical register is
242 /// free and available for use. This also includes checking to see if
243 /// aliased registers are all free...
245 bool isPhysRegAvailable(unsigned PhysReg) const;
247 /// getFreeReg - Look to see if there is a free register available in the
248 /// specified register class. If not, return 0.
250 unsigned getFreeReg(const TargetRegisterClass *RC);
252 /// chooseReg - Pick a physical register to hold the specified
253 /// virtual register by choosing the one which will be read furthest
254 /// in the future.
256 unsigned chooseReg(MachineBasicBlock &MBB, MachineInstr *MI,
257 unsigned VirtReg);
259 /// reloadVirtReg - This method transforms the specified specified virtual
260 /// register use to refer to a physical register. This method may do this
261 /// in one of several ways: if the register is available in a physical
262 /// register already, it uses that physical register. If the value is not
263 /// in a physical register, and if there are physical registers available,
264 /// it loads it into a register. If register pressure is high, and it is
265 /// possible, it tries to fold the load of the virtual register into the
266 /// instruction itself. It avoids doing this if register pressure is low to
267 /// improve the chance that subsequent instructions can use the reloaded
268 /// value. This method returns the modified instruction.
270 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
271 unsigned OpNum);
274 char RABigBlock::ID = 0;
277 /// getStackSpaceFor - This allocates space for the specified virtual register
278 /// to be held on the stack.
279 int RABigBlock::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
280 // Find the location Reg would belong...
281 int FrameIdx = getVirt2StackSlot(VirtReg);
283 if (FrameIdx)
284 return FrameIdx - 1; // Already has space allocated?
286 // Allocate a new stack object for this spill location...
287 FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
288 RC->getAlignment());
290 // Assign the slot...
291 getVirt2StackSlot(VirtReg) = FrameIdx + 1;
292 return FrameIdx;
296 /// removePhysReg - This method marks the specified physical register as no
297 /// longer being in use.
299 void RABigBlock::removePhysReg(unsigned PhysReg) {
300 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
304 /// spillVirtReg - This method spills the value specified by PhysReg into the
305 /// virtual register slot specified by VirtReg. It then updates the RA data
306 /// structures to indicate the fact that PhysReg is now available.
308 void RABigBlock::spillVirtReg(MachineBasicBlock &MBB,
309 MachineBasicBlock::iterator I,
310 unsigned VirtReg, unsigned PhysReg) {
311 assert(VirtReg && "Spilling a physical register is illegal!"
312 " Must not have appropriate kill for the register or use exists beyond"
313 " the intended one.");
314 DOUT << " Spilling register " << RegInfo->getName(PhysReg)
315 << " containing %reg" << VirtReg;
317 const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
319 if (!isVirtRegModified(VirtReg))
320 DOUT << " which has not been modified, so no store necessary!";
322 // Otherwise, there is a virtual register corresponding to this physical
323 // register. We only need to spill it into its stack slot if it has been
324 // modified.
325 if (isVirtRegModified(VirtReg)) {
326 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
327 int FrameIndex = getStackSpaceFor(VirtReg, RC);
328 DOUT << " to stack slot #" << FrameIndex;
329 TII->storeRegToStackSlot(MBB, I, PhysReg, true, FrameIndex, RC);
330 ++NumStores; // Update statistics
333 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
335 DOUT << "\n";
336 removePhysReg(PhysReg);
340 /// spillPhysReg - This method spills the specified physical register into the
341 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
342 /// then the request is ignored if the physical register does not contain a
343 /// virtual register.
345 void RABigBlock::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
346 unsigned PhysReg, bool OnlyVirtRegs) {
347 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
348 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
349 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
350 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
351 } else {
352 // If the selected register aliases any other registers, we must make
353 // sure that one of the aliases isn't alive.
354 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
355 *AliasSet; ++AliasSet)
356 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
357 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
358 if (PhysRegsUsed[*AliasSet])
359 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
364 /// assignVirtToPhysReg - This method updates local state so that we know
365 /// that PhysReg is the proper container for VirtReg now. The physical
366 /// register must not be used for anything else when this is called.
368 void RABigBlock::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
369 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
370 // Update information to note the fact that this register was just used, and
371 // it holds VirtReg.
372 PhysRegsUsed[PhysReg] = VirtReg;
373 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
377 /// isPhysRegAvailable - Return true if the specified physical register is free
378 /// and available for use. This also includes checking to see if aliased
379 /// registers are all free...
381 bool RABigBlock::isPhysRegAvailable(unsigned PhysReg) const {
382 if (PhysRegsUsed[PhysReg] != -1) return false;
384 // If the selected register aliases any other allocated registers, it is
385 // not free!
386 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
387 *AliasSet; ++AliasSet)
388 if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
389 return false; // Can't use this reg then.
390 return true;
394 /// getFreeReg - Look to see if there is a free register available in the
395 /// specified register class. If not, return 0.
397 unsigned RABigBlock::getFreeReg(const TargetRegisterClass *RC) {
398 // Get iterators defining the range of registers that are valid to allocate in
399 // this class, which also specifies the preferred allocation order.
400 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
401 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
403 for (; RI != RE; ++RI)
404 if (isPhysRegAvailable(*RI)) { // Is reg unused?
405 assert(*RI != 0 && "Cannot use register!");
406 return *RI; // Found an unused register!
408 return 0;
412 /// chooseReg - Pick a physical register to hold the specified
413 /// virtual register by choosing the one whose value will be read
414 /// furthest in the future.
416 unsigned RABigBlock::chooseReg(MachineBasicBlock &MBB, MachineInstr *I,
417 unsigned VirtReg) {
418 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
419 // First check to see if we have a free register of the requested type...
420 unsigned PhysReg = getFreeReg(RC);
422 // If we didn't find an unused register, find the one which will be
423 // read at the most distant point in time.
424 if (PhysReg == 0) {
425 unsigned delay=0, longest_delay=0;
426 VRegTimes* ReadTimes;
428 unsigned curTime = MBBCurTime;
430 // for all physical regs in the RC,
431 for(TargetRegisterClass::iterator pReg = RC->begin();
432 pReg != RC->end(); ++pReg) {
433 // how long until they're read?
434 if(PhysRegsUsed[*pReg]>0) { // ignore non-allocatable regs
435 ReadTimes = VRegReadTable[PhysRegsUsed[*pReg]];
436 if(ReadTimes && !ReadTimes->empty()) {
437 unsigned& pt = VRegReadIdx[PhysRegsUsed[*pReg]];
438 while(pt < ReadTimes->size() && (*ReadTimes)[pt] < curTime) {
439 ++pt;
442 if(pt < ReadTimes->size())
443 delay = (*ReadTimes)[pt] - curTime;
444 else
445 delay = MBBLastInsnTime + 1 - curTime;
446 } else {
447 // This register is only defined, but never
448 // read in this MBB. Therefore the next read
449 // happens after the end of this MBB
450 delay = MBBLastInsnTime + 1 - curTime;
454 if(delay > longest_delay) {
455 longest_delay = delay;
456 PhysReg = *pReg;
461 if(PhysReg == 0) { // ok, now we're desperate. We couldn't choose
462 // a register to spill by looking through the
463 // read timetable, so now we just spill the
464 // first allocatable register we find.
466 // for all physical regs in the RC,
467 for(TargetRegisterClass::iterator pReg = RC->begin();
468 pReg != RC->end(); ++pReg) {
469 // if we find a register we can spill
470 if(PhysRegsUsed[*pReg]>=-1)
471 PhysReg = *pReg; // choose it to be spilled
475 assert(PhysReg && "couldn't choose a register to spill :( ");
476 // TODO: assert that RC->contains(PhysReg) / handle aliased registers?
478 // since we needed to look in the table we need to spill this register.
479 spillPhysReg(MBB, I, PhysReg);
482 // assign the vreg to our chosen physical register
483 assignVirtToPhysReg(VirtReg, PhysReg);
484 return PhysReg; // and return it
488 /// reloadVirtReg - This method transforms an instruction with a virtual
489 /// register use to one that references a physical register. It does this as
490 /// follows:
492 /// 1) If the register is already in a physical register, it uses it.
493 /// 2) Otherwise, if there is a free physical register, it uses that.
494 /// 3) Otherwise, it calls chooseReg() to get the physical register
495 /// holding the most distantly needed value, generating a spill in
496 /// the process.
498 /// This method returns the modified instruction.
499 MachineInstr *RABigBlock::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
500 unsigned OpNum) {
501 unsigned VirtReg = MI->getOperand(OpNum).getReg();
502 const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
504 // If the virtual register is already available in a physical register,
505 // just update the instruction and return.
506 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
507 MI->getOperand(OpNum).setReg(PR);
508 return MI;
511 // Otherwise, if we have free physical registers available to hold the
512 // value, use them.
513 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
514 unsigned PhysReg = getFreeReg(RC);
515 int FrameIndex = getStackSpaceFor(VirtReg, RC);
517 if (PhysReg) { // we have a free register, so use it.
518 assignVirtToPhysReg(VirtReg, PhysReg);
519 } else { // no free registers available.
520 // try to fold the spill into the instruction
521 SmallVector<unsigned, 1> Ops;
522 Ops.push_back(OpNum);
523 if(MachineInstr* FMI = TII->foldMemoryOperand(*MF, MI, Ops, FrameIndex)) {
524 ++NumFolded;
525 FMI->copyKillDeadInfo(MI);
526 return MBB.insert(MBB.erase(MI), FMI);
529 // determine which of the physical registers we'll kill off, since we
530 // couldn't fold.
531 PhysReg = chooseReg(MBB, MI, VirtReg);
534 // this virtual register is now unmodified (since we just reloaded it)
535 markVirtRegModified(VirtReg, false);
537 DOUT << " Reloading %reg" << VirtReg << " into "
538 << RegInfo->getName(PhysReg) << "\n";
540 // Add move instruction(s)
541 TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
542 ++NumLoads; // Update statistics
544 MF->getRegInfo().setPhysRegUsed(PhysReg);
545 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
546 return MI;
549 /// Fill out the vreg read timetable. Since ReadTime increases
550 /// monotonically, the individual readtime sets will be sorted
551 /// in ascending order.
552 void RABigBlock::FillVRegReadTable(MachineBasicBlock &MBB) {
553 // loop over each instruction
554 MachineBasicBlock::iterator MII;
555 unsigned ReadTime;
557 for(ReadTime=0, MII = MBB.begin(); MII != MBB.end(); ++ReadTime, ++MII) {
558 MachineInstr *MI = MII;
560 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
561 MachineOperand& MO = MI->getOperand(i);
562 // look for vreg reads..
563 if (MO.isReg() && !MO.isDef() && MO.getReg() &&
564 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
565 // ..and add them to the read table.
566 VRegTimes* &Times = VRegReadTable[MO.getReg()];
567 if(!VRegReadTable[MO.getReg()]) {
568 Times = new VRegTimes;
569 VRegReadIdx[MO.getReg()] = 0;
571 Times->push_back(ReadTime);
577 MBBLastInsnTime = ReadTime;
579 for(DenseMap<unsigned, VRegTimes*, VRegKeyInfo>::iterator Reads = VRegReadTable.begin();
580 Reads != VRegReadTable.end(); ++Reads) {
581 if(Reads->second) {
582 DOUT << "Reads[" << Reads->first << "]=" << Reads->second->size() << "\n";
587 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
588 /// read/mod/write register, i.e. update partial register.
589 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
590 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
591 MachineOperand& MO = MI->getOperand(i);
592 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
593 MO.isDef() && !MO.isDead())
594 return true;
596 return false;
599 /// isReadModWriteImplicitDef - True if this is an implicit def for a
600 /// read/mod/write register, i.e. update partial register.
601 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
602 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
603 MachineOperand& MO = MI->getOperand(i);
604 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
605 !MO.isDef() && MO.isKill())
606 return true;
608 return false;
612 void RABigBlock::AllocateBasicBlock(MachineBasicBlock &MBB) {
613 // loop over each instruction
614 MachineBasicBlock::iterator MII = MBB.begin();
615 const TargetInstrInfo &TII = *TM->getInstrInfo();
617 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
618 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
620 // If this is the first basic block in the machine function, add live-in
621 // registers as active.
622 if (&MBB == &*MF->begin()) {
623 for (MachineRegisterInfo::livein_iterator
624 I = MF->getRegInfo().livein_begin(),
625 E = MF->getRegInfo().livein_end(); I != E; ++I) {
626 unsigned Reg = I->first;
627 MF->getRegInfo().setPhysRegUsed(Reg);
628 PhysRegsUsed[Reg] = 0; // It is free and reserved now
629 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
630 *AliasSet; ++AliasSet) {
631 if (PhysRegsUsed[*AliasSet] != -2) {
632 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
633 MF->getRegInfo().setPhysRegUsed(*AliasSet);
639 // Otherwise, sequentially allocate each instruction in the MBB.
640 MBBCurTime = -1;
641 while (MII != MBB.end()) {
642 MachineInstr *MI = MII++;
643 MBBCurTime++;
644 const TargetInstrDesc &TID = MI->getDesc();
645 DEBUG(DOUT << "\nTime=" << MBBCurTime << " Starting RegAlloc of: " << *MI;
646 DOUT << " Regs have values: ";
647 for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
648 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
649 DOUT << "[" << RegInfo->getName(i)
650 << ",%reg" << PhysRegsUsed[i] << "] ";
651 DOUT << "\n");
653 SmallVector<unsigned, 8> Kills;
654 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
655 MachineOperand& MO = MI->getOperand(i);
656 if (MO.isReg() && MO.isKill()) {
657 if (!MO.isImplicit())
658 Kills.push_back(MO.getReg());
659 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
660 // These are extra physical register kills when a sub-register
661 // is defined (def of a sub-register is a read/mod/write of the
662 // larger registers). Ignore.
663 Kills.push_back(MO.getReg());
667 // Get the used operands into registers. This has the potential to spill
668 // incoming values if we are out of registers. Note that we completely
669 // ignore physical register uses here. We assume that if an explicit
670 // physical register is referenced by the instruction, that it is guaranteed
671 // to be live-in, or the input is badly hosed.
673 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
674 MachineOperand& MO = MI->getOperand(i);
675 // here we are looking for only used operands (never def&use)
676 if (MO.isReg() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
677 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
678 MI = reloadVirtReg(MBB, MI, i);
681 // If this instruction is the last user of this register, kill the
682 // value, freeing the register being used, so it doesn't need to be
683 // spilled to memory.
685 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
686 unsigned VirtReg = Kills[i];
687 unsigned PhysReg = VirtReg;
688 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
689 // If the virtual register was never materialized into a register, it
690 // might not be in the map, but it won't hurt to zero it out anyway.
691 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
692 PhysReg = PhysRegSlot;
693 PhysRegSlot = 0;
694 } else if (PhysRegsUsed[PhysReg] == -2) {
695 // Unallocatable register dead, ignore.
696 continue;
697 } else {
698 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
699 "Silently clearing a virtual register?");
702 if (PhysReg) {
703 DOUT << " Last use of " << RegInfo->getName(PhysReg)
704 << "[%reg" << VirtReg <<"], removing it from live set\n";
705 removePhysReg(PhysReg);
706 for (const unsigned *AliasSet = RegInfo->getSubRegisters(PhysReg);
707 *AliasSet; ++AliasSet) {
708 if (PhysRegsUsed[*AliasSet] != -2) {
709 DOUT << " Last use of "
710 << RegInfo->getName(*AliasSet)
711 << "[%reg" << VirtReg <<"], removing it from live set\n";
712 removePhysReg(*AliasSet);
718 // Loop over all of the operands of the instruction, spilling registers that
719 // are defined, and marking explicit destinations in the PhysRegsUsed map.
720 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
721 MachineOperand& MO = MI->getOperand(i);
722 if (MO.isReg() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
723 TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
724 unsigned Reg = MO.getReg();
725 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
726 // These are extra physical register defs when a sub-register
727 // is defined (def of a sub-register is a read/mod/write of the
728 // larger registers). Ignore.
729 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
731 MF->getRegInfo().setPhysRegUsed(Reg);
732 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
733 PhysRegsUsed[Reg] = 0; // It is free and reserved now
734 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
735 *AliasSet; ++AliasSet) {
736 if (PhysRegsUsed[*AliasSet] != -2) {
737 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
738 MF->getRegInfo().setPhysRegUsed(*AliasSet);
744 // Loop over the implicit defs, spilling them as well.
745 if (TID.getImplicitDefs()) {
746 for (const unsigned *ImplicitDefs = TID.getImplicitDefs();
747 *ImplicitDefs; ++ImplicitDefs) {
748 unsigned Reg = *ImplicitDefs;
749 if (PhysRegsUsed[Reg] != -2) {
750 spillPhysReg(MBB, MI, Reg, true);
751 PhysRegsUsed[Reg] = 0; // It is free and reserved now
753 MF->getRegInfo().setPhysRegUsed(Reg);
754 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
755 *AliasSet; ++AliasSet) {
756 if (PhysRegsUsed[*AliasSet] != -2) {
757 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
758 MF->getRegInfo().setPhysRegUsed(*AliasSet);
764 SmallVector<unsigned, 8> DeadDefs;
765 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
766 MachineOperand& MO = MI->getOperand(i);
767 if (MO.isReg() && MO.isDead())
768 DeadDefs.push_back(MO.getReg());
771 // Okay, we have allocated all of the source operands and spilled any values
772 // that would be destroyed by defs of this instruction. Loop over the
773 // explicit defs and assign them to a register, spilling incoming values if
774 // we need to scavenge a register.
776 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
777 MachineOperand& MO = MI->getOperand(i);
778 if (MO.isReg() && MO.isDef() && MO.getReg() &&
779 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
780 unsigned DestVirtReg = MO.getReg();
781 unsigned DestPhysReg;
783 // If DestVirtReg already has a value, use it.
784 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
785 DestPhysReg = chooseReg(MBB, MI, DestVirtReg);
786 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
787 markVirtRegModified(DestVirtReg);
788 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
792 // If this instruction defines any registers that are immediately dead,
793 // kill them now.
795 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
796 unsigned VirtReg = DeadDefs[i];
797 unsigned PhysReg = VirtReg;
798 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
799 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
800 PhysReg = PhysRegSlot;
801 assert(PhysReg != 0);
802 PhysRegSlot = 0;
803 } else if (PhysRegsUsed[PhysReg] == -2) {
804 // Unallocatable register dead, ignore.
805 continue;
808 if (PhysReg) {
809 DOUT << " Register " << RegInfo->getName(PhysReg)
810 << " [%reg" << VirtReg
811 << "] is never used, removing it from live set\n";
812 removePhysReg(PhysReg);
813 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
814 *AliasSet; ++AliasSet) {
815 if (PhysRegsUsed[*AliasSet] != -2) {
816 DOUT << " Register " << RegInfo->getName(*AliasSet)
817 << " [%reg" << *AliasSet
818 << "] is never used, removing it from live set\n";
819 removePhysReg(*AliasSet);
825 // Finally, if this is a noop copy instruction, zap it.
826 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
827 if (TII.isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
828 SrcReg == DstReg)
829 MBB.erase(MI);
832 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
834 // Spill all physical registers holding virtual registers now.
835 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
836 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
837 if (unsigned VirtReg = PhysRegsUsed[i])
838 spillVirtReg(MBB, MI, VirtReg, i);
839 else
840 removePhysReg(i);
844 /// runOnMachineFunction - Register allocate the whole function
846 bool RABigBlock::runOnMachineFunction(MachineFunction &Fn) {
847 DOUT << "Machine Function " << "\n";
848 MF = &Fn;
849 TM = &Fn.getTarget();
850 RegInfo = TM->getRegisterInfo();
852 PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
854 // At various places we want to efficiently check to see whether a register
855 // is allocatable. To handle this, we mark all unallocatable registers as
856 // being pinned down, permanently.
858 BitVector Allocable = RegInfo->getAllocatableSet(Fn);
859 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
860 if (!Allocable[i])
861 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
864 // initialize the virtual->physical register map to have a 'null'
865 // mapping for all virtual registers
866 Virt2PhysRegMap.grow(MF->getRegInfo().getLastVirtReg());
867 StackSlotForVirtReg.grow(MF->getRegInfo().getLastVirtReg());
868 VirtRegModified.resize(MF->getRegInfo().getLastVirtReg() -
869 TargetRegisterInfo::FirstVirtualRegister + 1, 0);
871 // Loop over all of the basic blocks, eliminating virtual register references
872 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
873 MBB != MBBe; ++MBB) {
874 // fill out the read timetable
875 FillVRegReadTable(*MBB);
876 // use it to allocate the BB
877 AllocateBasicBlock(*MBB);
878 // clear it
879 VRegReadTable.clear();
882 StackSlotForVirtReg.clear();
883 PhysRegsUsed.clear();
884 VirtRegModified.clear();
885 Virt2PhysRegMap.clear();
886 return true;
889 FunctionPass *llvm::createBigBlockRegisterAllocator() {
890 return new RABigBlock();