blob: 5c894729a7e88fbdb58b7b7fd3c01d46efb2122c [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Duraid Madinaa8c76822007-06-22 08:27:12 +000035#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
Duraid Madinaa8c76822007-06-22 08:27:12 +000037#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; }
Chris Lattner76c1b972007-09-17 18:34:04 +000066 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
Duraid Madinaa8c76822007-06-22 08:27:12 +000067 static unsigned getHashValue(const unsigned &Key) { return Key; }
68 };
69
Duraid Madina837a6002007-06-26 00:21:58 +000070
71/// This register allocator is derived from RegAllocLocal.cpp. Like it, this
72/// allocator works on one basic block at a time, oblivious to others.
73/// However, the algorithm used here is suited for long blocks of
74/// instructions - registers are spilled by greedily choosing those holding
75/// values that will not be needed for the longest amount of time. This works
76/// particularly well for blocks with 10 or more times as many instructions
77/// as machine registers, but can be used for general code.
78///
79/// TODO: - automagically invoke linearscan for (groups of) small BBs?
80/// - break ties when picking regs? (probably not worth it in a
81/// JIT context)
82///
Duraid Madinaa8c76822007-06-22 08:27:12 +000083 class VISIBILITY_HIDDEN RABigBlock : public MachineFunctionPass {
84 public:
85 static char ID;
86 RABigBlock() : MachineFunctionPass((intptr_t)&ID) {}
87 private:
Duraid Madina837a6002007-06-26 00:21:58 +000088 /// TM - For getting at TargetMachine info
89 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +000090 const TargetMachine *TM;
Duraid Madina837a6002007-06-26 00:21:58 +000091
92 /// MF - Our generic MachineFunction pointer
93 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +000094 MachineFunction *MF;
Duraid Madina837a6002007-06-26 00:21:58 +000095
96 /// RegInfo - For dealing with machine register info (aliases, folds
97 /// etc)
Duraid Madinaa8c76822007-06-22 08:27:12 +000098 const MRegisterInfo *RegInfo;
Duraid Madina837a6002007-06-26 00:21:58 +000099
100 /// LV - Our generic LiveVariables pointer
101 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000102 LiveVariables *LV;
103
Duraid Madina2e0930c2007-06-25 23:46:54 +0000104 typedef SmallVector<unsigned, 2> VRegTimes;
105
Duraid Madina837a6002007-06-26 00:21:58 +0000106 /// VRegReadTable - maps VRegs in a BB to the set of times they are read
107 ///
Duraid Madina2e0930c2007-06-25 23:46:54 +0000108 DenseMap<unsigned, VRegTimes*, VRegKeyInfo> VRegReadTable;
Duraid Madina837a6002007-06-26 00:21:58 +0000109
110 /// VRegReadIdx - keeps track of the "current time" in terms of
111 /// positions in VRegReadTable
Duraid Madina2e0930c2007-06-25 23:46:54 +0000112 DenseMap<unsigned, unsigned , VRegKeyInfo> VRegReadIdx;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000113
Duraid Madina837a6002007-06-26 00:21:58 +0000114 /// StackSlotForVirtReg - Maps virtual regs to the frame index where these
115 /// values are spilled.
Duraid Madina2e0930c2007-06-25 23:46:54 +0000116 IndexedMap<unsigned, VirtReg2IndexFunctor> StackSlotForVirtReg;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000117
Duraid Madina837a6002007-06-26 00:21:58 +0000118 /// Virt2PhysRegMap - This map contains entries for each virtual register
119 /// that is currently available in a physical register.
Duraid Madinaa8c76822007-06-22 08:27:12 +0000120 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
121
Duraid Madina837a6002007-06-26 00:21:58 +0000122 /// PhysRegsUsed - This array is effectively a map, containing entries for
123 /// each physical register that currently has a value (ie, it is in
124 /// Virt2PhysRegMap). The value mapped to is the virtual register
125 /// corresponding to the physical register (the inverse of the
126 /// Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
127 /// because it is used by a future instruction, and to -2 if it is not
128 /// allocatable. If the entry for a physical register is -1, then the
129 /// physical register is "not in the map".
130 ///
131 std::vector<int> PhysRegsUsed;
132
133 /// VirtRegModified - This bitset contains information about which virtual
134 /// registers need to be spilled back to memory when their registers are
135 /// scavenged. If a virtual register has simply been rematerialized, there
136 /// is no reason to spill it to memory when we need the register back.
137 ///
138 std::vector<int> VirtRegModified;
139
140 /// MBBLastInsnTime - the number of the the last instruction in MBB
141 ///
142 int MBBLastInsnTime;
143
144 /// MBBCurTime - the number of the the instruction being currently processed
145 ///
146 int MBBCurTime;
147
Duraid Madinaa8c76822007-06-22 08:27:12 +0000148 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
149 return Virt2PhysRegMap[VirtReg];
150 }
151
Duraid Madina2e0930c2007-06-25 23:46:54 +0000152 unsigned &getVirt2StackSlot(unsigned VirtReg) {
153 return StackSlotForVirtReg[VirtReg];
154 }
155
Duraid Madina837a6002007-06-26 00:21:58 +0000156 /// markVirtRegModified - Lets us flip bits in the VirtRegModified bitset
157 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000158 void markVirtRegModified(unsigned Reg, bool Val = true) {
159 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
160 Reg -= MRegisterInfo::FirstVirtualRegister;
Duraid Madina837a6002007-06-26 00:21:58 +0000161 if (VirtRegModified.size() <= Reg)
162 VirtRegModified.resize(Reg+1);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000163 VirtRegModified[Reg] = Val;
164 }
165
Duraid Madina837a6002007-06-26 00:21:58 +0000166 /// isVirtRegModified - Lets us query the VirtRegModified bitset
167 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000168 bool isVirtRegModified(unsigned Reg) const {
169 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
170 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
171 && "Illegal virtual register!");
172 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
173 }
174
Duraid Madinaa8c76822007-06-22 08:27:12 +0000175 public:
Duraid Madina837a6002007-06-26 00:21:58 +0000176 /// getPassName - returns the BigBlock allocator's name
177 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000178 virtual const char *getPassName() const {
179 return "BigBlock Register Allocator";
180 }
181
Duraid Madina837a6002007-06-26 00:21:58 +0000182 /// getAnalaysisUsage - declares the required analyses
183 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000184 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
185 AU.addRequired<LiveVariables>();
186 AU.addRequiredID(PHIEliminationID);
187 AU.addRequiredID(TwoAddressInstructionPassID);
188 MachineFunctionPass::getAnalysisUsage(AU);
189 }
190
191 private:
192 /// runOnMachineFunction - Register allocate the whole function
Duraid Madina837a6002007-06-26 00:21:58 +0000193 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000194 bool runOnMachineFunction(MachineFunction &Fn);
195
196 /// AllocateBasicBlock - Register allocate the specified basic block.
Duraid Madina837a6002007-06-26 00:21:58 +0000197 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000198 void AllocateBasicBlock(MachineBasicBlock &MBB);
199
200 /// FillVRegReadTable - Fill out the table of vreg read times given a BB
Duraid Madina837a6002007-06-26 00:21:58 +0000201 ///
Duraid Madinaa8c76822007-06-22 08:27:12 +0000202 void FillVRegReadTable(MachineBasicBlock &MBB);
203
204 /// areRegsEqual - This method returns true if the specified registers are
205 /// related to each other. To do this, it checks to see if they are equal
206 /// or if the first register is in the alias set of the second register.
207 ///
208 bool areRegsEqual(unsigned R1, unsigned R2) const {
209 if (R1 == R2) return true;
210 for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
211 *AliasSet; ++AliasSet) {
212 if (*AliasSet == R1) return true;
213 }
214 return false;
215 }
216
217 /// getStackSpaceFor - This returns the frame index of the specified virtual
218 /// register on the stack, allocating space if necessary.
219 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
220
221 /// removePhysReg - This method marks the specified physical register as no
222 /// longer being in use.
223 ///
224 void removePhysReg(unsigned PhysReg);
225
226 /// spillVirtReg - This method spills the value specified by PhysReg into
227 /// the virtual register slot specified by VirtReg. It then updates the RA
228 /// data structures to indicate the fact that PhysReg is now available.
229 ///
230 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
231 unsigned VirtReg, unsigned PhysReg);
232
233 /// spillPhysReg - This method spills the specified physical register into
234 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
235 /// true, then the request is ignored if the physical register does not
236 /// contain a virtual register.
237 ///
238 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
239 unsigned PhysReg, bool OnlyVirtRegs = false);
240
241 /// assignVirtToPhysReg - This method updates local state so that we know
242 /// that PhysReg is the proper container for VirtReg now. The physical
243 /// register must not be used for anything else when this is called.
244 ///
245 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
246
Duraid Madinaa8c76822007-06-22 08:27:12 +0000247 /// isPhysRegAvailable - Return true if the specified physical register is
248 /// free and available for use. This also includes checking to see if
249 /// aliased registers are all free...
250 ///
251 bool isPhysRegAvailable(unsigned PhysReg) const;
252
253 /// getFreeReg - Look to see if there is a free register available in the
254 /// specified register class. If not, return 0.
255 ///
256 unsigned getFreeReg(const TargetRegisterClass *RC);
257
258 /// chooseReg - Pick a physical register to hold the specified
259 /// virtual register by choosing the one which will be read furthest
260 /// in the future.
261 ///
262 unsigned chooseReg(MachineBasicBlock &MBB, MachineInstr *MI,
263 unsigned VirtReg);
264
265 /// reloadVirtReg - This method transforms the specified specified virtual
266 /// register use to refer to a physical register. This method may do this
267 /// in one of several ways: if the register is available in a physical
268 /// register already, it uses that physical register. If the value is not
269 /// in a physical register, and if there are physical registers available,
270 /// it loads it into a register. If register pressure is high, and it is
271 /// possible, it tries to fold the load of the virtual register into the
272 /// instruction itself. It avoids doing this if register pressure is low to
273 /// improve the chance that subsequent instructions can use the reloaded
274 /// value. This method returns the modified instruction.
275 ///
276 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
277 unsigned OpNum);
278
279 };
280 char RABigBlock::ID = 0;
281}
282
283/// getStackSpaceFor - This allocates space for the specified virtual register
284/// to be held on the stack.
285int RABigBlock::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
286 // Find the location Reg would belong...
Duraid Madina2e0930c2007-06-25 23:46:54 +0000287 int FrameIdx = getVirt2StackSlot(VirtReg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000288
Duraid Madina2e0930c2007-06-25 23:46:54 +0000289 if (FrameIdx)
290 return FrameIdx - 1; // Already has space allocated?
Duraid Madinaa8c76822007-06-22 08:27:12 +0000291
292 // Allocate a new stack object for this spill location...
Duraid Madina2e0930c2007-06-25 23:46:54 +0000293 FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
Duraid Madinaa8c76822007-06-22 08:27:12 +0000294 RC->getAlignment());
295
296 // Assign the slot...
Duraid Madina2e0930c2007-06-25 23:46:54 +0000297 getVirt2StackSlot(VirtReg) = FrameIdx + 1;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000298 return FrameIdx;
299}
300
301
302/// removePhysReg - This method marks the specified physical register as no
303/// longer being in use.
304///
305void RABigBlock::removePhysReg(unsigned PhysReg) {
306 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
Duraid Madinaa8c76822007-06-22 08:27:12 +0000307}
308
309
310/// spillVirtReg - This method spills the value specified by PhysReg into the
311/// virtual register slot specified by VirtReg. It then updates the RA data
312/// structures to indicate the fact that PhysReg is now available.
313///
314void RABigBlock::spillVirtReg(MachineBasicBlock &MBB,
315 MachineBasicBlock::iterator I,
316 unsigned VirtReg, unsigned PhysReg) {
317 assert(VirtReg && "Spilling a physical register is illegal!"
318 " Must not have appropriate kill for the register or use exists beyond"
319 " the intended one.");
320 DOUT << " Spilling register " << RegInfo->getName(PhysReg)
321 << " containing %reg" << VirtReg;
322 if (!isVirtRegModified(VirtReg))
323 DOUT << " which has not been modified, so no store necessary!";
324
325 // Otherwise, there is a virtual register corresponding to this physical
326 // register. We only need to spill it into its stack slot if it has been
327 // modified.
328 if (isVirtRegModified(VirtReg)) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000329 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000330 int FrameIndex = getStackSpaceFor(VirtReg, RC);
331 DOUT << " to stack slot #" << FrameIndex;
Evan Chengd64b5c82007-12-05 03:14:33 +0000332 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, true, FrameIndex, RC);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000333 ++NumStores; // Update statistics
334 }
335
336 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
337
338 DOUT << "\n";
339 removePhysReg(PhysReg);
340}
341
342
343/// spillPhysReg - This method spills the specified physical register into the
344/// virtual register slot associated with it. If OnlyVirtRegs is set to true,
345/// then the request is ignored if the physical register does not contain a
346/// virtual register.
347///
348void RABigBlock::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
349 unsigned PhysReg, bool OnlyVirtRegs) {
350 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
351 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
352 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
353 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
354 } else {
355 // If the selected register aliases any other registers, we must make
356 // sure that one of the aliases isn't alive.
357 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
358 *AliasSet; ++AliasSet)
359 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
360 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
Duraid Madinab2efabd2007-06-27 08:31:07 +0000361 if (PhysRegsUsed[*AliasSet])
Duraid Madinaa8c76822007-06-22 08:27:12 +0000362 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
363 }
364}
365
366
367/// assignVirtToPhysReg - This method updates local state so that we know
368/// that PhysReg is the proper container for VirtReg now. The physical
369/// register must not be used for anything else when this is called.
370///
371void RABigBlock::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
372 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
373 // Update information to note the fact that this register was just used, and
374 // it holds VirtReg.
375 PhysRegsUsed[PhysReg] = VirtReg;
376 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000377}
378
379
380/// isPhysRegAvailable - Return true if the specified physical register is free
381/// and available for use. This also includes checking to see if aliased
382/// registers are all free...
383///
384bool RABigBlock::isPhysRegAvailable(unsigned PhysReg) const {
385 if (PhysRegsUsed[PhysReg] != -1) return false;
386
387 // If the selected register aliases any other allocated registers, it is
388 // not free!
389 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
390 *AliasSet; ++AliasSet)
391 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
392 return false; // Can't use this reg then.
393 return true;
394}
395
Duraid Madina837a6002007-06-26 00:21:58 +0000396
Duraid Madinaa8c76822007-06-22 08:27:12 +0000397/// getFreeReg - Look to see if there is a free register available in the
398/// specified register class. If not, return 0.
399///
400unsigned RABigBlock::getFreeReg(const TargetRegisterClass *RC) {
401 // Get iterators defining the range of registers that are valid to allocate in
402 // this class, which also specifies the preferred allocation order.
403 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
404 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
405
406 for (; RI != RE; ++RI)
407 if (isPhysRegAvailable(*RI)) { // Is reg unused?
408 assert(*RI != 0 && "Cannot use register!");
409 return *RI; // Found an unused register!
410 }
411 return 0;
412}
413
414
Duraid Madinaa8c76822007-06-22 08:27:12 +0000415/// chooseReg - Pick a physical register to hold the specified
416/// virtual register by choosing the one whose value will be read
417/// furthest in the future.
418///
419unsigned RABigBlock::chooseReg(MachineBasicBlock &MBB, MachineInstr *I,
420 unsigned VirtReg) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000421 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000422 // First check to see if we have a free register of the requested type...
423 unsigned PhysReg = getFreeReg(RC);
424
425 // If we didn't find an unused register, find the one which will be
426 // read at the most distant point in time.
427 if (PhysReg == 0) {
428 unsigned delay=0, longest_delay=0;
Duraid Madina2e0930c2007-06-25 23:46:54 +0000429 VRegTimes* ReadTimes;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000430
Duraid Madina2e0930c2007-06-25 23:46:54 +0000431 unsigned curTime = MBBCurTime;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000432
433 // for all physical regs in the RC,
434 for(TargetRegisterClass::iterator pReg = RC->begin();
435 pReg != RC->end(); ++pReg) {
436 // how long until they're read?
437 if(PhysRegsUsed[*pReg]>0) { // ignore non-allocatable regs
438 ReadTimes = VRegReadTable[PhysRegsUsed[*pReg]];
Duraid Madina2e0930c2007-06-25 23:46:54 +0000439 if(ReadTimes && !ReadTimes->empty()) {
440 unsigned& pt = VRegReadIdx[PhysRegsUsed[*pReg]];
441 while(pt < ReadTimes->size() && (*ReadTimes)[pt] < curTime) {
442 ++pt;
443 }
444
445 if(pt < ReadTimes->size())
446 delay = (*ReadTimes)[pt] - curTime;
447 else
448 delay = MBBLastInsnTime + 1 - curTime;
449 } else {
450 // This register is only defined, but never
451 // read in this MBB. Therefore the next read
452 // happens after the end of this MBB
453 delay = MBBLastInsnTime + 1 - curTime;
454 }
455
Duraid Madinaa8c76822007-06-22 08:27:12 +0000456
457 if(delay > longest_delay) {
458 longest_delay = delay;
459 PhysReg = *pReg;
460 }
461 }
462 }
Duraid Madinadf82c932007-06-27 09:01:14 +0000463
464 if(PhysReg == 0) { // ok, now we're desperate. We couldn't choose
465 // a register to spill by looking through the
466 // read timetable, so now we just spill the
467 // first allocatable register we find.
468
469 // for all physical regs in the RC,
470 for(TargetRegisterClass::iterator pReg = RC->begin();
471 pReg != RC->end(); ++pReg) {
472 // if we find a register we can spill
473 if(PhysRegsUsed[*pReg]>=-1)
474 PhysReg = *pReg; // choose it to be spilled
475 }
476 }
Duraid Madina4e378c62007-06-27 08:11:59 +0000477
Duraid Madinadf82c932007-06-27 09:01:14 +0000478 assert(PhysReg && "couldn't choose a register to spill :( ");
479 // TODO: assert that RC->contains(PhysReg) / handle aliased registers?
Duraid Madinaa8c76822007-06-22 08:27:12 +0000480
481 // since we needed to look in the table we need to spill this register.
482 spillPhysReg(MBB, I, PhysReg);
483 }
484
485 // assign the vreg to our chosen physical register
486 assignVirtToPhysReg(VirtReg, PhysReg);
487 return PhysReg; // and return it
488}
489
490
491/// reloadVirtReg - This method transforms an instruction with a virtual
492/// register use to one that references a physical register. It does this as
493/// follows:
494///
495/// 1) If the register is already in a physical register, it uses it.
496/// 2) Otherwise, if there is a free physical register, it uses that.
497/// 3) Otherwise, it calls chooseReg() to get the physical register
498/// holding the most distantly needed value, generating a spill in
499/// the process.
500///
501/// This method returns the modified instruction.
502MachineInstr *RABigBlock::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
503 unsigned OpNum) {
504 unsigned VirtReg = MI->getOperand(OpNum).getReg();
505
506 // If the virtual register is already available in a physical register,
507 // just update the instruction and return.
508 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
509 MI->getOperand(OpNum).setReg(PR);
510 return MI;
511 }
512
513 // Otherwise, if we have free physical registers available to hold the
514 // value, use them.
Chris Lattner84bc5422007-12-31 04:13:23 +0000515 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000516 unsigned PhysReg = getFreeReg(RC);
517 int FrameIndex = getStackSpaceFor(VirtReg, RC);
518
519 if (PhysReg) { // we have a free register, so use it.
520 assignVirtToPhysReg(VirtReg, PhysReg);
521 } else { // no free registers available.
522 // try to fold the spill into the instruction
Evan Chengaee4af62007-12-02 08:30:39 +0000523 SmallVector<unsigned, 2> Ops;
524 Ops.push_back(OpNum);
525 if(MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, Ops, FrameIndex)) {
Duraid Madinaa8c76822007-06-22 08:27:12 +0000526 ++NumFolded;
527 // Since we changed the address of MI, make sure to update live variables
528 // to know that the new instruction has the properties of the old one.
529 LV->instructionChanged(MI, FMI);
530 return MBB.insert(MBB.erase(MI), FMI);
531 }
532
533 // determine which of the physical registers we'll kill off, since we
534 // couldn't fold.
535 PhysReg = chooseReg(MBB, MI, VirtReg);
536 }
537
538 // this virtual register is now unmodified (since we just reloaded it)
539 markVirtRegModified(VirtReg, false);
540
541 DOUT << " Reloading %reg" << VirtReg << " into "
542 << RegInfo->getName(PhysReg) << "\n";
543
544 // Add move instruction(s)
545 RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
546 ++NumLoads; // Update statistics
547
Chris Lattner84bc5422007-12-31 04:13:23 +0000548 MF->getRegInfo().setPhysRegUsed(PhysReg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000549 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
550 return MI;
551}
552
553/// Fill out the vreg read timetable. Since ReadTime increases
554/// monotonically, the individual readtime sets will be sorted
555/// in ascending order.
556void RABigBlock::FillVRegReadTable(MachineBasicBlock &MBB) {
557 // loop over each instruction
558 MachineBasicBlock::iterator MII;
559 unsigned ReadTime;
560
561 for(ReadTime=0, MII = MBB.begin(); MII != MBB.end(); ++ReadTime, ++MII) {
562 MachineInstr *MI = MII;
563
Duraid Madinaa8c76822007-06-22 08:27:12 +0000564 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
565 MachineOperand& MO = MI->getOperand(i);
566 // look for vreg reads..
567 if (MO.isRegister() && !MO.isDef() && MO.getReg() &&
568 MRegisterInfo::isVirtualRegister(MO.getReg())) {
Duraid Madina2e0930c2007-06-25 23:46:54 +0000569 // ..and add them to the read table.
570 VRegTimes* &Times = VRegReadTable[MO.getReg()];
571 if(!VRegReadTable[MO.getReg()]) {
572 Times = new VRegTimes;
573 VRegReadIdx[MO.getReg()] = 0;
574 }
575 Times->push_back(ReadTime);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000576 }
577 }
578
579 }
580
Duraid Madina2e0930c2007-06-25 23:46:54 +0000581 MBBLastInsnTime = ReadTime;
582
583 for(DenseMap<unsigned, VRegTimes*, VRegKeyInfo>::iterator Reads = VRegReadTable.begin();
584 Reads != VRegReadTable.end(); ++Reads) {
585 if(Reads->second) {
586 DOUT << "Reads[" << Reads->first << "]=" << Reads->second->size() << "\n";
587 }
588 }
Duraid Madinaa8c76822007-06-22 08:27:12 +0000589}
590
Duraid Madinab2efabd2007-06-27 08:31:07 +0000591/// isReadModWriteImplicitKill - True if this is an implicit kill for a
592/// read/mod/write register, i.e. update partial register.
593static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
594 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
595 MachineOperand& MO = MI->getOperand(i);
596 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
597 MO.isDef() && !MO.isDead())
598 return true;
599 }
600 return false;
601}
602
603/// isReadModWriteImplicitDef - True if this is an implicit def for a
604/// read/mod/write register, i.e. update partial register.
605static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
606 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
607 MachineOperand& MO = MI->getOperand(i);
608 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
609 !MO.isDef() && MO.isKill())
610 return true;
611 }
612 return false;
613}
614
Duraid Madina2e0930c2007-06-25 23:46:54 +0000615
Duraid Madinaa8c76822007-06-22 08:27:12 +0000616void RABigBlock::AllocateBasicBlock(MachineBasicBlock &MBB) {
617 // loop over each instruction
618 MachineBasicBlock::iterator MII = MBB.begin();
619 const TargetInstrInfo &TII = *TM->getInstrInfo();
620
621 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
622 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
623
624 // If this is the first basic block in the machine function, add live-in
625 // registers as active.
626 if (&MBB == &*MF->begin()) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000627 for (MachineRegisterInfo::livein_iterator
628 I = MF->getRegInfo().livein_begin(),
629 E = MF->getRegInfo().livein_end(); I != E; ++I) {
Duraid Madinaa8c76822007-06-22 08:27:12 +0000630 unsigned Reg = I->first;
Chris Lattner84bc5422007-12-31 04:13:23 +0000631 MF->getRegInfo().setPhysRegUsed(Reg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000632 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Duraid Madinab2efabd2007-06-27 08:31:07 +0000633 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000634 *AliasSet; ++AliasSet) {
635 if (PhysRegsUsed[*AliasSet] != -2) {
Duraid Madinaa8c76822007-06-22 08:27:12 +0000636 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
Chris Lattner84bc5422007-12-31 04:13:23 +0000637 MF->getRegInfo().setPhysRegUsed(*AliasSet);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000638 }
639 }
640 }
641 }
642
643 // Otherwise, sequentially allocate each instruction in the MBB.
Duraid Madina4e378c62007-06-27 08:11:59 +0000644 MBBCurTime = -1;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000645 while (MII != MBB.end()) {
646 MachineInstr *MI = MII++;
Duraid Madina4e378c62007-06-27 08:11:59 +0000647 MBBCurTime++;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000648 const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
Duraid Madina4e378c62007-06-27 08:11:59 +0000649 DEBUG(DOUT << "\nTime=" << MBBCurTime << " Starting RegAlloc of: " << *MI;
Duraid Madinaa8c76822007-06-22 08:27:12 +0000650 DOUT << " Regs have values: ";
651 for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
652 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
653 DOUT << "[" << RegInfo->getName(i)
654 << ",%reg" << PhysRegsUsed[i] << "] ";
655 DOUT << "\n");
656
Duraid Madinaa8c76822007-06-22 08:27:12 +0000657 SmallVector<unsigned, 8> Kills;
658 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
659 MachineOperand& MO = MI->getOperand(i);
Duraid Madinab2efabd2007-06-27 08:31:07 +0000660 if (MO.isRegister() && MO.isKill()) {
661 if (!MO.isImplicit())
662 Kills.push_back(MO.getReg());
663 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
664 // These are extra physical register kills when a sub-register
665 // is defined (def of a sub-register is a read/mod/write of the
666 // larger registers). Ignore.
667 Kills.push_back(MO.getReg());
668 }
Duraid Madinaa8c76822007-06-22 08:27:12 +0000669 }
670
671 // Get the used operands into registers. This has the potential to spill
672 // incoming values if we are out of registers. Note that we completely
673 // ignore physical register uses here. We assume that if an explicit
674 // physical register is referenced by the instruction, that it is guaranteed
675 // to be live-in, or the input is badly hosed.
676 //
677 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
678 MachineOperand& MO = MI->getOperand(i);
679 // here we are looking for only used operands (never def&use)
680 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
681 MRegisterInfo::isVirtualRegister(MO.getReg()))
682 MI = reloadVirtReg(MBB, MI, i);
683 }
684
685 // If this instruction is the last user of this register, kill the
686 // value, freeing the register being used, so it doesn't need to be
687 // spilled to memory.
688 //
689 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
690 unsigned VirtReg = Kills[i];
691 unsigned PhysReg = VirtReg;
692 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
693 // If the virtual register was never materialized into a register, it
694 // might not be in the map, but it won't hurt to zero it out anyway.
695 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
696 PhysReg = PhysRegSlot;
697 PhysRegSlot = 0;
698 } else if (PhysRegsUsed[PhysReg] == -2) {
699 // Unallocatable register dead, ignore.
700 continue;
Duraid Madinab2efabd2007-06-27 08:31:07 +0000701 } else {
702 assert(!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1 &&
703 "Silently clearing a virtual register?");
Duraid Madinaa8c76822007-06-22 08:27:12 +0000704 }
705
706 if (PhysReg) {
707 DOUT << " Last use of " << RegInfo->getName(PhysReg)
708 << "[%reg" << VirtReg <<"], removing it from live set\n";
709 removePhysReg(PhysReg);
Duraid Madinab2efabd2007-06-27 08:31:07 +0000710 for (const unsigned *AliasSet = RegInfo->getSubRegisters(PhysReg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000711 *AliasSet; ++AliasSet) {
712 if (PhysRegsUsed[*AliasSet] != -2) {
713 DOUT << " Last use of "
714 << RegInfo->getName(*AliasSet)
715 << "[%reg" << VirtReg <<"], removing it from live set\n";
716 removePhysReg(*AliasSet);
717 }
718 }
719 }
720 }
721
722 // Loop over all of the operands of the instruction, spilling registers that
723 // are defined, and marking explicit destinations in the PhysRegsUsed map.
724 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
725 MachineOperand& MO = MI->getOperand(i);
726 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
727 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
728 unsigned Reg = MO.getReg();
729 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
Duraid Madinab2efabd2007-06-27 08:31:07 +0000730 // These are extra physical register defs when a sub-register
731 // is defined (def of a sub-register is a read/mod/write of the
732 // larger registers). Ignore.
733 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
734
Chris Lattner84bc5422007-12-31 04:13:23 +0000735 MF->getRegInfo().setPhysRegUsed(Reg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000736 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
737 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Duraid Madinab2efabd2007-06-27 08:31:07 +0000738 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000739 *AliasSet; ++AliasSet) {
740 if (PhysRegsUsed[*AliasSet] != -2) {
Duraid Madina669f7382007-06-27 07:07:13 +0000741 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
Chris Lattner84bc5422007-12-31 04:13:23 +0000742 MF->getRegInfo().setPhysRegUsed(*AliasSet);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000743 }
744 }
745 }
746 }
747
748 // Loop over the implicit defs, spilling them as well.
749 if (TID.ImplicitDefs) {
750 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
751 *ImplicitDefs; ++ImplicitDefs) {
752 unsigned Reg = *ImplicitDefs;
Duraid Madinab2efabd2007-06-27 08:31:07 +0000753 if (PhysRegsUsed[Reg] != -2) {
Duraid Madinaa8c76822007-06-22 08:27:12 +0000754 spillPhysReg(MBB, MI, Reg, true);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000755 PhysRegsUsed[Reg] = 0; // It is free and reserved now
756 }
Chris Lattner84bc5422007-12-31 04:13:23 +0000757 MF->getRegInfo().setPhysRegUsed(Reg);
Duraid Madinab2efabd2007-06-27 08:31:07 +0000758 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000759 *AliasSet; ++AliasSet) {
760 if (PhysRegsUsed[*AliasSet] != -2) {
Duraid Madinab2efabd2007-06-27 08:31:07 +0000761 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
Chris Lattner84bc5422007-12-31 04:13:23 +0000762 MF->getRegInfo().setPhysRegUsed(*AliasSet);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000763 }
764 }
765 }
766 }
767
768 SmallVector<unsigned, 8> DeadDefs;
769 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
770 MachineOperand& MO = MI->getOperand(i);
771 if (MO.isRegister() && MO.isDead())
772 DeadDefs.push_back(MO.getReg());
773 }
774
775 // Okay, we have allocated all of the source operands and spilled any values
776 // that would be destroyed by defs of this instruction. Loop over the
777 // explicit defs and assign them to a register, spilling incoming values if
778 // we need to scavenge a register.
779 //
780 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
781 MachineOperand& MO = MI->getOperand(i);
782 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
783 MRegisterInfo::isVirtualRegister(MO.getReg())) {
784 unsigned DestVirtReg = MO.getReg();
785 unsigned DestPhysReg;
786
787 // If DestVirtReg already has a value, use it.
788 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
789 DestPhysReg = chooseReg(MBB, MI, DestVirtReg);
Chris Lattner84bc5422007-12-31 04:13:23 +0000790 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000791 markVirtRegModified(DestVirtReg);
792 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
793 }
794 }
795
796 // If this instruction defines any registers that are immediately dead,
797 // kill them now.
798 //
799 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
800 unsigned VirtReg = DeadDefs[i];
801 unsigned PhysReg = VirtReg;
802 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
803 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
804 PhysReg = PhysRegSlot;
805 assert(PhysReg != 0);
806 PhysRegSlot = 0;
807 } else if (PhysRegsUsed[PhysReg] == -2) {
808 // Unallocatable register dead, ignore.
809 continue;
810 }
811
812 if (PhysReg) {
813 DOUT << " Register " << RegInfo->getName(PhysReg)
814 << " [%reg" << VirtReg
815 << "] is never used, removing it frame live list\n";
816 removePhysReg(PhysReg);
817 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
818 *AliasSet; ++AliasSet) {
819 if (PhysRegsUsed[*AliasSet] != -2) {
820 DOUT << " Register " << RegInfo->getName(*AliasSet)
821 << " [%reg" << *AliasSet
822 << "] is never used, removing it frame live list\n";
823 removePhysReg(*AliasSet);
824 }
825 }
826 }
827 }
828
829 // Finally, if this is a noop copy instruction, zap it.
830 unsigned SrcReg, DstReg;
831 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
832 LV->removeVirtualRegistersKilled(MI);
833 LV->removeVirtualRegistersDead(MI);
834 MBB.erase(MI);
835 }
836 }
837
838 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
839
840 // Spill all physical registers holding virtual registers now.
841 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
842 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
843 if (unsigned VirtReg = PhysRegsUsed[i])
844 spillVirtReg(MBB, MI, VirtReg, i);
845 else
846 removePhysReg(i);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000847}
848
849/// runOnMachineFunction - Register allocate the whole function
850///
851bool RABigBlock::runOnMachineFunction(MachineFunction &Fn) {
852 DOUT << "Machine Function " << "\n";
853 MF = &Fn;
854 TM = &Fn.getTarget();
855 RegInfo = TM->getRegisterInfo();
856 LV = &getAnalysis<LiveVariables>();
857
858 PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
859
860 // At various places we want to efficiently check to see whether a register
861 // is allocatable. To handle this, we mark all unallocatable registers as
862 // being pinned down, permanently.
863 {
864 BitVector Allocable = RegInfo->getAllocatableSet(Fn);
865 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
866 if (!Allocable[i])
867 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
868 }
869
870 // initialize the virtual->physical register map to have a 'null'
871 // mapping for all virtual registers
Chris Lattner84bc5422007-12-31 04:13:23 +0000872 Virt2PhysRegMap.grow(MF->getRegInfo().getLastVirtReg());
873 StackSlotForVirtReg.grow(MF->getRegInfo().getLastVirtReg());
874 VirtRegModified.resize(MF->getRegInfo().getLastVirtReg() -
875 MRegisterInfo::FirstVirtualRegister + 1, 0);
Duraid Madinaa8c76822007-06-22 08:27:12 +0000876
877 // Loop over all of the basic blocks, eliminating virtual register references
878 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
879 MBB != MBBe; ++MBB) {
880 // fill out the read timetable
881 FillVRegReadTable(*MBB);
882 // use it to allocate the BB
883 AllocateBasicBlock(*MBB);
884 // clear it
885 VRegReadTable.clear();
886 }
887
888 StackSlotForVirtReg.clear();
889 PhysRegsUsed.clear();
890 VirtRegModified.clear();
891 Virt2PhysRegMap.clear();
892 return true;
893}
894
895FunctionPass *llvm::createBigBlockRegisterAllocator() {
896 return new RABigBlock();
897}
Duraid Madina837a6002007-06-26 00:21:58 +0000898