blob: 400d72ae51467d5a33dd74c3acf3304f3e388018 [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
Duraid Madinaa8c76822007-06-22 08:27:12 +0000246 /// isPhysRegAvailable - Return true if the specified physical register is
247 /// free and available for use. This also includes checking to see if
248 /// aliased registers are all free...
249 ///
250 bool isPhysRegAvailable(unsigned PhysReg) const;
251
252 /// getFreeReg - Look to see if there is a free register available in the
253 /// specified register class. If not, return 0.
254 ///
255 unsigned getFreeReg(const TargetRegisterClass *RC);
256
257 /// chooseReg - Pick a physical register to hold the specified
258 /// virtual register by choosing the one which will be read furthest
259 /// in the future.
260 ///
261 unsigned chooseReg(MachineBasicBlock &MBB, MachineInstr *MI,
262 unsigned VirtReg);
263
264 /// reloadVirtReg - This method transforms the specified specified virtual
265 /// register use to refer to a physical register. This method may do this
266 /// in one of several ways: if the register is available in a physical
267 /// register already, it uses that physical register. If the value is not
268 /// in a physical register, and if there are physical registers available,
269 /// it loads it into a register. If register pressure is high, and it is
270 /// possible, it tries to fold the load of the virtual register into the
271 /// instruction itself. It avoids doing this if register pressure is low to
272 /// improve the chance that subsequent instructions can use the reloaded
273 /// value. This method returns the modified instruction.
274 ///
275 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
276 unsigned OpNum);
277
278 };
279 char RABigBlock::ID = 0;
280}
281
282/// getStackSpaceFor - This allocates space for the specified virtual register
283/// to be held on the stack.
284int RABigBlock::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
285 // Find the location Reg would belong...
Duraid Madina2e0930c2007-06-25 23:46:54 +0000286 int FrameIdx = getVirt2StackSlot(VirtReg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000287
Duraid Madina2e0930c2007-06-25 23:46:54 +0000288 if (FrameIdx)
289 return FrameIdx - 1; // Already has space allocated?
Duraid Madinaa8c76822007-06-22 08:27:12 +0000290
291 // Allocate a new stack object for this spill location...
Duraid Madina2e0930c2007-06-25 23:46:54 +0000292 FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
Duraid Madinaa8c76822007-06-22 08:27:12 +0000293 RC->getAlignment());
294
295 // Assign the slot...
Duraid Madina2e0930c2007-06-25 23:46:54 +0000296 getVirt2StackSlot(VirtReg) = FrameIdx + 1;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000297 return FrameIdx;
298}
299
300
301/// removePhysReg - This method marks the specified physical register as no
302/// longer being in use.
303///
304void RABigBlock::removePhysReg(unsigned PhysReg) {
305 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
Duraid Madinaa8c76822007-06-22 08:27:12 +0000306}
307
308
309/// spillVirtReg - This method spills the value specified by PhysReg into the
310/// virtual register slot specified by VirtReg. It then updates the RA data
311/// structures to indicate the fact that PhysReg is now available.
312///
313void RABigBlock::spillVirtReg(MachineBasicBlock &MBB,
314 MachineBasicBlock::iterator I,
315 unsigned VirtReg, unsigned PhysReg) {
316 assert(VirtReg && "Spilling a physical register is illegal!"
317 " Must not have appropriate kill for the register or use exists beyond"
318 " the intended one.");
319 DOUT << " Spilling register " << RegInfo->getName(PhysReg)
320 << " containing %reg" << VirtReg;
321 if (!isVirtRegModified(VirtReg))
322 DOUT << " which has not been modified, so no store necessary!";
323
324 // Otherwise, there is a virtual register corresponding to this physical
325 // register. We only need to spill it into its stack slot if it has been
326 // modified.
327 if (isVirtRegModified(VirtReg)) {
328 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
329 int FrameIndex = getStackSpaceFor(VirtReg, RC);
330 DOUT << " to stack slot #" << FrameIndex;
331 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RC);
332 ++NumStores; // Update statistics
333 }
334
335 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
336
337 DOUT << "\n";
338 removePhysReg(PhysReg);
339}
340
341
342/// spillPhysReg - This method spills the specified physical register into the
343/// virtual register slot associated with it. If OnlyVirtRegs is set to true,
344/// then the request is ignored if the physical register does not contain a
345/// virtual register.
346///
347void RABigBlock::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
348 unsigned PhysReg, bool OnlyVirtRegs) {
349 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
350 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
351 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
352 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
353 } else {
354 // If the selected register aliases any other registers, we must make
355 // sure that one of the aliases isn't alive.
356 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
357 *AliasSet; ++AliasSet)
358 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
359 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
Duraid Madinab2efabd2007-06-27 08:31:07 +0000360 if (PhysRegsUsed[*AliasSet])
Duraid Madinaa8c76822007-06-22 08:27:12 +0000361 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
362 }
363}
364
365
366/// assignVirtToPhysReg - This method updates local state so that we know
367/// that PhysReg is the proper container for VirtReg now. The physical
368/// register must not be used for anything else when this is called.
369///
370void RABigBlock::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
371 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
372 // Update information to note the fact that this register was just used, and
373 // it holds VirtReg.
374 PhysRegsUsed[PhysReg] = VirtReg;
375 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000376}
377
378
379/// isPhysRegAvailable - Return true if the specified physical register is free
380/// and available for use. This also includes checking to see if aliased
381/// registers are all free...
382///
383bool RABigBlock::isPhysRegAvailable(unsigned PhysReg) const {
384 if (PhysRegsUsed[PhysReg] != -1) return false;
385
386 // If the selected register aliases any other allocated registers, it is
387 // not free!
388 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
389 *AliasSet; ++AliasSet)
390 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
391 return false; // Can't use this reg then.
392 return true;
393}
394
Duraid Madina837a6002007-06-26 00:21:58 +0000395
Duraid Madinaa8c76822007-06-22 08:27:12 +0000396/// getFreeReg - Look to see if there is a free register available in the
397/// specified register class. If not, return 0.
398///
399unsigned RABigBlock::getFreeReg(const TargetRegisterClass *RC) {
400 // Get iterators defining the range of registers that are valid to allocate in
401 // this class, which also specifies the preferred allocation order.
402 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
403 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
404
405 for (; RI != RE; ++RI)
406 if (isPhysRegAvailable(*RI)) { // Is reg unused?
407 assert(*RI != 0 && "Cannot use register!");
408 return *RI; // Found an unused register!
409 }
410 return 0;
411}
412
413
Duraid Madinaa8c76822007-06-22 08:27:12 +0000414/// chooseReg - Pick a physical register to hold the specified
415/// virtual register by choosing the one whose value will be read
416/// furthest in the future.
417///
418unsigned RABigBlock::chooseReg(MachineBasicBlock &MBB, MachineInstr *I,
419 unsigned VirtReg) {
420 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
421 // First check to see if we have a free register of the requested type...
422 unsigned PhysReg = getFreeReg(RC);
423
424 // If we didn't find an unused register, find the one which will be
425 // read at the most distant point in time.
426 if (PhysReg == 0) {
427 unsigned delay=0, longest_delay=0;
Duraid Madina2e0930c2007-06-25 23:46:54 +0000428 VRegTimes* ReadTimes;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000429
Duraid Madina2e0930c2007-06-25 23:46:54 +0000430 unsigned curTime = MBBCurTime;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000431
432 // for all physical regs in the RC,
433 for(TargetRegisterClass::iterator pReg = RC->begin();
434 pReg != RC->end(); ++pReg) {
435 // how long until they're read?
436 if(PhysRegsUsed[*pReg]>0) { // ignore non-allocatable regs
437 ReadTimes = VRegReadTable[PhysRegsUsed[*pReg]];
Duraid Madina2e0930c2007-06-25 23:46:54 +0000438 if(ReadTimes && !ReadTimes->empty()) {
439 unsigned& pt = VRegReadIdx[PhysRegsUsed[*pReg]];
440 while(pt < ReadTimes->size() && (*ReadTimes)[pt] < curTime) {
441 ++pt;
442 }
443
444 if(pt < ReadTimes->size())
445 delay = (*ReadTimes)[pt] - curTime;
446 else
447 delay = MBBLastInsnTime + 1 - curTime;
448 } else {
449 // This register is only defined, but never
450 // read in this MBB. Therefore the next read
451 // happens after the end of this MBB
452 delay = MBBLastInsnTime + 1 - curTime;
453 }
454
Duraid Madinaa8c76822007-06-22 08:27:12 +0000455
456 if(delay > longest_delay) {
457 longest_delay = delay;
458 PhysReg = *pReg;
459 }
460 }
461 }
Duraid Madina4e378c62007-06-27 08:11:59 +0000462
463 assert(PhysReg && "couldn't grab a register from the table?");
Duraid Madinaa8c76822007-06-22 08:27:12 +0000464 // TODO: assert that RC->contains(PhysReg) / handle aliased registers
465
466 // since we needed to look in the table we need to spill this register.
467 spillPhysReg(MBB, I, PhysReg);
468 }
469
470 // assign the vreg to our chosen physical register
471 assignVirtToPhysReg(VirtReg, PhysReg);
472 return PhysReg; // and return it
473}
474
475
476/// reloadVirtReg - This method transforms an instruction with a virtual
477/// register use to one that references a physical register. It does this as
478/// follows:
479///
480/// 1) If the register is already in a physical register, it uses it.
481/// 2) Otherwise, if there is a free physical register, it uses that.
482/// 3) Otherwise, it calls chooseReg() to get the physical register
483/// holding the most distantly needed value, generating a spill in
484/// the process.
485///
486/// This method returns the modified instruction.
487MachineInstr *RABigBlock::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
488 unsigned OpNum) {
489 unsigned VirtReg = MI->getOperand(OpNum).getReg();
490
491 // If the virtual register is already available in a physical register,
492 // just update the instruction and return.
493 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
494 MI->getOperand(OpNum).setReg(PR);
495 return MI;
496 }
497
498 // Otherwise, if we have free physical registers available to hold the
499 // value, use them.
500 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
501 unsigned PhysReg = getFreeReg(RC);
502 int FrameIndex = getStackSpaceFor(VirtReg, RC);
503
504 if (PhysReg) { // we have a free register, so use it.
505 assignVirtToPhysReg(VirtReg, PhysReg);
506 } else { // no free registers available.
507 // try to fold the spill into the instruction
508 if(MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, OpNum, FrameIndex)) {
509 ++NumFolded;
510 // Since we changed the address of MI, make sure to update live variables
511 // to know that the new instruction has the properties of the old one.
512 LV->instructionChanged(MI, FMI);
513 return MBB.insert(MBB.erase(MI), FMI);
514 }
515
516 // determine which of the physical registers we'll kill off, since we
517 // couldn't fold.
518 PhysReg = chooseReg(MBB, MI, VirtReg);
519 }
520
521 // this virtual register is now unmodified (since we just reloaded it)
522 markVirtRegModified(VirtReg, false);
523
524 DOUT << " Reloading %reg" << VirtReg << " into "
525 << RegInfo->getName(PhysReg) << "\n";
526
527 // Add move instruction(s)
528 RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
529 ++NumLoads; // Update statistics
530
531 MF->setPhysRegUsed(PhysReg);
532 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
533 return MI;
534}
535
536/// Fill out the vreg read timetable. Since ReadTime increases
537/// monotonically, the individual readtime sets will be sorted
538/// in ascending order.
539void RABigBlock::FillVRegReadTable(MachineBasicBlock &MBB) {
540 // loop over each instruction
541 MachineBasicBlock::iterator MII;
542 unsigned ReadTime;
543
544 for(ReadTime=0, MII = MBB.begin(); MII != MBB.end(); ++ReadTime, ++MII) {
545 MachineInstr *MI = MII;
546
Duraid Madinaa8c76822007-06-22 08:27:12 +0000547 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
548 MachineOperand& MO = MI->getOperand(i);
549 // look for vreg reads..
550 if (MO.isRegister() && !MO.isDef() && MO.getReg() &&
551 MRegisterInfo::isVirtualRegister(MO.getReg())) {
Duraid Madina2e0930c2007-06-25 23:46:54 +0000552 // ..and add them to the read table.
553 VRegTimes* &Times = VRegReadTable[MO.getReg()];
554 if(!VRegReadTable[MO.getReg()]) {
555 Times = new VRegTimes;
556 VRegReadIdx[MO.getReg()] = 0;
557 }
558 Times->push_back(ReadTime);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000559 }
560 }
561
562 }
563
Duraid Madina2e0930c2007-06-25 23:46:54 +0000564 MBBLastInsnTime = ReadTime;
565
566 for(DenseMap<unsigned, VRegTimes*, VRegKeyInfo>::iterator Reads = VRegReadTable.begin();
567 Reads != VRegReadTable.end(); ++Reads) {
568 if(Reads->second) {
569 DOUT << "Reads[" << Reads->first << "]=" << Reads->second->size() << "\n";
570 }
571 }
Duraid Madinaa8c76822007-06-22 08:27:12 +0000572}
573
Duraid Madinab2efabd2007-06-27 08:31:07 +0000574/// isReadModWriteImplicitKill - True if this is an implicit kill for a
575/// read/mod/write register, i.e. update partial register.
576static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
577 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
578 MachineOperand& MO = MI->getOperand(i);
579 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
580 MO.isDef() && !MO.isDead())
581 return true;
582 }
583 return false;
584}
585
586/// isReadModWriteImplicitDef - True if this is an implicit def for a
587/// read/mod/write register, i.e. update partial register.
588static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
589 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
590 MachineOperand& MO = MI->getOperand(i);
591 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
592 !MO.isDef() && MO.isKill())
593 return true;
594 }
595 return false;
596}
597
Duraid Madina2e0930c2007-06-25 23:46:54 +0000598
Duraid Madinaa8c76822007-06-22 08:27:12 +0000599void RABigBlock::AllocateBasicBlock(MachineBasicBlock &MBB) {
600 // loop over each instruction
601 MachineBasicBlock::iterator MII = MBB.begin();
602 const TargetInstrInfo &TII = *TM->getInstrInfo();
603
604 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
605 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
606
607 // If this is the first basic block in the machine function, add live-in
608 // registers as active.
609 if (&MBB == &*MF->begin()) {
610 for (MachineFunction::livein_iterator I = MF->livein_begin(),
611 E = MF->livein_end(); I != E; ++I) {
612 unsigned Reg = I->first;
613 MF->setPhysRegUsed(Reg);
614 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Duraid Madinab2efabd2007-06-27 08:31:07 +0000615 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000616 *AliasSet; ++AliasSet) {
617 if (PhysRegsUsed[*AliasSet] != -2) {
Duraid Madinaa8c76822007-06-22 08:27:12 +0000618 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
619 MF->setPhysRegUsed(*AliasSet);
620 }
621 }
622 }
623 }
624
625 // Otherwise, sequentially allocate each instruction in the MBB.
Duraid Madina4e378c62007-06-27 08:11:59 +0000626 MBBCurTime = -1;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000627 while (MII != MBB.end()) {
628 MachineInstr *MI = MII++;
Duraid Madina4e378c62007-06-27 08:11:59 +0000629 MBBCurTime++;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000630 const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
Duraid Madina4e378c62007-06-27 08:11:59 +0000631 DEBUG(DOUT << "\nTime=" << MBBCurTime << " Starting RegAlloc of: " << *MI;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000632 DOUT << " Regs have values: ";
633 for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
634 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
635 DOUT << "[" << RegInfo->getName(i)
636 << ",%reg" << PhysRegsUsed[i] << "] ";
637 DOUT << "\n");
638
Duraid Madinaa8c76822007-06-22 08:27:12 +0000639 SmallVector<unsigned, 8> Kills;
640 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
641 MachineOperand& MO = MI->getOperand(i);
Duraid Madinab2efabd2007-06-27 08:31:07 +0000642 if (MO.isRegister() && MO.isKill()) {
643 if (!MO.isImplicit())
644 Kills.push_back(MO.getReg());
645 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
646 // These are extra physical register kills when a sub-register
647 // is defined (def of a sub-register is a read/mod/write of the
648 // larger registers). Ignore.
649 Kills.push_back(MO.getReg());
650 }
Duraid Madinaa8c76822007-06-22 08:27:12 +0000651 }
652
653 // Get the used operands into registers. This has the potential to spill
654 // incoming values if we are out of registers. Note that we completely
655 // ignore physical register uses here. We assume that if an explicit
656 // physical register is referenced by the instruction, that it is guaranteed
657 // to be live-in, or the input is badly hosed.
658 //
659 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
660 MachineOperand& MO = MI->getOperand(i);
661 // here we are looking for only used operands (never def&use)
662 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
663 MRegisterInfo::isVirtualRegister(MO.getReg()))
664 MI = reloadVirtReg(MBB, MI, i);
665 }
666
667 // If this instruction is the last user of this register, kill the
668 // value, freeing the register being used, so it doesn't need to be
669 // spilled to memory.
670 //
671 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
672 unsigned VirtReg = Kills[i];
673 unsigned PhysReg = VirtReg;
674 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
675 // If the virtual register was never materialized into a register, it
676 // might not be in the map, but it won't hurt to zero it out anyway.
677 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
678 PhysReg = PhysRegSlot;
679 PhysRegSlot = 0;
680 } else if (PhysRegsUsed[PhysReg] == -2) {
681 // Unallocatable register dead, ignore.
682 continue;
Duraid Madinab2efabd2007-06-27 08:31:07 +0000683 } else {
684 assert(!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1 &&
685 "Silently clearing a virtual register?");
Duraid Madinaa8c76822007-06-22 08:27:12 +0000686 }
687
688 if (PhysReg) {
689 DOUT << " Last use of " << RegInfo->getName(PhysReg)
690 << "[%reg" << VirtReg <<"], removing it from live set\n";
691 removePhysReg(PhysReg);
Duraid Madinab2efabd2007-06-27 08:31:07 +0000692 for (const unsigned *AliasSet = RegInfo->getSubRegisters(PhysReg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000693 *AliasSet; ++AliasSet) {
694 if (PhysRegsUsed[*AliasSet] != -2) {
695 DOUT << " Last use of "
696 << RegInfo->getName(*AliasSet)
697 << "[%reg" << VirtReg <<"], removing it from live set\n";
698 removePhysReg(*AliasSet);
699 }
700 }
701 }
702 }
703
704 // Loop over all of the operands of the instruction, spilling registers that
705 // are defined, and marking explicit destinations in the PhysRegsUsed map.
706 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
707 MachineOperand& MO = MI->getOperand(i);
708 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
709 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
710 unsigned Reg = MO.getReg();
711 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
Duraid Madinab2efabd2007-06-27 08:31:07 +0000712 // These are extra physical register defs when a sub-register
713 // is defined (def of a sub-register is a read/mod/write of the
714 // larger registers). Ignore.
715 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
716
Duraid Madinaa8c76822007-06-22 08:27:12 +0000717 MF->setPhysRegUsed(Reg);
718 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
719 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Duraid Madinab2efabd2007-06-27 08:31:07 +0000720 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000721 *AliasSet; ++AliasSet) {
722 if (PhysRegsUsed[*AliasSet] != -2) {
Duraid Madina669f7382007-06-27 07:07:13 +0000723 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
Duraid Madina4e378c62007-06-27 08:11:59 +0000724 MF->setPhysRegUsed(*AliasSet);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000725 }
726 }
727 }
728 }
729
730 // Loop over the implicit defs, spilling them as well.
731 if (TID.ImplicitDefs) {
732 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
733 *ImplicitDefs; ++ImplicitDefs) {
734 unsigned Reg = *ImplicitDefs;
Duraid Madinab2efabd2007-06-27 08:31:07 +0000735 if (PhysRegsUsed[Reg] != -2) {
Duraid Madinaa8c76822007-06-22 08:27:12 +0000736 spillPhysReg(MBB, MI, Reg, true);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000737 PhysRegsUsed[Reg] = 0; // It is free and reserved now
738 }
739 MF->setPhysRegUsed(Reg);
Duraid Madinab2efabd2007-06-27 08:31:07 +0000740 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000741 *AliasSet; ++AliasSet) {
742 if (PhysRegsUsed[*AliasSet] != -2) {
Duraid Madinab2efabd2007-06-27 08:31:07 +0000743 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
Duraid Madinaa8c76822007-06-22 08:27:12 +0000744 MF->setPhysRegUsed(*AliasSet);
745 }
746 }
747 }
748 }
749
750 SmallVector<unsigned, 8> DeadDefs;
751 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
752 MachineOperand& MO = MI->getOperand(i);
753 if (MO.isRegister() && MO.isDead())
754 DeadDefs.push_back(MO.getReg());
755 }
756
757 // Okay, we have allocated all of the source operands and spilled any values
758 // that would be destroyed by defs of this instruction. Loop over the
759 // explicit defs and assign them to a register, spilling incoming values if
760 // we need to scavenge a register.
761 //
762 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
763 MachineOperand& MO = MI->getOperand(i);
764 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
765 MRegisterInfo::isVirtualRegister(MO.getReg())) {
766 unsigned DestVirtReg = MO.getReg();
767 unsigned DestPhysReg;
768
769 // If DestVirtReg already has a value, use it.
770 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
771 DestPhysReg = chooseReg(MBB, MI, DestVirtReg);
772 MF->setPhysRegUsed(DestPhysReg);
773 markVirtRegModified(DestVirtReg);
774 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
775 }
776 }
777
778 // If this instruction defines any registers that are immediately dead,
779 // kill them now.
780 //
781 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
782 unsigned VirtReg = DeadDefs[i];
783 unsigned PhysReg = VirtReg;
784 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
785 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
786 PhysReg = PhysRegSlot;
787 assert(PhysReg != 0);
788 PhysRegSlot = 0;
789 } else if (PhysRegsUsed[PhysReg] == -2) {
790 // Unallocatable register dead, ignore.
791 continue;
792 }
793
794 if (PhysReg) {
795 DOUT << " Register " << RegInfo->getName(PhysReg)
796 << " [%reg" << VirtReg
797 << "] is never used, removing it frame live list\n";
798 removePhysReg(PhysReg);
799 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
800 *AliasSet; ++AliasSet) {
801 if (PhysRegsUsed[*AliasSet] != -2) {
802 DOUT << " Register " << RegInfo->getName(*AliasSet)
803 << " [%reg" << *AliasSet
804 << "] is never used, removing it frame live list\n";
805 removePhysReg(*AliasSet);
806 }
807 }
808 }
809 }
810
811 // Finally, if this is a noop copy instruction, zap it.
812 unsigned SrcReg, DstReg;
813 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
814 LV->removeVirtualRegistersKilled(MI);
815 LV->removeVirtualRegistersDead(MI);
816 MBB.erase(MI);
817 }
818 }
819
820 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
821
822 // Spill all physical registers holding virtual registers now.
823 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
824 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
825 if (unsigned VirtReg = PhysRegsUsed[i])
826 spillVirtReg(MBB, MI, VirtReg, i);
827 else
828 removePhysReg(i);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000829}
830
831/// runOnMachineFunction - Register allocate the whole function
832///
833bool RABigBlock::runOnMachineFunction(MachineFunction &Fn) {
834 DOUT << "Machine Function " << "\n";
835 MF = &Fn;
836 TM = &Fn.getTarget();
837 RegInfo = TM->getRegisterInfo();
838 LV = &getAnalysis<LiveVariables>();
839
840 PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
841
842 // At various places we want to efficiently check to see whether a register
843 // is allocatable. To handle this, we mark all unallocatable registers as
844 // being pinned down, permanently.
845 {
846 BitVector Allocable = RegInfo->getAllocatableSet(Fn);
847 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
848 if (!Allocable[i])
849 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
850 }
851
852 // initialize the virtual->physical register map to have a 'null'
853 // mapping for all virtual registers
854 Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
Duraid Madina2e0930c2007-06-25 23:46:54 +0000855 StackSlotForVirtReg.grow(MF->getSSARegMap()->getLastVirtReg());
856 VirtRegModified.resize(MF->getSSARegMap()->getLastVirtReg() - MRegisterInfo::FirstVirtualRegister + 1,0);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000857
858 // Loop over all of the basic blocks, eliminating virtual register references
859 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
860 MBB != MBBe; ++MBB) {
861 // fill out the read timetable
862 FillVRegReadTable(*MBB);
863 // use it to allocate the BB
864 AllocateBasicBlock(*MBB);
865 // clear it
866 VRegReadTable.clear();
867 }
868
869 StackSlotForVirtReg.clear();
870 PhysRegsUsed.clear();
871 VirtRegModified.clear();
872 Virt2PhysRegMap.clear();
873 return true;
874}
875
876FunctionPass *llvm::createBigBlockRegisterAllocator() {
877 return new RABigBlock();
878}
Duraid Madina837a6002007-06-26 00:21:58 +0000879