blob: 398fc97307b0402b7f7c1712a2e8d49a5e866e4c [file] [log] [blame]
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001//===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
Alkis Evlogimenos4de473b2004-02-13 18:20:47 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Alkis Evlogimenos4de473b2004-02-13 18:20:47 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerb74e83c2002-12-16 16:15:28 +00009//
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
Chris Lattner4cc662b2003-08-03 21:47:31 +000015#define DEBUG_TYPE "regalloc"
Evan Chengddee8422006-11-15 20:55:15 +000016#include "llvm/BasicBlock.h"
Chris Lattner580f9be2002-12-28 20:40:43 +000017#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattnerb74e83c2002-12-16 16:15:28 +000018#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnereb24db92002-12-28 21:08:26 +000019#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000020#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Cheng22ff3ee2008-02-06 08:00:32 +000021#include "llvm/CodeGen/Passes.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000022#include "llvm/CodeGen/RegAllocRegistry.h"
Chris Lattner3501fea2003-01-14 22:00:31 +000023#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerb74e83c2002-12-16 16:15:28 +000024#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000027#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/raw_ostream.h"
Owen Anderson743a1e62008-07-10 01:56:35 +000029#include "llvm/ADT/DenseMap.h"
Chris Lattner94c002a2007-02-01 05:32:05 +000030#include "llvm/ADT/IndexedMap.h"
Evan Cheng5a3c6a82009-01-29 02:20:59 +000031#include "llvm/ADT/SmallSet.h"
Evan Chengddee8422006-11-15 20:55:15 +000032#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/Statistic.h"
Evan Cheng2fc628d2008-02-06 19:16:53 +000034#include "llvm/ADT/STLExtras.h"
Chris Lattner27f29162004-10-26 15:35:58 +000035#include <algorithm>
Chris Lattneref09c632004-01-31 21:27:19 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Chris Lattnercd3245a2006-12-19 22:41:21 +000038STATISTIC(NumStores, "Number of stores added");
39STATISTIC(NumLoads , "Number of loads added");
Jim Laskey13ec7022006-08-01 14:21:23 +000040
Dan Gohman844731a2008-05-13 00:00:25 +000041static RegisterRegAlloc
Dan Gohmanb8cab922008-10-14 20:25:08 +000042 localRegAlloc("local", "local register allocator",
Dan Gohman844731a2008-05-13 00:00:25 +000043 createLocalRegisterAllocator);
44
Chris Lattnercd3245a2006-12-19 22:41:21 +000045namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000046 class RALocal : public MachineFunctionPass {
Devang Patel794fd752007-05-01 21:15:47 +000047 public:
Devang Patel19974732007-05-03 01:11:54 +000048 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +000049 RALocal() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1) {}
Devang Patel794fd752007-05-01 21:15:47 +000050 private:
Chris Lattner580f9be2002-12-28 20:40:43 +000051 const TargetMachine *TM;
Chris Lattnerb74e83c2002-12-16 16:15:28 +000052 MachineFunction *MF;
Dan Gohman6f0d0242008-02-10 18:45:23 +000053 const TargetRegisterInfo *TRI;
Owen Anderson6425f8b2008-01-07 01:35:56 +000054 const TargetInstrInfo *TII;
Chris Lattnerff863ba2002-12-25 05:05:46 +000055
Chris Lattnerb8822ad2003-08-04 23:36:39 +000056 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
57 // values are spilled.
Evan Chengbdb10fe2008-07-10 18:23:23 +000058 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
Chris Lattnerb74e83c2002-12-16 16:15:28 +000059
60 // Virt2PhysRegMap - This map contains entries for each virtual register
Alkis Evlogimenos4d0d8642004-02-25 21:55:45 +000061 // that is currently available in a physical register.
Chris Lattner94c002a2007-02-01 05:32:05 +000062 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
Chris Lattnerecea5632004-02-09 02:12:04 +000063
64 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
Alkis Evlogimenos4d0d8642004-02-25 21:55:45 +000065 return Virt2PhysRegMap[VirtReg];
Chris Lattnerecea5632004-02-09 02:12:04 +000066 }
Alkis Evlogimenos4de473b2004-02-13 18:20:47 +000067
Chris Lattner64667b62004-02-09 01:26:13 +000068 // PhysRegsUsed - This array is effectively a map, containing entries for
69 // each physical register that currently has a value (ie, it is in
70 // Virt2PhysRegMap). The value mapped to is the virtual register
71 // corresponding to the physical register (the inverse of the
72 // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
Chris Lattner45d57882006-09-08 19:03:30 +000073 // because it is used by a future instruction, and to -2 if it is not
74 // allocatable. If the entry for a physical register is -1, then the
75 // physical register is "not in the map".
Chris Lattnerb74e83c2002-12-16 16:15:28 +000076 //
Alkis Evlogimenos4de473b2004-02-13 18:20:47 +000077 std::vector<int> PhysRegsUsed;
Chris Lattnerb74e83c2002-12-16 16:15:28 +000078
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +000079 // PhysRegsUseOrder - This contains a list of the physical registers that
80 // currently have a virtual register value in them. This list provides an
81 // ordering of registers, imposing a reallocation order. This list is only
82 // used if all registers are allocated and we have to spill one, in which
83 // case we spill the least recently used register. Entries at the front of
84 // the list are the least recently used registers, entries at the back are
85 // the most recently used.
Chris Lattnerb74e83c2002-12-16 16:15:28 +000086 //
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +000087 std::vector<unsigned> PhysRegsUseOrder;
Chris Lattnerb74e83c2002-12-16 16:15:28 +000088
Evan Cheng839b7592008-01-17 02:08:17 +000089 // Virt2LastUseMap - This maps each virtual register to its last use
90 // (MachineInstr*, operand index pair).
91 IndexedMap<std::pair<MachineInstr*, unsigned>, VirtReg2IndexFunctor>
92 Virt2LastUseMap;
93
94 std::pair<MachineInstr*,unsigned>& getVirtRegLastUse(unsigned Reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +000095 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
Evan Cheng839b7592008-01-17 02:08:17 +000096 return Virt2LastUseMap[Reg];
97 }
98
Chris Lattner91a452b2003-01-13 00:25:40 +000099 // VirtRegModified - This bitset contains information about which virtual
100 // registers need to be spilled back to memory when their registers are
101 // scavenged. If a virtual register has simply been rematerialized, there
102 // is no reason to spill it to memory when we need the register back.
Chris Lattner82bee0f2002-12-18 08:14:26 +0000103 //
Evan Cheng644340a2008-01-17 00:35:26 +0000104 BitVector VirtRegModified;
Owen Anderson491fccc2008-07-08 22:24:50 +0000105
106 // UsedInMultipleBlocks - Tracks whether a particular register is used in
107 // more than one block.
108 BitVector UsedInMultipleBlocks;
Chris Lattner91a452b2003-01-13 00:25:40 +0000109
110 void markVirtRegModified(unsigned Reg, bool Val = true) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000111 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
112 Reg -= TargetRegisterInfo::FirstVirtualRegister;
Evan Cheng644340a2008-01-17 00:35:26 +0000113 if (Val)
114 VirtRegModified.set(Reg);
115 else
116 VirtRegModified.reset(Reg);
Chris Lattner91a452b2003-01-13 00:25:40 +0000117 }
118
119 bool isVirtRegModified(unsigned Reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000120 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
Chris Lattner4dd81632010-03-31 05:15:22 +0000121 assert(Reg - TargetRegisterInfo::FirstVirtualRegister <
122 VirtRegModified.size() && "Illegal virtual register!");
Dan Gohman6f0d0242008-02-10 18:45:23 +0000123 return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
Chris Lattner91a452b2003-01-13 00:25:40 +0000124 }
Chris Lattner82bee0f2002-12-18 08:14:26 +0000125
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000126 void AddToPhysRegsUseOrder(unsigned Reg) {
127 std::vector<unsigned>::iterator It =
128 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg);
129 if (It != PhysRegsUseOrder.end())
130 PhysRegsUseOrder.erase(It);
131 PhysRegsUseOrder.push_back(Reg);
132 }
133
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000134 void MarkPhysRegRecentlyUsed(unsigned Reg) {
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000135 if (PhysRegsUseOrder.empty() ||
136 PhysRegsUseOrder.back() == Reg) return; // Already most recently used
137
138 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i) {
139 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
140 if (!areRegsEqual(Reg, RegMatch)) continue;
141
142 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
143 // Add it to the end of the list
144 PhysRegsUseOrder.push_back(RegMatch);
145 if (RegMatch == Reg)
146 return; // Found an exact match, exit early
147 }
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000148 }
149
150 public:
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000151 virtual const char *getPassName() const {
152 return "Local Register Allocator";
153 }
154
Chris Lattner91a452b2003-01-13 00:25:40 +0000155 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000156 AU.setPreservesCFG();
Chris Lattner91a452b2003-01-13 00:25:40 +0000157 AU.addRequiredID(PHIEliminationID);
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000158 AU.addRequiredID(TwoAddressInstructionPassID);
Chris Lattner91a452b2003-01-13 00:25:40 +0000159 MachineFunctionPass::getAnalysisUsage(AU);
160 }
161
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000162 private:
163 /// runOnMachineFunction - Register allocate the whole function
164 bool runOnMachineFunction(MachineFunction &Fn);
165
166 /// AllocateBasicBlock - Register allocate the specified basic block.
167 void AllocateBasicBlock(MachineBasicBlock &MBB);
168
Chris Lattner82bee0f2002-12-18 08:14:26 +0000169
Chris Lattner82bee0f2002-12-18 08:14:26 +0000170 /// areRegsEqual - This method returns true if the specified registers are
171 /// related to each other. To do this, it checks to see if they are equal
172 /// or if the first register is in the alias set of the second register.
173 ///
174 bool areRegsEqual(unsigned R1, unsigned R2) const {
175 if (R1 == R2) return true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000176 for (const unsigned *AliasSet = TRI->getAliasSet(R2);
Alkis Evlogimenos73ff5122003-10-08 05:20:08 +0000177 *AliasSet; ++AliasSet) {
178 if (*AliasSet == R1) return true;
179 }
Chris Lattner82bee0f2002-12-18 08:14:26 +0000180 return false;
181 }
182
Chris Lattner580f9be2002-12-28 20:40:43 +0000183 /// getStackSpaceFor - This returns the frame index of the specified virtual
Chris Lattnerb8822ad2003-08-04 23:36:39 +0000184 /// register on the stack, allocating space if necessary.
Chris Lattner580f9be2002-12-28 20:40:43 +0000185 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000186
Chris Lattnerb8822ad2003-08-04 23:36:39 +0000187 /// removePhysReg - This method marks the specified physical register as no
188 /// longer being in use.
189 ///
Chris Lattner82bee0f2002-12-18 08:14:26 +0000190 void removePhysReg(unsigned PhysReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000191
Jakob Stoklund Olesen8387d7d2010-04-30 21:19:29 +0000192 void storeVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
193 unsigned VirtReg, unsigned PhysReg, bool isKill);
194
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000195 /// spillVirtReg - This method spills the value specified by PhysReg into
196 /// the virtual register slot specified by VirtReg. It then updates the RA
197 /// data structures to indicate the fact that PhysReg is now available.
198 ///
Chris Lattner688c8252004-02-22 19:08:15 +0000199 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000200 unsigned VirtReg, unsigned PhysReg);
201
Chris Lattnerc21be922002-12-16 17:44:42 +0000202 /// spillPhysReg - This method spills the specified physical register into
Chris Lattner128c2aa2003-08-17 18:01:15 +0000203 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
204 /// true, then the request is ignored if the physical register does not
205 /// contain a virtual register.
Chris Lattner91a452b2003-01-13 00:25:40 +0000206 ///
Chris Lattner42e0a8f2004-02-17 03:57:19 +0000207 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
Chris Lattner128c2aa2003-08-17 18:01:15 +0000208 unsigned PhysReg, bool OnlyVirtRegs = false);
Chris Lattnerc21be922002-12-16 17:44:42 +0000209
Chris Lattner91a452b2003-01-13 00:25:40 +0000210 /// assignVirtToPhysReg - This method updates local state so that we know
211 /// that PhysReg is the proper container for VirtReg now. The physical
212 /// register must not be used for anything else when this is called.
213 ///
214 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
215
Chris Lattnerae640432002-12-17 02:50:10 +0000216 /// isPhysRegAvailable - Return true if the specified physical register is
217 /// free and available for use. This also includes checking to see if
218 /// aliased registers are all free...
219 ///
Chris Lattner82bee0f2002-12-18 08:14:26 +0000220 bool isPhysRegAvailable(unsigned PhysReg) const;
Chris Lattner91a452b2003-01-13 00:25:40 +0000221
222 /// getFreeReg - Look to see if there is a free register available in the
223 /// specified register class. If not, return 0.
224 ///
225 unsigned getFreeReg(const TargetRegisterClass *RC);
Alkis Evlogimenos4de473b2004-02-13 18:20:47 +0000226
Chris Lattner91a452b2003-01-13 00:25:40 +0000227 /// getReg - Find a physical register to hold the specified virtual
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000228 /// register. If all compatible physical registers are used, this method
229 /// spills the last used virtual register to the stack, and uses that
Evan Cheng7ddee0a2009-01-29 01:13:00 +0000230 /// register. If NoFree is true, that means the caller knows there isn't
231 /// a free register, do not call getFreeReg().
Chris Lattner42e0a8f2004-02-17 03:57:19 +0000232 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
Evan Cheng7ddee0a2009-01-29 01:13:00 +0000233 unsigned VirtReg, bool NoFree = false);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000234
Bob Wilsone0f745b2009-05-07 21:19:45 +0000235 /// reloadVirtReg - This method transforms the specified virtual
Chris Lattner42e0a8f2004-02-17 03:57:19 +0000236 /// register use to refer to a physical register. This method may do this
237 /// in one of several ways: if the register is available in a physical
238 /// register already, it uses that physical register. If the value is not
239 /// in a physical register, and if there are physical registers available,
Dale Johannesenfc49bd22009-12-16 00:29:41 +0000240 /// it loads it into a register: PhysReg if that is an available physical
241 /// register, otherwise any physical register of the right class.
242 /// If register pressure is high, and it is possible, it tries to fold the
243 /// load of the virtual register into the instruction itself. It avoids
244 /// doing this if register pressure is low to improve the chance that
245 /// subsequent instructions can use the reloaded value. This method
246 /// returns the modified instruction.
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000247 ///
Chris Lattner42e0a8f2004-02-17 03:57:19 +0000248 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
Dale Johannesenfc49bd22009-12-16 00:29:41 +0000249 unsigned OpNum, SmallSet<unsigned, 4> &RRegs,
250 unsigned PhysReg);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000251
Owen Anderson9094db12008-07-09 20:14:53 +0000252 /// ComputeLocalLiveness - Computes liveness of registers within a basic
253 /// block, setting the killed/dead flags as appropriate.
254 void ComputeLocalLiveness(MachineBasicBlock& MBB);
Chris Lattnerb8822ad2003-08-04 23:36:39 +0000255
256 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
257 unsigned PhysReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000258 };
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000259 char RALocal::ID = 0;
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000260}
261
Chris Lattnerb8822ad2003-08-04 23:36:39 +0000262/// getStackSpaceFor - This allocates space for the specified virtual register
263/// to be held on the stack.
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000264int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
Chris Lattnerb8822ad2003-08-04 23:36:39 +0000265 // Find the location Reg would belong...
Evan Chengbdb10fe2008-07-10 18:23:23 +0000266 int SS = StackSlotForVirtReg[VirtReg];
267 if (SS != -1)
268 return SS; // Already has space allocated?
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000269
Chris Lattner580f9be2002-12-28 20:40:43 +0000270 // Allocate a new stack object for this spill location...
David Greene3f2bf852009-11-12 20:49:22 +0000271 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
272 RC->getAlignment());
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000273
Chris Lattner4dd81632010-03-31 05:15:22 +0000274 // Assign the slot.
Evan Chengbdb10fe2008-07-10 18:23:23 +0000275 StackSlotForVirtReg[VirtReg] = FrameIdx;
Chris Lattner580f9be2002-12-28 20:40:43 +0000276 return FrameIdx;
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000277}
278
Chris Lattnerae640432002-12-17 02:50:10 +0000279
Alkis Evlogimenos4de473b2004-02-13 18:20:47 +0000280/// removePhysReg - This method marks the specified physical register as no
Chris Lattner82bee0f2002-12-18 08:14:26 +0000281/// longer being in use.
282///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000283void RALocal::removePhysReg(unsigned PhysReg) {
Chris Lattner64667b62004-02-09 01:26:13 +0000284 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000285
286 std::vector<unsigned>::iterator It =
287 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
288 if (It != PhysRegsUseOrder.end())
289 PhysRegsUseOrder.erase(It);
Chris Lattner82bee0f2002-12-18 08:14:26 +0000290}
291
Jakob Stoklund Olesen8387d7d2010-04-30 21:19:29 +0000292/// storeVirtReg - Store a virtual register to its assigned stack slot.
293void RALocal::storeVirtReg(MachineBasicBlock &MBB,
294 MachineBasicBlock::iterator I,
295 unsigned VirtReg, unsigned PhysReg,
296 bool isKill) {
297 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
298 int FrameIndex = getStackSpaceFor(VirtReg, RC);
299 DEBUG(dbgs() << " to stack slot #" << FrameIndex);
Evan Cheng746ad692010-05-06 19:06:44 +0000300 TII->storeRegToStackSlot(MBB, I, PhysReg, isKill, FrameIndex, RC, TRI);
Jakob Stoklund Olesen8387d7d2010-04-30 21:19:29 +0000301 ++NumStores; // Update statistics
302}
Chris Lattner91a452b2003-01-13 00:25:40 +0000303
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000304/// spillVirtReg - This method spills the value specified by PhysReg into the
305/// virtual register slot specified by VirtReg. It then updates the RA data
306/// structures to indicate the fact that PhysReg is now available.
307///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000308void RALocal::spillVirtReg(MachineBasicBlock &MBB,
309 MachineBasicBlock::iterator I,
310 unsigned VirtReg, unsigned PhysReg) {
Chris Lattner8c819452003-08-05 04:13:58 +0000311 assert(VirtReg && "Spilling a physical register is illegal!"
Chris Lattnerd9ac6a72003-08-05 00:49:09 +0000312 " Must not have appropriate kill for the register or use exists beyond"
313 " the intended one.");
David Greene44248172010-01-05 01:26:05 +0000314 DEBUG(dbgs() << " Spilling register " << TRI->getName(PhysReg)
Bill Wendlingfbb594f2009-08-22 20:38:09 +0000315 << " containing %reg" << VirtReg);
Owen Andersonf6372aa2008-01-01 21:11:32 +0000316
Evan Cheng839b7592008-01-17 02:08:17 +0000317 if (!isVirtRegModified(VirtReg)) {
David Greene44248172010-01-05 01:26:05 +0000318 DEBUG(dbgs() << " which has not been modified, so no store necessary!");
Evan Cheng839b7592008-01-17 02:08:17 +0000319 std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
320 if (LastUse.first)
321 LastUse.first->getOperand(LastUse.second).setIsKill();
Evan Cheng2fc628d2008-02-06 19:16:53 +0000322 } else {
323 // Otherwise, there is a virtual register corresponding to this physical
324 // register. We only need to spill it into its stack slot if it has been
325 // modified.
Evan Cheng2fc628d2008-02-06 19:16:53 +0000326 // If the instruction reads the register that's spilled, (e.g. this can
327 // happen if it is a move to a physical register), then the spill
328 // instruction is not a kill.
Evan Cheng6130f662008-03-05 00:59:57 +0000329 bool isKill = !(I != MBB.end() && I->readsRegister(PhysReg));
Jakob Stoklund Olesen8387d7d2010-04-30 21:19:29 +0000330 storeVirtReg(MBB, I, VirtReg, PhysReg, isKill);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000331 }
Chris Lattnerecea5632004-02-09 02:12:04 +0000332
333 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000334
David Greene44248172010-01-05 01:26:05 +0000335 DEBUG(dbgs() << '\n');
Chris Lattner82bee0f2002-12-18 08:14:26 +0000336 removePhysReg(PhysReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000337}
338
Chris Lattnerae640432002-12-17 02:50:10 +0000339
Chris Lattner91a452b2003-01-13 00:25:40 +0000340/// spillPhysReg - This method spills the specified physical register into the
Chris Lattner128c2aa2003-08-17 18:01:15 +0000341/// virtual register slot associated with it. If OnlyVirtRegs is set to true,
342/// then the request is ignored if the physical register does not contain a
343/// virtual register.
Chris Lattner91a452b2003-01-13 00:25:40 +0000344///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000345void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
346 unsigned PhysReg, bool OnlyVirtRegs) {
Chris Lattner64667b62004-02-09 01:26:13 +0000347 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
Chris Lattner45d57882006-09-08 19:03:30 +0000348 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
Chris Lattner64667b62004-02-09 01:26:13 +0000349 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
350 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
Chris Lattner4dd81632010-03-31 05:15:22 +0000351 return;
352 }
353
354 // If the selected register aliases any other registers, we must make
355 // sure that one of the aliases isn't alive.
356 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
357 *AliasSet; ++AliasSet) {
358 if (PhysRegsUsed[*AliasSet] == -1 || // Spill aliased register.
359 PhysRegsUsed[*AliasSet] == -2) // If allocatable.
360 continue;
361
362 if (PhysRegsUsed[*AliasSet])
363 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
Chris Lattner91a452b2003-01-13 00:25:40 +0000364 }
365}
366
367
368/// assignVirtToPhysReg - This method updates local state so that we know
369/// that PhysReg is the proper container for VirtReg now. The physical
370/// register must not be used for anything else when this is called.
371///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000372void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
Chris Lattner64667b62004-02-09 01:26:13 +0000373 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
Chris Lattner91a452b2003-01-13 00:25:40 +0000374 // Update information to note the fact that this register was just used, and
375 // it holds VirtReg.
376 PhysRegsUsed[PhysReg] = VirtReg;
Alkis Evlogimenos4de473b2004-02-13 18:20:47 +0000377 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000378 AddToPhysRegsUseOrder(PhysReg); // New use of PhysReg
Chris Lattner91a452b2003-01-13 00:25:40 +0000379}
380
381
Chris Lattnerae640432002-12-17 02:50:10 +0000382/// isPhysRegAvailable - Return true if the specified physical register is free
383/// and available for use. This also includes checking to see if aliased
384/// registers are all free...
385///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000386bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
Chris Lattner64667b62004-02-09 01:26:13 +0000387 if (PhysRegsUsed[PhysReg] != -1) return false;
Chris Lattnerae640432002-12-17 02:50:10 +0000388
389 // If the selected register aliases any other allocated registers, it is
390 // not free!
Dan Gohman6f0d0242008-02-10 18:45:23 +0000391 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
Alkis Evlogimenos73ff5122003-10-08 05:20:08 +0000392 *AliasSet; ++AliasSet)
Evan Chengbcfa1ca2008-02-22 20:30:53 +0000393 if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
Alkis Evlogimenos73ff5122003-10-08 05:20:08 +0000394 return false; // Can't use this reg then.
Chris Lattnerae640432002-12-17 02:50:10 +0000395 return true;
396}
397
398
Chris Lattner91a452b2003-01-13 00:25:40 +0000399/// getFreeReg - Look to see if there is a free register available in the
400/// specified register class. If not, return 0.
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000401///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000402unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
Chris Lattner580f9be2002-12-28 20:40:43 +0000403 // Get iterators defining the range of registers that are valid to allocate in
404 // this class, which also specifies the preferred allocation order.
405 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
406 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
Chris Lattnerae640432002-12-17 02:50:10 +0000407
Chris Lattner91a452b2003-01-13 00:25:40 +0000408 for (; RI != RE; ++RI)
409 if (isPhysRegAvailable(*RI)) { // Is reg unused?
410 assert(*RI != 0 && "Cannot use register!");
411 return *RI; // Found an unused register!
412 }
413 return 0;
414}
415
416
Chris Lattner91a452b2003-01-13 00:25:40 +0000417/// getReg - Find a physical register to hold the specified virtual
418/// register. If all compatible physical registers are used, this method spills
419/// the last used virtual register to the stack, and uses that register.
420///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000421unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
Evan Cheng7ddee0a2009-01-29 01:13:00 +0000422 unsigned VirtReg, bool NoFree) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000423 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Chris Lattner91a452b2003-01-13 00:25:40 +0000424
425 // First check to see if we have a free register of the requested type...
Evan Cheng7ddee0a2009-01-29 01:13:00 +0000426 unsigned PhysReg = NoFree ? 0 : getFreeReg(RC);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000427
Chris Lattner4dd81632010-03-31 05:15:22 +0000428 if (PhysReg != 0) {
429 // Assign the register.
430 assignVirtToPhysReg(VirtReg, PhysReg);
431 return PhysReg;
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000432 }
433
434 // If we didn't find an unused register, scavenge one now!
435 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
Chris Lattnerae640432002-12-17 02:50:10 +0000436
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000437 // Loop over all of the preallocated registers from the least recently used
438 // to the most recently used. When we find one that is capable of holding
439 // our register, use it.
440 for (unsigned i = 0; PhysReg == 0; ++i) {
441 assert(i != PhysRegsUseOrder.size() &&
442 "Couldn't find a register of the appropriate class!");
443
444 unsigned R = PhysRegsUseOrder[i];
445
446 // We can only use this register if it holds a virtual register (ie, it
447 // can be spilled). Do not use it if it is an explicitly allocated
448 // physical register!
449 assert(PhysRegsUsed[R] != -1 &&
450 "PhysReg in PhysRegsUseOrder, but is not allocated?");
451 if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
452 // If the current register is compatible, use it.
453 if (RC->contains(R)) {
454 PhysReg = R;
455 break;
456 }
457
458 // If one of the registers aliased to the current register is
459 // compatible, use it.
460 for (const unsigned *AliasIt = TRI->getAliasSet(R);
461 *AliasIt; ++AliasIt) {
462 if (!RC->contains(*AliasIt)) continue;
463
464 // If this is pinned down for some reason, don't use it. For
465 // example, if CL is pinned, and we run across CH, don't use
466 // CH as justification for using scavenging ECX (which will
467 // fail).
468 if (PhysRegsUsed[*AliasIt] == 0) continue;
469
470 // Make sure the register is allocatable. Don't allocate SIL on
471 // x86-32.
472 if (PhysRegsUsed[*AliasIt] == -2) continue;
473
474 PhysReg = *AliasIt; // Take an aliased register
475 break;
476 }
477 }
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000478 }
479
Chris Lattner4dd81632010-03-31 05:15:22 +0000480 assert(PhysReg && "Physical register not assigned!?!?");
481
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000482 // At this point PhysRegsUseOrder[i] is the least recently used register of
483 // compatible register class. Spill it to memory and reap its remains.
Chris Lattner4dd81632010-03-31 05:15:22 +0000484 spillPhysReg(MBB, I, PhysReg);
485
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000486 // Now that we know which register we need to assign this to, do it now!
Chris Lattner91a452b2003-01-13 00:25:40 +0000487 assignVirtToPhysReg(VirtReg, PhysReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000488 return PhysReg;
489}
490
Chris Lattnerae640432002-12-17 02:50:10 +0000491
Bob Wilson8d24f412009-05-07 21:20:42 +0000492/// reloadVirtReg - This method transforms the specified virtual
Chris Lattner42e0a8f2004-02-17 03:57:19 +0000493/// register use to refer to a physical register. This method may do this in
494/// one of several ways: if the register is available in a physical register
495/// already, it uses that physical register. If the value is not in a physical
496/// register, and if there are physical registers available, it loads it into a
Dale Johannesenfc49bd22009-12-16 00:29:41 +0000497/// register: PhysReg if that is an available physical register, otherwise any
Chris Lattner42e0a8f2004-02-17 03:57:19 +0000498/// register. If register pressure is high, and it is possible, it tries to
499/// fold the load of the virtual register into the instruction itself. It
500/// avoids doing this if register pressure is low to improve the chance that
Dale Johannesenfc49bd22009-12-16 00:29:41 +0000501/// subsequent instructions can use the reloaded value. This method returns
502/// the modified instruction.
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000503///
Bill Wendlinge23e00d2007-05-08 19:02:46 +0000504MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
Evan Cheng5a3c6a82009-01-29 02:20:59 +0000505 unsigned OpNum,
Dale Johannesenfc49bd22009-12-16 00:29:41 +0000506 SmallSet<unsigned, 4> &ReloadedRegs,
507 unsigned PhysReg) {
Chris Lattner42e0a8f2004-02-17 03:57:19 +0000508 unsigned VirtReg = MI->getOperand(OpNum).getReg();
509
510 // If the virtual register is already available, just update the instruction
511 // and return.
Alkis Evlogimenos4de473b2004-02-13 18:20:47 +0000512 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
Chris Lattnere53f4a02006-05-04 17:52:23 +0000513 MI->getOperand(OpNum).setReg(PR); // Assign the input register
Dale Johannesenf463d952010-02-16 01:27:47 +0000514 if (!MI->isDebugValue()) {
515 // Do not do these for DBG_VALUE as they can affect codegen.
516 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
Dale Johannesen3da6e092010-02-15 01:45:47 +0000517 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
Dale Johannesenf463d952010-02-16 01:27:47 +0000518 }
Chris Lattner42e0a8f2004-02-17 03:57:19 +0000519 return MI;
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000520 }
521
Chris Lattner1e3812c2004-02-17 04:08:37 +0000522 // Otherwise, we need to fold it into the current instruction, or reload it.
523 // If we have registers available to hold the value, use them.
Chris Lattner84bc5422007-12-31 04:13:23 +0000524 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
Dale Johannesenfc49bd22009-12-16 00:29:41 +0000525 // If we already have a PhysReg (this happens when the instruction is a
526 // reg-to-reg copy with a PhysReg destination) use that.
527 if (!PhysReg || !TargetRegisterInfo::isPhysicalRegister(PhysReg) ||
528 !isPhysRegAvailable(PhysReg))
529 PhysReg = getFreeReg(RC);
Chris Lattner11390e72004-02-17 08:09:40 +0000530 int FrameIndex = getStackSpaceFor(VirtReg, RC);
Chris Lattner1e3812c2004-02-17 04:08:37 +0000531
Chris Lattner11390e72004-02-17 08:09:40 +0000532 if (PhysReg) { // Register is available, allocate it!
533 assignVirtToPhysReg(VirtReg, PhysReg);
534 } else { // No registers available.
Evan Cheng27240c72008-02-07 19:46:55 +0000535 // Force some poor hapless value out of the register file to
Chris Lattner1e3812c2004-02-17 04:08:37 +0000536 // make room for the new register, and reload it.
Evan Cheng7ddee0a2009-01-29 01:13:00 +0000537 PhysReg = getReg(MBB, MI, VirtReg, true);
Chris Lattner1e3812c2004-02-17 04:08:37 +0000538 }
539
Chris Lattner91a452b2003-01-13 00:25:40 +0000540 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
541
David Greene44248172010-01-05 01:26:05 +0000542 DEBUG(dbgs() << " Reloading %reg" << VirtReg << " into "
Bill Wendlingfbb594f2009-08-22 20:38:09 +0000543 << TRI->getName(PhysReg) << "\n");
Chris Lattnerb8822ad2003-08-04 23:36:39 +0000544
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000545 // Add move instruction(s)
Evan Cheng746ad692010-05-06 19:06:44 +0000546 TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC, TRI);
Alkis Evlogimenos2acef2d2004-02-19 06:19:09 +0000547 ++NumLoads; // Update statistics
Chris Lattner42e0a8f2004-02-17 03:57:19 +0000548
Chris Lattner84bc5422007-12-31 04:13:23 +0000549 MF->getRegInfo().setPhysRegUsed(PhysReg);
Chris Lattnere53f4a02006-05-04 17:52:23 +0000550 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
Evan Cheng839b7592008-01-17 02:08:17 +0000551 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
Evan Cheng5a3c6a82009-01-29 02:20:59 +0000552
553 if (!ReloadedRegs.insert(PhysReg)) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000554 std::string msg;
555 raw_string_ostream Msg(msg);
556 Msg << "Ran out of registers during register allocation!";
Chris Lattner518bb532010-02-09 19:54:29 +0000557 if (MI->isInlineAsm()) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000558 Msg << "\nPlease check your inline asm statement for invalid "
Evan Cheng5a3c6a82009-01-29 02:20:59 +0000559 << "constraints:\n";
Torok Edwin7d696d82009-07-11 13:10:19 +0000560 MI->print(Msg, TM);
Evan Cheng5a3c6a82009-01-29 02:20:59 +0000561 }
Chris Lattner75361b62010-04-07 22:58:41 +0000562 report_fatal_error(Msg.str());
Evan Cheng5a3c6a82009-01-29 02:20:59 +0000563 }
564 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
565 *SubRegs; ++SubRegs) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000566 if (ReloadedRegs.insert(*SubRegs)) continue;
567
568 std::string msg;
569 raw_string_ostream Msg(msg);
570 Msg << "Ran out of registers during register allocation!";
571 if (MI->isInlineAsm()) {
572 Msg << "\nPlease check your inline asm statement for invalid "
573 << "constraints:\n";
574 MI->print(Msg, TM);
Evan Cheng5a3c6a82009-01-29 02:20:59 +0000575 }
Chris Lattner75361b62010-04-07 22:58:41 +0000576 report_fatal_error(Msg.str());
Evan Cheng5a3c6a82009-01-29 02:20:59 +0000577 }
578
Chris Lattner42e0a8f2004-02-17 03:57:19 +0000579 return MI;
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000580}
581
Evan Cheng7ac19af2007-06-26 21:05:13 +0000582/// isReadModWriteImplicitKill - True if this is an implicit kill for a
583/// read/mod/write register, i.e. update partial register.
584static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
585 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000586 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000587 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
Evan Cheng7ac19af2007-06-26 21:05:13 +0000588 MO.isDef() && !MO.isDead())
589 return true;
590 }
591 return false;
592}
Chris Lattnerb8822ad2003-08-04 23:36:39 +0000593
Evan Cheng7ac19af2007-06-26 21:05:13 +0000594/// isReadModWriteImplicitDef - True if this is an implicit def for a
595/// read/mod/write register, i.e. update partial register.
596static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
597 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000598 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000599 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
Evan Cheng7ac19af2007-06-26 21:05:13 +0000600 !MO.isDef() && MO.isKill())
601 return true;
602 }
603 return false;
604}
Chris Lattnerb8822ad2003-08-04 23:36:39 +0000605
Owen Anderson491fccc2008-07-08 22:24:50 +0000606// precedes - Helper function to determine with MachineInstr A
607// precedes MachineInstr B within the same MBB.
608static bool precedes(MachineBasicBlock::iterator A,
609 MachineBasicBlock::iterator B) {
610 if (A == B)
611 return false;
612
613 MachineBasicBlock::iterator I = A->getParent()->begin();
614 while (I != A->getParent()->end()) {
615 if (I == A)
616 return true;
617 else if (I == B)
618 return false;
619
620 ++I;
621 }
622
623 return false;
624}
625
Owen Anderson9094db12008-07-09 20:14:53 +0000626/// ComputeLocalLiveness - Computes liveness of registers within a basic
627/// block, setting the killed/dead flags as appropriate.
628void RALocal::ComputeLocalLiveness(MachineBasicBlock& MBB) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000629 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
Owen Anderson491fccc2008-07-08 22:24:50 +0000630 // Keep track of the most recently seen previous use or def of each reg,
631 // so that we can update them with dead/kill markers.
Owen Anderson743a1e62008-07-10 01:56:35 +0000632 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> > LastUseDef;
Owen Anderson491fccc2008-07-08 22:24:50 +0000633 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
634 I != E; ++I) {
Dale Johannesen3da6e092010-02-15 01:45:47 +0000635 if (I->isDebugValue())
636 continue;
Chris Lattner4dd81632010-03-31 05:15:22 +0000637
Owen Anderson491fccc2008-07-08 22:24:50 +0000638 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000639 MachineOperand &MO = I->getOperand(i);
Owen Anderson491fccc2008-07-08 22:24:50 +0000640 // Uses don't trigger any flags, but we need to save
641 // them for later. Also, we have to process these
642 // _before_ processing the defs, since an instr
643 // uses regs before it defs them.
Chris Lattner4dd81632010-03-31 05:15:22 +0000644 if (!MO.isReg() || !MO.getReg() || !MO.isUse())
645 continue;
Jakob Stoklund Olesena50fba92010-05-03 23:49:20 +0000646
647 // Ignore helpful kill flags from earlier passes.
648 MO.setIsKill(false);
649
Chris Lattner4dd81632010-03-31 05:15:22 +0000650 LastUseDef[MO.getReg()] = std::make_pair(I, i);
651
652 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) continue;
653
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000654 const unsigned *Aliases = TRI->getAliasSet(MO.getReg());
655 if (Aliases == 0)
656 continue;
657
658 while (*Aliases) {
659 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
660 alias = LastUseDef.find(*Aliases);
661
662 if (alias != LastUseDef.end() && alias->second.first != I)
663 LastUseDef[*Aliases] = std::make_pair(I, i);
664
665 ++Aliases;
Owen Anderson04764de2008-10-08 04:30:51 +0000666 }
Owen Anderson491fccc2008-07-08 22:24:50 +0000667 }
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000668
Owen Anderson491fccc2008-07-08 22:24:50 +0000669 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000670 MachineOperand &MO = I->getOperand(i);
Owen Anderson491fccc2008-07-08 22:24:50 +0000671 // Defs others than 2-addr redefs _do_ trigger flag changes:
672 // - A def followed by a def is dead
673 // - A use followed by a def is a kill
Chris Lattner4dd81632010-03-31 05:15:22 +0000674 if (!MO.isReg() || !MO.getReg() || !MO.isDef()) continue;
675
676 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
677 last = LastUseDef.find(MO.getReg());
678 if (last != LastUseDef.end()) {
679 // Check if this is a two address instruction. If so, then
680 // the def does not kill the use.
681 if (last->second.first == I &&
682 I->isRegTiedToUseOperand(i))
683 continue;
Owen Anderson491fccc2008-07-08 22:24:50 +0000684
Chris Lattner4dd81632010-03-31 05:15:22 +0000685 MachineOperand &lastUD =
686 last->second.first->getOperand(last->second.second);
687 if (lastUD.isDef())
688 lastUD.setIsDead(true);
689 else
690 lastUD.setIsKill(true);
Owen Anderson491fccc2008-07-08 22:24:50 +0000691 }
Chris Lattner4dd81632010-03-31 05:15:22 +0000692
693 LastUseDef[MO.getReg()] = std::make_pair(I, i);
Owen Anderson491fccc2008-07-08 22:24:50 +0000694 }
695 }
696
697 // Live-out (of the function) registers contain return values of the function,
698 // so we need to make sure they are alive at return time.
Bill Wendlingb0d27662010-03-16 02:01:51 +0000699 MachineBasicBlock::iterator Ret = MBB.getFirstTerminator();
700 bool BBEndsInReturn = (Ret != MBB.end() && Ret->getDesc().isReturn());
701
702 if (BBEndsInReturn)
Owen Anderson491fccc2008-07-08 22:24:50 +0000703 for (MachineRegisterInfo::liveout_iterator
704 I = MF->getRegInfo().liveout_begin(),
705 E = MF->getRegInfo().liveout_end(); I != E; ++I)
706 if (!Ret->readsRegister(*I)) {
707 Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
708 LastUseDef[*I] = std::make_pair(Ret, Ret->getNumOperands()-1);
709 }
Owen Anderson491fccc2008-07-08 22:24:50 +0000710
711 // Finally, loop over the final use/def of each reg
712 // in the block and determine if it is dead.
Owen Anderson743a1e62008-07-10 01:56:35 +0000713 for (DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
Owen Anderson491fccc2008-07-08 22:24:50 +0000714 I = LastUseDef.begin(), E = LastUseDef.end(); I != E; ++I) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000715 MachineInstr *MI = I->second.first;
Owen Anderson491fccc2008-07-08 22:24:50 +0000716 unsigned idx = I->second.second;
Chris Lattner4dd81632010-03-31 05:15:22 +0000717 MachineOperand &MO = MI->getOperand(idx);
Owen Anderson491fccc2008-07-08 22:24:50 +0000718
719 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(MO.getReg());
720
721 // A crude approximation of "live-out" calculation
722 bool usedOutsideBlock = isPhysReg ? false :
723 UsedInMultipleBlocks.test(MO.getReg() -
724 TargetRegisterInfo::FirstVirtualRegister);
Bill Wendling8fe347a2010-03-16 01:05:35 +0000725
726 // If the machine BB ends in a return instruction, then the value isn't used
727 // outside of the BB.
728 if (!isPhysReg && (!usedOutsideBlock || BBEndsInReturn)) {
Dale Johannesenf463d952010-02-16 01:27:47 +0000729 // DBG_VALUE complicates this: if the only refs of a register outside
730 // this block are DBG_VALUE, we can't keep the reg live just for that,
731 // as it will cause the reg to be spilled at the end of this block when
732 // it wouldn't have been otherwise. Nullify the DBG_VALUEs when that
733 // happens.
734 bool UsedByDebugValueOnly = false;
Owen Anderson491fccc2008-07-08 22:24:50 +0000735 for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
Bill Wendling8fe347a2010-03-16 01:05:35 +0000736 UE = MRI.reg_end(); UI != UE; ++UI) {
Owen Anderson491fccc2008-07-08 22:24:50 +0000737 // Two cases:
738 // - used in another block
739 // - used in the same block before it is defined (loop)
Chris Lattner4dd81632010-03-31 05:15:22 +0000740 if (UI->getParent() == &MBB &&
741 !(MO.isDef() && UI.getOperand().isUse() && precedes(&*UI, MI)))
742 continue;
743
744 if (UI->isDebugValue()) {
745 UsedByDebugValueOnly = true;
746 continue;
Owen Anderson491fccc2008-07-08 22:24:50 +0000747 }
Chris Lattner4dd81632010-03-31 05:15:22 +0000748
749 // A non-DBG_VALUE use means we can leave DBG_VALUE uses alone.
750 UsedInMultipleBlocks.set(MO.getReg() -
751 TargetRegisterInfo::FirstVirtualRegister);
752 usedOutsideBlock = true;
753 UsedByDebugValueOnly = false;
754 break;
Bill Wendling8fe347a2010-03-16 01:05:35 +0000755 }
756
Dale Johannesenf463d952010-02-16 01:27:47 +0000757 if (UsedByDebugValueOnly)
758 for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
759 UE = MRI.reg_end(); UI != UE; ++UI)
760 if (UI->isDebugValue() &&
761 (UI->getParent() != &MBB ||
762 (MO.isDef() && precedes(&*UI, MI))))
763 UI.getOperand().setReg(0U);
764 }
765
Bill Wendling8fe347a2010-03-16 01:05:35 +0000766 // Physical registers and those that are not live-out of the block are
767 // killed/dead at their last use/def within this block.
Dan Gohman15843902010-03-18 18:07:13 +0000768 if (isPhysReg || !usedOutsideBlock || BBEndsInReturn) {
Dan Gohman022b21f2008-10-04 00:31:14 +0000769 if (MO.isUse()) {
770 // Don't mark uses that are tied to defs as kills.
Evan Chenga24752f2009-03-19 20:30:06 +0000771 if (!MI->isRegTiedToDefOperand(idx))
Dan Gohman022b21f2008-10-04 00:31:14 +0000772 MO.setIsKill(true);
Bill Wendling8fe347a2010-03-16 01:05:35 +0000773 } else {
Owen Anderson491fccc2008-07-08 22:24:50 +0000774 MO.setIsDead(true);
Bill Wendling8fe347a2010-03-16 01:05:35 +0000775 }
Dan Gohman15843902010-03-18 18:07:13 +0000776 }
Owen Anderson491fccc2008-07-08 22:24:50 +0000777 }
Owen Anderson9094db12008-07-09 20:14:53 +0000778}
779
780void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
781 // loop over each instruction
782 MachineBasicBlock::iterator MII = MBB.begin();
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000783
Bill Wendlingfbb594f2009-08-22 20:38:09 +0000784 DEBUG({
785 const BasicBlock *LBB = MBB.getBasicBlock();
786 if (LBB)
David Greene44248172010-01-05 01:26:05 +0000787 dbgs() << "\nStarting RegAlloc of BB: " << LBB->getName();
Bill Wendlingfbb594f2009-08-22 20:38:09 +0000788 });
Owen Anderson9094db12008-07-09 20:14:53 +0000789
Evan Chengd5a48022009-01-29 18:37:30 +0000790 // Add live-in registers as active.
791 for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
Owen Anderson9094db12008-07-09 20:14:53 +0000792 E = MBB.livein_end(); I != E; ++I) {
Evan Chengd5a48022009-01-29 18:37:30 +0000793 unsigned Reg = *I;
794 MF->getRegInfo().setPhysRegUsed(Reg);
795 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000796 AddToPhysRegsUseOrder(Reg);
Evan Chengd5a48022009-01-29 18:37:30 +0000797 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
798 *SubRegs; ++SubRegs) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000799 if (PhysRegsUsed[*SubRegs] == -2) continue;
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000800
801 AddToPhysRegsUseOrder(*SubRegs);
Chris Lattner4dd81632010-03-31 05:15:22 +0000802 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
803 MF->getRegInfo().setPhysRegUsed(*SubRegs);
Evan Chengd5a48022009-01-29 18:37:30 +0000804 }
Owen Anderson9094db12008-07-09 20:14:53 +0000805 }
806
807 ComputeLocalLiveness(MBB);
Owen Anderson491fccc2008-07-08 22:24:50 +0000808
Chris Lattner44500e32006-06-15 22:21:53 +0000809 // Otherwise, sequentially allocate each instruction in the MBB.
Chris Lattnere6a88ac2005-11-09 18:22:42 +0000810 while (MII != MBB.end()) {
811 MachineInstr *MI = MII++;
Chris Lattner749c6f62008-01-07 07:27:27 +0000812 const TargetInstrDesc &TID = MI->getDesc();
Bill Wendlingfbb594f2009-08-22 20:38:09 +0000813 DEBUG({
David Greene44248172010-01-05 01:26:05 +0000814 dbgs() << "\nStarting RegAlloc of: " << *MI;
815 dbgs() << " Regs have values: ";
Bill Wendlingfbb594f2009-08-22 20:38:09 +0000816 for (unsigned i = 0; i != TRI->getNumRegs(); ++i)
Jakob Stoklund Olesen8387d7d2010-04-30 21:19:29 +0000817 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
818 if (PhysRegsUsed[i] && isVirtRegModified(PhysRegsUsed[i]))
819 dbgs() << "*";
David Greene44248172010-01-05 01:26:05 +0000820 dbgs() << "[" << TRI->getName(i)
Bill Wendlingfbb594f2009-08-22 20:38:09 +0000821 << ",%reg" << PhysRegsUsed[i] << "] ";
Jakob Stoklund Olesen8387d7d2010-04-30 21:19:29 +0000822 }
David Greene44248172010-01-05 01:26:05 +0000823 dbgs() << '\n';
Bill Wendlingfbb594f2009-08-22 20:38:09 +0000824 });
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000825
Dale Johannesenfc49bd22009-12-16 00:29:41 +0000826 // Determine whether this is a copy instruction. The cases where the
827 // source or destination are phys regs are handled specially.
828 unsigned SrcCopyReg, DstCopyReg, SrcCopySubReg, DstCopySubReg;
Dale Johannesen9a6636b2010-02-03 01:40:33 +0000829 unsigned SrcCopyPhysReg = 0U;
Dale Johannesenfc49bd22009-12-16 00:29:41 +0000830 bool isCopy = TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
831 SrcCopySubReg, DstCopySubReg);
Dale Johannesen9a6636b2010-02-03 01:40:33 +0000832 if (isCopy && TargetRegisterInfo::isVirtualRegister(SrcCopyReg))
833 SrcCopyPhysReg = getVirt2PhysRegMapSlot(SrcCopyReg);
Dale Johannesenfc49bd22009-12-16 00:29:41 +0000834
Chris Lattnerae640432002-12-17 02:50:10 +0000835 // Loop over the implicit uses, making sure that they are at the head of the
836 // use order list, so they don't get reallocated.
Jim Laskeycd4317e2006-07-21 21:15:20 +0000837 if (TID.ImplicitUses) {
838 for (const unsigned *ImplicitUses = TID.ImplicitUses;
839 *ImplicitUses; ++ImplicitUses)
840 MarkPhysRegRecentlyUsed(*ImplicitUses);
841 }
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000842
Evan Chengddee8422006-11-15 20:55:15 +0000843 SmallVector<unsigned, 8> Kills;
844 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000845 MachineOperand &MO = MI->getOperand(i);
Nick Lewycky403d3122010-05-07 01:45:38 +0000846 if (!MO.isReg() || !MO.isKill()) continue;
847
Chris Lattner4dd81632010-03-31 05:15:22 +0000848 if (!MO.isImplicit())
849 Kills.push_back(MO.getReg());
850 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
851 // These are extra physical register kills when a sub-register
852 // is defined (def of a sub-register is a read/mod/write of the
853 // larger registers). Ignore.
854 Kills.push_back(MO.getReg());
Evan Chengddee8422006-11-15 20:55:15 +0000855 }
856
Dale Johannesen8e3455b2008-09-24 23:13:09 +0000857 // If any physical regs are earlyclobber, spill any value they might
858 // have in them, then mark them unallocatable.
859 // If any virtual regs are earlyclobber, allocate them now (before
860 // freeing inputs that are killed).
Chris Lattner518bb532010-02-09 19:54:29 +0000861 if (MI->isInlineAsm()) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000862 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
863 MachineOperand &MO = MI->getOperand(i);
864 if (!MO.isReg() || !MO.isDef() || !MO.isEarlyClobber() ||
865 !MO.getReg())
866 continue;
867
868 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
869 unsigned DestVirtReg = MO.getReg();
870 unsigned DestPhysReg;
Dale Johannesen8e3455b2008-09-24 23:13:09 +0000871
Chris Lattner4dd81632010-03-31 05:15:22 +0000872 // If DestVirtReg already has a value, use it.
873 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
874 DestPhysReg = getReg(MBB, MI, DestVirtReg);
875 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
876 markVirtRegModified(DestVirtReg);
877 getVirtRegLastUse(DestVirtReg) =
878 std::make_pair((MachineInstr*)0, 0);
879 DEBUG(dbgs() << " Assigning " << TRI->getName(DestPhysReg)
880 << " to %reg" << DestVirtReg << "\n");
881 MO.setReg(DestPhysReg); // Assign the earlyclobber register
882 } else {
883 unsigned Reg = MO.getReg();
884 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
885 // These are extra physical register defs when a sub-register
886 // is defined (def of a sub-register is a read/mod/write of the
887 // larger registers). Ignore.
888 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
Dale Johannesen8e3455b2008-09-24 23:13:09 +0000889
Chris Lattner4dd81632010-03-31 05:15:22 +0000890 MF->getRegInfo().setPhysRegUsed(Reg);
891 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
892 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000893 AddToPhysRegsUseOrder(Reg);
Dale Johannesen8e3455b2008-09-24 23:13:09 +0000894
Chris Lattner4dd81632010-03-31 05:15:22 +0000895 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
896 *SubRegs; ++SubRegs) {
897 if (PhysRegsUsed[*SubRegs] == -2) continue;
898 MF->getRegInfo().setPhysRegUsed(*SubRegs);
899 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000900 AddToPhysRegsUseOrder(*SubRegs);
Dale Johannesen8e3455b2008-09-24 23:13:09 +0000901 }
902 }
903 }
904 }
905
Dale Johannesen10fedd22010-02-10 00:11:11 +0000906 // If a DBG_VALUE says something is located in a spilled register,
907 // change the DBG_VALUE to be undef, which prevents the register
Dale Johannesenca134612010-01-30 00:57:47 +0000908 // from being reloaded here. Doing that would change the generated
909 // code, unless another use immediately follows this instruction.
Chris Lattner518bb532010-02-09 19:54:29 +0000910 if (MI->isDebugValue() &&
Dale Johannesenca134612010-01-30 00:57:47 +0000911 MI->getNumOperands()==3 && MI->getOperand(0).isReg()) {
912 unsigned VirtReg = MI->getOperand(0).getReg();
913 if (VirtReg && TargetRegisterInfo::isVirtualRegister(VirtReg) &&
914 !getVirt2PhysRegMapSlot(VirtReg))
915 MI->getOperand(0).setReg(0U);
916 }
917
Brian Gaeke53b99a02003-08-15 21:19:25 +0000918 // Get the used operands into registers. This has the potential to spill
Chris Lattnerb8822ad2003-08-04 23:36:39 +0000919 // incoming values if we are out of registers. Note that we completely
920 // ignore physical register uses here. We assume that if an explicit
921 // physical register is referenced by the instruction, that it is guaranteed
922 // to be live-in, or the input is badly hosed.
Chris Lattnerb74e83c2002-12-16 16:15:28 +0000923 //
Evan Cheng5a3c6a82009-01-29 02:20:59 +0000924 SmallSet<unsigned, 4> ReloadedRegs;
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000925 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000926 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000927 // here we are looking for only used operands (never def&use)
Dan Gohmand735b802008-10-03 15:45:36 +0000928 if (MO.isReg() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +0000929 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Dale Johannesenfc49bd22009-12-16 00:29:41 +0000930 MI = reloadVirtReg(MBB, MI, i, ReloadedRegs,
931 isCopy ? DstCopyReg : 0);
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000932 }
Alkis Evlogimenos4de473b2004-02-13 18:20:47 +0000933
Evan Chengddee8422006-11-15 20:55:15 +0000934 // If this instruction is the last user of this register, kill the
Chris Lattner56ddada2004-02-17 17:49:10 +0000935 // value, freeing the register being used, so it doesn't need to be
936 // spilled to memory.
937 //
Evan Chengddee8422006-11-15 20:55:15 +0000938 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
939 unsigned VirtReg = Kills[i];
Chris Lattner56ddada2004-02-17 17:49:10 +0000940 unsigned PhysReg = VirtReg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000941 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
Chris Lattner56ddada2004-02-17 17:49:10 +0000942 // If the virtual register was never materialized into a register, it
943 // might not be in the map, but it won't hurt to zero it out anyway.
944 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
945 PhysReg = PhysRegSlot;
946 PhysRegSlot = 0;
Chris Lattner0c5b8da2006-09-08 20:21:31 +0000947 } else if (PhysRegsUsed[PhysReg] == -2) {
948 // Unallocatable register dead, ignore.
949 continue;
Evan Cheng7ac19af2007-06-26 21:05:13 +0000950 } else {
Evan Cheng76500d52007-10-22 19:42:28 +0000951 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
Evan Cheng7ac19af2007-06-26 21:05:13 +0000952 "Silently clearing a virtual register?");
Chris Lattner56ddada2004-02-17 17:49:10 +0000953 }
Chris Lattner91a452b2003-01-13 00:25:40 +0000954
Chris Lattner4dd81632010-03-31 05:15:22 +0000955 if (!PhysReg) continue;
956
957 DEBUG(dbgs() << " Last use of " << TRI->getName(PhysReg)
958 << "[%reg" << VirtReg <<"], removing it from live set\n");
959 removePhysReg(PhysReg);
960 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
961 *SubRegs; ++SubRegs) {
962 if (PhysRegsUsed[*SubRegs] != -2) {
963 DEBUG(dbgs() << " Last use of "
964 << TRI->getName(*SubRegs) << "[%reg" << VirtReg
965 <<"], removing it from live set\n");
966 removePhysReg(*SubRegs);
Evan Chengddee8422006-11-15 20:55:15 +0000967 }
Chris Lattner91a452b2003-01-13 00:25:40 +0000968 }
969 }
970
971 // Loop over all of the operands of the instruction, spilling registers that
972 // are defined, and marking explicit destinations in the PhysRegsUsed map.
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000973 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattner4dd81632010-03-31 05:15:22 +0000974 MachineOperand &MO = MI->getOperand(i);
975 if (!MO.isReg() || !MO.isDef() || MO.isImplicit() || !MO.getReg() ||
976 MO.isEarlyClobber() ||
977 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
978 continue;
979
980 unsigned Reg = MO.getReg();
981 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
982 // These are extra physical register defs when a sub-register
983 // is defined (def of a sub-register is a read/mod/write of the
984 // larger registers). Ignore.
985 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
Evan Cheng7ac19af2007-06-26 21:05:13 +0000986
Chris Lattner4dd81632010-03-31 05:15:22 +0000987 MF->getRegInfo().setPhysRegUsed(Reg);
988 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
989 PhysRegsUsed[Reg] = 0; // It is free and reserved now
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000990 AddToPhysRegsUseOrder(Reg);
Evan Cheng7ac19af2007-06-26 21:05:13 +0000991
Chris Lattner4dd81632010-03-31 05:15:22 +0000992 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
993 *SubRegs; ++SubRegs) {
994 if (PhysRegsUsed[*SubRegs] == -2) continue;
995
996 MF->getRegInfo().setPhysRegUsed(*SubRegs);
997 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +0000998 AddToPhysRegsUseOrder(*SubRegs);
Chris Lattner91a452b2003-01-13 00:25:40 +0000999 }
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +00001000 }
Chris Lattner91a452b2003-01-13 00:25:40 +00001001
1002 // Loop over the implicit defs, spilling them as well.
Jim Laskeycd4317e2006-07-21 21:15:20 +00001003 if (TID.ImplicitDefs) {
1004 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
1005 *ImplicitDefs; ++ImplicitDefs) {
1006 unsigned Reg = *ImplicitDefs;
Evan Cheng7ac19af2007-06-26 21:05:13 +00001007 if (PhysRegsUsed[Reg] != -2) {
Chris Lattner2b41b8e2006-09-19 18:02:01 +00001008 spillPhysReg(MBB, MI, Reg, true);
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +00001009 AddToPhysRegsUseOrder(Reg);
Chris Lattner2b41b8e2006-09-19 18:02:01 +00001010 PhysRegsUsed[Reg] = 0; // It is free and reserved now
1011 }
Chris Lattner84bc5422007-12-31 04:13:23 +00001012 MF->getRegInfo().setPhysRegUsed(Reg);
Evan Cheng5a3c6a82009-01-29 02:20:59 +00001013 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
1014 *SubRegs; ++SubRegs) {
Chris Lattner4dd81632010-03-31 05:15:22 +00001015 if (PhysRegsUsed[*SubRegs] == -2) continue;
1016
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +00001017 AddToPhysRegsUseOrder(*SubRegs);
Chris Lattner4dd81632010-03-31 05:15:22 +00001018 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
1019 MF->getRegInfo().setPhysRegUsed(*SubRegs);
Jim Laskeycd4317e2006-07-21 21:15:20 +00001020 }
Alkis Evlogimenos19b64862004-01-13 06:24:30 +00001021 }
Alkis Evlogimenosefe995a2003-12-13 01:20:58 +00001022 }
Chris Lattner91a452b2003-01-13 00:25:40 +00001023
Evan Chengddee8422006-11-15 20:55:15 +00001024 SmallVector<unsigned, 8> DeadDefs;
1025 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattner4dd81632010-03-31 05:15:22 +00001026 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001027 if (MO.isReg() && MO.isDead())
Evan Chengddee8422006-11-15 20:55:15 +00001028 DeadDefs.push_back(MO.getReg());
1029 }
1030
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001031 // Okay, we have allocated all of the source operands and spilled any values
1032 // that would be destroyed by defs of this instruction. Loop over the
Chris Lattner0648b162005-01-23 22:51:56 +00001033 // explicit defs and assign them to a register, spilling incoming values if
Chris Lattner91a452b2003-01-13 00:25:40 +00001034 // we need to scavenge a register.
Chris Lattner82bee0f2002-12-18 08:14:26 +00001035 //
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +00001036 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Chris Lattner4dd81632010-03-31 05:15:22 +00001037 MachineOperand &MO = MI->getOperand(i);
1038 if (!MO.isReg() || !MO.isDef() || !MO.getReg() ||
1039 MO.isEarlyClobber() ||
1040 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1041 continue;
1042
1043 unsigned DestVirtReg = MO.getReg();
1044 unsigned DestPhysReg;
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001045
Chris Lattner4dd81632010-03-31 05:15:22 +00001046 // If DestVirtReg already has a value, use it.
1047 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg))) {
1048 // If this is a copy try to reuse the input as the output;
1049 // that will make the copy go away.
1050 // If this is a copy, the source reg is a phys reg, and
1051 // that reg is available, use that phys reg for DestPhysReg.
1052 // If this is a copy, the source reg is a virtual reg, and
1053 // the phys reg that was assigned to that virtual reg is now
1054 // available, use that phys reg for DestPhysReg. (If it's now
1055 // available that means this was the last use of the source.)
1056 if (isCopy &&
1057 TargetRegisterInfo::isPhysicalRegister(SrcCopyReg) &&
1058 isPhysRegAvailable(SrcCopyReg)) {
1059 DestPhysReg = SrcCopyReg;
1060 assignVirtToPhysReg(DestVirtReg, DestPhysReg);
1061 } else if (isCopy &&
1062 TargetRegisterInfo::isVirtualRegister(SrcCopyReg) &&
1063 SrcCopyPhysReg && isPhysRegAvailable(SrcCopyPhysReg) &&
1064 MF->getRegInfo().getRegClass(DestVirtReg)->
1065 contains(SrcCopyPhysReg)) {
1066 DestPhysReg = SrcCopyPhysReg;
1067 assignVirtToPhysReg(DestVirtReg, DestPhysReg);
1068 } else
1069 DestPhysReg = getReg(MBB, MI, DestVirtReg);
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001070 }
Chris Lattner4dd81632010-03-31 05:15:22 +00001071 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
1072 markVirtRegModified(DestVirtReg);
1073 getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
1074 DEBUG(dbgs() << " Assigning " << TRI->getName(DestPhysReg)
1075 << " to %reg" << DestVirtReg << "\n");
1076 MO.setReg(DestPhysReg); // Assign the output register
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +00001077 }
Chris Lattner82bee0f2002-12-18 08:14:26 +00001078
Chris Lattner56ddada2004-02-17 17:49:10 +00001079 // If this instruction defines any registers that are immediately dead,
1080 // kill them now.
1081 //
Evan Chengddee8422006-11-15 20:55:15 +00001082 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
1083 unsigned VirtReg = DeadDefs[i];
Chris Lattner56ddada2004-02-17 17:49:10 +00001084 unsigned PhysReg = VirtReg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001085 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
Chris Lattner56ddada2004-02-17 17:49:10 +00001086 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
1087 PhysReg = PhysRegSlot;
1088 assert(PhysReg != 0);
1089 PhysRegSlot = 0;
Chris Lattner0c5b8da2006-09-08 20:21:31 +00001090 } else if (PhysRegsUsed[PhysReg] == -2) {
1091 // Unallocatable register dead, ignore.
1092 continue;
Chris Lattner4dd81632010-03-31 05:15:22 +00001093 } else if (!PhysReg)
1094 continue;
1095
1096 DEBUG(dbgs() << " Register " << TRI->getName(PhysReg)
1097 << " [%reg" << VirtReg
1098 << "] is never used, removing it from live set\n");
1099 removePhysReg(PhysReg);
1100 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
1101 *AliasSet; ++AliasSet) {
1102 if (PhysRegsUsed[*AliasSet] != -2) {
1103 DEBUG(dbgs() << " Register " << TRI->getName(*AliasSet)
1104 << " [%reg" << *AliasSet
1105 << "] is never used, removing it from live set\n");
1106 removePhysReg(*AliasSet);
Evan Chengddee8422006-11-15 20:55:15 +00001107 }
Chris Lattner82bee0f2002-12-18 08:14:26 +00001108 }
1109 }
Chris Lattnere6a88ac2005-11-09 18:22:42 +00001110
Jakob Stoklund Olesen8387d7d2010-04-30 21:19:29 +00001111 // If this instruction is a call, make sure there are no dirty registers. The
1112 // call might throw an exception, and the landing pad expects to find all
1113 // registers in stack slots.
1114 if (TID.isCall())
1115 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
1116 if (PhysRegsUsed[i] <= 0) continue;
1117 unsigned VirtReg = PhysRegsUsed[i];
1118 if (!isVirtRegModified(VirtReg)) continue;
1119 DEBUG(dbgs() << " Storing dirty %reg" << VirtReg);
1120 storeVirtReg(MBB, MI, VirtReg, i, false);
1121 markVirtRegModified(VirtReg, false);
1122 DEBUG(dbgs() << " because the call might throw\n");
1123 }
1124
Bob Wilson9d928c22009-05-07 23:47:03 +00001125 // Finally, if this is a noop copy instruction, zap it. (Except that if
1126 // the copy is dead, it must be kept to avoid messing up liveness info for
1127 // the register scavenger. See pr4100.)
Dale Johannesenfc49bd22009-12-16 00:29:41 +00001128 if (TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
1129 SrcCopySubReg, DstCopySubReg) &&
1130 SrcCopyReg == DstCopyReg && DeadDefs.empty())
Chris Lattnere6a88ac2005-11-09 18:22:42 +00001131 MBB.erase(MI);
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001132 }
1133
Chris Lattnere6a88ac2005-11-09 18:22:42 +00001134 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001135
1136 // Spill all physical registers holding virtual registers now.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001137 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001138 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
Chris Lattner64667b62004-02-09 01:26:13 +00001139 if (unsigned VirtReg = PhysRegsUsed[i])
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +00001140 spillVirtReg(MBB, MI, VirtReg, i);
Chris Lattner64667b62004-02-09 01:26:13 +00001141 else
1142 removePhysReg(i);
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00001143 }
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001144
Chris Lattner9a5ef202005-11-09 05:28:45 +00001145#if 0
1146 // This checking code is very expensive.
Chris Lattnerecea5632004-02-09 02:12:04 +00001147 bool AllOk = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001148 for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
Chris Lattner84bc5422007-12-31 04:13:23 +00001149 e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
Chris Lattnerecea5632004-02-09 02:12:04 +00001150 if (unsigned PR = Virt2PhysRegMap[i]) {
Bill Wendling832171c2006-12-07 20:04:42 +00001151 cerr << "Register still mapped: " << i << " -> " << PR << "\n";
Chris Lattnerecea5632004-02-09 02:12:04 +00001152 AllOk = false;
1153 }
1154 assert(AllOk && "Virtual registers still in phys regs?");
1155#endif
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +00001156
1157 // Clear any physical register which appear live at the end of the basic
1158 // block, but which do not hold any virtual registers. e.g., the stack
1159 // pointer.
1160 PhysRegsUseOrder.clear();
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001161}
1162
1163/// runOnMachineFunction - Register allocate the whole function
1164///
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001165bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
David Greene44248172010-01-05 01:26:05 +00001166 DEBUG(dbgs() << "Machine Function\n");
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001167 MF = &Fn;
Chris Lattner580f9be2002-12-28 20:40:43 +00001168 TM = &Fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001169 TRI = TM->getRegisterInfo();
Owen Anderson6425f8b2008-01-07 01:35:56 +00001170 TII = TM->getInstrInfo();
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001171
Dan Gohman6f0d0242008-02-10 18:45:23 +00001172 PhysRegsUsed.assign(TRI->getNumRegs(), -1);
Jakob Stoklund Olesen23eaf262010-04-17 00:38:36 +00001173
Chris Lattner45d57882006-09-08 19:03:30 +00001174 // At various places we want to efficiently check to see whether a register
1175 // is allocatable. To handle this, we mark all unallocatable registers as
1176 // being pinned down, permanently.
1177 {
Dan Gohman6f0d0242008-02-10 18:45:23 +00001178 BitVector Allocable = TRI->getAllocatableSet(Fn);
Chris Lattner45d57882006-09-08 19:03:30 +00001179 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
1180 if (!Allocable[i])
1181 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
1182 }
Chris Lattner64667b62004-02-09 01:26:13 +00001183
Alkis Evlogimenos4de473b2004-02-13 18:20:47 +00001184 // initialize the virtual->physical register map to have a 'null'
1185 // mapping for all virtual registers
Evan Cheng644340a2008-01-17 00:35:26 +00001186 unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
Evan Chengbdb10fe2008-07-10 18:23:23 +00001187 StackSlotForVirtReg.grow(LastVirtReg);
Evan Cheng644340a2008-01-17 00:35:26 +00001188 Virt2PhysRegMap.grow(LastVirtReg);
Evan Cheng839b7592008-01-17 02:08:17 +00001189 Virt2LastUseMap.grow(LastVirtReg);
Chris Lattner4dd81632010-03-31 05:15:22 +00001190 VirtRegModified.resize(LastVirtReg+1 -
1191 TargetRegisterInfo::FirstVirtualRegister);
1192 UsedInMultipleBlocks.resize(LastVirtReg+1 -
1193 TargetRegisterInfo::FirstVirtualRegister);
Owen Anderson491fccc2008-07-08 22:24:50 +00001194
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001195 // Loop over all of the basic blocks, eliminating virtual register references
1196 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
1197 MBB != MBBe; ++MBB)
1198 AllocateBasicBlock(*MBB);
1199
Chris Lattner580f9be2002-12-28 20:40:43 +00001200 StackSlotForVirtReg.clear();
Alkis Evlogimenos4de473b2004-02-13 18:20:47 +00001201 PhysRegsUsed.clear();
Chris Lattner91a452b2003-01-13 00:25:40 +00001202 VirtRegModified.clear();
Owen Anderson491fccc2008-07-08 22:24:50 +00001203 UsedInMultipleBlocks.clear();
Chris Lattnerecea5632004-02-09 02:12:04 +00001204 Virt2PhysRegMap.clear();
Evan Cheng839b7592008-01-17 02:08:17 +00001205 Virt2LastUseMap.clear();
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001206 return true;
1207}
1208
Chris Lattneref09c632004-01-31 21:27:19 +00001209FunctionPass *llvm::createLocalRegisterAllocator() {
Bill Wendlinge23e00d2007-05-08 19:02:46 +00001210 return new RALocal();
Chris Lattnerb74e83c2002-12-16 16:15:28 +00001211}