blob: 251d175ea6f7b18b9808cbfbbe7f312b4c0a6884 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This register allocator allocates registers to a basic block at a time,
11// attempting to keep values in registers and reusing registers as appropriate.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
16#include "llvm/BasicBlock.h"
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/CodeGen/MachineInstr.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000020#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner1b989192007-12-31 04:13:23 +000021#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/CodeGen/LiveVariables.h"
23#include "llvm/CodeGen/RegAllocRegistry.h"
24#include "llvm/Target/TargetInstrInfo.h"
25#include "llvm/Target/TargetMachine.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/Compiler.h"
29#include "llvm/ADT/IndexedMap.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include <algorithm>
33using namespace llvm;
34
35STATISTIC(NumStores, "Number of stores added");
36STATISTIC(NumLoads , "Number of loads added");
37STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
38
39namespace {
40 static RegisterRegAlloc
41 localRegAlloc("local", " local register allocator",
42 createLocalRegisterAllocator);
43
44
45 class VISIBILITY_HIDDEN RALocal : public MachineFunctionPass {
46 public:
47 static char ID;
48 RALocal() : MachineFunctionPass((intptr_t)&ID) {}
49 private:
50 const TargetMachine *TM;
51 MachineFunction *MF;
Chris Lattner1b989192007-12-31 04:13:23 +000052 const MRegisterInfo *MRI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053 LiveVariables *LV;
54
55 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
56 // values are spilled.
57 std::map<unsigned, int> StackSlotForVirtReg;
58
59 // Virt2PhysRegMap - This map contains entries for each virtual register
60 // that is currently available in a physical register.
61 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
62
63 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
64 return Virt2PhysRegMap[VirtReg];
65 }
66
67 // PhysRegsUsed - This array is effectively a map, containing entries for
68 // each physical register that currently has a value (ie, it is in
69 // Virt2PhysRegMap). The value mapped to is the virtual register
70 // corresponding to the physical register (the inverse of the
71 // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
72 // because it is used by a future instruction, and to -2 if it is not
73 // allocatable. If the entry for a physical register is -1, then the
74 // physical register is "not in the map".
75 //
76 std::vector<int> PhysRegsUsed;
77
78 // PhysRegsUseOrder - This contains a list of the physical registers that
79 // currently have a virtual register value in them. This list provides an
80 // ordering of registers, imposing a reallocation order. This list is only
81 // used if all registers are allocated and we have to spill one, in which
82 // case we spill the least recently used register. Entries at the front of
83 // the list are the least recently used registers, entries at the back are
84 // the most recently used.
85 //
86 std::vector<unsigned> PhysRegsUseOrder;
87
88 // VirtRegModified - This bitset contains information about which virtual
89 // registers need to be spilled back to memory when their registers are
90 // scavenged. If a virtual register has simply been rematerialized, there
91 // is no reason to spill it to memory when we need the register back.
92 //
93 std::vector<bool> VirtRegModified;
94
95 void markVirtRegModified(unsigned Reg, bool Val = true) {
96 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
97 Reg -= MRegisterInfo::FirstVirtualRegister;
98 if (VirtRegModified.size() <= Reg) VirtRegModified.resize(Reg+1);
99 VirtRegModified[Reg] = Val;
100 }
101
102 bool isVirtRegModified(unsigned Reg) const {
103 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
104 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
105 && "Illegal virtual register!");
106 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
107 }
108
109 void AddToPhysRegsUseOrder(unsigned Reg) {
110 std::vector<unsigned>::iterator It =
111 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg);
112 if (It != PhysRegsUseOrder.end())
113 PhysRegsUseOrder.erase(It);
114 PhysRegsUseOrder.push_back(Reg);
115 }
116
117 void MarkPhysRegRecentlyUsed(unsigned Reg) {
118 if (PhysRegsUseOrder.empty() ||
119 PhysRegsUseOrder.back() == Reg) return; // Already most recently used
120
121 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
122 if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
123 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
124 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
125 // Add it to the end of the list
126 PhysRegsUseOrder.push_back(RegMatch);
127 if (RegMatch == Reg)
128 return; // Found an exact match, exit early
129 }
130 }
131
132 public:
133 virtual const char *getPassName() const {
134 return "Local Register Allocator";
135 }
136
137 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
138 AU.addRequired<LiveVariables>();
139 AU.addRequiredID(PHIEliminationID);
140 AU.addRequiredID(TwoAddressInstructionPassID);
141 MachineFunctionPass::getAnalysisUsage(AU);
142 }
143
144 private:
145 /// runOnMachineFunction - Register allocate the whole function
146 bool runOnMachineFunction(MachineFunction &Fn);
147
148 /// AllocateBasicBlock - Register allocate the specified basic block.
149 void AllocateBasicBlock(MachineBasicBlock &MBB);
150
151
152 /// areRegsEqual - This method returns true if the specified registers are
153 /// related to each other. To do this, it checks to see if they are equal
154 /// or if the first register is in the alias set of the second register.
155 ///
156 bool areRegsEqual(unsigned R1, unsigned R2) const {
157 if (R1 == R2) return true;
Chris Lattner1b989192007-12-31 04:13:23 +0000158 for (const unsigned *AliasSet = MRI->getAliasSet(R2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 *AliasSet; ++AliasSet) {
160 if (*AliasSet == R1) return true;
161 }
162 return false;
163 }
164
165 /// getStackSpaceFor - This returns the frame index of the specified virtual
166 /// register on the stack, allocating space if necessary.
167 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
168
169 /// removePhysReg - This method marks the specified physical register as no
170 /// longer being in use.
171 ///
172 void removePhysReg(unsigned PhysReg);
173
174 /// spillVirtReg - This method spills the value specified by PhysReg into
175 /// the virtual register slot specified by VirtReg. It then updates the RA
176 /// data structures to indicate the fact that PhysReg is now available.
177 ///
178 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
179 unsigned VirtReg, unsigned PhysReg);
180
181 /// spillPhysReg - This method spills the specified physical register into
182 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
183 /// true, then the request is ignored if the physical register does not
184 /// contain a virtual register.
185 ///
186 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
187 unsigned PhysReg, bool OnlyVirtRegs = false);
188
189 /// assignVirtToPhysReg - This method updates local state so that we know
190 /// that PhysReg is the proper container for VirtReg now. The physical
191 /// register must not be used for anything else when this is called.
192 ///
193 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
194
195 /// isPhysRegAvailable - Return true if the specified physical register is
196 /// free and available for use. This also includes checking to see if
197 /// aliased registers are all free...
198 ///
199 bool isPhysRegAvailable(unsigned PhysReg) const;
200
201 /// getFreeReg - Look to see if there is a free register available in the
202 /// specified register class. If not, return 0.
203 ///
204 unsigned getFreeReg(const TargetRegisterClass *RC);
205
206 /// getReg - Find a physical register to hold the specified virtual
207 /// register. If all compatible physical registers are used, this method
208 /// spills the last used virtual register to the stack, and uses that
209 /// register.
210 ///
211 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
212 unsigned VirtReg);
213
214 /// reloadVirtReg - This method transforms the specified specified virtual
215 /// register use to refer to a physical register. This method may do this
216 /// in one of several ways: if the register is available in a physical
217 /// register already, it uses that physical register. If the value is not
218 /// in a physical register, and if there are physical registers available,
219 /// it loads it into a register. If register pressure is high, and it is
220 /// possible, it tries to fold the load of the virtual register into the
221 /// instruction itself. It avoids doing this if register pressure is low to
222 /// improve the chance that subsequent instructions can use the reloaded
223 /// value. This method returns the modified instruction.
224 ///
225 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
226 unsigned OpNum);
227
228
229 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
230 unsigned PhysReg);
231 };
232 char RALocal::ID = 0;
233}
234
235/// getStackSpaceFor - This allocates space for the specified virtual register
236/// to be held on the stack.
237int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
238 // Find the location Reg would belong...
239 std::map<unsigned, int>::iterator I =StackSlotForVirtReg.lower_bound(VirtReg);
240
241 if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
242 return I->second; // Already has space allocated?
243
244 // Allocate a new stack object for this spill location...
245 int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
246 RC->getAlignment());
247
248 // Assign the slot...
249 StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
250 return FrameIdx;
251}
252
253
254/// removePhysReg - This method marks the specified physical register as no
255/// longer being in use.
256///
257void RALocal::removePhysReg(unsigned PhysReg) {
258 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
259
260 std::vector<unsigned>::iterator It =
261 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
262 if (It != PhysRegsUseOrder.end())
263 PhysRegsUseOrder.erase(It);
264}
265
266
267/// spillVirtReg - This method spills the value specified by PhysReg into the
268/// virtual register slot specified by VirtReg. It then updates the RA data
269/// structures to indicate the fact that PhysReg is now available.
270///
271void RALocal::spillVirtReg(MachineBasicBlock &MBB,
272 MachineBasicBlock::iterator I,
273 unsigned VirtReg, unsigned PhysReg) {
274 assert(VirtReg && "Spilling a physical register is illegal!"
275 " Must not have appropriate kill for the register or use exists beyond"
276 " the intended one.");
Chris Lattner1b989192007-12-31 04:13:23 +0000277 DOUT << " Spilling register " << MRI->getName(PhysReg)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 << " containing %reg" << VirtReg;
Owen Anderson81875432008-01-01 21:11:32 +0000279
280 const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
281
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282 if (!isVirtRegModified(VirtReg))
283 DOUT << " which has not been modified, so no store necessary!";
284
285 // Otherwise, there is a virtual register corresponding to this physical
286 // register. We only need to spill it into its stack slot if it has been
287 // modified.
288 if (isVirtRegModified(VirtReg)) {
Chris Lattner1b989192007-12-31 04:13:23 +0000289 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 int FrameIndex = getStackSpaceFor(VirtReg, RC);
291 DOUT << " to stack slot #" << FrameIndex;
Owen Anderson81875432008-01-01 21:11:32 +0000292 TII->storeRegToStackSlot(MBB, I, PhysReg, true, FrameIndex, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293 ++NumStores; // Update statistics
294 }
295
296 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
297
298 DOUT << "\n";
299 removePhysReg(PhysReg);
300}
301
302
303/// spillPhysReg - This method spills the specified physical register into the
304/// virtual register slot associated with it. If OnlyVirtRegs is set to true,
305/// then the request is ignored if the physical register does not contain a
306/// virtual register.
307///
308void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
309 unsigned PhysReg, bool OnlyVirtRegs) {
310 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
311 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
312 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
313 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
314 } else {
315 // If the selected register aliases any other registers, we must make
316 // sure that one of the aliases isn't alive.
Chris Lattner1b989192007-12-31 04:13:23 +0000317 for (const unsigned *AliasSet = MRI->getAliasSet(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 *AliasSet; ++AliasSet)
319 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
320 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
321 if (PhysRegsUsed[*AliasSet])
322 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
323 }
324}
325
326
327/// assignVirtToPhysReg - This method updates local state so that we know
328/// that PhysReg is the proper container for VirtReg now. The physical
329/// register must not be used for anything else when this is called.
330///
331void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
332 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
333 // Update information to note the fact that this register was just used, and
334 // it holds VirtReg.
335 PhysRegsUsed[PhysReg] = VirtReg;
336 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
337 AddToPhysRegsUseOrder(PhysReg); // New use of PhysReg
338}
339
340
341/// isPhysRegAvailable - Return true if the specified physical register is free
342/// and available for use. This also includes checking to see if aliased
343/// registers are all free...
344///
345bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
346 if (PhysRegsUsed[PhysReg] != -1) return false;
347
348 // If the selected register aliases any other allocated registers, it is
349 // not free!
Chris Lattner1b989192007-12-31 04:13:23 +0000350 for (const unsigned *AliasSet = MRI->getAliasSet(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351 *AliasSet; ++AliasSet)
352 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
353 return false; // Can't use this reg then.
354 return true;
355}
356
357
358/// getFreeReg - Look to see if there is a free register available in the
359/// specified register class. If not, return 0.
360///
361unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
362 // Get iterators defining the range of registers that are valid to allocate in
363 // this class, which also specifies the preferred allocation order.
364 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
365 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
366
367 for (; RI != RE; ++RI)
368 if (isPhysRegAvailable(*RI)) { // Is reg unused?
369 assert(*RI != 0 && "Cannot use register!");
370 return *RI; // Found an unused register!
371 }
372 return 0;
373}
374
375
376/// getReg - Find a physical register to hold the specified virtual
377/// register. If all compatible physical registers are used, this method spills
378/// the last used virtual register to the stack, and uses that register.
379///
380unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
381 unsigned VirtReg) {
Chris Lattner1b989192007-12-31 04:13:23 +0000382 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383
384 // First check to see if we have a free register of the requested type...
385 unsigned PhysReg = getFreeReg(RC);
386
387 // If we didn't find an unused register, scavenge one now!
388 if (PhysReg == 0) {
389 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
390
391 // Loop over all of the preallocated registers from the least recently used
392 // to the most recently used. When we find one that is capable of holding
393 // our register, use it.
394 for (unsigned i = 0; PhysReg == 0; ++i) {
395 assert(i != PhysRegsUseOrder.size() &&
396 "Couldn't find a register of the appropriate class!");
397
398 unsigned R = PhysRegsUseOrder[i];
399
400 // We can only use this register if it holds a virtual register (ie, it
401 // can be spilled). Do not use it if it is an explicitly allocated
402 // physical register!
403 assert(PhysRegsUsed[R] != -1 &&
404 "PhysReg in PhysRegsUseOrder, but is not allocated?");
405 if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
406 // If the current register is compatible, use it.
407 if (RC->contains(R)) {
408 PhysReg = R;
409 break;
410 } else {
411 // If one of the registers aliased to the current register is
412 // compatible, use it.
Chris Lattner1b989192007-12-31 04:13:23 +0000413 for (const unsigned *AliasIt = MRI->getAliasSet(R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 *AliasIt; ++AliasIt) {
415 if (RC->contains(*AliasIt) &&
416 // If this is pinned down for some reason, don't use it. For
417 // example, if CL is pinned, and we run across CH, don't use
418 // CH as justification for using scavenging ECX (which will
419 // fail).
420 PhysRegsUsed[*AliasIt] != 0 &&
421
422 // Make sure the register is allocatable. Don't allocate SIL on
423 // x86-32.
424 PhysRegsUsed[*AliasIt] != -2) {
425 PhysReg = *AliasIt; // Take an aliased register
426 break;
427 }
428 }
429 }
430 }
431 }
432
433 assert(PhysReg && "Physical register not assigned!?!?");
434
435 // At this point PhysRegsUseOrder[i] is the least recently used register of
436 // compatible register class. Spill it to memory and reap its remains.
437 spillPhysReg(MBB, I, PhysReg);
438 }
439
440 // Now that we know which register we need to assign this to, do it now!
441 assignVirtToPhysReg(VirtReg, PhysReg);
442 return PhysReg;
443}
444
445
446/// reloadVirtReg - This method transforms the specified specified virtual
447/// register use to refer to a physical register. This method may do this in
448/// one of several ways: if the register is available in a physical register
449/// already, it uses that physical register. If the value is not in a physical
450/// register, and if there are physical registers available, it loads it into a
451/// register. If register pressure is high, and it is possible, it tries to
452/// fold the load of the virtual register into the instruction itself. It
453/// avoids doing this if register pressure is low to improve the chance that
454/// subsequent instructions can use the reloaded value. This method returns the
455/// modified instruction.
456///
457MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
458 unsigned OpNum) {
459 unsigned VirtReg = MI->getOperand(OpNum).getReg();
460
461 // If the virtual register is already available, just update the instruction
462 // and return.
463 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
464 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
465 MI->getOperand(OpNum).setReg(PR); // Assign the input register
466 return MI;
467 }
468
469 // Otherwise, we need to fold it into the current instruction, or reload it.
470 // If we have registers available to hold the value, use them.
Chris Lattner1b989192007-12-31 04:13:23 +0000471 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000472 unsigned PhysReg = getFreeReg(RC);
473 int FrameIndex = getStackSpaceFor(VirtReg, RC);
474
475 if (PhysReg) { // Register is available, allocate it!
476 assignVirtToPhysReg(VirtReg, PhysReg);
477 } else { // No registers available.
478 // If we can fold this spill into this instruction, do so now.
Evan Chengfd0bd3c2007-12-02 08:30:39 +0000479 SmallVector<unsigned, 2> Ops;
480 Ops.push_back(OpNum);
Chris Lattner1b989192007-12-31 04:13:23 +0000481 if (MachineInstr* FMI = MRI->foldMemoryOperand(MI, Ops, FrameIndex)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000482 ++NumFolded;
483 // Since we changed the address of MI, make sure to update live variables
484 // to know that the new instruction has the properties of the old one.
485 LV->instructionChanged(MI, FMI);
486 return MBB.insert(MBB.erase(MI), FMI);
487 }
488
489 // It looks like we can't fold this virtual register load into this
490 // instruction. Force some poor hapless value out of the register file to
491 // make room for the new register, and reload it.
492 PhysReg = getReg(MBB, MI, VirtReg);
493 }
494
495 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
496
497 DOUT << " Reloading %reg" << VirtReg << " into "
Chris Lattner1b989192007-12-31 04:13:23 +0000498 << MRI->getName(PhysReg) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000499
500 // Add move instruction(s)
Owen Anderson81875432008-01-01 21:11:32 +0000501 const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
502 TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503 ++NumLoads; // Update statistics
504
Chris Lattner1b989192007-12-31 04:13:23 +0000505 MF->getRegInfo().setPhysRegUsed(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
507 return MI;
508}
509
510/// isReadModWriteImplicitKill - True if this is an implicit kill for a
511/// read/mod/write register, i.e. update partial register.
512static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
513 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
514 MachineOperand& MO = MI->getOperand(i);
515 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
516 MO.isDef() && !MO.isDead())
517 return true;
518 }
519 return false;
520}
521
522/// isReadModWriteImplicitDef - True if this is an implicit def for a
523/// read/mod/write register, i.e. update partial register.
524static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
525 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
526 MachineOperand& MO = MI->getOperand(i);
527 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
528 !MO.isDef() && MO.isKill())
529 return true;
530 }
531 return false;
532}
533
534void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
535 // loop over each instruction
536 MachineBasicBlock::iterator MII = MBB.begin();
537 const TargetInstrInfo &TII = *TM->getInstrInfo();
538
539 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
540 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
541
542 // If this is the first basic block in the machine function, add live-in
543 // registers as active.
544 if (&MBB == &*MF->begin()) {
Chris Lattner1b989192007-12-31 04:13:23 +0000545 for (MachineRegisterInfo::livein_iterator I=MF->getRegInfo().livein_begin(),
546 E = MF->getRegInfo().livein_end(); I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 unsigned Reg = I->first;
Chris Lattner1b989192007-12-31 04:13:23 +0000548 MF->getRegInfo().setPhysRegUsed(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549 PhysRegsUsed[Reg] = 0; // It is free and reserved now
550 AddToPhysRegsUseOrder(Reg);
Chris Lattner1b989192007-12-31 04:13:23 +0000551 for (const unsigned *AliasSet = MRI->getSubRegisters(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552 *AliasSet; ++AliasSet) {
553 if (PhysRegsUsed[*AliasSet] != -2) {
554 AddToPhysRegsUseOrder(*AliasSet);
555 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
Chris Lattner1b989192007-12-31 04:13:23 +0000556 MF->getRegInfo().setPhysRegUsed(*AliasSet);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000557 }
558 }
559 }
560 }
561
562 // Otherwise, sequentially allocate each instruction in the MBB.
563 while (MII != MBB.end()) {
564 MachineInstr *MI = MII++;
565 const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
566 DEBUG(DOUT << "\nStarting RegAlloc of: " << *MI;
567 DOUT << " Regs have values: ";
Chris Lattner1b989192007-12-31 04:13:23 +0000568 for (unsigned i = 0; i != MRI->getNumRegs(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
Chris Lattner1b989192007-12-31 04:13:23 +0000570 DOUT << "[" << MRI->getName(i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000571 << ",%reg" << PhysRegsUsed[i] << "] ";
572 DOUT << "\n");
573
574 // Loop over the implicit uses, making sure that they are at the head of the
575 // use order list, so they don't get reallocated.
576 if (TID.ImplicitUses) {
577 for (const unsigned *ImplicitUses = TID.ImplicitUses;
578 *ImplicitUses; ++ImplicitUses)
579 MarkPhysRegRecentlyUsed(*ImplicitUses);
580 }
581
582 SmallVector<unsigned, 8> Kills;
583 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
584 MachineOperand& MO = MI->getOperand(i);
585 if (MO.isRegister() && MO.isKill()) {
586 if (!MO.isImplicit())
587 Kills.push_back(MO.getReg());
588 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
589 // These are extra physical register kills when a sub-register
590 // is defined (def of a sub-register is a read/mod/write of the
591 // larger registers). Ignore.
592 Kills.push_back(MO.getReg());
593 }
594 }
595
596 // Get the used operands into registers. This has the potential to spill
597 // incoming values if we are out of registers. Note that we completely
598 // ignore physical register uses here. We assume that if an explicit
599 // physical register is referenced by the instruction, that it is guaranteed
600 // to be live-in, or the input is badly hosed.
601 //
602 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
603 MachineOperand& MO = MI->getOperand(i);
604 // here we are looking for only used operands (never def&use)
605 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
606 MRegisterInfo::isVirtualRegister(MO.getReg()))
607 MI = reloadVirtReg(MBB, MI, i);
608 }
609
610 // If this instruction is the last user of this register, kill the
611 // value, freeing the register being used, so it doesn't need to be
612 // spilled to memory.
613 //
614 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
615 unsigned VirtReg = Kills[i];
616 unsigned PhysReg = VirtReg;
617 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
618 // If the virtual register was never materialized into a register, it
619 // might not be in the map, but it won't hurt to zero it out anyway.
620 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
621 PhysReg = PhysRegSlot;
622 PhysRegSlot = 0;
623 } else if (PhysRegsUsed[PhysReg] == -2) {
624 // Unallocatable register dead, ignore.
625 continue;
626 } else {
Evan Cheng358d8dd2007-10-22 19:42:28 +0000627 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 "Silently clearing a virtual register?");
629 }
630
631 if (PhysReg) {
Chris Lattner1b989192007-12-31 04:13:23 +0000632 DOUT << " Last use of " << MRI->getName(PhysReg)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633 << "[%reg" << VirtReg <<"], removing it from live set\n";
634 removePhysReg(PhysReg);
Chris Lattner1b989192007-12-31 04:13:23 +0000635 for (const unsigned *AliasSet = MRI->getSubRegisters(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636 *AliasSet; ++AliasSet) {
637 if (PhysRegsUsed[*AliasSet] != -2) {
638 DOUT << " Last use of "
Chris Lattner1b989192007-12-31 04:13:23 +0000639 << MRI->getName(*AliasSet)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 << "[%reg" << VirtReg <<"], removing it from live set\n";
641 removePhysReg(*AliasSet);
642 }
643 }
644 }
645 }
646
647 // Loop over all of the operands of the instruction, spilling registers that
648 // are defined, and marking explicit destinations in the PhysRegsUsed map.
649 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
650 MachineOperand& MO = MI->getOperand(i);
651 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
652 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
653 unsigned Reg = MO.getReg();
654 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
655 // These are extra physical register defs when a sub-register
656 // is defined (def of a sub-register is a read/mod/write of the
657 // larger registers). Ignore.
658 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
659
Chris Lattner1b989192007-12-31 04:13:23 +0000660 MF->getRegInfo().setPhysRegUsed(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
662 PhysRegsUsed[Reg] = 0; // It is free and reserved now
663 AddToPhysRegsUseOrder(Reg);
664
Chris Lattner1b989192007-12-31 04:13:23 +0000665 for (const unsigned *AliasSet = MRI->getSubRegisters(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666 *AliasSet; ++AliasSet) {
667 if (PhysRegsUsed[*AliasSet] != -2) {
Chris Lattner1b989192007-12-31 04:13:23 +0000668 MF->getRegInfo().setPhysRegUsed(*AliasSet);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
670 AddToPhysRegsUseOrder(*AliasSet);
671 }
672 }
673 }
674 }
675
676 // Loop over the implicit defs, spilling them as well.
677 if (TID.ImplicitDefs) {
678 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
679 *ImplicitDefs; ++ImplicitDefs) {
680 unsigned Reg = *ImplicitDefs;
681 if (PhysRegsUsed[Reg] != -2) {
682 spillPhysReg(MBB, MI, Reg, true);
683 AddToPhysRegsUseOrder(Reg);
684 PhysRegsUsed[Reg] = 0; // It is free and reserved now
685 }
Chris Lattner1b989192007-12-31 04:13:23 +0000686 MF->getRegInfo().setPhysRegUsed(Reg);
687 for (const unsigned *AliasSet = MRI->getSubRegisters(Reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688 *AliasSet; ++AliasSet) {
689 if (PhysRegsUsed[*AliasSet] != -2) {
690 AddToPhysRegsUseOrder(*AliasSet);
691 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
Chris Lattner1b989192007-12-31 04:13:23 +0000692 MF->getRegInfo().setPhysRegUsed(*AliasSet);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693 }
694 }
695 }
696 }
697
698 SmallVector<unsigned, 8> DeadDefs;
699 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
700 MachineOperand& MO = MI->getOperand(i);
701 if (MO.isRegister() && MO.isDead())
702 DeadDefs.push_back(MO.getReg());
703 }
704
705 // Okay, we have allocated all of the source operands and spilled any values
706 // that would be destroyed by defs of this instruction. Loop over the
707 // explicit defs and assign them to a register, spilling incoming values if
708 // we need to scavenge a register.
709 //
710 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
711 MachineOperand& MO = MI->getOperand(i);
712 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
713 MRegisterInfo::isVirtualRegister(MO.getReg())) {
714 unsigned DestVirtReg = MO.getReg();
715 unsigned DestPhysReg;
716
717 // If DestVirtReg already has a value, use it.
718 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
719 DestPhysReg = getReg(MBB, MI, DestVirtReg);
Chris Lattner1b989192007-12-31 04:13:23 +0000720 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 markVirtRegModified(DestVirtReg);
722 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
723 }
724 }
725
726 // If this instruction defines any registers that are immediately dead,
727 // kill them now.
728 //
729 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
730 unsigned VirtReg = DeadDefs[i];
731 unsigned PhysReg = VirtReg;
732 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
733 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
734 PhysReg = PhysRegSlot;
735 assert(PhysReg != 0);
736 PhysRegSlot = 0;
737 } else if (PhysRegsUsed[PhysReg] == -2) {
738 // Unallocatable register dead, ignore.
739 continue;
740 }
741
742 if (PhysReg) {
Chris Lattner1b989192007-12-31 04:13:23 +0000743 DOUT << " Register " << MRI->getName(PhysReg)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000744 << " [%reg" << VirtReg
745 << "] is never used, removing it frame live list\n";
746 removePhysReg(PhysReg);
Chris Lattner1b989192007-12-31 04:13:23 +0000747 for (const unsigned *AliasSet = MRI->getAliasSet(PhysReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000748 *AliasSet; ++AliasSet) {
749 if (PhysRegsUsed[*AliasSet] != -2) {
Chris Lattner1b989192007-12-31 04:13:23 +0000750 DOUT << " Register " << MRI->getName(*AliasSet)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 << " [%reg" << *AliasSet
752 << "] is never used, removing it frame live list\n";
753 removePhysReg(*AliasSet);
754 }
755 }
756 }
757 }
758
759 // Finally, if this is a noop copy instruction, zap it.
760 unsigned SrcReg, DstReg;
761 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
762 LV->removeVirtualRegistersKilled(MI);
763 LV->removeVirtualRegistersDead(MI);
764 MBB.erase(MI);
765 }
766 }
767
768 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
769
770 // Spill all physical registers holding virtual registers now.
Chris Lattner1b989192007-12-31 04:13:23 +0000771 for (unsigned i = 0, e = MRI->getNumRegs(); i != e; ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
773 if (unsigned VirtReg = PhysRegsUsed[i])
774 spillVirtReg(MBB, MI, VirtReg, i);
775 else
776 removePhysReg(i);
777
778#if 0
779 // This checking code is very expensive.
780 bool AllOk = true;
781 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
Chris Lattner1b989192007-12-31 04:13:23 +0000782 e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783 if (unsigned PR = Virt2PhysRegMap[i]) {
784 cerr << "Register still mapped: " << i << " -> " << PR << "\n";
785 AllOk = false;
786 }
787 assert(AllOk && "Virtual registers still in phys regs?");
788#endif
789
790 // Clear any physical register which appear live at the end of the basic
791 // block, but which do not hold any virtual registers. e.g., the stack
792 // pointer.
793 PhysRegsUseOrder.clear();
794}
795
796
797/// runOnMachineFunction - Register allocate the whole function
798///
799bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
800 DOUT << "Machine Function " << "\n";
801 MF = &Fn;
802 TM = &Fn.getTarget();
Chris Lattner1b989192007-12-31 04:13:23 +0000803 MRI = TM->getRegisterInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804 LV = &getAnalysis<LiveVariables>();
805
Chris Lattner1b989192007-12-31 04:13:23 +0000806 PhysRegsUsed.assign(MRI->getNumRegs(), -1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807
808 // At various places we want to efficiently check to see whether a register
809 // is allocatable. To handle this, we mark all unallocatable registers as
810 // being pinned down, permanently.
811 {
Chris Lattner1b989192007-12-31 04:13:23 +0000812 BitVector Allocable = MRI->getAllocatableSet(Fn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
814 if (!Allocable[i])
815 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
816 }
817
818 // initialize the virtual->physical register map to have a 'null'
819 // mapping for all virtual registers
Chris Lattner1b989192007-12-31 04:13:23 +0000820 Virt2PhysRegMap.grow(MF->getRegInfo().getLastVirtReg());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821
822 // Loop over all of the basic blocks, eliminating virtual register references
823 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
824 MBB != MBBe; ++MBB)
825 AllocateBasicBlock(*MBB);
826
827 StackSlotForVirtReg.clear();
828 PhysRegsUsed.clear();
829 VirtRegModified.clear();
830 Virt2PhysRegMap.clear();
831 return true;
832}
833
834FunctionPass *llvm::createLocalRegisterAllocator() {
835 return new RALocal();
836}