1 //===- RegAllocBigBlock.cpp - A register allocator for large basic blocks -===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This register allocator is derived from RegAllocLocal.cpp. Like it, this
11 // allocator works on one basic block at a time, oblivious to others.
12 // However, the algorithm used here is suited for long blocks of
13 // instructions - registers are spilled by greedily choosing those holding
14 // values that will not be needed for the longest amount of time. This works
15 // particularly well for blocks with 10 or more times as many instructions
16 // as machine registers, but can be used for general code.
18 //===----------------------------------------------------------------------===//
20 // TODO: - automagically invoke linearscan for (groups of) small BBs?
21 // - break ties when picking regs? (probably not worth it in a
24 //===----------------------------------------------------------------------===//
26 #define DEBUG_TYPE "regalloc"
27 #include "llvm/BasicBlock.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/SSARegMap.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/RegAllocRegistry.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/ADT/IndexedMap.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/Statistic.h"
48 STATISTIC(NumStores, "Number of stores added");
49 STATISTIC(NumLoads , "Number of loads added");
50 STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
53 static RegisterRegAlloc
54 bigBlockRegAlloc("bigblock", " Big-block register allocator",
55 createBigBlockRegisterAllocator);
58 static inline unsigned getEmptyKey() { return -1U; }
59 static inline unsigned getTombstoneKey() { return -2U; }
60 static unsigned getHashValue(const unsigned &Key) { return Key; }
63 class VISIBILITY_HIDDEN RABigBlock : public MachineFunctionPass {
66 RABigBlock() : MachineFunctionPass((intptr_t)&ID) {}
68 const TargetMachine *TM;
70 const MRegisterInfo *RegInfo;
73 // VRegReadTable - maps VRegs in a BB to the set of times they are read
74 // This is a sorted list
75 typedef SmallVector<unsigned, 2> VRegTimes;
77 DenseMap<unsigned, VRegTimes*, VRegKeyInfo> VRegReadTable;
78 DenseMap<unsigned, unsigned , VRegKeyInfo> VRegReadIdx;
80 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
81 // values are spilled.
82 //DenseMap<unsigned, int, VRegKeyInf> StackSlotForVirtReg;
83 IndexedMap<unsigned, VirtReg2IndexFunctor> StackSlotForVirtReg;
85 // Virt2PhysRegMap - This map contains entries for each virtual register
86 // that is currently available in a physical register.
87 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
89 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
90 return Virt2PhysRegMap[VirtReg];
93 unsigned &getVirt2StackSlot(unsigned VirtReg) {
94 return StackSlotForVirtReg[VirtReg];
98 // PhysRegsUsed - This array is effectively a map, containing entries for
99 // each physical register that currently has a value (ie, it is in
100 // Virt2PhysRegMap). The value mapped to is the virtual register
101 // corresponding to the physical register (the inverse of the
102 // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
103 // because it is used by a future instruction, and to -2 if it is not
104 // allocatable. If the entry for a physical register is -1, then the
105 // physical register is "not in the map".
107 std::vector<int> PhysRegsUsed;
110 // VirtRegModified - This bitset contains information about which virtual
111 // registers need to be spilled back to memory when their registers are
112 // scavenged. If a virtual register has simply been rematerialized, there
113 // is no reason to spill it to memory when we need the register back.
115 std::vector<int> VirtRegModified;
117 // MBBLastInsnTime - the number of the the last instruction in MBB
120 // MBBCurTime - the number of the the instruction being currently processed
123 void markVirtRegModified(unsigned Reg, bool Val = true) {
124 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
125 Reg -= MRegisterInfo::FirstVirtualRegister;
126 if (VirtRegModified.size() <= Reg) VirtRegModified.resize(Reg+1);
127 VirtRegModified[Reg] = Val;
130 bool isVirtRegModified(unsigned Reg) const {
131 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
132 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
133 && "Illegal virtual register!");
134 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
138 virtual const char *getPassName() const {
139 return "BigBlock Register Allocator";
142 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
143 AU.addRequired<LiveVariables>();
144 AU.addRequiredID(PHIEliminationID);
145 AU.addRequiredID(TwoAddressInstructionPassID);
146 MachineFunctionPass::getAnalysisUsage(AU);
150 /// runOnMachineFunction - Register allocate the whole function
151 bool runOnMachineFunction(MachineFunction &Fn);
153 /// AllocateBasicBlock - Register allocate the specified basic block.
154 void AllocateBasicBlock(MachineBasicBlock &MBB);
156 /// FillVRegReadTable - Fill out the table of vreg read times given a BB
157 void FillVRegReadTable(MachineBasicBlock &MBB);
159 /// areRegsEqual - This method returns true if the specified registers are
160 /// related to each other. To do this, it checks to see if they are equal
161 /// or if the first register is in the alias set of the second register.
163 bool areRegsEqual(unsigned R1, unsigned R2) const {
164 if (R1 == R2) return true;
165 for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
166 *AliasSet; ++AliasSet) {
167 if (*AliasSet == R1) return true;
172 /// getStackSpaceFor - This returns the frame index of the specified virtual
173 /// register on the stack, allocating space if necessary.
174 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
176 /// removePhysReg - This method marks the specified physical register as no
177 /// longer being in use.
179 void removePhysReg(unsigned PhysReg);
181 /// spillVirtReg - This method spills the value specified by PhysReg into
182 /// the virtual register slot specified by VirtReg. It then updates the RA
183 /// data structures to indicate the fact that PhysReg is now available.
185 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
186 unsigned VirtReg, unsigned PhysReg);
188 /// spillPhysReg - This method spills the specified physical register into
189 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
190 /// true, then the request is ignored if the physical register does not
191 /// contain a virtual register.
193 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
194 unsigned PhysReg, bool OnlyVirtRegs = false);
196 /// assignVirtToPhysReg - This method updates local state so that we know
197 /// that PhysReg is the proper container for VirtReg now. The physical
198 /// register must not be used for anything else when this is called.
200 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
202 /// liberatePhysReg - Make sure the specified physical register is available
203 /// for use. If there is currently a value in it, it is either moved out of
204 /// the way or spilled to memory.
206 void liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
209 /// isPhysRegAvailable - Return true if the specified physical register is
210 /// free and available for use. This also includes checking to see if
211 /// aliased registers are all free...
213 bool isPhysRegAvailable(unsigned PhysReg) const;
215 /// getFreeReg - Look to see if there is a free register available in the
216 /// specified register class. If not, return 0.
218 unsigned getFreeReg(const TargetRegisterClass *RC);
220 /// chooseReg - Pick a physical register to hold the specified
221 /// virtual register by choosing the one which will be read furthest
224 unsigned chooseReg(MachineBasicBlock &MBB, MachineInstr *MI,
227 /// reloadVirtReg - This method transforms the specified specified virtual
228 /// register use to refer to a physical register. This method may do this
229 /// in one of several ways: if the register is available in a physical
230 /// register already, it uses that physical register. If the value is not
231 /// in a physical register, and if there are physical registers available,
232 /// it loads it into a register. If register pressure is high, and it is
233 /// possible, it tries to fold the load of the virtual register into the
234 /// instruction itself. It avoids doing this if register pressure is low to
235 /// improve the chance that subsequent instructions can use the reloaded
236 /// value. This method returns the modified instruction.
238 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
242 char RABigBlock::ID = 0;
245 /// getStackSpaceFor - This allocates space for the specified virtual register
246 /// to be held on the stack.
247 int RABigBlock::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
248 // Find the location Reg would belong...
249 int FrameIdx = getVirt2StackSlot(VirtReg);
252 return FrameIdx - 1; // Already has space allocated?
254 // Allocate a new stack object for this spill location...
255 FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
258 // Assign the slot...
259 getVirt2StackSlot(VirtReg) = FrameIdx + 1;
264 /// removePhysReg - This method marks the specified physical register as no
265 /// longer being in use.
267 void RABigBlock::removePhysReg(unsigned PhysReg) {
268 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
272 /// spillVirtReg - This method spills the value specified by PhysReg into the
273 /// virtual register slot specified by VirtReg. It then updates the RA data
274 /// structures to indicate the fact that PhysReg is now available.
276 void RABigBlock::spillVirtReg(MachineBasicBlock &MBB,
277 MachineBasicBlock::iterator I,
278 unsigned VirtReg, unsigned PhysReg) {
279 assert(VirtReg && "Spilling a physical register is illegal!"
280 " Must not have appropriate kill for the register or use exists beyond"
281 " the intended one.");
282 DOUT << " Spilling register " << RegInfo->getName(PhysReg)
283 << " containing %reg" << VirtReg;
284 if (!isVirtRegModified(VirtReg))
285 DOUT << " which has not been modified, so no store necessary!";
287 // Otherwise, there is a virtual register corresponding to this physical
288 // register. We only need to spill it into its stack slot if it has been
290 if (isVirtRegModified(VirtReg)) {
291 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
292 int FrameIndex = getStackSpaceFor(VirtReg, RC);
293 DOUT << " to stack slot #" << FrameIndex;
294 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RC);
295 ++NumStores; // Update statistics
298 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
301 removePhysReg(PhysReg);
305 /// spillPhysReg - This method spills the specified physical register into the
306 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
307 /// then the request is ignored if the physical register does not contain a
308 /// virtual register.
310 void RABigBlock::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
311 unsigned PhysReg, bool OnlyVirtRegs) {
312 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
313 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
314 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
315 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
317 // If the selected register aliases any other registers, we must make
318 // sure that one of the aliases isn't alive.
319 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
320 *AliasSet; ++AliasSet)
321 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
322 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
323 if (PhysRegsUsed[*AliasSet] == 0) {
324 // This must have been a dead def due to something like this:
327 // No more use of %EAX, %AH, etc.
328 // %EAX isn't dead upon definition, but %AH is. However %AH isn't
329 // an operand of definition MI so it's not marked as such.
330 DOUT << " Register " << RegInfo->getName(*AliasSet)
331 << " [%reg" << *AliasSet
332 << "] is never used, removing it frame live list\n";
333 removePhysReg(*AliasSet);
335 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
340 /// assignVirtToPhysReg - This method updates local state so that we know
341 /// that PhysReg is the proper container for VirtReg now. The physical
342 /// register must not be used for anything else when this is called.
344 void RABigBlock::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
345 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
346 // Update information to note the fact that this register was just used, and
348 PhysRegsUsed[PhysReg] = VirtReg;
349 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
353 /// isPhysRegAvailable - Return true if the specified physical register is free
354 /// and available for use. This also includes checking to see if aliased
355 /// registers are all free...
357 bool RABigBlock::isPhysRegAvailable(unsigned PhysReg) const {
358 if (PhysRegsUsed[PhysReg] != -1) return false;
360 // If the selected register aliases any other allocated registers, it is
362 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
363 *AliasSet; ++AliasSet)
364 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
365 return false; // Can't use this reg then.
371 /// getFreeReg - Look to see if there is a free register available in the
372 /// specified register class. If not, return 0.
374 unsigned RABigBlock::getFreeReg(const TargetRegisterClass *RC) {
375 // Get iterators defining the range of registers that are valid to allocate in
376 // this class, which also specifies the preferred allocation order.
377 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
378 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
380 for (; RI != RE; ++RI)
381 if (isPhysRegAvailable(*RI)) { // Is reg unused?
382 assert(*RI != 0 && "Cannot use register!");
383 return *RI; // Found an unused register!
389 /// liberatePhysReg - Make sure the specified physical register is available for
390 /// use. If there is currently a value in it, it is either moved out of the way
391 /// or spilled to memory.
393 void RABigBlock::liberatePhysReg(MachineBasicBlock &MBB,
394 MachineBasicBlock::iterator &I,
396 spillPhysReg(MBB, I, PhysReg);
399 /// chooseReg - Pick a physical register to hold the specified
400 /// virtual register by choosing the one whose value will be read
401 /// furthest in the future.
403 unsigned RABigBlock::chooseReg(MachineBasicBlock &MBB, MachineInstr *I,
405 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
406 // First check to see if we have a free register of the requested type...
407 unsigned PhysReg = getFreeReg(RC);
409 // If we didn't find an unused register, find the one which will be
410 // read at the most distant point in time.
412 unsigned delay=0, longest_delay=0;
413 VRegTimes* ReadTimes;
415 unsigned curTime = MBBCurTime;
417 // for all physical regs in the RC,
418 for(TargetRegisterClass::iterator pReg = RC->begin();
419 pReg != RC->end(); ++pReg) {
420 // how long until they're read?
421 if(PhysRegsUsed[*pReg]>0) { // ignore non-allocatable regs
422 ReadTimes = VRegReadTable[PhysRegsUsed[*pReg]];
423 if(ReadTimes && !ReadTimes->empty()) {
424 unsigned& pt = VRegReadIdx[PhysRegsUsed[*pReg]];
425 while(pt < ReadTimes->size() && (*ReadTimes)[pt] < curTime) {
429 if(pt < ReadTimes->size())
430 delay = (*ReadTimes)[pt] - curTime;
432 delay = MBBLastInsnTime + 1 - curTime;
434 // This register is only defined, but never
435 // read in this MBB. Therefore the next read
436 // happens after the end of this MBB
437 delay = MBBLastInsnTime + 1 - curTime;
441 if(delay > longest_delay) {
442 longest_delay = delay;
448 assert(PhysReg && "couldn't grab a register from the table?");
449 // TODO: assert that RC->contains(PhysReg) / handle aliased registers
451 // since we needed to look in the table we need to spill this register.
452 spillPhysReg(MBB, I, PhysReg);
455 // assign the vreg to our chosen physical register
456 assignVirtToPhysReg(VirtReg, PhysReg);
457 return PhysReg; // and return it
461 /// reloadVirtReg - This method transforms an instruction with a virtual
462 /// register use to one that references a physical register. It does this as
465 /// 1) If the register is already in a physical register, it uses it.
466 /// 2) Otherwise, if there is a free physical register, it uses that.
467 /// 3) Otherwise, it calls chooseReg() to get the physical register
468 /// holding the most distantly needed value, generating a spill in
471 /// This method returns the modified instruction.
472 MachineInstr *RABigBlock::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
474 unsigned VirtReg = MI->getOperand(OpNum).getReg();
476 // If the virtual register is already available in a physical register,
477 // just update the instruction and return.
478 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
479 MI->getOperand(OpNum).setReg(PR);
483 // Otherwise, if we have free physical registers available to hold the
485 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
486 unsigned PhysReg = getFreeReg(RC);
487 int FrameIndex = getStackSpaceFor(VirtReg, RC);
489 if (PhysReg) { // we have a free register, so use it.
490 assignVirtToPhysReg(VirtReg, PhysReg);
491 } else { // no free registers available.
492 // try to fold the spill into the instruction
493 if(MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, OpNum, FrameIndex)) {
495 // Since we changed the address of MI, make sure to update live variables
496 // to know that the new instruction has the properties of the old one.
497 LV->instructionChanged(MI, FMI);
498 return MBB.insert(MBB.erase(MI), FMI);
501 // determine which of the physical registers we'll kill off, since we
503 PhysReg = chooseReg(MBB, MI, VirtReg);
506 // this virtual register is now unmodified (since we just reloaded it)
507 markVirtRegModified(VirtReg, false);
509 DOUT << " Reloading %reg" << VirtReg << " into "
510 << RegInfo->getName(PhysReg) << "\n";
512 // Add move instruction(s)
513 RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
514 ++NumLoads; // Update statistics
516 MF->setPhysRegUsed(PhysReg);
517 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
521 /// Fill out the vreg read timetable. Since ReadTime increases
522 /// monotonically, the individual readtime sets will be sorted
523 /// in ascending order.
524 void RABigBlock::FillVRegReadTable(MachineBasicBlock &MBB) {
525 // loop over each instruction
526 MachineBasicBlock::iterator MII;
529 for(ReadTime=0, MII = MBB.begin(); MII != MBB.end(); ++ReadTime, ++MII) {
530 MachineInstr *MI = MII;
532 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
533 MachineOperand& MO = MI->getOperand(i);
534 // look for vreg reads..
535 if (MO.isRegister() && !MO.isDef() && MO.getReg() &&
536 MRegisterInfo::isVirtualRegister(MO.getReg())) {
537 // ..and add them to the read table.
538 VRegTimes* &Times = VRegReadTable[MO.getReg()];
539 if(!VRegReadTable[MO.getReg()]) {
540 Times = new VRegTimes;
541 VRegReadIdx[MO.getReg()] = 0;
543 Times->push_back(ReadTime);
549 MBBLastInsnTime = ReadTime;
551 for(DenseMap<unsigned, VRegTimes*, VRegKeyInfo>::iterator Reads = VRegReadTable.begin();
552 Reads != VRegReadTable.end(); ++Reads) {
554 DOUT << "Reads[" << Reads->first << "]=" << Reads->second->size() << "\n";
560 void RABigBlock::AllocateBasicBlock(MachineBasicBlock &MBB) {
561 // loop over each instruction
562 MachineBasicBlock::iterator MII = MBB.begin();
563 const TargetInstrInfo &TII = *TM->getInstrInfo();
565 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
566 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
568 // If this is the first basic block in the machine function, add live-in
569 // registers as active.
570 if (&MBB == &*MF->begin()) {
571 for (MachineFunction::livein_iterator I = MF->livein_begin(),
572 E = MF->livein_end(); I != E; ++I) {
573 unsigned Reg = I->first;
574 MF->setPhysRegUsed(Reg);
575 PhysRegsUsed[Reg] = 0; // It is free and reserved now
576 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
577 *AliasSet; ++AliasSet) {
578 if (PhysRegsUsed[*AliasSet] != -2) {
579 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
580 MF->setPhysRegUsed(*AliasSet);
586 // Otherwise, sequentially allocate each instruction in the MBB.
588 while (MII != MBB.end()) {
589 MachineInstr *MI = MII++;
591 const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
592 DEBUG(DOUT << "\nTime=" << MBBCurTime << " Starting RegAlloc of: " << *MI;
593 DOUT << " Regs have values: ";
594 for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
595 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
596 DOUT << "[" << RegInfo->getName(i)
597 << ",%reg" << PhysRegsUsed[i] << "] ";
600 SmallVector<unsigned, 8> Kills;
601 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
602 MachineOperand& MO = MI->getOperand(i);
603 if (MO.isRegister() && MO.isKill())
604 Kills.push_back(MO.getReg());
607 // Get the used operands into registers. This has the potential to spill
608 // incoming values if we are out of registers. Note that we completely
609 // ignore physical register uses here. We assume that if an explicit
610 // physical register is referenced by the instruction, that it is guaranteed
611 // to be live-in, or the input is badly hosed.
613 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
614 MachineOperand& MO = MI->getOperand(i);
615 // here we are looking for only used operands (never def&use)
616 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
617 MRegisterInfo::isVirtualRegister(MO.getReg()))
618 MI = reloadVirtReg(MBB, MI, i);
621 // If this instruction is the last user of this register, kill the
622 // value, freeing the register being used, so it doesn't need to be
623 // spilled to memory.
625 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
626 unsigned VirtReg = Kills[i];
627 unsigned PhysReg = VirtReg;
628 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
629 // If the virtual register was never materialized into a register, it
630 // might not be in the map, but it won't hurt to zero it out anyway.
631 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
632 PhysReg = PhysRegSlot;
634 } else if (PhysRegsUsed[PhysReg] == -2) {
635 // Unallocatable register dead, ignore.
640 DOUT << " Last use of " << RegInfo->getName(PhysReg)
641 << "[%reg" << VirtReg <<"], removing it from live set\n";
642 removePhysReg(PhysReg);
643 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
644 *AliasSet; ++AliasSet) {
645 if (PhysRegsUsed[*AliasSet] != -2) {
646 DOUT << " Last use of "
647 << RegInfo->getName(*AliasSet)
648 << "[%reg" << VirtReg <<"], removing it from live set\n";
649 removePhysReg(*AliasSet);
655 // Loop over all of the operands of the instruction, spilling registers that
656 // are defined, and marking explicit destinations in the PhysRegsUsed map.
657 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
658 MachineOperand& MO = MI->getOperand(i);
659 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
660 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
661 unsigned Reg = MO.getReg();
662 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
664 MF->setPhysRegUsed(Reg);
665 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
666 PhysRegsUsed[Reg] = 0; // It is free and reserved now
667 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
668 *AliasSet; ++AliasSet) {
669 if (PhysRegsUsed[*AliasSet] != -2) {
670 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
671 MF->setPhysRegUsed(*AliasSet);
677 // Loop over the implicit defs, spilling them as well.
678 if (TID.ImplicitDefs) {
679 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
680 *ImplicitDefs; ++ImplicitDefs) {
681 unsigned Reg = *ImplicitDefs;
682 bool IsNonAllocatable = PhysRegsUsed[Reg] == -2;
683 if (!IsNonAllocatable) {
684 spillPhysReg(MBB, MI, Reg, true);
685 PhysRegsUsed[Reg] = 0; // It is free and reserved now
687 MF->setPhysRegUsed(Reg);
689 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
690 *AliasSet; ++AliasSet) {
691 if (PhysRegsUsed[*AliasSet] != -2) {
692 if (!IsNonAllocatable) {
693 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
695 MF->setPhysRegUsed(*AliasSet);
701 SmallVector<unsigned, 8> DeadDefs;
702 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
703 MachineOperand& MO = MI->getOperand(i);
704 if (MO.isRegister() && MO.isDead())
705 DeadDefs.push_back(MO.getReg());
708 // Okay, we have allocated all of the source operands and spilled any values
709 // that would be destroyed by defs of this instruction. Loop over the
710 // explicit defs and assign them to a register, spilling incoming values if
711 // we need to scavenge a register.
713 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
714 MachineOperand& MO = MI->getOperand(i);
715 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
716 MRegisterInfo::isVirtualRegister(MO.getReg())) {
717 unsigned DestVirtReg = MO.getReg();
718 unsigned DestPhysReg;
720 // If DestVirtReg already has a value, use it.
721 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
722 DestPhysReg = chooseReg(MBB, MI, DestVirtReg);
723 MF->setPhysRegUsed(DestPhysReg);
724 markVirtRegModified(DestVirtReg);
725 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
729 // If this instruction defines any registers that are immediately dead,
732 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
733 unsigned VirtReg = DeadDefs[i];
734 unsigned PhysReg = VirtReg;
735 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
736 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
737 PhysReg = PhysRegSlot;
738 assert(PhysReg != 0);
740 } else if (PhysRegsUsed[PhysReg] == -2) {
741 // Unallocatable register dead, ignore.
746 DOUT << " Register " << RegInfo->getName(PhysReg)
747 << " [%reg" << VirtReg
748 << "] is never used, removing it frame live list\n";
749 removePhysReg(PhysReg);
750 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
751 *AliasSet; ++AliasSet) {
752 if (PhysRegsUsed[*AliasSet] != -2) {
753 DOUT << " Register " << RegInfo->getName(*AliasSet)
754 << " [%reg" << *AliasSet
755 << "] is never used, removing it frame live list\n";
756 removePhysReg(*AliasSet);
762 // Finally, if this is a noop copy instruction, zap it.
763 unsigned SrcReg, DstReg;
764 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
765 LV->removeVirtualRegistersKilled(MI);
766 LV->removeVirtualRegistersDead(MI);
771 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
773 // Spill all physical registers holding virtual registers now.
774 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
775 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
776 if (unsigned VirtReg = PhysRegsUsed[i])
777 spillVirtReg(MBB, MI, VirtReg, i);
782 // This checking code is very expensive.
784 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
785 e = MF->getSSARegMap()->getLastVirtReg(); i <= e; ++i)
786 if (unsigned PR = Virt2PhysRegMap[i]) {
787 cerr << "Register still mapped: " << i << " -> " << PR << "\n";
790 assert(AllOk && "Virtual registers still in phys regs?");
793 // Clear any physical register which appear live at the end of the basic
794 // block, but which do not hold any virtual registers. e.g., the stack
798 /// runOnMachineFunction - Register allocate the whole function
800 bool RABigBlock::runOnMachineFunction(MachineFunction &Fn) {
801 DOUT << "Machine Function " << "\n";
803 TM = &Fn.getTarget();
804 RegInfo = TM->getRegisterInfo();
805 LV = &getAnalysis<LiveVariables>();
807 PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
809 // At various places we want to efficiently check to see whether a register
810 // is allocatable. To handle this, we mark all unallocatable registers as
811 // being pinned down, permanently.
813 BitVector Allocable = RegInfo->getAllocatableSet(Fn);
814 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
816 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
819 // initialize the virtual->physical register map to have a 'null'
820 // mapping for all virtual registers
821 Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
822 StackSlotForVirtReg.grow(MF->getSSARegMap()->getLastVirtReg());
823 VirtRegModified.resize(MF->getSSARegMap()->getLastVirtReg() - MRegisterInfo::FirstVirtualRegister + 1,0);
825 // Loop over all of the basic blocks, eliminating virtual register references
826 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
827 MBB != MBBe; ++MBB) {
828 // fill out the read timetable
829 FillVRegReadTable(*MBB);
830 // use it to allocate the BB
831 AllocateBasicBlock(*MBB);
833 VRegReadTable.clear();
836 StackSlotForVirtReg.clear();
837 PhysRegsUsed.clear();
838 VirtRegModified.clear();
839 Virt2PhysRegMap.clear();
843 FunctionPass *llvm::createBigBlockRegisterAllocator() {
844 return new RABigBlock();