blob: d4f69dc6c7d0afe3f063d896b0200ff841d443a3 [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"
Lang Hames87e3bca2009-05-06 02:36:21 +000039#include "VirtRegRewriter.h"
Rafael Espindolafdf16ca2011-06-26 21:41:06 +000040#include "RegisterCoalescer.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"
Misha Brukman2a835f92009-01-08 15:50:22 +000045#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Chengb1290a62008-10-02 18:29:27 +000046#include "llvm/CodeGen/MachineLoopInfo.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000047#include "llvm/CodeGen/MachineRegisterInfo.h"
Lang Hameseb6c8f52010-09-18 09:07:10 +000048#include "llvm/CodeGen/PBQP/HeuristicSolver.h"
49#include "llvm/CodeGen/PBQP/Graph.h"
50#include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000051#include "llvm/CodeGen/RegAllocRegistry.h"
Evan Chengb1290a62008-10-02 18:29:27 +000052#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000053#include "llvm/Support/raw_ostream.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000054#include "llvm/Target/TargetInstrInfo.h"
55#include "llvm/Target/TargetMachine.h"
56#include <limits>
Misha Brukman2a835f92009-01-08 15:50:22 +000057#include <memory>
Evan Chengb1290a62008-10-02 18:29:27 +000058#include <set>
59#include <vector>
Evan Chengb1290a62008-10-02 18:29:27 +000060
Lang Hamesf70e7cc2010-09-23 04:28:54 +000061using namespace llvm;
Lang Hameseb6c8f52010-09-18 09:07:10 +000062
Evan Chengb1290a62008-10-02 18:29:27 +000063static RegisterRegAlloc
Duncan Sands1aecd152010-02-18 14:10:41 +000064registerPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesf70e7cc2010-09-23 04:28:54 +000065 createDefaultPBQPRegisterAllocator);
Evan Chengb1290a62008-10-02 18:29:27 +000066
Lang Hames8481e3b2009-08-19 01:36:14 +000067static cl::opt<bool>
68pbqpCoalescing("pbqp-coalescing",
Lang Hames030c4bf2010-01-26 04:49:58 +000069 cl::desc("Attempt coalescing during PBQP register allocation."),
70 cl::init(false), cl::Hidden);
Lang Hames8481e3b2009-08-19 01:36:14 +000071
Lang Hames12f35c52010-07-18 00:57:59 +000072static cl::opt<bool>
73pbqpPreSplitting("pbqp-pre-splitting",
Lang Hamesf70e7cc2010-09-23 04:28:54 +000074 cl::desc("Pre-split before PBQP register allocation."),
Lang Hames12f35c52010-07-18 00:57:59 +000075 cl::init(false), cl::Hidden);
76
Lang Hamesf70e7cc2010-09-23 04:28:54 +000077namespace {
78
79///
80/// PBQP based allocators solve the register allocation problem by mapping
81/// register allocation problems to Partitioned Boolean Quadratic
82/// Programming problems.
83class RegAllocPBQP : public MachineFunctionPass {
84public:
85
86 static char ID;
87
88 /// Construct a PBQP register allocator.
Lang Hames8d857662011-06-17 07:09:01 +000089 RegAllocPBQP(std::auto_ptr<PBQPBuilder> b, char *cPassID=0)
90 : MachineFunctionPass(ID), builder(b), customPassID(cPassID) {
Owen Anderson081c34b2010-10-19 17:21:58 +000091 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
92 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +000093 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +000094 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
95 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
96 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
97 initializeLoopSplitterPass(*PassRegistry::getPassRegistry());
98 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
99 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
100 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000101
102 /// Return the pass name.
103 virtual const char* getPassName() const {
104 return "PBQP Register Allocator";
105 }
106
107 /// PBQP analysis usage.
108 virtual void getAnalysisUsage(AnalysisUsage &au) const;
109
110 /// Perform register allocation
111 virtual bool runOnMachineFunction(MachineFunction &MF);
112
113private:
114
115 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
116 typedef std::vector<const LiveInterval*> Node2LIMap;
117 typedef std::vector<unsigned> AllowedSet;
118 typedef std::vector<AllowedSet> AllowedSetMap;
119 typedef std::pair<unsigned, unsigned> RegPair;
120 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
121 typedef std::vector<PBQP::Graph::NodeItr> NodeVector;
122 typedef std::set<unsigned> RegSet;
123
124
125 std::auto_ptr<PBQPBuilder> builder;
126
Lang Hames8d857662011-06-17 07:09:01 +0000127 char *customPassID;
128
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000129 MachineFunction *mf;
130 const TargetMachine *tm;
131 const TargetRegisterInfo *tri;
132 const TargetInstrInfo *tii;
133 const MachineLoopInfo *loopInfo;
134 MachineRegisterInfo *mri;
135 RenderMachineFunction *rmf;
136
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000137 std::auto_ptr<Spiller> spiller;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000138 LiveIntervals *lis;
139 LiveStacks *lss;
140 VirtRegMap *vrm;
141
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000142 RegSet vregsToAlloc, emptyIntervalVRegs;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000143
144 /// \brief Finds the initial set of vreg intervals to allocate.
145 void findVRegIntervalsToAlloc();
146
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000147 /// \brief Given a solved PBQP problem maps this solution back to a register
148 /// assignment.
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000149 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
150 const PBQP::Solution &solution);
151
152 /// \brief Postprocessing before final spilling. Sets basic block "live in"
153 /// variables.
154 void finalizeAlloc() const;
155
156};
157
Lang Hameseb6c8f52010-09-18 09:07:10 +0000158char RegAllocPBQP::ID = 0;
Evan Chengb1290a62008-10-02 18:29:27 +0000159
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000160} // End anonymous namespace.
161
Lang Hameseb6c8f52010-09-18 09:07:10 +0000162unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
163 Node2VReg::const_iterator vregItr = node2VReg.find(node);
164 assert(vregItr != node2VReg.end() && "No vreg for node.");
165 return vregItr->second;
166}
Evan Chengb1290a62008-10-02 18:29:27 +0000167
Lang Hameseb6c8f52010-09-18 09:07:10 +0000168PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
169 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
170 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
171 return nodeItr->second;
172
173}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000174
Lang Hameseb6c8f52010-09-18 09:07:10 +0000175const PBQPRAProblem::AllowedSet&
176 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
177 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
178 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
179 const AllowedSet &allowedSet = allowedSetItr->second;
180 return allowedSet;
181}
Evan Chengb1290a62008-10-02 18:29:27 +0000182
Lang Hameseb6c8f52010-09-18 09:07:10 +0000183unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
184 assert(isPRegOption(vreg, option) && "Not a preg option.");
185
186 const AllowedSet& allowedSet = getAllowedSet(vreg);
187 assert(option <= allowedSet.size() && "Option outside allowed set.");
188 return allowedSet[option - 1];
189}
190
Lang Hamese9c93562010-09-21 13:19:36 +0000191std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
192 const LiveIntervals *lis,
193 const MachineLoopInfo *loopInfo,
194 const RegSet &vregs) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000195
196 typedef std::vector<const LiveInterval*> LIVector;
197
198 MachineRegisterInfo *mri = &mf->getRegInfo();
199 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
200
201 std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
202 PBQP::Graph &g = p->getGraph();
203 RegSet pregs;
204
205 // Collect the set of preg intervals, record that they're used in the MF.
206 for (LiveIntervals::const_iterator itr = lis->begin(), end = lis->end();
207 itr != end; ++itr) {
208 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
209 pregs.insert(itr->first);
210 mri->setPhysRegUsed(itr->first);
Evan Chengb1290a62008-10-02 18:29:27 +0000211 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000212 }
Evan Chengb1290a62008-10-02 18:29:27 +0000213
Lang Hameseb6c8f52010-09-18 09:07:10 +0000214 BitVector reservedRegs = tri->getReservedRegs(*mf);
Evan Chengb1290a62008-10-02 18:29:27 +0000215
Lang Hameseb6c8f52010-09-18 09:07:10 +0000216 // Iterate over vregs.
217 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
218 vregItr != vregEnd; ++vregItr) {
219 unsigned vreg = *vregItr;
220 const TargetRegisterClass *trc = mri->getRegClass(vreg);
221 const LiveInterval *vregLI = &lis->getInterval(vreg);
Evan Chengb1290a62008-10-02 18:29:27 +0000222
Lang Hameseb6c8f52010-09-18 09:07:10 +0000223 // Compute an initial allowed set for the current vreg.
224 typedef std::vector<unsigned> VRAllowed;
225 VRAllowed vrAllowed;
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000226 ArrayRef<unsigned> rawOrder = trc->getRawAllocationOrder(*mf);
227 for (unsigned i = 0; i != rawOrder.size(); ++i) {
228 unsigned preg = rawOrder[i];
Lang Hameseb6c8f52010-09-18 09:07:10 +0000229 if (!reservedRegs.test(preg)) {
230 vrAllowed.push_back(preg);
Lang Hamesd0f6f012010-07-17 06:31:41 +0000231 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000232 }
Lang Hamesd0f6f012010-07-17 06:31:41 +0000233
Lang Hameseb6c8f52010-09-18 09:07:10 +0000234 // Remove any physical registers which overlap.
235 for (RegSet::const_iterator pregItr = pregs.begin(),
236 pregEnd = pregs.end();
237 pregItr != pregEnd; ++pregItr) {
238 unsigned preg = *pregItr;
239 const LiveInterval *pregLI = &lis->getInterval(preg);
Lang Hames27601ef2008-11-16 12:12:54 +0000240
Lang Hames5e77f4b2010-11-12 05:47:21 +0000241 if (pregLI->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000242 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000243 }
Evan Chengb1290a62008-10-02 18:29:27 +0000244
Lang Hames5e77f4b2010-11-12 05:47:21 +0000245 if (!vregLI->overlaps(*pregLI)) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000246 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000247 }
Lang Hames030c4bf2010-01-26 04:49:58 +0000248
Lang Hameseb6c8f52010-09-18 09:07:10 +0000249 // Remove the register from the allowed set.
250 VRAllowed::iterator eraseItr =
251 std::find(vrAllowed.begin(), vrAllowed.end(), preg);
Evan Chengb1290a62008-10-02 18:29:27 +0000252
Lang Hameseb6c8f52010-09-18 09:07:10 +0000253 if (eraseItr != vrAllowed.end()) {
254 vrAllowed.erase(eraseItr);
255 }
Evan Chengb1290a62008-10-02 18:29:27 +0000256
Lang Hameseb6c8f52010-09-18 09:07:10 +0000257 // Also remove any aliases.
258 const unsigned *aliasItr = tri->getAliasSet(preg);
259 if (aliasItr != 0) {
260 for (; *aliasItr != 0; ++aliasItr) {
261 VRAllowed::iterator eraseItr =
262 std::find(vrAllowed.begin(), vrAllowed.end(), *aliasItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000263
Lang Hameseb6c8f52010-09-18 09:07:10 +0000264 if (eraseItr != vrAllowed.end()) {
265 vrAllowed.erase(eraseItr);
266 }
267 }
268 }
269 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000270
Lang Hameseb6c8f52010-09-18 09:07:10 +0000271 // Construct the node.
272 PBQP::Graph::NodeItr node =
273 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
Evan Chengb1290a62008-10-02 18:29:27 +0000274
Lang Hameseb6c8f52010-09-18 09:07:10 +0000275 // Record the mapping and allowed set in the problem.
276 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
Evan Chengb1290a62008-10-02 18:29:27 +0000277
Lang Hameseb6c8f52010-09-18 09:07:10 +0000278 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
279 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb1290a62008-10-02 18:29:27 +0000280
Lang Hameseb6c8f52010-09-18 09:07:10 +0000281 addSpillCosts(g.getNodeCosts(node), spillCost);
282 }
Evan Chengb1290a62008-10-02 18:29:27 +0000283
Lang Hames481630d2010-09-18 09:49:08 +0000284 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000285 vr1Itr != vrEnd; ++vr1Itr) {
286 unsigned vr1 = *vr1Itr;
287 const LiveInterval &l1 = lis->getInterval(vr1);
288 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb1290a62008-10-02 18:29:27 +0000289
Benjamin Kramer9e8d1f92010-09-18 14:41:26 +0000290 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000291 vr2Itr != vrEnd; ++vr2Itr) {
292 unsigned vr2 = *vr2Itr;
293 const LiveInterval &l2 = lis->getInterval(vr2);
294 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb1290a62008-10-02 18:29:27 +0000295
Lang Hameseb6c8f52010-09-18 09:07:10 +0000296 assert(!l2.empty() && "Empty interval in vreg set?");
297 if (l1.overlaps(l2)) {
298 PBQP::Graph::EdgeItr edge =
299 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
300 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
Lang Hames27601ef2008-11-16 12:12:54 +0000301
Lang Hameseb6c8f52010-09-18 09:07:10 +0000302 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
303 }
304 }
305 }
Evan Chengb1290a62008-10-02 18:29:27 +0000306
Lang Hameseb6c8f52010-09-18 09:07:10 +0000307 return p;
308}
Lang Hames27601ef2008-11-16 12:12:54 +0000309
Lang Hameseb6c8f52010-09-18 09:07:10 +0000310void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
311 PBQP::PBQPNum spillCost) {
312 costVec[0] = spillCost;
313}
Evan Chengb1290a62008-10-02 18:29:27 +0000314
Lang Hamese9c93562010-09-21 13:19:36 +0000315void PBQPBuilder::addInterferenceCosts(
316 PBQP::Matrix &costMat,
317 const PBQPRAProblem::AllowedSet &vr1Allowed,
318 const PBQPRAProblem::AllowedSet &vr2Allowed,
319 const TargetRegisterInfo *tri) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000320 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
321 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
322
Lang Hames5e77f4b2010-11-12 05:47:21 +0000323 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000324 unsigned preg1 = vr1Allowed[i];
325
Lang Hames5e77f4b2010-11-12 05:47:21 +0000326 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000327 unsigned preg2 = vr2Allowed[j];
328
329 if (tri->regsOverlap(preg1, preg2)) {
330 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
331 }
332 }
333 }
Evan Chengb1290a62008-10-02 18:29:27 +0000334}
335
Lang Hamese9c93562010-09-21 13:19:36 +0000336std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
337 MachineFunction *mf,
338 const LiveIntervals *lis,
339 const MachineLoopInfo *loopInfo,
340 const RegSet &vregs) {
341
342 std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
343 PBQP::Graph &g = p->getGraph();
344
345 const TargetMachine &tm = mf->getTarget();
346 CoalescerPair cp(*tm.getInstrInfo(), *tm.getRegisterInfo());
347
348 // Scan the machine function and add a coalescing cost whenever CoalescerPair
349 // gives the Ok.
350 for (MachineFunction::const_iterator mbbItr = mf->begin(),
351 mbbEnd = mf->end();
352 mbbItr != mbbEnd; ++mbbItr) {
353 const MachineBasicBlock *mbb = &*mbbItr;
354
355 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
356 miEnd = mbb->end();
357 miItr != miEnd; ++miItr) {
358 const MachineInstr *mi = &*miItr;
359
Lang Hames5e77f4b2010-11-12 05:47:21 +0000360 if (!cp.setRegisters(mi)) {
Lang Hamese9c93562010-09-21 13:19:36 +0000361 continue; // Not coalescable.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000362 }
Lang Hamese9c93562010-09-21 13:19:36 +0000363
Lang Hames5e77f4b2010-11-12 05:47:21 +0000364 if (cp.getSrcReg() == cp.getDstReg()) {
Lang Hamese9c93562010-09-21 13:19:36 +0000365 continue; // Already coalesced.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000366 }
Lang Hamese9c93562010-09-21 13:19:36 +0000367
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000368 unsigned dst = cp.getDstReg(),
369 src = cp.getSrcReg();
Lang Hamese9c93562010-09-21 13:19:36 +0000370
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000371 const float copyFactor = 0.5; // Cost of copy relative to load. Current
372 // value plucked randomly out of the air.
373
374 PBQP::PBQPNum cBenefit =
375 copyFactor * LiveIntervals::getSpillWeight(false, true,
376 loopInfo->getLoopDepth(mbb));
Lang Hamese9c93562010-09-21 13:19:36 +0000377
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000378 if (cp.isPhys()) {
Lang Hames5e77f4b2010-11-12 05:47:21 +0000379 if (!lis->isAllocatable(dst)) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000380 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000381 }
Lang Hamese9c93562010-09-21 13:19:36 +0000382
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000383 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
384 unsigned pregOpt = 0;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000385 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000386 ++pregOpt;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000387 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000388 if (pregOpt < allowed.size()) {
389 ++pregOpt; // +1 to account for spill option.
390 PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
391 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000392 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000393 } else {
394 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
395 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
396 PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
397 PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
398 PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
399 if (edge == g.edgesEnd()) {
400 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
401 allowed2->size() + 1,
402 0));
403 } else {
404 if (g.getEdgeNode1(edge) == node2) {
405 std::swap(node1, node2);
406 std::swap(allowed1, allowed2);
407 }
408 }
409
410 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
411 cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000412 }
413 }
414 }
415
416 return p;
417}
418
Lang Hamese9c93562010-09-21 13:19:36 +0000419void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
420 unsigned pregOption,
421 PBQP::PBQPNum benefit) {
422 costVec[pregOption] += -benefit;
423}
424
425void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
426 PBQP::Matrix &costMat,
427 const PBQPRAProblem::AllowedSet &vr1Allowed,
428 const PBQPRAProblem::AllowedSet &vr2Allowed,
429 PBQP::PBQPNum benefit) {
430
431 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
432 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
433
Lang Hames5e77f4b2010-11-12 05:47:21 +0000434 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hamese9c93562010-09-21 13:19:36 +0000435 unsigned preg1 = vr1Allowed[i];
Lang Hames5e77f4b2010-11-12 05:47:21 +0000436 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hamese9c93562010-09-21 13:19:36 +0000437 unsigned preg2 = vr2Allowed[j];
438
439 if (preg1 == preg2) {
440 costMat[i + 1][j + 1] += -benefit;
441 }
442 }
443 }
444}
Evan Chengb1290a62008-10-02 18:29:27 +0000445
Lang Hameseb6c8f52010-09-18 09:07:10 +0000446
447void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
448 au.addRequired<SlotIndexes>();
449 au.addPreserved<SlotIndexes>();
450 au.addRequired<LiveIntervals>();
451 //au.addRequiredID(SplitCriticalEdgesID);
Jakob Stoklund Olesen27215672011-08-09 00:29:53 +0000452 au.addRequiredID(RegisterCoalescerPassID);
Lang Hames8d857662011-06-17 07:09:01 +0000453 if (customPassID)
454 au.addRequiredID(*customPassID);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000455 au.addRequired<CalculateSpillWeights>();
456 au.addRequired<LiveStacks>();
457 au.addPreserved<LiveStacks>();
458 au.addRequired<MachineLoopInfo>();
459 au.addPreserved<MachineLoopInfo>();
460 if (pbqpPreSplitting)
461 au.addRequired<LoopSplitter>();
462 au.addRequired<VirtRegMap>();
463 au.addRequired<RenderMachineFunction>();
464 MachineFunctionPass::getAnalysisUsage(au);
465}
466
Lang Hameseb6c8f52010-09-18 09:07:10 +0000467void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames27601ef2008-11-16 12:12:54 +0000468
469 // Iterate over all live ranges.
470 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
471 itr != end; ++itr) {
472
473 // Ignore physical ones.
474 if (TargetRegisterInfo::isPhysicalRegister(itr->first))
475 continue;
476
477 LiveInterval *li = itr->second;
478
479 // If this live interval is non-empty we will use pbqp to allocate it.
480 // Empty intervals we allocate in a simple post-processing stage in
481 // finalizeAlloc.
482 if (!li->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000483 vregsToAlloc.insert(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000484 } else {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000485 emptyIntervalVRegs.insert(li->reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000486 }
487 }
Evan Chengb1290a62008-10-02 18:29:27 +0000488}
489
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000490bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
491 const PBQP::Solution &solution) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000492 // Set to true if we have any spills
493 bool anotherRoundNeeded = false;
494
495 // Clear the existing allocation.
496 vrm->clearAllVirt();
497
498 const PBQP::Graph &g = problem.getGraph();
499 // Iterate over the nodes mapping the PBQP solution to a register
500 // assignment.
501 for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
502 nodeEnd = g.nodesEnd();
503 node != nodeEnd; ++node) {
504 unsigned vreg = problem.getVRegForNode(node);
505 unsigned alloc = solution.getSelection(node);
506
507 if (problem.isPRegOption(vreg, alloc)) {
508 unsigned preg = problem.getPRegForOption(vreg, alloc);
509 DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "\n");
510 assert(preg != 0 && "Invalid preg selected.");
511 vrm->assignVirt2Phys(vreg, preg);
512 } else if (problem.isSpillOption(vreg, alloc)) {
513 vregsToAlloc.erase(vreg);
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000514 SmallVector<LiveInterval*, 8> newSpills;
515 LiveRangeEdit LRE(lis->getInterval(vreg), newSpills);
516 spiller->spill(LRE);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000517
Lang Hameseb6c8f52010-09-18 09:07:10 +0000518 DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000519 << LRE.getParent().weight << ", New vregs: ");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000520
521 // Copy any newly inserted live intervals into the list of regs to
522 // allocate.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000523 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000524 itr != end; ++itr) {
525 assert(!(*itr)->empty() && "Empty spill range.");
526 DEBUG(dbgs() << (*itr)->reg << " ");
527 vregsToAlloc.insert((*itr)->reg);
528 }
529
530 DEBUG(dbgs() << ")\n");
531
532 // We need another round if spill intervals were added.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000533 anotherRoundNeeded |= !LRE.empty();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000534 } else {
535 assert(false && "Unknown allocation option.");
536 }
537 }
538
539 return !anotherRoundNeeded;
540}
541
542
543void RegAllocPBQP::finalizeAlloc() const {
Lang Hames27601ef2008-11-16 12:12:54 +0000544 typedef LiveIntervals::iterator LIIterator;
545 typedef LiveInterval::Ranges::const_iterator LRIterator;
546
547 // First allocate registers for the empty intervals.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000548 for (RegSet::const_iterator
549 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames27601ef2008-11-16 12:12:54 +0000550 itr != end; ++itr) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000551 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames27601ef2008-11-16 12:12:54 +0000552
Evan Cheng90f95f82009-06-14 20:22:55 +0000553 unsigned physReg = vrm->getRegAllocPref(li->reg);
Lang Hames6699fb22009-08-06 23:32:48 +0000554
Lang Hames27601ef2008-11-16 12:12:54 +0000555 if (physReg == 0) {
556 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000557 physReg = liRC->getRawAllocationOrder(*mf).front();
Lang Hames27601ef2008-11-16 12:12:54 +0000558 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000559
560 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames27601ef2008-11-16 12:12:54 +0000561 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000562
Lang Hames27601ef2008-11-16 12:12:54 +0000563 // Finally iterate over the basic blocks to compute and set the live-in sets.
564 SmallVector<MachineBasicBlock*, 8> liveInMBBs;
565 MachineBasicBlock *entryMBB = &*mf->begin();
566
567 for (LIIterator liItr = lis->begin(), liEnd = lis->end();
568 liItr != liEnd; ++liItr) {
569
570 const LiveInterval *li = liItr->second;
571 unsigned reg = 0;
Misha Brukman2a835f92009-01-08 15:50:22 +0000572
Lang Hames27601ef2008-11-16 12:12:54 +0000573 // Get the physical register for this interval
574 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
575 reg = li->reg;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000576 } else if (vrm->isAssignedReg(li->reg)) {
Lang Hames27601ef2008-11-16 12:12:54 +0000577 reg = vrm->getPhys(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000578 } else {
Lang Hames27601ef2008-11-16 12:12:54 +0000579 // Ranges which are assigned a stack slot only are ignored.
580 continue;
581 }
582
Lang Hamesb0e519f2009-05-17 23:50:36 +0000583 if (reg == 0) {
Lang Hames6699fb22009-08-06 23:32:48 +0000584 // Filter out zero regs - they're for intervals that were spilled.
Lang Hamesb0e519f2009-05-17 23:50:36 +0000585 continue;
586 }
587
Lang Hames27601ef2008-11-16 12:12:54 +0000588 // Iterate over the ranges of the current interval...
589 for (LRIterator lrItr = li->begin(), lrEnd = li->end();
590 lrItr != lrEnd; ++lrItr) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000591
Lang Hames27601ef2008-11-16 12:12:54 +0000592 // Find the set of basic blocks which this range is live into...
593 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
594 // And add the physreg for this interval to their live-in sets.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000595 for (unsigned i = 0; i != liveInMBBs.size(); ++i) {
Lang Hames27601ef2008-11-16 12:12:54 +0000596 if (liveInMBBs[i] != entryMBB) {
597 if (!liveInMBBs[i]->isLiveIn(reg)) {
598 liveInMBBs[i]->addLiveIn(reg);
599 }
600 }
601 }
602 liveInMBBs.clear();
603 }
604 }
605 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000606
Lang Hames27601ef2008-11-16 12:12:54 +0000607}
608
Lang Hameseb6c8f52010-09-18 09:07:10 +0000609bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames27601ef2008-11-16 12:12:54 +0000610
Evan Chengb1290a62008-10-02 18:29:27 +0000611 mf = &MF;
612 tm = &mf->getTarget();
613 tri = tm->getRegisterInfo();
Lang Hames27601ef2008-11-16 12:12:54 +0000614 tii = tm->getInstrInfo();
Lang Hames233a60e2009-11-03 23:52:08 +0000615 mri = &mf->getRegInfo();
Evan Chengb1290a62008-10-02 18:29:27 +0000616
Lang Hames27601ef2008-11-16 12:12:54 +0000617 lis = &getAnalysis<LiveIntervals>();
618 lss = &getAnalysis<LiveStacks>();
Evan Chengb1290a62008-10-02 18:29:27 +0000619 loopInfo = &getAnalysis<MachineLoopInfo>();
Lang Hames33198392010-09-02 08:27:00 +0000620 rmf = &getAnalysis<RenderMachineFunction>();
Evan Chengb1290a62008-10-02 18:29:27 +0000621
Owen Anderson49c8aa02009-03-13 05:55:11 +0000622 vrm = &getAnalysis<VirtRegMap>();
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000623 spiller.reset(createInlineSpiller(*this, MF, *vrm));
Evan Chengb1290a62008-10-02 18:29:27 +0000624
Lang Hames54cc2ef2010-07-19 15:22:28 +0000625
Lang Hames030c4bf2010-01-26 04:49:58 +0000626 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000627
Evan Chengb1290a62008-10-02 18:29:27 +0000628 // Allocator main loop:
Misha Brukman2a835f92009-01-08 15:50:22 +0000629 //
Evan Chengb1290a62008-10-02 18:29:27 +0000630 // * Map current regalloc problem to a PBQP problem
631 // * Solve the PBQP problem
632 // * Map the solution back to a register allocation
633 // * Spill if necessary
Misha Brukman2a835f92009-01-08 15:50:22 +0000634 //
Evan Chengb1290a62008-10-02 18:29:27 +0000635 // This process is continued till no more spills are generated.
636
Lang Hames27601ef2008-11-16 12:12:54 +0000637 // Find the vreg intervals in need of allocation.
638 findVRegIntervalsToAlloc();
Misha Brukman2a835f92009-01-08 15:50:22 +0000639
Lang Hames27601ef2008-11-16 12:12:54 +0000640 // If there are non-empty intervals allocate them using pbqp.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000641 if (!vregsToAlloc.empty()) {
Evan Chengb1290a62008-10-02 18:29:27 +0000642
Lang Hames27601ef2008-11-16 12:12:54 +0000643 bool pbqpAllocComplete = false;
644 unsigned round = 0;
645
Lang Hamesab62b7e2010-10-04 12:13:07 +0000646 while (!pbqpAllocComplete) {
647 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000648
Lang Hamesab62b7e2010-10-04 12:13:07 +0000649 std::auto_ptr<PBQPRAProblem> problem =
650 builder->build(mf, lis, loopInfo, vregsToAlloc);
651 PBQP::Solution solution =
652 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
653 problem->getGraph());
Lang Hames233fd9c2009-08-18 23:34:50 +0000654
Lang Hamesab62b7e2010-10-04 12:13:07 +0000655 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames27601ef2008-11-16 12:12:54 +0000656
Lang Hamesab62b7e2010-10-04 12:13:07 +0000657 ++round;
Lang Hames27601ef2008-11-16 12:12:54 +0000658 }
Evan Chengb1290a62008-10-02 18:29:27 +0000659 }
660
Lang Hames27601ef2008-11-16 12:12:54 +0000661 // Finalise allocation, allocate empty ranges.
662 finalizeAlloc();
Evan Chengb1290a62008-10-02 18:29:27 +0000663
Lang Hamesc4bcc772010-07-20 07:41:44 +0000664 rmf->renderMachineFunction("After PBQP register allocation.", vrm);
665
Lang Hameseb6c8f52010-09-18 09:07:10 +0000666 vregsToAlloc.clear();
667 emptyIntervalVRegs.clear();
Lang Hames27601ef2008-11-16 12:12:54 +0000668
David Greene30931542010-01-05 01:25:43 +0000669 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000670
Lang Hames87e3bca2009-05-06 02:36:21 +0000671 // Run rewriter
672 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
673
674 rewriter->runOnMachineFunction(*mf, *vrm, lis);
Lang Hames27601ef2008-11-16 12:12:54 +0000675
Misha Brukman2a835f92009-01-08 15:50:22 +0000676 return true;
Evan Chengb1290a62008-10-02 18:29:27 +0000677}
678
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000679FunctionPass* llvm::createPBQPRegisterAllocator(
Lang Hames8d857662011-06-17 07:09:01 +0000680 std::auto_ptr<PBQPBuilder> builder,
681 char *customPassID) {
682 return new RegAllocPBQP(builder, customPassID);
Evan Chengb1290a62008-10-02 18:29:27 +0000683}
684
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000685FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
686 if (pbqpCoalescing) {
687 return createPBQPRegisterAllocator(
688 std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
689 } // else
690 return createPBQPRegisterAllocator(
691 std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
Lang Hameseb6c8f52010-09-18 09:07:10 +0000692}
Evan Chengb1290a62008-10-02 18:29:27 +0000693
694#undef DEBUG_TYPE