blob: 206f798e76a0323f3d4981ab9eeb33960f40ac17 [file] [log] [blame]
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001//===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
2//
3// This register allocator allocates registers to a basic block at a time,
4// attempting to keep values in registers and reusing registers as appropriate.
5//
6//===----------------------------------------------------------------------===//
7
Chris Lattner580f9be2002-12-28 20:40:43 +00008#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattnerb74e83c2002-12-16 16:15:28 +00009#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnerff863ba2002-12-25 05:05:46 +000010#include "llvm/CodeGen/SSARegMap.h"
Chris Lattner580f9be2002-12-28 20:40:43 +000011#include "llvm/CodeGen/FunctionFrameInfo.h"
Chris Lattnerb74e83c2002-12-16 16:15:28 +000012#include "llvm/Target/MachineInstrInfo.h"
13#include "llvm/Target/TargetMachine.h"
14#include "Support/Statistic.h"
Chris Lattner82bee0f2002-12-18 08:14:26 +000015#include "Support/CommandLine.h"
Chris Lattnerb74e83c2002-12-16 16:15:28 +000016#include <iostream>
Chris Lattnerff863ba2002-12-25 05:05:46 +000017#include <set>
Chris Lattnerb74e83c2002-12-16 16:15:28 +000018
Chris Lattnerb74e83c2002-12-16 16:15:28 +000019namespace {
20 Statistic<> NumSpilled ("ra-local", "Number of registers spilled");
21 Statistic<> NumReloaded("ra-local", "Number of registers reloaded");
Chris Lattner82bee0f2002-12-18 08:14:26 +000022 cl::opt<bool> DisableKill("no-kill", cl::Hidden,
23 cl::desc("Disable register kill in local-ra"));
Chris Lattnerb74e83c2002-12-16 16:15:28 +000024
Chris Lattner580f9be2002-12-28 20:40:43 +000025 class RA : public MachineFunctionPass {
26 const TargetMachine *TM;
Chris Lattnerb74e83c2002-12-16 16:15:28 +000027 MachineFunction *MF;
Chris Lattner580f9be2002-12-28 20:40:43 +000028 const MRegisterInfo *RegInfo;
Chris Lattnerff863ba2002-12-25 05:05:46 +000029
Chris Lattner580f9be2002-12-28 20:40:43 +000030 // StackSlotForVirtReg - Maps SSA Regs => frame index where these values are
31 // spilled
32 std::map<unsigned, int> StackSlotForVirtReg;
Chris Lattnerb74e83c2002-12-16 16:15:28 +000033
34 // Virt2PhysRegMap - This map contains entries for each virtual register
35 // that is currently available in a physical register.
36 //
37 std::map<unsigned, unsigned> Virt2PhysRegMap;
38
39 // PhysRegsUsed - This map contains entries for each physical register that
40 // currently has a value (ie, it is in Virt2PhysRegMap). The value mapped
41 // to is the virtual register corresponding to the physical register (the
42 // inverse of the Virt2PhysRegMap), or 0. The value is set to 0 if this
43 // register is pinned because it is used by a future instruction.
44 //
45 std::map<unsigned, unsigned> PhysRegsUsed;
46
47 // PhysRegsUseOrder - This contains a list of the physical registers that
48 // currently have a virtual register value in them. This list provides an
49 // ordering of registers, imposing a reallocation order. This list is only
50 // used if all registers are allocated and we have to spill one, in which
51 // case we spill the least recently used register. Entries at the front of
52 // the list are the least recently used registers, entries at the back are
53 // the most recently used.
54 //
55 std::vector<unsigned> PhysRegsUseOrder;
56
Chris Lattner82bee0f2002-12-18 08:14:26 +000057 // LastUserOf map - This multimap contains the set of registers that each
58 // key instruction is the last user of. If an instruction has an entry in
59 // this map, that means that the specified operands are killed after the
60 // instruction is executed, thus they don't need to be spilled into memory
61 //
62 std::multimap<MachineInstr*, unsigned> LastUserOf;
63
Chris Lattnerb74e83c2002-12-16 16:15:28 +000064 void MarkPhysRegRecentlyUsed(unsigned Reg) {
Chris Lattner82bee0f2002-12-18 08:14:26 +000065 assert(!PhysRegsUseOrder.empty() && "No registers used!");
Chris Lattner0eb172c2002-12-24 00:04:55 +000066 if (PhysRegsUseOrder.back() == Reg) return; // Already most recently used
67
68 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
69 if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
70 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
71 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
72 // Add it to the end of the list
73 PhysRegsUseOrder.push_back(RegMatch);
74 if (RegMatch == Reg)
75 return; // Found an exact match, exit early
76 }
Chris Lattnerb74e83c2002-12-16 16:15:28 +000077 }
78
79 public:
Chris Lattnerb74e83c2002-12-16 16:15:28 +000080 virtual const char *getPassName() const {
81 return "Local Register Allocator";
82 }
83
84 private:
85 /// runOnMachineFunction - Register allocate the whole function
86 bool runOnMachineFunction(MachineFunction &Fn);
87
88 /// AllocateBasicBlock - Register allocate the specified basic block.
89 void AllocateBasicBlock(MachineBasicBlock &MBB);
90
91 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
92 /// in predecessor basic blocks.
93 void EliminatePHINodes(MachineBasicBlock &MBB);
94
Chris Lattner82bee0f2002-12-18 08:14:26 +000095 /// CalculateLastUseOfVReg - Calculate an approximation of the killing
96 /// uses for the virtual registers in the function. Here we try to capture
97 /// registers that are defined and only used within the same basic block.
98 /// Because we don't have use-def chains yet, we have to do this the hard
99 /// way.
100 ///
101 void CalculateLastUseOfVReg(MachineBasicBlock &MBB,
102 std::map<unsigned, MachineInstr*> &LastUseOfVReg) const;
103
104
Chris Lattner82bee0f2002-12-18 08:14:26 +0000105 /// areRegsEqual - This method returns true if the specified registers are
106 /// related to each other. To do this, it checks to see if they are equal
107 /// or if the first register is in the alias set of the second register.
108 ///
109 bool areRegsEqual(unsigned R1, unsigned R2) const {
110 if (R1 == R2) return true;
Chris Lattner580f9be2002-12-28 20:40:43 +0000111 if (const unsigned *AliasSet = RegInfo->getAliasSet(R2))
Chris Lattner82bee0f2002-12-18 08:14:26 +0000112 for (unsigned i = 0; AliasSet[i]; ++i)
113 if (AliasSet[i] == R1) return true;
114 return false;
115 }
116
Chris Lattner580f9be2002-12-28 20:40:43 +0000117 /// getStackSpaceFor - This returns the frame index of the specified virtual
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000118 /// register on the stack, allocating space if neccesary.
Chris Lattner580f9be2002-12-28 20:40:43 +0000119 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000120
Chris Lattner82bee0f2002-12-18 08:14:26 +0000121 void removePhysReg(unsigned PhysReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000122
123 /// spillVirtReg - This method spills the value specified by PhysReg into
124 /// the virtual register slot specified by VirtReg. It then updates the RA
125 /// data structures to indicate the fact that PhysReg is now available.
126 ///
127 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
128 unsigned VirtReg, unsigned PhysReg);
129
Chris Lattnerc21be922002-12-16 17:44:42 +0000130 /// spillPhysReg - This method spills the specified physical register into
131 /// the virtual register slot associated with it.
132 //
133 void spillPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
134 unsigned PhysReg) {
Chris Lattnerae640432002-12-17 02:50:10 +0000135 std::map<unsigned, unsigned>::iterator PI = PhysRegsUsed.find(PhysReg);
Chris Lattner0eb172c2002-12-24 00:04:55 +0000136 if (PI != PhysRegsUsed.end()) { // Only spill it if it's used!
Chris Lattnerae640432002-12-17 02:50:10 +0000137 spillVirtReg(MBB, I, PI->second, PhysReg);
Chris Lattner580f9be2002-12-28 20:40:43 +0000138 } else if (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg)) {
Chris Lattner0eb172c2002-12-24 00:04:55 +0000139 // If the selected register aliases any other registers, we must make
140 // sure that one of the aliases isn't alive...
Chris Lattner82bee0f2002-12-18 08:14:26 +0000141 for (unsigned i = 0; AliasSet[i]; ++i) {
142 PI = PhysRegsUsed.find(AliasSet[i]);
143 if (PI != PhysRegsUsed.end()) // Spill aliased register...
144 spillVirtReg(MBB, I, PI->second, AliasSet[i]);
145 }
146 }
Chris Lattnerc21be922002-12-16 17:44:42 +0000147 }
148
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000149 void AssignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
150
Chris Lattnerae640432002-12-17 02:50:10 +0000151 /// isPhysRegAvailable - Return true if the specified physical register is
152 /// free and available for use. This also includes checking to see if
153 /// aliased registers are all free...
154 ///
Chris Lattner82bee0f2002-12-18 08:14:26 +0000155 bool isPhysRegAvailable(unsigned PhysReg) const;
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000156
157 /// getFreeReg - Find a physical register to hold the specified virtual
158 /// register. If all compatible physical registers are used, this method
159 /// spills the last used virtual register to the stack, and uses that
160 /// register.
161 ///
162 unsigned getFreeReg(MachineBasicBlock &MBB,
163 MachineBasicBlock::iterator &I,
164 unsigned virtualReg);
165
166 /// reloadVirtReg - This method loads the specified virtual register into a
167 /// physical register, returning the physical register chosen. This updates
168 /// the regalloc data structures to reflect the fact that the virtual reg is
169 /// now alive in a physical register, and the previous one isn't.
170 ///
171 unsigned reloadVirtReg(MachineBasicBlock &MBB,
172 MachineBasicBlock::iterator &I, unsigned VirtReg);
173 };
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000174}
175
Chris Lattnerae640432002-12-17 02:50:10 +0000176
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000177/// getStackSpaceFor - This allocates space for the specified virtual
178/// register to be held on the stack.
Chris Lattner580f9be2002-12-28 20:40:43 +0000179int RA::getStackSpaceFor(unsigned VirtReg,
180 const TargetRegisterClass *RC) {
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000181 // Find the location VirtReg would belong...
Chris Lattner580f9be2002-12-28 20:40:43 +0000182 std::map<unsigned, int>::iterator I =
183 StackSlotForVirtReg.lower_bound(VirtReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000184
Chris Lattner580f9be2002-12-28 20:40:43 +0000185 if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000186 return I->second; // Already has space allocated?
187
Chris Lattner580f9be2002-12-28 20:40:43 +0000188 // Allocate a new stack object for this spill location...
189 int FrameIdx =
190 MF->getFrameInfo()->CreateStackObject(RC->getSize(), RC->getAlignment());
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000191
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000192 // Assign the slot...
Chris Lattner580f9be2002-12-28 20:40:43 +0000193 StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
194 return FrameIdx;
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000195}
196
Chris Lattnerae640432002-12-17 02:50:10 +0000197
Chris Lattner82bee0f2002-12-18 08:14:26 +0000198/// removePhysReg - This method marks the specified physical register as no
199/// longer being in use.
200///
201void RA::removePhysReg(unsigned PhysReg) {
202 PhysRegsUsed.erase(PhysReg); // PhyReg no longer used
203
204 std::vector<unsigned>::iterator It =
205 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
206 assert(It != PhysRegsUseOrder.end() &&
207 "Spilled a physical register, but it was not in use list!");
208 PhysRegsUseOrder.erase(It);
209}
210
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000211/// spillVirtReg - This method spills the value specified by PhysReg into the
212/// virtual register slot specified by VirtReg. It then updates the RA data
213/// structures to indicate the fact that PhysReg is now available.
214///
215void RA::spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
216 unsigned VirtReg, unsigned PhysReg) {
217 // If this is just a marker register, we don't need to spill it.
218 if (VirtReg != 0) {
Chris Lattnerff863ba2002-12-25 05:05:46 +0000219 const TargetRegisterClass *RegClass =
220 MF->getSSARegMap()->getRegClass(VirtReg);
Chris Lattner580f9be2002-12-28 20:40:43 +0000221 int FrameIndex = getStackSpaceFor(VirtReg, RegClass);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000222
223 // Add move instruction(s)
Chris Lattner580f9be2002-12-28 20:40:43 +0000224 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RegClass);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000225 ++NumSpilled; // Update statistics
226 Virt2PhysRegMap.erase(VirtReg); // VirtReg no longer available
227 }
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000228
Chris Lattner82bee0f2002-12-18 08:14:26 +0000229 removePhysReg(PhysReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000230}
231
Chris Lattnerae640432002-12-17 02:50:10 +0000232
233/// isPhysRegAvailable - Return true if the specified physical register is free
234/// and available for use. This also includes checking to see if aliased
235/// registers are all free...
236///
237bool RA::isPhysRegAvailable(unsigned PhysReg) const {
238 if (PhysRegsUsed.count(PhysReg)) return false;
239
240 // If the selected register aliases any other allocated registers, it is
241 // not free!
Chris Lattner580f9be2002-12-28 20:40:43 +0000242 if (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg))
Chris Lattnerae640432002-12-17 02:50:10 +0000243 for (unsigned i = 0; AliasSet[i]; ++i)
244 if (PhysRegsUsed.count(AliasSet[i])) // Aliased register in use?
245 return false; // Can't use this reg then.
246 return true;
247}
248
249
250
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000251/// getFreeReg - Find a physical register to hold the specified virtual
252/// register. If all compatible physical registers are used, this method spills
253/// the last used virtual register to the stack, and uses that register.
254///
255unsigned RA::getFreeReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
256 unsigned VirtReg) {
Chris Lattner580f9be2002-12-28 20:40:43 +0000257 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
258
259 // Get iterators defining the range of registers that are valid to allocate in
260 // this class, which also specifies the preferred allocation order.
261 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
262 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
Chris Lattnerae640432002-12-17 02:50:10 +0000263
264 // First check to see if we have a free register of the requested type...
Chris Lattner580f9be2002-12-28 20:40:43 +0000265 unsigned PhysReg = 0;
266 for (; RI != RE; ++RI) {
267 unsigned R = *RI;
Chris Lattnerae640432002-12-17 02:50:10 +0000268 if (isPhysRegAvailable(R)) { // Is reg unused?
Chris Lattner580f9be2002-12-28 20:40:43 +0000269 // Found an unused register!
270 PhysReg = R;
271 assert(PhysReg != 0 && "Cannot use register!");
272 break;
Chris Lattnerae640432002-12-17 02:50:10 +0000273 }
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000274 }
275
Chris Lattnerae640432002-12-17 02:50:10 +0000276 // If we didn't find an unused register, scavenge one now!
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000277 if (PhysReg == 0) {
Chris Lattnerc21be922002-12-16 17:44:42 +0000278 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
Chris Lattnerae640432002-12-17 02:50:10 +0000279
280 // Loop over all of the preallocated registers from the least recently used
281 // to the most recently used. When we find one that is capable of holding
282 // our register, use it.
283 for (unsigned i = 0; PhysReg == 0; ++i) {
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000284 assert(i != PhysRegsUseOrder.size() &&
285 "Couldn't find a register of the appropriate class!");
Chris Lattnerae640432002-12-17 02:50:10 +0000286
287 unsigned R = PhysRegsUseOrder[i];
288 // If the current register is compatible, use it.
Chris Lattner580f9be2002-12-28 20:40:43 +0000289 if (RegInfo->getRegClass(R) == RC) {
290 PhysReg = R;
291 break;
292 } else {
293 // If one of the registers aliased to the current register is
294 // compatible, use it.
295 if (const unsigned *AliasSet = RegInfo->getAliasSet(R))
296 for (unsigned a = 0; AliasSet[a]; ++a)
297 if (RegInfo->getRegClass(AliasSet[a]) == RC) {
298 PhysReg = AliasSet[a]; // Take an aliased register
299 break;
300 }
Chris Lattnerae640432002-12-17 02:50:10 +0000301 }
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000302 }
303
Chris Lattnerae640432002-12-17 02:50:10 +0000304 assert(PhysReg && "Physical register not assigned!?!?");
305
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000306 // At this point PhysRegsUseOrder[i] is the least recently used register of
307 // compatible register class. Spill it to memory and reap its remains.
Chris Lattnerc21be922002-12-16 17:44:42 +0000308 spillPhysReg(MBB, I, PhysReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000309 }
310
311 // Now that we know which register we need to assign this to, do it now!
312 AssignVirtToPhysReg(VirtReg, PhysReg);
313 return PhysReg;
314}
315
Chris Lattnerae640432002-12-17 02:50:10 +0000316
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000317void RA::AssignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
318 assert(PhysRegsUsed.find(PhysReg) == PhysRegsUsed.end() &&
319 "Phys reg already assigned!");
320 // Update information to note the fact that this register was just used, and
321 // it holds VirtReg.
322 PhysRegsUsed[PhysReg] = VirtReg;
323 Virt2PhysRegMap[VirtReg] = PhysReg;
324 PhysRegsUseOrder.push_back(PhysReg); // New use of PhysReg
325}
326
327
328/// reloadVirtReg - This method loads the specified virtual register into a
329/// physical register, returning the physical register chosen. This updates the
330/// regalloc data structures to reflect the fact that the virtual reg is now
331/// alive in a physical register, and the previous one isn't.
332///
333unsigned RA::reloadVirtReg(MachineBasicBlock &MBB,
334 MachineBasicBlock::iterator &I,
335 unsigned VirtReg) {
336 std::map<unsigned, unsigned>::iterator It = Virt2PhysRegMap.find(VirtReg);
337 if (It != Virt2PhysRegMap.end()) {
338 MarkPhysRegRecentlyUsed(It->second);
339 return It->second; // Already have this value available!
340 }
341
342 unsigned PhysReg = getFreeReg(MBB, I, VirtReg);
343
Chris Lattnerff863ba2002-12-25 05:05:46 +0000344 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
Chris Lattner580f9be2002-12-28 20:40:43 +0000345 int FrameIndex = getStackSpaceFor(VirtReg, RC);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000346
347 // Add move instruction(s)
Chris Lattner580f9be2002-12-28 20:40:43 +0000348 RegInfo->loadRegFromStackSlot(MBB, I, PhysReg, FrameIndex, RC);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000349 ++NumReloaded; // Update statistics
350 return PhysReg;
351}
352
Chris Lattner82bee0f2002-12-18 08:14:26 +0000353/// CalculateLastUseOfVReg - Calculate an approximation of the killing uses for
354/// the virtual registers in the function. Here we try to capture registers
355/// that are defined and only used within the same basic block. Because we
356/// don't have use-def chains yet, we have to do this the hard way.
357///
358void RA::CalculateLastUseOfVReg(MachineBasicBlock &MBB,
359 std::map<unsigned, MachineInstr*> &LastUseOfVReg) const {
360 // Calculate the last machine instruction in this basic block that uses the
361 // specified virtual register defined in this basic block.
362 std::map<unsigned, MachineInstr*> LastLocalUses;
363
364 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;++I){
365 MachineInstr *MI = *I;
366 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
367 MachineOperand &Op = MI->getOperand(i);
368 if (Op.isVirtualRegister()) {
369 if (Op.opIsDef()) { // Definition of a new virtual reg?
370 LastLocalUses[Op.getAllocatedRegNum()] = 0; // Record it
371 } else { // Use of a virtual reg.
372 std::map<unsigned, MachineInstr*>::iterator It =
373 LastLocalUses.find(Op.getAllocatedRegNum());
374 if (It != LastLocalUses.end()) // Local use?
375 It->second = MI; // Update last use
376 else
377 LastUseOfVReg[Op.getAllocatedRegNum()] = 0;
378 }
379 }
380 }
381 }
382
383 // Move local uses over... if there are any uses of a local already in the
384 // lastuse map, the newly inserted entry is ignored.
385 LastUseOfVReg.insert(LastLocalUses.begin(), LastLocalUses.end());
386}
387
Chris Lattnerae640432002-12-17 02:50:10 +0000388
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000389/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
390/// predecessor basic blocks.
391///
392void RA::EliminatePHINodes(MachineBasicBlock &MBB) {
Chris Lattner580f9be2002-12-28 20:40:43 +0000393 const MachineInstrInfo &MII = TM->getInstrInfo();
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000394
395 while (MBB.front()->getOpcode() == MachineInstrInfo::PHI) {
396 MachineInstr *MI = MBB.front();
397 // Unlink the PHI node from the basic block... but don't delete the PHI yet
398 MBB.erase(MBB.begin());
399
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000400 assert(MI->getOperand(0).isVirtualRegister() &&
401 "PHI node doesn't write virt reg?");
402
403 unsigned virtualReg = MI->getOperand(0).getAllocatedRegNum();
404
405 for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
406 MachineOperand &opVal = MI->getOperand(i-1);
407
408 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
409 // source path the phi
410 MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
411
412 // Check to make sure we haven't already emitted the copy for this block.
413 // This can happen because PHI nodes may have multiple entries for the
414 // same basic block. It doesn't matter which entry we use though, because
415 // all incoming values are guaranteed to be the same for a particular bb.
416 //
417 // Note that this is N^2 in the number of phi node entries, but since the
418 // # of entries is tiny, this is not a problem.
419 //
420 bool HaveNotEmitted = true;
421 for (int op = MI->getNumOperands() - 1; op != i; op -= 2)
422 if (&opBlock == MI->getOperand(op).getMachineBasicBlock()) {
423 HaveNotEmitted = false;
424 break;
425 }
426
427 if (HaveNotEmitted) {
428 MachineBasicBlock::iterator opI = opBlock.end();
429 MachineInstr *opMI = *--opI;
430
431 // must backtrack over ALL the branches in the previous block
432 while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
433 opMI = *--opI;
434
435 // move back to the first branch instruction so new instructions
436 // are inserted right in front of it and not in front of a non-branch
437 if (!MII.isBranch(opMI->getOpcode()))
438 ++opI;
439
Chris Lattnerff863ba2002-12-25 05:05:46 +0000440 const TargetRegisterClass *RC =
441 MF->getSSARegMap()->getRegClass(virtualReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000442
Chris Lattner580f9be2002-12-28 20:40:43 +0000443 assert(opVal.isVirtualRegister() &&
444 "Machine PHI Operands must all be virtual registers!");
445 RegInfo->copyRegToReg(opBlock, opI, virtualReg, opVal.getReg(), RC);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000446 }
447 }
448
449 // really delete the PHI instruction now!
450 delete MI;
451 }
452}
453
Chris Lattnerae640432002-12-17 02:50:10 +0000454
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000455void RA::AllocateBasicBlock(MachineBasicBlock &MBB) {
456 // loop over each instruction
457 MachineBasicBlock::iterator I = MBB.begin();
458 for (; I != MBB.end(); ++I) {
459 MachineInstr *MI = *I;
Chris Lattner580f9be2002-12-28 20:40:43 +0000460 const MachineInstrDescriptor &MID = TM->getInstrInfo().get(MI->getOpcode());
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000461
462 // Loop over all of the operands of the instruction, spilling registers that
463 // are defined, and marking explicit destinations in the PhysRegsUsed map.
Chris Lattner0eb172c2002-12-24 00:04:55 +0000464
465 // FIXME: We don't need to spill a register if this is the last use of the
466 // value!
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000467 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
468 if (MI->getOperand(i).opIsDef() &&
469 MI->getOperand(i).isPhysicalRegister()) {
Chris Lattnerae640432002-12-17 02:50:10 +0000470 unsigned Reg = MI->getOperand(i).getAllocatedRegNum();
471 spillPhysReg(MBB, I, Reg);
Chris Lattner0eb172c2002-12-24 00:04:55 +0000472 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000473 PhysRegsUseOrder.push_back(Reg);
474 }
475
Chris Lattnerae640432002-12-17 02:50:10 +0000476 // Loop over the implicit defs, spilling them, as above.
477 if (const unsigned *ImplicitDefs = MID.ImplicitDefs)
478 for (unsigned i = 0; ImplicitDefs[i]; ++i) {
479 unsigned Reg = ImplicitDefs[i];
Chris Lattner82bee0f2002-12-18 08:14:26 +0000480
481 // We don't want to spill implicit definitions if they were explicitly
482 // chosen. For this reason, check to see now if the register we are
483 // to spill has a vreg of 0.
Chris Lattner0eb172c2002-12-24 00:04:55 +0000484 if (PhysRegsUsed.count(Reg) && PhysRegsUsed[Reg] != 0)
Chris Lattner82bee0f2002-12-18 08:14:26 +0000485 spillPhysReg(MBB, I, Reg);
Chris Lattner0eb172c2002-12-24 00:04:55 +0000486 else if (PhysRegsUsed.count(Reg)) {
487 // Remove the entry from PhysRegsUseOrder to avoid having two entries!
488 removePhysReg(Reg);
489 }
490 PhysRegsUseOrder.push_back(Reg);
Chris Lattnerff863ba2002-12-25 05:05:46 +0000491 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Chris Lattnerae640432002-12-17 02:50:10 +0000492 }
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000493
Chris Lattnerae640432002-12-17 02:50:10 +0000494 // Loop over the implicit uses, making sure that they are at the head of the
495 // use order list, so they don't get reallocated.
496 if (const unsigned *ImplicitUses = MID.ImplicitUses)
497 for (unsigned i = 0; ImplicitUses[i]; ++i)
498 MarkPhysRegRecentlyUsed(ImplicitUses[i]);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000499
500 // Loop over all of the operands again, getting the used operands into
Chris Lattner0eb172c2002-12-24 00:04:55 +0000501 // registers. This has the potiential to spill incoming values if we are
502 // out of registers.
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000503 //
504 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
505 if (MI->getOperand(i).opIsUse() &&
506 MI->getOperand(i).isVirtualRegister()) {
507 unsigned VirtSrcReg = MI->getOperand(i).getAllocatedRegNum();
508 unsigned PhysSrcReg = reloadVirtReg(MBB, I, VirtSrcReg);
509 MI->SetMachineOperandReg(i, PhysSrcReg); // Assign the input register
510 }
511
512 // Okay, we have allocated all of the source operands and spilled any values
513 // that would be destroyed by defs of this instruction. Loop over the
514 // implicit defs and assign them to a register, spilling the incoming value
515 // if we need to scavange a register.
Chris Lattner82bee0f2002-12-18 08:14:26 +0000516 //
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000517 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
518 if (MI->getOperand(i).opIsDef() &&
519 !MI->getOperand(i).isPhysicalRegister()) {
520 unsigned DestVirtReg = MI->getOperand(i).getAllocatedRegNum();
521 unsigned DestPhysReg;
522
Chris Lattner580f9be2002-12-28 20:40:43 +0000523 if (TM->getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000524 // must be same register number as the first operand
525 // This maps a = b + c into b += c, and saves b into a's spot
526 assert(MI->getOperand(1).isRegister() &&
527 MI->getOperand(1).getAllocatedRegNum() &&
528 MI->getOperand(1).opIsUse() &&
529 "Two address instruction invalid!");
530 DestPhysReg = MI->getOperand(1).getAllocatedRegNum();
531
532 // Spill the incoming value, because we are about to change the
533 // register contents.
Chris Lattnerc21be922002-12-16 17:44:42 +0000534 spillPhysReg(MBB, I, DestPhysReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000535 AssignVirtToPhysReg(DestVirtReg, DestPhysReg);
536 } else {
537 DestPhysReg = getFreeReg(MBB, I, DestVirtReg);
538 }
539 MI->SetMachineOperandReg(i, DestPhysReg); // Assign the output register
540 }
Chris Lattner82bee0f2002-12-18 08:14:26 +0000541
542 if (!DisableKill) {
Chris Lattner0eb172c2002-12-24 00:04:55 +0000543 // If this instruction is the last user of anything in registers, kill the
544 // value, freeing the register being used, so it doesn't need to be
545 // spilled to memory at the end of the block.
Chris Lattner82bee0f2002-12-18 08:14:26 +0000546 std::multimap<MachineInstr*, unsigned>::iterator LUOI =
547 LastUserOf.lower_bound(MI);
Chris Lattner0eb172c2002-12-24 00:04:55 +0000548 for (; LUOI != LastUserOf.end() && LUOI->first == MI; ++MI) {
549 unsigned VirtReg = LUOI->second; // entry found?
Chris Lattner82bee0f2002-12-18 08:14:26 +0000550 unsigned PhysReg = Virt2PhysRegMap[VirtReg];
551 if (PhysReg) {
Chris Lattner0eb172c2002-12-24 00:04:55 +0000552 DEBUG(std::cout << "V: " << VirtReg << " P: " << PhysReg
553 << " Last use of: " << *MI);
Chris Lattner82bee0f2002-12-18 08:14:26 +0000554 removePhysReg(PhysReg);
555 }
556 Virt2PhysRegMap.erase(VirtReg);
557 }
558 }
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000559 }
560
561 // Rewind the iterator to point to the first flow control instruction...
Chris Lattner580f9be2002-12-28 20:40:43 +0000562 const MachineInstrInfo &MII = TM->getInstrInfo();
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000563 I = MBB.end();
564 do {
565 --I;
566 } while ((MII.isReturn((*I)->getOpcode()) ||
567 MII.isBranch((*I)->getOpcode())) && I != MBB.begin());
568
569 if (!MII.isReturn((*I)->getOpcode()) && !MII.isBranch((*I)->getOpcode()))
570 ++I;
571
572 // Spill all physical registers holding virtual registers now.
573 while (!PhysRegsUsed.empty())
574 spillVirtReg(MBB, I, PhysRegsUsed.begin()->second,
575 PhysRegsUsed.begin()->first);
576
577 assert(Virt2PhysRegMap.empty() && "Virtual registers still in phys regs?");
578 assert(PhysRegsUseOrder.empty() && "Physical regs still allocated?");
579}
580
Chris Lattner86c69a62002-12-17 03:16:10 +0000581
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000582/// runOnMachineFunction - Register allocate the whole function
583///
584bool RA::runOnMachineFunction(MachineFunction &Fn) {
585 DEBUG(std::cerr << "Machine Function " << "\n");
586 MF = &Fn;
Chris Lattner580f9be2002-12-28 20:40:43 +0000587 TM = &Fn.getTarget();
588 RegInfo = TM->getRegisterInfo();
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000589
590 // First pass: eliminate PHI instructions by inserting copies into predecessor
Chris Lattner82bee0f2002-12-18 08:14:26 +0000591 // blocks, and calculate a simple approximation of killing uses for virtual
592 // registers.
593 //
594 std::map<unsigned, MachineInstr*> LastUseOfVReg;
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000595 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Chris Lattnere7d361d2002-12-17 04:19:40 +0000596 MBB != MBBe; ++MBB) {
Chris Lattner82bee0f2002-12-18 08:14:26 +0000597 if (!DisableKill)
598 CalculateLastUseOfVReg(*MBB, LastUseOfVReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000599 EliminatePHINodes(*MBB);
Chris Lattnere7d361d2002-12-17 04:19:40 +0000600 }
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000601
Chris Lattner82bee0f2002-12-18 08:14:26 +0000602 // At this point LastUseOfVReg has been filled in to contain the last
603 // MachineInstr user of the specified virtual register, if that user is
604 // within the same basic block as the definition (otherwise it contains
605 // null). Invert this mapping now:
606 if (!DisableKill)
607 for (std::map<unsigned, MachineInstr*>::iterator I = LastUseOfVReg.begin(),
608 E = LastUseOfVReg.end(); I != E; ++I)
609 if (I->second)
610 LastUserOf.insert(std::make_pair(I->second, I->first));
611
612 // We're done with the temporary list now.
613 LastUseOfVReg.clear();
614
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000615 // Loop over all of the basic blocks, eliminating virtual register references
616 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
617 MBB != MBBe; ++MBB)
618 AllocateBasicBlock(*MBB);
619
Chris Lattner82bee0f2002-12-18 08:14:26 +0000620 LastUserOf.clear();
Chris Lattner580f9be2002-12-28 20:40:43 +0000621 StackSlotForVirtReg.clear();
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000622 return true;
623}
624
Chris Lattner580f9be2002-12-28 20:40:43 +0000625Pass *createLocalRegisterAllocator() {
626 return new RA();
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000627}