blob: 6fa23dbfa9e20ee00f0b743ff9552379ddfead58 [file] [log] [blame]
Duraid Madinaa8c76822007-06-22 08:27:12 +00001//===- RegAllocBigBlock.cpp - A register allocator for large basic blocks -===//
2//
3// The LLVM Compiler Infrastructure
4//
Duraid Madina837a6002007-06-26 00:21:58 +00005// This file was developed by Duraid Madina and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Duraid Madinaa8c76822007-06-22 08:27:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Duraid Madina837a6002007-06-26 00:21:58 +000010// This file implements the RABigBlock class
11//
12//===----------------------------------------------------------------------===//
13
Duraid Madinaa8c76822007-06-22 08:27:12 +000014// 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.
21//
22//===----------------------------------------------------------------------===//
23//
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)
27//
28//===----------------------------------------------------------------------===//
29
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"
Duraid Madina2e0930c2007-06-25 23:46:54 +000047#include "llvm/ADT/SmallPtrSet.h"
Duraid Madinaa8c76822007-06-22 08:27:12 +000048#include "llvm/ADT/Statistic.h"
49#include <algorithm>
50using namespace llvm;
51
52STATISTIC(NumStores, "Number of stores added");
53STATISTIC(NumLoads , "Number of loads added");
54STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
55
56namespace {
57 static RegisterRegAlloc
58 bigBlockRegAlloc("bigblock", " Big-block register allocator",
59 createBigBlockRegisterAllocator);
60
Duraid Madina837a6002007-06-26 00:21:58 +000061/// VRegKeyInfo - Defines magic values required to use VirtRegs as DenseMap
62/// keys.
Duraid Madinaa8c76822007-06-22 08:27:12 +000063 struct VRegKeyInfo {
64 static inline unsigned getEmptyKey() { return -1U; }
65 static inline unsigned getTombstoneKey() { return -2U; }
66 static unsigned getHashValue(const unsigned &Key) { return Key; }
67 };
68
Duraid Madina837a6002007-06-26 00:21:58 +000069
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///
Duraid Madinaa8c76822007-06-22 08:27:12 +000082 class VISIBILITY_HIDDEN RABigBlock : public MachineFunctionPass {
83 public:
84 static char ID;
85 RABigBlock() : MachineFunctionPass((intptr_t)&ID) {}
86 private:
Duraid Madina837a6002007-06-26 00:21:58 +000087 /// TM - For getting at TargetMachine info
88 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +000089 const TargetMachine *TM;
Duraid Madina837a6002007-06-26 00:21:58 +000090
91 /// MF - Our generic MachineFunction pointer
92 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +000093 MachineFunction *MF;
Duraid Madina837a6002007-06-26 00:21:58 +000094
95 /// RegInfo - For dealing with machine register info (aliases, folds
96 /// etc)
Duraid Madinaa8c76822007-06-22 08:27:12 +000097 const MRegisterInfo *RegInfo;
Duraid Madina837a6002007-06-26 00:21:58 +000098
99 /// LV - Our generic LiveVariables pointer
100 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000101 LiveVariables *LV;
102
Duraid Madina2e0930c2007-06-25 23:46:54 +0000103 typedef SmallVector<unsigned, 2> VRegTimes;
104
Duraid Madina837a6002007-06-26 00:21:58 +0000105 /// VRegReadTable - maps VRegs in a BB to the set of times they are read
106 ///
Duraid Madina2e0930c2007-06-25 23:46:54 +0000107 DenseMap<unsigned, VRegTimes*, VRegKeyInfo> VRegReadTable;
Duraid Madina837a6002007-06-26 00:21:58 +0000108
109 /// VRegReadIdx - keeps track of the "current time" in terms of
110 /// positions in VRegReadTable
Duraid Madina2e0930c2007-06-25 23:46:54 +0000111 DenseMap<unsigned, unsigned , VRegKeyInfo> VRegReadIdx;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000112
Duraid Madina837a6002007-06-26 00:21:58 +0000113 /// StackSlotForVirtReg - Maps virtual regs to the frame index where these
114 /// values are spilled.
Duraid Madina2e0930c2007-06-25 23:46:54 +0000115 IndexedMap<unsigned, VirtReg2IndexFunctor> StackSlotForVirtReg;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000116
Duraid Madina837a6002007-06-26 00:21:58 +0000117 /// Virt2PhysRegMap - This map contains entries for each virtual register
118 /// that is currently available in a physical register.
Duraid Madinaa8c76822007-06-22 08:27:12 +0000119 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
120
Duraid Madina837a6002007-06-26 00:21:58 +0000121 /// PhysRegsUsed - This array is effectively a map, containing entries for
122 /// each physical register that currently has a value (ie, it is in
123 /// Virt2PhysRegMap). The value mapped to is the virtual register
124 /// corresponding to the physical register (the inverse of the
125 /// Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
126 /// because it is used by a future instruction, and to -2 if it is not
127 /// allocatable. If the entry for a physical register is -1, then the
128 /// physical register is "not in the map".
129 ///
130 std::vector<int> PhysRegsUsed;
131
132 /// VirtRegModified - This bitset contains information about which virtual
133 /// registers need to be spilled back to memory when their registers are
134 /// scavenged. If a virtual register has simply been rematerialized, there
135 /// is no reason to spill it to memory when we need the register back.
136 ///
137 std::vector<int> VirtRegModified;
138
139 /// MBBLastInsnTime - the number of the the last instruction in MBB
140 ///
141 int MBBLastInsnTime;
142
143 /// MBBCurTime - the number of the the instruction being currently processed
144 ///
145 int MBBCurTime;
146
Duraid Madinaa8c76822007-06-22 08:27:12 +0000147 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
148 return Virt2PhysRegMap[VirtReg];
149 }
150
Duraid Madina2e0930c2007-06-25 23:46:54 +0000151 unsigned &getVirt2StackSlot(unsigned VirtReg) {
152 return StackSlotForVirtReg[VirtReg];
153 }
154
Duraid Madina837a6002007-06-26 00:21:58 +0000155 /// markVirtRegModified - Lets us flip bits in the VirtRegModified bitset
156 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000157 void markVirtRegModified(unsigned Reg, bool Val = true) {
158 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
159 Reg -= MRegisterInfo::FirstVirtualRegister;
Duraid Madina837a6002007-06-26 00:21:58 +0000160 if (VirtRegModified.size() <= Reg)
161 VirtRegModified.resize(Reg+1);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000162 VirtRegModified[Reg] = Val;
163 }
164
Duraid Madina837a6002007-06-26 00:21:58 +0000165 /// isVirtRegModified - Lets us query the VirtRegModified bitset
166 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000167 bool isVirtRegModified(unsigned Reg) const {
168 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
169 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
170 && "Illegal virtual register!");
171 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
172 }
173
Duraid Madinaa8c76822007-06-22 08:27:12 +0000174 public:
Duraid Madina837a6002007-06-26 00:21:58 +0000175 /// getPassName - returns the BigBlock allocator's name
176 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000177 virtual const char *getPassName() const {
178 return "BigBlock Register Allocator";
179 }
180
Duraid Madina837a6002007-06-26 00:21:58 +0000181 /// getAnalaysisUsage - declares the required analyses
182 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000183 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
184 AU.addRequired<LiveVariables>();
185 AU.addRequiredID(PHIEliminationID);
186 AU.addRequiredID(TwoAddressInstructionPassID);
187 MachineFunctionPass::getAnalysisUsage(AU);
188 }
189
190 private:
191 /// runOnMachineFunction - Register allocate the whole function
Duraid Madina837a6002007-06-26 00:21:58 +0000192 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000193 bool runOnMachineFunction(MachineFunction &Fn);
194
195 /// AllocateBasicBlock - Register allocate the specified basic block.
Duraid Madina837a6002007-06-26 00:21:58 +0000196 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000197 void AllocateBasicBlock(MachineBasicBlock &MBB);
198
199 /// FillVRegReadTable - Fill out the table of vreg read times given a BB
Duraid Madina837a6002007-06-26 00:21:58 +0000200 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000201 void FillVRegReadTable(MachineBasicBlock &MBB);
202
203 /// areRegsEqual - This method returns true if the specified registers are
204 /// related to each other. To do this, it checks to see if they are equal
205 /// or if the first register is in the alias set of the second register.
206 ///
207 bool areRegsEqual(unsigned R1, unsigned R2) const {
208 if (R1 == R2) return true;
209 for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
210 *AliasSet; ++AliasSet) {
211 if (*AliasSet == R1) return true;
212 }
213 return false;
214 }
215
216 /// getStackSpaceFor - This returns the frame index of the specified virtual
217 /// register on the stack, allocating space if necessary.
218 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
219
220 /// removePhysReg - This method marks the specified physical register as no
221 /// longer being in use.
222 ///
223 void removePhysReg(unsigned PhysReg);
224
225 /// spillVirtReg - This method spills the value specified by PhysReg into
226 /// the virtual register slot specified by VirtReg. It then updates the RA
227 /// data structures to indicate the fact that PhysReg is now available.
228 ///
229 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
230 unsigned VirtReg, unsigned PhysReg);
231
232 /// spillPhysReg - This method spills the specified physical register into
233 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
234 /// true, then the request is ignored if the physical register does not
235 /// contain a virtual register.
236 ///
237 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
238 unsigned PhysReg, bool OnlyVirtRegs = false);
239
240 /// assignVirtToPhysReg - This method updates local state so that we know
241 /// that PhysReg is the proper container for VirtReg now. The physical
242 /// register must not be used for anything else when this is called.
243 ///
244 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
245
246 /// liberatePhysReg - Make sure the specified physical register is available
247 /// for use. If there is currently a value in it, it is either moved out of
248 /// the way or spilled to memory.
249 ///
250 void liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
251 unsigned PhysReg);
252
253 /// isPhysRegAvailable - Return true if the specified physical register is
254 /// free and available for use. This also includes checking to see if
255 /// aliased registers are all free...
256 ///
257 bool isPhysRegAvailable(unsigned PhysReg) const;
258
259 /// getFreeReg - Look to see if there is a free register available in the
260 /// specified register class. If not, return 0.
261 ///
262 unsigned getFreeReg(const TargetRegisterClass *RC);
263
264 /// chooseReg - Pick a physical register to hold the specified
265 /// virtual register by choosing the one which will be read furthest
266 /// in the future.
267 ///
268 unsigned chooseReg(MachineBasicBlock &MBB, MachineInstr *MI,
269 unsigned VirtReg);
270
271 /// reloadVirtReg - This method transforms the specified specified virtual
272 /// register use to refer to a physical register. This method may do this
273 /// in one of several ways: if the register is available in a physical
274 /// register already, it uses that physical register. If the value is not
275 /// in a physical register, and if there are physical registers available,
276 /// it loads it into a register. If register pressure is high, and it is
277 /// possible, it tries to fold the load of the virtual register into the
278 /// instruction itself. It avoids doing this if register pressure is low to
279 /// improve the chance that subsequent instructions can use the reloaded
280 /// value. This method returns the modified instruction.
281 ///
282 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
283 unsigned OpNum);
284
285 };
286 char RABigBlock::ID = 0;
287}
288
289/// getStackSpaceFor - This allocates space for the specified virtual register
290/// to be held on the stack.
291int RABigBlock::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
292 // Find the location Reg would belong...
Duraid Madina2e0930c2007-06-25 23:46:54 +0000293 int FrameIdx = getVirt2StackSlot(VirtReg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000294
Duraid Madina2e0930c2007-06-25 23:46:54 +0000295 if (FrameIdx)
296 return FrameIdx - 1; // Already has space allocated?
Duraid Madinaa8c76822007-06-22 08:27:12 +0000297
298 // Allocate a new stack object for this spill location...
Duraid Madina2e0930c2007-06-25 23:46:54 +0000299 FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
Duraid Madinaa8c76822007-06-22 08:27:12 +0000300 RC->getAlignment());
301
302 // Assign the slot...
Duraid Madina2e0930c2007-06-25 23:46:54 +0000303 getVirt2StackSlot(VirtReg) = FrameIdx + 1;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000304 return FrameIdx;
305}
306
307
308/// removePhysReg - This method marks the specified physical register as no
309/// longer being in use.
310///
311void RABigBlock::removePhysReg(unsigned PhysReg) {
312 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
Duraid Madinaa8c76822007-06-22 08:27:12 +0000313}
314
315
316/// spillVirtReg - This method spills the value specified by PhysReg into the
317/// virtual register slot specified by VirtReg. It then updates the RA data
318/// structures to indicate the fact that PhysReg is now available.
319///
320void RABigBlock::spillVirtReg(MachineBasicBlock &MBB,
321 MachineBasicBlock::iterator I,
322 unsigned VirtReg, unsigned PhysReg) {
323 assert(VirtReg && "Spilling a physical register is illegal!"
324 " Must not have appropriate kill for the register or use exists beyond"
325 " the intended one.");
326 DOUT << " Spilling register " << RegInfo->getName(PhysReg)
327 << " containing %reg" << VirtReg;
328 if (!isVirtRegModified(VirtReg))
329 DOUT << " which has not been modified, so no store necessary!";
330
331 // Otherwise, there is a virtual register corresponding to this physical
332 // register. We only need to spill it into its stack slot if it has been
333 // modified.
334 if (isVirtRegModified(VirtReg)) {
335 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
336 int FrameIndex = getStackSpaceFor(VirtReg, RC);
337 DOUT << " to stack slot #" << FrameIndex;
338 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RC);
339 ++NumStores; // Update statistics
340 }
341
342 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
343
344 DOUT << "\n";
345 removePhysReg(PhysReg);
346}
347
348
349/// spillPhysReg - This method spills the specified physical register into the
350/// virtual register slot associated with it. If OnlyVirtRegs is set to true,
351/// then the request is ignored if the physical register does not contain a
352/// virtual register.
353///
354void RABigBlock::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
355 unsigned PhysReg, bool OnlyVirtRegs) {
356 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
357 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
358 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
359 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
360 } else {
361 // If the selected register aliases any other registers, we must make
362 // sure that one of the aliases isn't alive.
363 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
364 *AliasSet; ++AliasSet)
365 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
366 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
367 if (PhysRegsUsed[*AliasSet] == 0) {
368 // This must have been a dead def due to something like this:
369 // %EAX :=
370 // := op %AL
371 // No more use of %EAX, %AH, etc.
372 // %EAX isn't dead upon definition, but %AH is. However %AH isn't
373 // an operand of definition MI so it's not marked as such.
374 DOUT << " Register " << RegInfo->getName(*AliasSet)
375 << " [%reg" << *AliasSet
376 << "] is never used, removing it frame live list\n";
377 removePhysReg(*AliasSet);
378 } else
379 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
380 }
381}
382
383
384/// assignVirtToPhysReg - This method updates local state so that we know
385/// that PhysReg is the proper container for VirtReg now. The physical
386/// register must not be used for anything else when this is called.
387///
388void RABigBlock::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
389 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
390 // Update information to note the fact that this register was just used, and
391 // it holds VirtReg.
392 PhysRegsUsed[PhysReg] = VirtReg;
393 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000394}
395
396
397/// isPhysRegAvailable - Return true if the specified physical register is free
398/// and available for use. This also includes checking to see if aliased
399/// registers are all free...
400///
401bool RABigBlock::isPhysRegAvailable(unsigned PhysReg) const {
402 if (PhysRegsUsed[PhysReg] != -1) return false;
403
404 // If the selected register aliases any other allocated registers, it is
405 // not free!
406 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
407 *AliasSet; ++AliasSet)
408 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
409 return false; // Can't use this reg then.
410 return true;
411}
412
Duraid Madina837a6002007-06-26 00:21:58 +0000413
Duraid Madinaa8c76822007-06-22 08:27:12 +0000414/// getFreeReg - Look to see if there is a free register available in the
415/// specified register class. If not, return 0.
416///
417unsigned RABigBlock::getFreeReg(const TargetRegisterClass *RC) {
418 // Get iterators defining the range of registers that are valid to allocate in
419 // this class, which also specifies the preferred allocation order.
420 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
421 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
422
423 for (; RI != RE; ++RI)
424 if (isPhysRegAvailable(*RI)) { // Is reg unused?
425 assert(*RI != 0 && "Cannot use register!");
426 return *RI; // Found an unused register!
427 }
428 return 0;
429}
430
431
432/// liberatePhysReg - Make sure the specified physical register is available for
433/// use. If there is currently a value in it, it is either moved out of the way
434/// or spilled to memory.
435///
436void RABigBlock::liberatePhysReg(MachineBasicBlock &MBB,
437 MachineBasicBlock::iterator &I,
438 unsigned PhysReg) {
439 spillPhysReg(MBB, I, PhysReg);
440}
441
442/// chooseReg - Pick a physical register to hold the specified
443/// virtual register by choosing the one whose value will be read
444/// furthest in the future.
445///
446unsigned RABigBlock::chooseReg(MachineBasicBlock &MBB, MachineInstr *I,
447 unsigned VirtReg) {
448 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
449 // First check to see if we have a free register of the requested type...
450 unsigned PhysReg = getFreeReg(RC);
451
452 // If we didn't find an unused register, find the one which will be
453 // read at the most distant point in time.
454 if (PhysReg == 0) {
455 unsigned delay=0, longest_delay=0;
Duraid Madina2e0930c2007-06-25 23:46:54 +0000456 VRegTimes* ReadTimes;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000457
Duraid Madina2e0930c2007-06-25 23:46:54 +0000458 unsigned curTime = MBBCurTime;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000459
460 // for all physical regs in the RC,
461 for(TargetRegisterClass::iterator pReg = RC->begin();
462 pReg != RC->end(); ++pReg) {
463 // how long until they're read?
464 if(PhysRegsUsed[*pReg]>0) { // ignore non-allocatable regs
465 ReadTimes = VRegReadTable[PhysRegsUsed[*pReg]];
Duraid Madina2e0930c2007-06-25 23:46:54 +0000466 if(ReadTimes && !ReadTimes->empty()) {
467 unsigned& pt = VRegReadIdx[PhysRegsUsed[*pReg]];
468 while(pt < ReadTimes->size() && (*ReadTimes)[pt] < curTime) {
469 ++pt;
470 }
471
472 if(pt < ReadTimes->size())
473 delay = (*ReadTimes)[pt] - curTime;
474 else
475 delay = MBBLastInsnTime + 1 - curTime;
476 } else {
477 // This register is only defined, but never
478 // read in this MBB. Therefore the next read
479 // happens after the end of this MBB
480 delay = MBBLastInsnTime + 1 - curTime;
481 }
482
Duraid Madinaa8c76822007-06-22 08:27:12 +0000483
484 if(delay > longest_delay) {
485 longest_delay = delay;
486 PhysReg = *pReg;
487 }
488 }
489 }
490
491 assert(PhysReg && "couldn't grab a register from the table?");
492 // TODO: assert that RC->contains(PhysReg) / handle aliased registers
493
494 // since we needed to look in the table we need to spill this register.
495 spillPhysReg(MBB, I, PhysReg);
496 }
497
498 // assign the vreg to our chosen physical register
499 assignVirtToPhysReg(VirtReg, PhysReg);
500 return PhysReg; // and return it
501}
502
503
504/// reloadVirtReg - This method transforms an instruction with a virtual
505/// register use to one that references a physical register. It does this as
506/// follows:
507///
508/// 1) If the register is already in a physical register, it uses it.
509/// 2) Otherwise, if there is a free physical register, it uses that.
510/// 3) Otherwise, it calls chooseReg() to get the physical register
511/// holding the most distantly needed value, generating a spill in
512/// the process.
513///
514/// This method returns the modified instruction.
515MachineInstr *RABigBlock::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
516 unsigned OpNum) {
517 unsigned VirtReg = MI->getOperand(OpNum).getReg();
518
519 // If the virtual register is already available in a physical register,
520 // just update the instruction and return.
521 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
522 MI->getOperand(OpNum).setReg(PR);
523 return MI;
524 }
525
526 // Otherwise, if we have free physical registers available to hold the
527 // value, use them.
528 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
529 unsigned PhysReg = getFreeReg(RC);
530 int FrameIndex = getStackSpaceFor(VirtReg, RC);
531
532 if (PhysReg) { // we have a free register, so use it.
533 assignVirtToPhysReg(VirtReg, PhysReg);
534 } else { // no free registers available.
535 // try to fold the spill into the instruction
536 if(MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, OpNum, FrameIndex)) {
537 ++NumFolded;
538 // Since we changed the address of MI, make sure to update live variables
539 // to know that the new instruction has the properties of the old one.
540 LV->instructionChanged(MI, FMI);
541 return MBB.insert(MBB.erase(MI), FMI);
542 }
543
544 // determine which of the physical registers we'll kill off, since we
545 // couldn't fold.
546 PhysReg = chooseReg(MBB, MI, VirtReg);
547 }
548
549 // this virtual register is now unmodified (since we just reloaded it)
550 markVirtRegModified(VirtReg, false);
551
552 DOUT << " Reloading %reg" << VirtReg << " into "
553 << RegInfo->getName(PhysReg) << "\n";
554
555 // Add move instruction(s)
556 RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
557 ++NumLoads; // Update statistics
558
559 MF->setPhysRegUsed(PhysReg);
560 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
561 return MI;
562}
563
564/// Fill out the vreg read timetable. Since ReadTime increases
565/// monotonically, the individual readtime sets will be sorted
566/// in ascending order.
567void RABigBlock::FillVRegReadTable(MachineBasicBlock &MBB) {
568 // loop over each instruction
569 MachineBasicBlock::iterator MII;
570 unsigned ReadTime;
571
572 for(ReadTime=0, MII = MBB.begin(); MII != MBB.end(); ++ReadTime, ++MII) {
573 MachineInstr *MI = MII;
574
Duraid Madinaa8c76822007-06-22 08:27:12 +0000575 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
576 MachineOperand& MO = MI->getOperand(i);
577 // look for vreg reads..
578 if (MO.isRegister() && !MO.isDef() && MO.getReg() &&
579 MRegisterInfo::isVirtualRegister(MO.getReg())) {
Duraid Madina2e0930c2007-06-25 23:46:54 +0000580 // ..and add them to the read table.
581 VRegTimes* &Times = VRegReadTable[MO.getReg()];
582 if(!VRegReadTable[MO.getReg()]) {
583 Times = new VRegTimes;
584 VRegReadIdx[MO.getReg()] = 0;
585 }
586 Times->push_back(ReadTime);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000587 }
588 }
589
590 }
591
Duraid Madina2e0930c2007-06-25 23:46:54 +0000592 MBBLastInsnTime = ReadTime;
593
594 for(DenseMap<unsigned, VRegTimes*, VRegKeyInfo>::iterator Reads = VRegReadTable.begin();
595 Reads != VRegReadTable.end(); ++Reads) {
596 if(Reads->second) {
597 DOUT << "Reads[" << Reads->first << "]=" << Reads->second->size() << "\n";
598 }
599 }
Duraid Madinaa8c76822007-06-22 08:27:12 +0000600}
601
Duraid Madina2e0930c2007-06-25 23:46:54 +0000602
Duraid Madinaa8c76822007-06-22 08:27:12 +0000603void RABigBlock::AllocateBasicBlock(MachineBasicBlock &MBB) {
604 // loop over each instruction
605 MachineBasicBlock::iterator MII = MBB.begin();
606 const TargetInstrInfo &TII = *TM->getInstrInfo();
607
608 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
609 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
610
611 // If this is the first basic block in the machine function, add live-in
612 // registers as active.
613 if (&MBB == &*MF->begin()) {
614 for (MachineFunction::livein_iterator I = MF->livein_begin(),
615 E = MF->livein_end(); I != E; ++I) {
616 unsigned Reg = I->first;
617 MF->setPhysRegUsed(Reg);
618 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Duraid Madinaa8c76822007-06-22 08:27:12 +0000619 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
620 *AliasSet; ++AliasSet) {
621 if (PhysRegsUsed[*AliasSet] != -2) {
Duraid Madinaa8c76822007-06-22 08:27:12 +0000622 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
623 MF->setPhysRegUsed(*AliasSet);
624 }
625 }
626 }
627 }
628
629 // Otherwise, sequentially allocate each instruction in the MBB.
Duraid Madina2e0930c2007-06-25 23:46:54 +0000630 MBBCurTime = -1;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000631 while (MII != MBB.end()) {
632 MachineInstr *MI = MII++;
Duraid Madina2e0930c2007-06-25 23:46:54 +0000633 MBBCurTime++;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000634 const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
Duraid Madina2e0930c2007-06-25 23:46:54 +0000635 DEBUG(DOUT << "\nTime=" << MBBCurTime << " Starting RegAlloc of: " << *MI;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000636 DOUT << " Regs have values: ";
637 for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
638 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
639 DOUT << "[" << RegInfo->getName(i)
640 << ",%reg" << PhysRegsUsed[i] << "] ";
641 DOUT << "\n");
642
Duraid Madinaa8c76822007-06-22 08:27:12 +0000643 SmallVector<unsigned, 8> Kills;
644 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
645 MachineOperand& MO = MI->getOperand(i);
646 if (MO.isRegister() && MO.isKill())
647 Kills.push_back(MO.getReg());
648 }
649
650 // Get the used operands into registers. This has the potential to spill
651 // incoming values if we are out of registers. Note that we completely
652 // ignore physical register uses here. We assume that if an explicit
653 // physical register is referenced by the instruction, that it is guaranteed
654 // to be live-in, or the input is badly hosed.
655 //
656 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
657 MachineOperand& MO = MI->getOperand(i);
658 // here we are looking for only used operands (never def&use)
659 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
660 MRegisterInfo::isVirtualRegister(MO.getReg()))
661 MI = reloadVirtReg(MBB, MI, i);
662 }
663
664 // If this instruction is the last user of this register, kill the
665 // value, freeing the register being used, so it doesn't need to be
666 // spilled to memory.
667 //
668 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
669 unsigned VirtReg = Kills[i];
670 unsigned PhysReg = VirtReg;
671 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
672 // If the virtual register was never materialized into a register, it
673 // might not be in the map, but it won't hurt to zero it out anyway.
674 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
675 PhysReg = PhysRegSlot;
676 PhysRegSlot = 0;
677 } else if (PhysRegsUsed[PhysReg] == -2) {
678 // Unallocatable register dead, ignore.
679 continue;
680 }
681
682 if (PhysReg) {
683 DOUT << " Last use of " << RegInfo->getName(PhysReg)
684 << "[%reg" << VirtReg <<"], removing it from live set\n";
685 removePhysReg(PhysReg);
686 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
687 *AliasSet; ++AliasSet) {
688 if (PhysRegsUsed[*AliasSet] != -2) {
689 DOUT << " Last use of "
690 << RegInfo->getName(*AliasSet)
691 << "[%reg" << VirtReg <<"], removing it from live set\n";
692 removePhysReg(*AliasSet);
693 }
694 }
695 }
696 }
697
698 // Loop over all of the operands of the instruction, spilling registers that
699 // are defined, and marking explicit destinations in the PhysRegsUsed map.
700 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
701 MachineOperand& MO = MI->getOperand(i);
702 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
703 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
704 unsigned Reg = MO.getReg();
705 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
706
707 MF->setPhysRegUsed(Reg);
708 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
709 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Duraid Madinaa8c76822007-06-22 08:27:12 +0000710 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
711 *AliasSet; ++AliasSet) {
712 if (PhysRegsUsed[*AliasSet] != -2) {
Duraid Madinaa8c76822007-06-22 08:27:12 +0000713 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
714 MF->setPhysRegUsed(*AliasSet);
715 }
716 }
717 }
718 }
719
720 // Loop over the implicit defs, spilling them as well.
721 if (TID.ImplicitDefs) {
722 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
723 *ImplicitDefs; ++ImplicitDefs) {
724 unsigned Reg = *ImplicitDefs;
725 bool IsNonAllocatable = PhysRegsUsed[Reg] == -2;
726 if (!IsNonAllocatable) {
727 spillPhysReg(MBB, MI, Reg, true);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000728 PhysRegsUsed[Reg] = 0; // It is free and reserved now
729 }
730 MF->setPhysRegUsed(Reg);
731
732 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
733 *AliasSet; ++AliasSet) {
734 if (PhysRegsUsed[*AliasSet] != -2) {
735 if (!IsNonAllocatable) {
Duraid Madinaa8c76822007-06-22 08:27:12 +0000736 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
737 }
738 MF->setPhysRegUsed(*AliasSet);
739 }
740 }
741 }
742 }
743
744 SmallVector<unsigned, 8> DeadDefs;
745 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
746 MachineOperand& MO = MI->getOperand(i);
747 if (MO.isRegister() && MO.isDead())
748 DeadDefs.push_back(MO.getReg());
749 }
750
751 // Okay, we have allocated all of the source operands and spilled any values
752 // that would be destroyed by defs of this instruction. Loop over the
753 // explicit defs and assign them to a register, spilling incoming values if
754 // we need to scavenge a register.
755 //
756 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
757 MachineOperand& MO = MI->getOperand(i);
758 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
759 MRegisterInfo::isVirtualRegister(MO.getReg())) {
760 unsigned DestVirtReg = MO.getReg();
761 unsigned DestPhysReg;
762
763 // If DestVirtReg already has a value, use it.
764 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
765 DestPhysReg = chooseReg(MBB, MI, DestVirtReg);
766 MF->setPhysRegUsed(DestPhysReg);
767 markVirtRegModified(DestVirtReg);
768 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
769 }
770 }
771
772 // If this instruction defines any registers that are immediately dead,
773 // kill them now.
774 //
775 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
776 unsigned VirtReg = DeadDefs[i];
777 unsigned PhysReg = VirtReg;
778 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
779 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
780 PhysReg = PhysRegSlot;
781 assert(PhysReg != 0);
782 PhysRegSlot = 0;
783 } else if (PhysRegsUsed[PhysReg] == -2) {
784 // Unallocatable register dead, ignore.
785 continue;
786 }
787
788 if (PhysReg) {
789 DOUT << " Register " << RegInfo->getName(PhysReg)
790 << " [%reg" << VirtReg
791 << "] is never used, removing it frame live list\n";
792 removePhysReg(PhysReg);
793 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
794 *AliasSet; ++AliasSet) {
795 if (PhysRegsUsed[*AliasSet] != -2) {
796 DOUT << " Register " << RegInfo->getName(*AliasSet)
797 << " [%reg" << *AliasSet
798 << "] is never used, removing it frame live list\n";
799 removePhysReg(*AliasSet);
800 }
801 }
802 }
803 }
804
805 // Finally, if this is a noop copy instruction, zap it.
806 unsigned SrcReg, DstReg;
807 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
808 LV->removeVirtualRegistersKilled(MI);
809 LV->removeVirtualRegistersDead(MI);
810 MBB.erase(MI);
811 }
812 }
813
814 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
815
816 // Spill all physical registers holding virtual registers now.
817 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
818 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
819 if (unsigned VirtReg = PhysRegsUsed[i])
820 spillVirtReg(MBB, MI, VirtReg, i);
821 else
822 removePhysReg(i);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000823}
824
825/// runOnMachineFunction - Register allocate the whole function
826///
827bool RABigBlock::runOnMachineFunction(MachineFunction &Fn) {
828 DOUT << "Machine Function " << "\n";
829 MF = &Fn;
830 TM = &Fn.getTarget();
831 RegInfo = TM->getRegisterInfo();
832 LV = &getAnalysis<LiveVariables>();
833
834 PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
835
836 // At various places we want to efficiently check to see whether a register
837 // is allocatable. To handle this, we mark all unallocatable registers as
838 // being pinned down, permanently.
839 {
840 BitVector Allocable = RegInfo->getAllocatableSet(Fn);
841 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
842 if (!Allocable[i])
843 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
844 }
845
846 // initialize the virtual->physical register map to have a 'null'
847 // mapping for all virtual registers
848 Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
Duraid Madina2e0930c2007-06-25 23:46:54 +0000849 StackSlotForVirtReg.grow(MF->getSSARegMap()->getLastVirtReg());
850 VirtRegModified.resize(MF->getSSARegMap()->getLastVirtReg() - MRegisterInfo::FirstVirtualRegister + 1,0);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000851
852 // Loop over all of the basic blocks, eliminating virtual register references
853 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
854 MBB != MBBe; ++MBB) {
855 // fill out the read timetable
856 FillVRegReadTable(*MBB);
857 // use it to allocate the BB
858 AllocateBasicBlock(*MBB);
859 // clear it
860 VRegReadTable.clear();
861 }
862
863 StackSlotForVirtReg.clear();
864 PhysRegsUsed.clear();
865 VirtRegModified.clear();
866 Virt2PhysRegMap.clear();
867 return true;
868}
869
870FunctionPass *llvm::createBigBlockRegisterAllocator() {
871 return new RABigBlock();
872}
Duraid Madina837a6002007-06-26 00:21:58 +0000873