blob: db35ce06150ee1f87a6dd4ff54089325c17b479a [file] [log] [blame]
Evan Chengb1290a62008-10-02 18:29:27 +00001//===------ RegAllocPBQP.cpp ---- PBQP Register Allocator -------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Misha Brukman2a835f92009-01-08 15:50:22 +00009//
Evan Chengb1290a62008-10-02 18:29:27 +000010// This file contains a Partitioned Boolean Quadratic Programming (PBQP) based
11// register allocator for LLVM. This allocator works by constructing a PBQP
12// problem representing the register allocation problem under consideration,
13// solving this using a PBQP solver, and mapping the solution back to a
14// register assignment. If any variables are selected for spilling then spill
Misha Brukman2a835f92009-01-08 15:50:22 +000015// code is inserted and the process repeated.
Evan Chengb1290a62008-10-02 18:29:27 +000016//
17// The PBQP solver (pbqp.c) provided for this allocator uses a heuristic tuned
18// for register allocation. For more information on PBQP for register
Misha Brukmance07e992009-01-08 16:40:25 +000019// allocation, see the following papers:
Evan Chengb1290a62008-10-02 18:29:27 +000020//
21// (1) Hames, L. and Scholz, B. 2006. Nearly optimal register allocation with
22// PBQP. In Proceedings of the 7th Joint Modular Languages Conference
23// (JMLC'06). LNCS, vol. 4228. Springer, New York, NY, USA. 346-361.
24//
25// (2) Scholz, B., Eckstein, E. 2002. Register allocation for irregular
26// architectures. In Proceedings of the Joint Conference on Languages,
27// Compilers and Tools for Embedded Systems (LCTES'02), ACM Press, New York,
28// NY, USA, 139-148.
Misha Brukman2a835f92009-01-08 15:50:22 +000029//
Evan Chengb1290a62008-10-02 18:29:27 +000030//===----------------------------------------------------------------------===//
31
Evan Chengb1290a62008-10-02 18:29:27 +000032#define DEBUG_TYPE "regalloc"
33
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +000034#include "LiveRangeEdit.h"
Lang Hames54cc2ef2010-07-19 15:22:28 +000035#include "RenderMachineFunction.h"
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +000036#include "Spiller.h"
Lang Hames12f35c52010-07-18 00:57:59 +000037#include "Splitter.h"
Evan Chengb1290a62008-10-02 18:29:27 +000038#include "VirtRegMap.h"
Rafael Espindolafdf16ca2011-06-26 21:41:06 +000039#include "RegisterCoalescer.h"
Lang Hames9ad7e072011-12-06 01:45:57 +000040#include "llvm/Analysis/AliasAnalysis.h"
Lang Hamesa937f222009-12-14 06:49:42 +000041#include "llvm/CodeGen/CalcSpillWeights.h"
Evan Chengb1290a62008-10-02 18:29:27 +000042#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Lang Hames27601ef2008-11-16 12:12:54 +000043#include "llvm/CodeGen/LiveStackAnalysis.h"
Lang Hameseb6c8f52010-09-18 09:07:10 +000044#include "llvm/CodeGen/RegAllocPBQP.h"
Lang Hames9ad7e072011-12-06 01:45:57 +000045#include "llvm/CodeGen/MachineDominators.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000046#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Chengb1290a62008-10-02 18:29:27 +000047#include "llvm/CodeGen/MachineLoopInfo.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000048#include "llvm/CodeGen/MachineRegisterInfo.h"
Lang Hameseb6c8f52010-09-18 09:07:10 +000049#include "llvm/CodeGen/PBQP/HeuristicSolver.h"
50#include "llvm/CodeGen/PBQP/Graph.h"
51#include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000052#include "llvm/CodeGen/RegAllocRegistry.h"
Evan Chengb1290a62008-10-02 18:29:27 +000053#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000054#include "llvm/Support/raw_ostream.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000055#include "llvm/Target/TargetInstrInfo.h"
56#include "llvm/Target/TargetMachine.h"
57#include <limits>
Misha Brukman2a835f92009-01-08 15:50:22 +000058#include <memory>
Evan Chengb1290a62008-10-02 18:29:27 +000059#include <set>
60#include <vector>
Evan Chengb1290a62008-10-02 18:29:27 +000061
Lang Hamesf70e7cc2010-09-23 04:28:54 +000062using namespace llvm;
Lang Hameseb6c8f52010-09-18 09:07:10 +000063
Evan Chengb1290a62008-10-02 18:29:27 +000064static RegisterRegAlloc
Duncan Sands1aecd152010-02-18 14:10:41 +000065registerPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesf70e7cc2010-09-23 04:28:54 +000066 createDefaultPBQPRegisterAllocator);
Evan Chengb1290a62008-10-02 18:29:27 +000067
Lang Hames8481e3b2009-08-19 01:36:14 +000068static cl::opt<bool>
69pbqpCoalescing("pbqp-coalescing",
Lang Hames030c4bf2010-01-26 04:49:58 +000070 cl::desc("Attempt coalescing during PBQP register allocation."),
71 cl::init(false), cl::Hidden);
Lang Hames8481e3b2009-08-19 01:36:14 +000072
Lang Hames12f35c52010-07-18 00:57:59 +000073static cl::opt<bool>
74pbqpPreSplitting("pbqp-pre-splitting",
Lang Hamesf70e7cc2010-09-23 04:28:54 +000075 cl::desc("Pre-split before PBQP register allocation."),
Lang Hames12f35c52010-07-18 00:57:59 +000076 cl::init(false), cl::Hidden);
77
Lang Hamesf70e7cc2010-09-23 04:28:54 +000078namespace {
79
80///
81/// PBQP based allocators solve the register allocation problem by mapping
82/// register allocation problems to Partitioned Boolean Quadratic
83/// Programming problems.
84class RegAllocPBQP : public MachineFunctionPass {
85public:
86
87 static char ID;
88
89 /// Construct a PBQP register allocator.
Lang Hames8d857662011-06-17 07:09:01 +000090 RegAllocPBQP(std::auto_ptr<PBQPBuilder> b, char *cPassID=0)
91 : MachineFunctionPass(ID), builder(b), customPassID(cPassID) {
Owen Anderson081c34b2010-10-19 17:21:58 +000092 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
93 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +000094 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +000095 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
96 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
97 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
98 initializeLoopSplitterPass(*PassRegistry::getPassRegistry());
99 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
100 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
101 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000102
103 /// Return the pass name.
104 virtual const char* getPassName() const {
105 return "PBQP Register Allocator";
106 }
107
108 /// PBQP analysis usage.
109 virtual void getAnalysisUsage(AnalysisUsage &au) const;
110
111 /// Perform register allocation
112 virtual bool runOnMachineFunction(MachineFunction &MF);
113
114private:
115
116 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
117 typedef std::vector<const LiveInterval*> Node2LIMap;
118 typedef std::vector<unsigned> AllowedSet;
119 typedef std::vector<AllowedSet> AllowedSetMap;
120 typedef std::pair<unsigned, unsigned> RegPair;
121 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
122 typedef std::vector<PBQP::Graph::NodeItr> NodeVector;
123 typedef std::set<unsigned> RegSet;
124
125
126 std::auto_ptr<PBQPBuilder> builder;
127
Lang Hames8d857662011-06-17 07:09:01 +0000128 char *customPassID;
129
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000130 MachineFunction *mf;
131 const TargetMachine *tm;
132 const TargetRegisterInfo *tri;
133 const TargetInstrInfo *tii;
134 const MachineLoopInfo *loopInfo;
135 MachineRegisterInfo *mri;
136 RenderMachineFunction *rmf;
137
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000138 std::auto_ptr<Spiller> spiller;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000139 LiveIntervals *lis;
140 LiveStacks *lss;
141 VirtRegMap *vrm;
142
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000143 RegSet vregsToAlloc, emptyIntervalVRegs;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000144
145 /// \brief Finds the initial set of vreg intervals to allocate.
146 void findVRegIntervalsToAlloc();
147
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000148 /// \brief Given a solved PBQP problem maps this solution back to a register
149 /// assignment.
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000150 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
151 const PBQP::Solution &solution);
152
153 /// \brief Postprocessing before final spilling. Sets basic block "live in"
154 /// variables.
155 void finalizeAlloc() const;
156
157};
158
Lang Hameseb6c8f52010-09-18 09:07:10 +0000159char RegAllocPBQP::ID = 0;
Evan Chengb1290a62008-10-02 18:29:27 +0000160
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000161} // End anonymous namespace.
162
Lang Hameseb6c8f52010-09-18 09:07:10 +0000163unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
164 Node2VReg::const_iterator vregItr = node2VReg.find(node);
165 assert(vregItr != node2VReg.end() && "No vreg for node.");
166 return vregItr->second;
167}
Evan Chengb1290a62008-10-02 18:29:27 +0000168
Lang Hameseb6c8f52010-09-18 09:07:10 +0000169PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
170 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
171 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
172 return nodeItr->second;
173
174}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000175
Lang Hameseb6c8f52010-09-18 09:07:10 +0000176const PBQPRAProblem::AllowedSet&
177 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
178 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
179 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
180 const AllowedSet &allowedSet = allowedSetItr->second;
181 return allowedSet;
182}
Evan Chengb1290a62008-10-02 18:29:27 +0000183
Lang Hameseb6c8f52010-09-18 09:07:10 +0000184unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
185 assert(isPRegOption(vreg, option) && "Not a preg option.");
186
187 const AllowedSet& allowedSet = getAllowedSet(vreg);
188 assert(option <= allowedSet.size() && "Option outside allowed set.");
189 return allowedSet[option - 1];
190}
191
Lang Hamese9c93562010-09-21 13:19:36 +0000192std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
193 const LiveIntervals *lis,
194 const MachineLoopInfo *loopInfo,
195 const RegSet &vregs) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000196
197 typedef std::vector<const LiveInterval*> LIVector;
198
199 MachineRegisterInfo *mri = &mf->getRegInfo();
200 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
201
202 std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
203 PBQP::Graph &g = p->getGraph();
204 RegSet pregs;
205
206 // Collect the set of preg intervals, record that they're used in the MF.
207 for (LiveIntervals::const_iterator itr = lis->begin(), end = lis->end();
208 itr != end; ++itr) {
209 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
210 pregs.insert(itr->first);
211 mri->setPhysRegUsed(itr->first);
Evan Chengb1290a62008-10-02 18:29:27 +0000212 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000213 }
Evan Chengb1290a62008-10-02 18:29:27 +0000214
Lang Hameseb6c8f52010-09-18 09:07:10 +0000215 BitVector reservedRegs = tri->getReservedRegs(*mf);
Evan Chengb1290a62008-10-02 18:29:27 +0000216
Lang Hameseb6c8f52010-09-18 09:07:10 +0000217 // Iterate over vregs.
218 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
219 vregItr != vregEnd; ++vregItr) {
220 unsigned vreg = *vregItr;
221 const TargetRegisterClass *trc = mri->getRegClass(vreg);
222 const LiveInterval *vregLI = &lis->getInterval(vreg);
Evan Chengb1290a62008-10-02 18:29:27 +0000223
Lang Hameseb6c8f52010-09-18 09:07:10 +0000224 // Compute an initial allowed set for the current vreg.
225 typedef std::vector<unsigned> VRAllowed;
226 VRAllowed vrAllowed;
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000227 ArrayRef<unsigned> rawOrder = trc->getRawAllocationOrder(*mf);
228 for (unsigned i = 0; i != rawOrder.size(); ++i) {
229 unsigned preg = rawOrder[i];
Lang Hameseb6c8f52010-09-18 09:07:10 +0000230 if (!reservedRegs.test(preg)) {
231 vrAllowed.push_back(preg);
Lang Hamesd0f6f012010-07-17 06:31:41 +0000232 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000233 }
Lang Hamesd0f6f012010-07-17 06:31:41 +0000234
Lang Hameseb6c8f52010-09-18 09:07:10 +0000235 // Remove any physical registers which overlap.
236 for (RegSet::const_iterator pregItr = pregs.begin(),
237 pregEnd = pregs.end();
238 pregItr != pregEnd; ++pregItr) {
239 unsigned preg = *pregItr;
240 const LiveInterval *pregLI = &lis->getInterval(preg);
Lang Hames27601ef2008-11-16 12:12:54 +0000241
Lang Hames5e77f4b2010-11-12 05:47:21 +0000242 if (pregLI->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000243 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000244 }
Evan Chengb1290a62008-10-02 18:29:27 +0000245
Lang Hames5e77f4b2010-11-12 05:47:21 +0000246 if (!vregLI->overlaps(*pregLI)) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000247 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000248 }
Lang Hames030c4bf2010-01-26 04:49:58 +0000249
Lang Hameseb6c8f52010-09-18 09:07:10 +0000250 // Remove the register from the allowed set.
251 VRAllowed::iterator eraseItr =
252 std::find(vrAllowed.begin(), vrAllowed.end(), preg);
Evan Chengb1290a62008-10-02 18:29:27 +0000253
Lang Hameseb6c8f52010-09-18 09:07:10 +0000254 if (eraseItr != vrAllowed.end()) {
255 vrAllowed.erase(eraseItr);
256 }
Evan Chengb1290a62008-10-02 18:29:27 +0000257
Lang Hameseb6c8f52010-09-18 09:07:10 +0000258 // Also remove any aliases.
259 const unsigned *aliasItr = tri->getAliasSet(preg);
260 if (aliasItr != 0) {
261 for (; *aliasItr != 0; ++aliasItr) {
262 VRAllowed::iterator eraseItr =
263 std::find(vrAllowed.begin(), vrAllowed.end(), *aliasItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000264
Lang Hameseb6c8f52010-09-18 09:07:10 +0000265 if (eraseItr != vrAllowed.end()) {
266 vrAllowed.erase(eraseItr);
267 }
268 }
269 }
270 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000271
Lang Hameseb6c8f52010-09-18 09:07:10 +0000272 // Construct the node.
273 PBQP::Graph::NodeItr node =
274 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
Evan Chengb1290a62008-10-02 18:29:27 +0000275
Lang Hameseb6c8f52010-09-18 09:07:10 +0000276 // Record the mapping and allowed set in the problem.
277 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
Evan Chengb1290a62008-10-02 18:29:27 +0000278
Lang Hameseb6c8f52010-09-18 09:07:10 +0000279 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
280 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb1290a62008-10-02 18:29:27 +0000281
Lang Hameseb6c8f52010-09-18 09:07:10 +0000282 addSpillCosts(g.getNodeCosts(node), spillCost);
283 }
Evan Chengb1290a62008-10-02 18:29:27 +0000284
Lang Hames481630d2010-09-18 09:49:08 +0000285 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000286 vr1Itr != vrEnd; ++vr1Itr) {
287 unsigned vr1 = *vr1Itr;
288 const LiveInterval &l1 = lis->getInterval(vr1);
289 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb1290a62008-10-02 18:29:27 +0000290
Benjamin Kramer9e8d1f92010-09-18 14:41:26 +0000291 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000292 vr2Itr != vrEnd; ++vr2Itr) {
293 unsigned vr2 = *vr2Itr;
294 const LiveInterval &l2 = lis->getInterval(vr2);
295 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb1290a62008-10-02 18:29:27 +0000296
Lang Hameseb6c8f52010-09-18 09:07:10 +0000297 assert(!l2.empty() && "Empty interval in vreg set?");
298 if (l1.overlaps(l2)) {
299 PBQP::Graph::EdgeItr edge =
300 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
301 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
Lang Hames27601ef2008-11-16 12:12:54 +0000302
Lang Hameseb6c8f52010-09-18 09:07:10 +0000303 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
304 }
305 }
306 }
Evan Chengb1290a62008-10-02 18:29:27 +0000307
Lang Hameseb6c8f52010-09-18 09:07:10 +0000308 return p;
309}
Lang Hames27601ef2008-11-16 12:12:54 +0000310
Lang Hameseb6c8f52010-09-18 09:07:10 +0000311void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
312 PBQP::PBQPNum spillCost) {
313 costVec[0] = spillCost;
314}
Evan Chengb1290a62008-10-02 18:29:27 +0000315
Lang Hamese9c93562010-09-21 13:19:36 +0000316void PBQPBuilder::addInterferenceCosts(
317 PBQP::Matrix &costMat,
318 const PBQPRAProblem::AllowedSet &vr1Allowed,
319 const PBQPRAProblem::AllowedSet &vr2Allowed,
320 const TargetRegisterInfo *tri) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000321 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
322 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
323
Lang Hames5e77f4b2010-11-12 05:47:21 +0000324 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000325 unsigned preg1 = vr1Allowed[i];
326
Lang Hames5e77f4b2010-11-12 05:47:21 +0000327 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000328 unsigned preg2 = vr2Allowed[j];
329
330 if (tri->regsOverlap(preg1, preg2)) {
331 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
332 }
333 }
334 }
Evan Chengb1290a62008-10-02 18:29:27 +0000335}
336
Lang Hamese9c93562010-09-21 13:19:36 +0000337std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
338 MachineFunction *mf,
339 const LiveIntervals *lis,
340 const MachineLoopInfo *loopInfo,
341 const RegSet &vregs) {
342
343 std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
344 PBQP::Graph &g = p->getGraph();
345
346 const TargetMachine &tm = mf->getTarget();
347 CoalescerPair cp(*tm.getInstrInfo(), *tm.getRegisterInfo());
348
349 // Scan the machine function and add a coalescing cost whenever CoalescerPair
350 // gives the Ok.
351 for (MachineFunction::const_iterator mbbItr = mf->begin(),
352 mbbEnd = mf->end();
353 mbbItr != mbbEnd; ++mbbItr) {
354 const MachineBasicBlock *mbb = &*mbbItr;
355
356 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
357 miEnd = mbb->end();
358 miItr != miEnd; ++miItr) {
359 const MachineInstr *mi = &*miItr;
360
Lang Hames5e77f4b2010-11-12 05:47:21 +0000361 if (!cp.setRegisters(mi)) {
Lang Hamese9c93562010-09-21 13:19:36 +0000362 continue; // Not coalescable.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000363 }
Lang Hamese9c93562010-09-21 13:19:36 +0000364
Lang Hames5e77f4b2010-11-12 05:47:21 +0000365 if (cp.getSrcReg() == cp.getDstReg()) {
Lang Hamese9c93562010-09-21 13:19:36 +0000366 continue; // Already coalesced.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000367 }
Lang Hamese9c93562010-09-21 13:19:36 +0000368
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000369 unsigned dst = cp.getDstReg(),
370 src = cp.getSrcReg();
Lang Hamese9c93562010-09-21 13:19:36 +0000371
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000372 const float copyFactor = 0.5; // Cost of copy relative to load. Current
373 // value plucked randomly out of the air.
374
375 PBQP::PBQPNum cBenefit =
376 copyFactor * LiveIntervals::getSpillWeight(false, true,
377 loopInfo->getLoopDepth(mbb));
Lang Hamese9c93562010-09-21 13:19:36 +0000378
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000379 if (cp.isPhys()) {
Lang Hames5e77f4b2010-11-12 05:47:21 +0000380 if (!lis->isAllocatable(dst)) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000381 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000382 }
Lang Hamese9c93562010-09-21 13:19:36 +0000383
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000384 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
385 unsigned pregOpt = 0;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000386 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000387 ++pregOpt;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000388 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000389 if (pregOpt < allowed.size()) {
390 ++pregOpt; // +1 to account for spill option.
391 PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
392 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000393 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000394 } else {
395 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
396 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
397 PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
398 PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
399 PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
400 if (edge == g.edgesEnd()) {
401 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
402 allowed2->size() + 1,
403 0));
404 } else {
405 if (g.getEdgeNode1(edge) == node2) {
406 std::swap(node1, node2);
407 std::swap(allowed1, allowed2);
408 }
409 }
410
411 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
412 cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000413 }
414 }
415 }
416
417 return p;
418}
419
Lang Hamese9c93562010-09-21 13:19:36 +0000420void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
421 unsigned pregOption,
422 PBQP::PBQPNum benefit) {
423 costVec[pregOption] += -benefit;
424}
425
426void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
427 PBQP::Matrix &costMat,
428 const PBQPRAProblem::AllowedSet &vr1Allowed,
429 const PBQPRAProblem::AllowedSet &vr2Allowed,
430 PBQP::PBQPNum benefit) {
431
432 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
433 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
434
Lang Hames5e77f4b2010-11-12 05:47:21 +0000435 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hamese9c93562010-09-21 13:19:36 +0000436 unsigned preg1 = vr1Allowed[i];
Lang Hames5e77f4b2010-11-12 05:47:21 +0000437 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hamese9c93562010-09-21 13:19:36 +0000438 unsigned preg2 = vr2Allowed[j];
439
440 if (preg1 == preg2) {
441 costMat[i + 1][j + 1] += -benefit;
442 }
443 }
444 }
445}
Evan Chengb1290a62008-10-02 18:29:27 +0000446
Lang Hameseb6c8f52010-09-18 09:07:10 +0000447
448void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hames9ad7e072011-12-06 01:45:57 +0000449 au.setPreservesCFG();
450 au.addRequired<AliasAnalysis>();
451 au.addPreserved<AliasAnalysis>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000452 au.addRequired<SlotIndexes>();
453 au.addPreserved<SlotIndexes>();
454 au.addRequired<LiveIntervals>();
455 //au.addRequiredID(SplitCriticalEdgesID);
Jakob Stoklund Olesen27215672011-08-09 00:29:53 +0000456 au.addRequiredID(RegisterCoalescerPassID);
Lang Hames8d857662011-06-17 07:09:01 +0000457 if (customPassID)
458 au.addRequiredID(*customPassID);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000459 au.addRequired<CalculateSpillWeights>();
460 au.addRequired<LiveStacks>();
461 au.addPreserved<LiveStacks>();
Lang Hames9ad7e072011-12-06 01:45:57 +0000462 au.addRequired<MachineDominatorTree>();
463 au.addPreserved<MachineDominatorTree>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000464 au.addRequired<MachineLoopInfo>();
465 au.addPreserved<MachineLoopInfo>();
466 if (pbqpPreSplitting)
467 au.addRequired<LoopSplitter>();
468 au.addRequired<VirtRegMap>();
469 au.addRequired<RenderMachineFunction>();
470 MachineFunctionPass::getAnalysisUsage(au);
471}
472
Lang Hameseb6c8f52010-09-18 09:07:10 +0000473void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames27601ef2008-11-16 12:12:54 +0000474
475 // Iterate over all live ranges.
476 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
477 itr != end; ++itr) {
478
479 // Ignore physical ones.
480 if (TargetRegisterInfo::isPhysicalRegister(itr->first))
481 continue;
482
483 LiveInterval *li = itr->second;
484
485 // If this live interval is non-empty we will use pbqp to allocate it.
486 // Empty intervals we allocate in a simple post-processing stage in
487 // finalizeAlloc.
488 if (!li->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000489 vregsToAlloc.insert(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000490 } else {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000491 emptyIntervalVRegs.insert(li->reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000492 }
493 }
Evan Chengb1290a62008-10-02 18:29:27 +0000494}
495
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000496bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
497 const PBQP::Solution &solution) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000498 // Set to true if we have any spills
499 bool anotherRoundNeeded = false;
500
501 // Clear the existing allocation.
502 vrm->clearAllVirt();
503
504 const PBQP::Graph &g = problem.getGraph();
505 // Iterate over the nodes mapping the PBQP solution to a register
506 // assignment.
507 for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
508 nodeEnd = g.nodesEnd();
509 node != nodeEnd; ++node) {
510 unsigned vreg = problem.getVRegForNode(node);
511 unsigned alloc = solution.getSelection(node);
512
513 if (problem.isPRegOption(vreg, alloc)) {
514 unsigned preg = problem.getPRegForOption(vreg, alloc);
515 DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "\n");
516 assert(preg != 0 && "Invalid preg selected.");
517 vrm->assignVirt2Phys(vreg, preg);
518 } else if (problem.isSpillOption(vreg, alloc)) {
519 vregsToAlloc.erase(vreg);
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000520 SmallVector<LiveInterval*, 8> newSpills;
521 LiveRangeEdit LRE(lis->getInterval(vreg), newSpills);
522 spiller->spill(LRE);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000523
Lang Hameseb6c8f52010-09-18 09:07:10 +0000524 DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000525 << LRE.getParent().weight << ", New vregs: ");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000526
527 // Copy any newly inserted live intervals into the list of regs to
528 // allocate.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000529 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000530 itr != end; ++itr) {
531 assert(!(*itr)->empty() && "Empty spill range.");
532 DEBUG(dbgs() << (*itr)->reg << " ");
533 vregsToAlloc.insert((*itr)->reg);
534 }
535
536 DEBUG(dbgs() << ")\n");
537
538 // We need another round if spill intervals were added.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000539 anotherRoundNeeded |= !LRE.empty();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000540 } else {
541 assert(false && "Unknown allocation option.");
542 }
543 }
544
545 return !anotherRoundNeeded;
546}
547
548
549void RegAllocPBQP::finalizeAlloc() const {
Lang Hames27601ef2008-11-16 12:12:54 +0000550 typedef LiveIntervals::iterator LIIterator;
551 typedef LiveInterval::Ranges::const_iterator LRIterator;
552
553 // First allocate registers for the empty intervals.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000554 for (RegSet::const_iterator
555 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames27601ef2008-11-16 12:12:54 +0000556 itr != end; ++itr) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000557 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames27601ef2008-11-16 12:12:54 +0000558
Evan Cheng90f95f82009-06-14 20:22:55 +0000559 unsigned physReg = vrm->getRegAllocPref(li->reg);
Lang Hames6699fb22009-08-06 23:32:48 +0000560
Lang Hames27601ef2008-11-16 12:12:54 +0000561 if (physReg == 0) {
562 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000563 physReg = liRC->getRawAllocationOrder(*mf).front();
Lang Hames27601ef2008-11-16 12:12:54 +0000564 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000565
566 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames27601ef2008-11-16 12:12:54 +0000567 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000568
Lang Hames27601ef2008-11-16 12:12:54 +0000569 // Finally iterate over the basic blocks to compute and set the live-in sets.
570 SmallVector<MachineBasicBlock*, 8> liveInMBBs;
571 MachineBasicBlock *entryMBB = &*mf->begin();
572
573 for (LIIterator liItr = lis->begin(), liEnd = lis->end();
574 liItr != liEnd; ++liItr) {
575
576 const LiveInterval *li = liItr->second;
577 unsigned reg = 0;
Misha Brukman2a835f92009-01-08 15:50:22 +0000578
Lang Hames27601ef2008-11-16 12:12:54 +0000579 // Get the physical register for this interval
580 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
581 reg = li->reg;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000582 } else if (vrm->isAssignedReg(li->reg)) {
Lang Hames27601ef2008-11-16 12:12:54 +0000583 reg = vrm->getPhys(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000584 } else {
Lang Hames27601ef2008-11-16 12:12:54 +0000585 // Ranges which are assigned a stack slot only are ignored.
586 continue;
587 }
588
Lang Hamesb0e519f2009-05-17 23:50:36 +0000589 if (reg == 0) {
Lang Hames6699fb22009-08-06 23:32:48 +0000590 // Filter out zero regs - they're for intervals that were spilled.
Lang Hamesb0e519f2009-05-17 23:50:36 +0000591 continue;
592 }
593
Lang Hames27601ef2008-11-16 12:12:54 +0000594 // Iterate over the ranges of the current interval...
595 for (LRIterator lrItr = li->begin(), lrEnd = li->end();
596 lrItr != lrEnd; ++lrItr) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000597
Lang Hames27601ef2008-11-16 12:12:54 +0000598 // Find the set of basic blocks which this range is live into...
599 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
600 // And add the physreg for this interval to their live-in sets.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000601 for (unsigned i = 0; i != liveInMBBs.size(); ++i) {
Lang Hames27601ef2008-11-16 12:12:54 +0000602 if (liveInMBBs[i] != entryMBB) {
603 if (!liveInMBBs[i]->isLiveIn(reg)) {
604 liveInMBBs[i]->addLiveIn(reg);
605 }
606 }
607 }
608 liveInMBBs.clear();
609 }
610 }
611 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000612
Lang Hames27601ef2008-11-16 12:12:54 +0000613}
614
Lang Hameseb6c8f52010-09-18 09:07:10 +0000615bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames27601ef2008-11-16 12:12:54 +0000616
Evan Chengb1290a62008-10-02 18:29:27 +0000617 mf = &MF;
618 tm = &mf->getTarget();
619 tri = tm->getRegisterInfo();
Lang Hames27601ef2008-11-16 12:12:54 +0000620 tii = tm->getInstrInfo();
Lang Hames233a60e2009-11-03 23:52:08 +0000621 mri = &mf->getRegInfo();
Evan Chengb1290a62008-10-02 18:29:27 +0000622
Lang Hames27601ef2008-11-16 12:12:54 +0000623 lis = &getAnalysis<LiveIntervals>();
624 lss = &getAnalysis<LiveStacks>();
Evan Chengb1290a62008-10-02 18:29:27 +0000625 loopInfo = &getAnalysis<MachineLoopInfo>();
Lang Hames33198392010-09-02 08:27:00 +0000626 rmf = &getAnalysis<RenderMachineFunction>();
Evan Chengb1290a62008-10-02 18:29:27 +0000627
Owen Anderson49c8aa02009-03-13 05:55:11 +0000628 vrm = &getAnalysis<VirtRegMap>();
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000629 spiller.reset(createInlineSpiller(*this, MF, *vrm));
Evan Chengb1290a62008-10-02 18:29:27 +0000630
Lang Hames54cc2ef2010-07-19 15:22:28 +0000631
Lang Hames030c4bf2010-01-26 04:49:58 +0000632 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000633
Evan Chengb1290a62008-10-02 18:29:27 +0000634 // Allocator main loop:
Misha Brukman2a835f92009-01-08 15:50:22 +0000635 //
Evan Chengb1290a62008-10-02 18:29:27 +0000636 // * Map current regalloc problem to a PBQP problem
637 // * Solve the PBQP problem
638 // * Map the solution back to a register allocation
639 // * Spill if necessary
Misha Brukman2a835f92009-01-08 15:50:22 +0000640 //
Evan Chengb1290a62008-10-02 18:29:27 +0000641 // This process is continued till no more spills are generated.
642
Lang Hames27601ef2008-11-16 12:12:54 +0000643 // Find the vreg intervals in need of allocation.
644 findVRegIntervalsToAlloc();
Misha Brukman2a835f92009-01-08 15:50:22 +0000645
Lang Hames27601ef2008-11-16 12:12:54 +0000646 // If there are non-empty intervals allocate them using pbqp.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000647 if (!vregsToAlloc.empty()) {
Evan Chengb1290a62008-10-02 18:29:27 +0000648
Lang Hames27601ef2008-11-16 12:12:54 +0000649 bool pbqpAllocComplete = false;
650 unsigned round = 0;
651
Lang Hamesab62b7e2010-10-04 12:13:07 +0000652 while (!pbqpAllocComplete) {
653 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000654
Lang Hamesab62b7e2010-10-04 12:13:07 +0000655 std::auto_ptr<PBQPRAProblem> problem =
656 builder->build(mf, lis, loopInfo, vregsToAlloc);
657 PBQP::Solution solution =
658 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
659 problem->getGraph());
Lang Hames233fd9c2009-08-18 23:34:50 +0000660
Lang Hamesab62b7e2010-10-04 12:13:07 +0000661 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames27601ef2008-11-16 12:12:54 +0000662
Lang Hamesab62b7e2010-10-04 12:13:07 +0000663 ++round;
Lang Hames27601ef2008-11-16 12:12:54 +0000664 }
Evan Chengb1290a62008-10-02 18:29:27 +0000665 }
666
Lang Hames27601ef2008-11-16 12:12:54 +0000667 // Finalise allocation, allocate empty ranges.
668 finalizeAlloc();
Evan Chengb1290a62008-10-02 18:29:27 +0000669
Lang Hamesc4bcc772010-07-20 07:41:44 +0000670 rmf->renderMachineFunction("After PBQP register allocation.", vrm);
671
Lang Hameseb6c8f52010-09-18 09:07:10 +0000672 vregsToAlloc.clear();
673 emptyIntervalVRegs.clear();
Lang Hames27601ef2008-11-16 12:12:54 +0000674
David Greene30931542010-01-05 01:25:43 +0000675 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000676
Lang Hames87e3bca2009-05-06 02:36:21 +0000677 // Run rewriter
Jakob Stoklund Olesenc3f27222011-11-13 00:02:24 +0000678 vrm->rewrite(lis->getSlotIndexes());
Lang Hames27601ef2008-11-16 12:12:54 +0000679
Misha Brukman2a835f92009-01-08 15:50:22 +0000680 return true;
Evan Chengb1290a62008-10-02 18:29:27 +0000681}
682
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000683FunctionPass* llvm::createPBQPRegisterAllocator(
Lang Hames8d857662011-06-17 07:09:01 +0000684 std::auto_ptr<PBQPBuilder> builder,
685 char *customPassID) {
686 return new RegAllocPBQP(builder, customPassID);
Evan Chengb1290a62008-10-02 18:29:27 +0000687}
688
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000689FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
690 if (pbqpCoalescing) {
691 return createPBQPRegisterAllocator(
692 std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
693 } // else
694 return createPBQPRegisterAllocator(
695 std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
Lang Hameseb6c8f52010-09-18 09:07:10 +0000696}
Evan Chengb1290a62008-10-02 18:29:27 +0000697
698#undef DEBUG_TYPE