blob: f15574c8cbdc329418f64a9ba69e2edbb1eb709f [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"
Evan Chengb1290a62008-10-02 18:29:27 +000037#include "VirtRegMap.h"
Rafael Espindolafdf16ca2011-06-26 21:41:06 +000038#include "RegisterCoalescer.h"
Lang Hames9ad7e072011-12-06 01:45:57 +000039#include "llvm/Analysis/AliasAnalysis.h"
Lang Hamesa937f222009-12-14 06:49:42 +000040#include "llvm/CodeGen/CalcSpillWeights.h"
Evan Chengb1290a62008-10-02 18:29:27 +000041#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Lang Hames27601ef2008-11-16 12:12:54 +000042#include "llvm/CodeGen/LiveStackAnalysis.h"
Lang Hameseb6c8f52010-09-18 09:07:10 +000043#include "llvm/CodeGen/RegAllocPBQP.h"
Lang Hames9ad7e072011-12-06 01:45:57 +000044#include "llvm/CodeGen/MachineDominators.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 Hamesf70e7cc2010-09-23 04:28:54 +000072namespace {
73
74///
75/// PBQP based allocators solve the register allocation problem by mapping
76/// register allocation problems to Partitioned Boolean Quadratic
77/// Programming problems.
78class RegAllocPBQP : public MachineFunctionPass {
79public:
80
81 static char ID;
82
83 /// Construct a PBQP register allocator.
Lang Hames8d857662011-06-17 07:09:01 +000084 RegAllocPBQP(std::auto_ptr<PBQPBuilder> b, char *cPassID=0)
85 : MachineFunctionPass(ID), builder(b), customPassID(cPassID) {
Owen Anderson081c34b2010-10-19 17:21:58 +000086 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
87 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +000088 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
89 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
90 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +000091 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
92 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
93 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +000094
95 /// Return the pass name.
96 virtual const char* getPassName() const {
97 return "PBQP Register Allocator";
98 }
99
100 /// PBQP analysis usage.
101 virtual void getAnalysisUsage(AnalysisUsage &au) const;
102
103 /// Perform register allocation
104 virtual bool runOnMachineFunction(MachineFunction &MF);
105
106private:
107
108 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
109 typedef std::vector<const LiveInterval*> Node2LIMap;
110 typedef std::vector<unsigned> AllowedSet;
111 typedef std::vector<AllowedSet> AllowedSetMap;
112 typedef std::pair<unsigned, unsigned> RegPair;
113 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
114 typedef std::vector<PBQP::Graph::NodeItr> NodeVector;
115 typedef std::set<unsigned> RegSet;
116
117
118 std::auto_ptr<PBQPBuilder> builder;
119
Lang Hames8d857662011-06-17 07:09:01 +0000120 char *customPassID;
121
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000122 MachineFunction *mf;
123 const TargetMachine *tm;
124 const TargetRegisterInfo *tri;
125 const TargetInstrInfo *tii;
126 const MachineLoopInfo *loopInfo;
127 MachineRegisterInfo *mri;
128 RenderMachineFunction *rmf;
129
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000130 std::auto_ptr<Spiller> spiller;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000131 LiveIntervals *lis;
132 LiveStacks *lss;
133 VirtRegMap *vrm;
134
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000135 RegSet vregsToAlloc, emptyIntervalVRegs;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000136
137 /// \brief Finds the initial set of vreg intervals to allocate.
138 void findVRegIntervalsToAlloc();
139
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000140 /// \brief Given a solved PBQP problem maps this solution back to a register
141 /// assignment.
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000142 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
143 const PBQP::Solution &solution);
144
145 /// \brief Postprocessing before final spilling. Sets basic block "live in"
146 /// variables.
147 void finalizeAlloc() const;
148
149};
150
Lang Hameseb6c8f52010-09-18 09:07:10 +0000151char RegAllocPBQP::ID = 0;
Evan Chengb1290a62008-10-02 18:29:27 +0000152
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000153} // End anonymous namespace.
154
Lang Hameseb6c8f52010-09-18 09:07:10 +0000155unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
156 Node2VReg::const_iterator vregItr = node2VReg.find(node);
157 assert(vregItr != node2VReg.end() && "No vreg for node.");
158 return vregItr->second;
159}
Evan Chengb1290a62008-10-02 18:29:27 +0000160
Lang Hameseb6c8f52010-09-18 09:07:10 +0000161PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
162 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
163 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
164 return nodeItr->second;
Andrew Trick16f72dd2012-02-10 04:10:26 +0000165
Lang Hameseb6c8f52010-09-18 09:07:10 +0000166}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000167
Lang Hameseb6c8f52010-09-18 09:07:10 +0000168const PBQPRAProblem::AllowedSet&
169 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
170 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
171 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
172 const AllowedSet &allowedSet = allowedSetItr->second;
173 return allowedSet;
174}
Evan Chengb1290a62008-10-02 18:29:27 +0000175
Lang Hameseb6c8f52010-09-18 09:07:10 +0000176unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
177 assert(isPRegOption(vreg, option) && "Not a preg option.");
178
179 const AllowedSet& allowedSet = getAllowedSet(vreg);
180 assert(option <= allowedSet.size() && "Option outside allowed set.");
181 return allowedSet[option - 1];
182}
183
Lang Hamese9c93562010-09-21 13:19:36 +0000184std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
185 const LiveIntervals *lis,
186 const MachineLoopInfo *loopInfo,
187 const RegSet &vregs) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000188
189 typedef std::vector<const LiveInterval*> LIVector;
190
191 MachineRegisterInfo *mri = &mf->getRegInfo();
Andrew Trick16f72dd2012-02-10 04:10:26 +0000192 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000193
194 std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
195 PBQP::Graph &g = p->getGraph();
196 RegSet pregs;
197
198 // Collect the set of preg intervals, record that they're used in the MF.
199 for (LiveIntervals::const_iterator itr = lis->begin(), end = lis->end();
200 itr != end; ++itr) {
201 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
202 pregs.insert(itr->first);
203 mri->setPhysRegUsed(itr->first);
Evan Chengb1290a62008-10-02 18:29:27 +0000204 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000205 }
Evan Chengb1290a62008-10-02 18:29:27 +0000206
Lang Hameseb6c8f52010-09-18 09:07:10 +0000207 BitVector reservedRegs = tri->getReservedRegs(*mf);
Evan Chengb1290a62008-10-02 18:29:27 +0000208
Andrew Trick16f72dd2012-02-10 04:10:26 +0000209 // Iterate over vregs.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000210 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
211 vregItr != vregEnd; ++vregItr) {
212 unsigned vreg = *vregItr;
213 const TargetRegisterClass *trc = mri->getRegClass(vreg);
214 const LiveInterval *vregLI = &lis->getInterval(vreg);
Evan Chengb1290a62008-10-02 18:29:27 +0000215
Lang Hameseb6c8f52010-09-18 09:07:10 +0000216 // Compute an initial allowed set for the current vreg.
217 typedef std::vector<unsigned> VRAllowed;
218 VRAllowed vrAllowed;
Craig Topperb6632ba2012-03-04 10:16:38 +0000219 ArrayRef<uint16_t> rawOrder = trc->getRawAllocationOrder(*mf);
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000220 for (unsigned i = 0; i != rawOrder.size(); ++i) {
221 unsigned preg = rawOrder[i];
Lang Hameseb6c8f52010-09-18 09:07:10 +0000222 if (!reservedRegs.test(preg)) {
223 vrAllowed.push_back(preg);
Lang Hamesd0f6f012010-07-17 06:31:41 +0000224 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000225 }
Lang Hamesd0f6f012010-07-17 06:31:41 +0000226
Lang Hameseb6c8f52010-09-18 09:07:10 +0000227 // Remove any physical registers which overlap.
228 for (RegSet::const_iterator pregItr = pregs.begin(),
229 pregEnd = pregs.end();
230 pregItr != pregEnd; ++pregItr) {
231 unsigned preg = *pregItr;
232 const LiveInterval *pregLI = &lis->getInterval(preg);
Lang Hames27601ef2008-11-16 12:12:54 +0000233
Lang Hames5e77f4b2010-11-12 05:47:21 +0000234 if (pregLI->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000235 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000236 }
Evan Chengb1290a62008-10-02 18:29:27 +0000237
Lang Hames5e77f4b2010-11-12 05:47:21 +0000238 if (!vregLI->overlaps(*pregLI)) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000239 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000240 }
Lang Hames030c4bf2010-01-26 04:49:58 +0000241
Lang Hameseb6c8f52010-09-18 09:07:10 +0000242 // Remove the register from the allowed set.
243 VRAllowed::iterator eraseItr =
244 std::find(vrAllowed.begin(), vrAllowed.end(), preg);
Evan Chengb1290a62008-10-02 18:29:27 +0000245
Lang Hameseb6c8f52010-09-18 09:07:10 +0000246 if (eraseItr != vrAllowed.end()) {
247 vrAllowed.erase(eraseItr);
248 }
Evan Chengb1290a62008-10-02 18:29:27 +0000249
Lang Hameseb6c8f52010-09-18 09:07:10 +0000250 // Also remove any aliases.
251 const unsigned *aliasItr = tri->getAliasSet(preg);
252 if (aliasItr != 0) {
253 for (; *aliasItr != 0; ++aliasItr) {
254 VRAllowed::iterator eraseItr =
255 std::find(vrAllowed.begin(), vrAllowed.end(), *aliasItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000256
Lang Hameseb6c8f52010-09-18 09:07:10 +0000257 if (eraseItr != vrAllowed.end()) {
258 vrAllowed.erase(eraseItr);
259 }
260 }
261 }
262 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000263
Lang Hameseb6c8f52010-09-18 09:07:10 +0000264 // Construct the node.
Andrew Trick16f72dd2012-02-10 04:10:26 +0000265 PBQP::Graph::NodeItr node =
Lang Hameseb6c8f52010-09-18 09:07:10 +0000266 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
Evan Chengb1290a62008-10-02 18:29:27 +0000267
Lang Hameseb6c8f52010-09-18 09:07:10 +0000268 // Record the mapping and allowed set in the problem.
269 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
Evan Chengb1290a62008-10-02 18:29:27 +0000270
Lang Hameseb6c8f52010-09-18 09:07:10 +0000271 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
272 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb1290a62008-10-02 18:29:27 +0000273
Lang Hameseb6c8f52010-09-18 09:07:10 +0000274 addSpillCosts(g.getNodeCosts(node), spillCost);
275 }
Evan Chengb1290a62008-10-02 18:29:27 +0000276
Lang Hames481630d2010-09-18 09:49:08 +0000277 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000278 vr1Itr != vrEnd; ++vr1Itr) {
279 unsigned vr1 = *vr1Itr;
280 const LiveInterval &l1 = lis->getInterval(vr1);
281 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb1290a62008-10-02 18:29:27 +0000282
Benjamin Kramer9e8d1f92010-09-18 14:41:26 +0000283 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000284 vr2Itr != vrEnd; ++vr2Itr) {
285 unsigned vr2 = *vr2Itr;
286 const LiveInterval &l2 = lis->getInterval(vr2);
287 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb1290a62008-10-02 18:29:27 +0000288
Lang Hameseb6c8f52010-09-18 09:07:10 +0000289 assert(!l2.empty() && "Empty interval in vreg set?");
290 if (l1.overlaps(l2)) {
291 PBQP::Graph::EdgeItr edge =
292 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
293 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
Lang Hames27601ef2008-11-16 12:12:54 +0000294
Lang Hameseb6c8f52010-09-18 09:07:10 +0000295 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
296 }
297 }
298 }
Evan Chengb1290a62008-10-02 18:29:27 +0000299
Lang Hameseb6c8f52010-09-18 09:07:10 +0000300 return p;
301}
Lang Hames27601ef2008-11-16 12:12:54 +0000302
Lang Hameseb6c8f52010-09-18 09:07:10 +0000303void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
304 PBQP::PBQPNum spillCost) {
305 costVec[0] = spillCost;
306}
Evan Chengb1290a62008-10-02 18:29:27 +0000307
Lang Hamese9c93562010-09-21 13:19:36 +0000308void PBQPBuilder::addInterferenceCosts(
309 PBQP::Matrix &costMat,
310 const PBQPRAProblem::AllowedSet &vr1Allowed,
311 const PBQPRAProblem::AllowedSet &vr2Allowed,
312 const TargetRegisterInfo *tri) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000313 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
314 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
315
Lang Hames5e77f4b2010-11-12 05:47:21 +0000316 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000317 unsigned preg1 = vr1Allowed[i];
318
Lang Hames5e77f4b2010-11-12 05:47:21 +0000319 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000320 unsigned preg2 = vr2Allowed[j];
321
322 if (tri->regsOverlap(preg1, preg2)) {
323 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
324 }
325 }
326 }
Evan Chengb1290a62008-10-02 18:29:27 +0000327}
328
Lang Hamese9c93562010-09-21 13:19:36 +0000329std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
330 MachineFunction *mf,
331 const LiveIntervals *lis,
332 const MachineLoopInfo *loopInfo,
333 const RegSet &vregs) {
334
335 std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
336 PBQP::Graph &g = p->getGraph();
337
338 const TargetMachine &tm = mf->getTarget();
339 CoalescerPair cp(*tm.getInstrInfo(), *tm.getRegisterInfo());
340
341 // Scan the machine function and add a coalescing cost whenever CoalescerPair
342 // gives the Ok.
343 for (MachineFunction::const_iterator mbbItr = mf->begin(),
344 mbbEnd = mf->end();
345 mbbItr != mbbEnd; ++mbbItr) {
346 const MachineBasicBlock *mbb = &*mbbItr;
347
348 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
349 miEnd = mbb->end();
350 miItr != miEnd; ++miItr) {
351 const MachineInstr *mi = &*miItr;
352
Lang Hames5e77f4b2010-11-12 05:47:21 +0000353 if (!cp.setRegisters(mi)) {
Lang Hamese9c93562010-09-21 13:19:36 +0000354 continue; // Not coalescable.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000355 }
Lang Hamese9c93562010-09-21 13:19:36 +0000356
Lang Hames5e77f4b2010-11-12 05:47:21 +0000357 if (cp.getSrcReg() == cp.getDstReg()) {
Lang Hamese9c93562010-09-21 13:19:36 +0000358 continue; // Already coalesced.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000359 }
Lang Hamese9c93562010-09-21 13:19:36 +0000360
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000361 unsigned dst = cp.getDstReg(),
362 src = cp.getSrcReg();
Lang Hamese9c93562010-09-21 13:19:36 +0000363
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000364 const float copyFactor = 0.5; // Cost of copy relative to load. Current
365 // value plucked randomly out of the air.
Andrew Trick16f72dd2012-02-10 04:10:26 +0000366
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000367 PBQP::PBQPNum cBenefit =
368 copyFactor * LiveIntervals::getSpillWeight(false, true,
369 loopInfo->getLoopDepth(mbb));
Lang Hamese9c93562010-09-21 13:19:36 +0000370
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000371 if (cp.isPhys()) {
Lang Hames5e77f4b2010-11-12 05:47:21 +0000372 if (!lis->isAllocatable(dst)) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000373 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000374 }
Lang Hamese9c93562010-09-21 13:19:36 +0000375
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000376 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
Andrew Trick16f72dd2012-02-10 04:10:26 +0000377 unsigned pregOpt = 0;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000378 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000379 ++pregOpt;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000380 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000381 if (pregOpt < allowed.size()) {
382 ++pregOpt; // +1 to account for spill option.
383 PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
384 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000385 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000386 } else {
387 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
388 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
389 PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
390 PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
391 PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
392 if (edge == g.edgesEnd()) {
393 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
394 allowed2->size() + 1,
395 0));
396 } else {
397 if (g.getEdgeNode1(edge) == node2) {
398 std::swap(node1, node2);
399 std::swap(allowed1, allowed2);
400 }
401 }
Andrew Trick16f72dd2012-02-10 04:10:26 +0000402
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000403 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
404 cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000405 }
406 }
407 }
408
409 return p;
410}
411
Lang Hamese9c93562010-09-21 13:19:36 +0000412void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
413 unsigned pregOption,
414 PBQP::PBQPNum benefit) {
415 costVec[pregOption] += -benefit;
416}
417
418void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
419 PBQP::Matrix &costMat,
420 const PBQPRAProblem::AllowedSet &vr1Allowed,
421 const PBQPRAProblem::AllowedSet &vr2Allowed,
422 PBQP::PBQPNum benefit) {
423
424 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
425 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
426
Lang Hames5e77f4b2010-11-12 05:47:21 +0000427 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hamese9c93562010-09-21 13:19:36 +0000428 unsigned preg1 = vr1Allowed[i];
Lang Hames5e77f4b2010-11-12 05:47:21 +0000429 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hamese9c93562010-09-21 13:19:36 +0000430 unsigned preg2 = vr2Allowed[j];
431
432 if (preg1 == preg2) {
433 costMat[i + 1][j + 1] += -benefit;
Andrew Trick16f72dd2012-02-10 04:10:26 +0000434 }
Lang Hamese9c93562010-09-21 13:19:36 +0000435 }
436 }
437}
Evan Chengb1290a62008-10-02 18:29:27 +0000438
Lang Hameseb6c8f52010-09-18 09:07:10 +0000439
440void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hames9ad7e072011-12-06 01:45:57 +0000441 au.setPreservesCFG();
442 au.addRequired<AliasAnalysis>();
443 au.addPreserved<AliasAnalysis>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000444 au.addRequired<SlotIndexes>();
445 au.addPreserved<SlotIndexes>();
446 au.addRequired<LiveIntervals>();
447 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames8d857662011-06-17 07:09:01 +0000448 if (customPassID)
449 au.addRequiredID(*customPassID);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000450 au.addRequired<CalculateSpillWeights>();
451 au.addRequired<LiveStacks>();
452 au.addPreserved<LiveStacks>();
Lang Hames9ad7e072011-12-06 01:45:57 +0000453 au.addRequired<MachineDominatorTree>();
454 au.addPreserved<MachineDominatorTree>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000455 au.addRequired<MachineLoopInfo>();
456 au.addPreserved<MachineLoopInfo>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000457 au.addRequired<VirtRegMap>();
458 au.addRequired<RenderMachineFunction>();
459 MachineFunctionPass::getAnalysisUsage(au);
460}
461
Lang Hameseb6c8f52010-09-18 09:07:10 +0000462void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames27601ef2008-11-16 12:12:54 +0000463
464 // Iterate over all live ranges.
465 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
466 itr != end; ++itr) {
467
468 // Ignore physical ones.
469 if (TargetRegisterInfo::isPhysicalRegister(itr->first))
470 continue;
471
472 LiveInterval *li = itr->second;
473
474 // If this live interval is non-empty we will use pbqp to allocate it.
475 // Empty intervals we allocate in a simple post-processing stage in
476 // finalizeAlloc.
477 if (!li->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000478 vregsToAlloc.insert(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000479 } else {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000480 emptyIntervalVRegs.insert(li->reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000481 }
482 }
Evan Chengb1290a62008-10-02 18:29:27 +0000483}
484
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000485bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
486 const PBQP::Solution &solution) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000487 // Set to true if we have any spills
488 bool anotherRoundNeeded = false;
489
490 // Clear the existing allocation.
491 vrm->clearAllVirt();
492
493 const PBQP::Graph &g = problem.getGraph();
494 // Iterate over the nodes mapping the PBQP solution to a register
495 // assignment.
496 for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
497 nodeEnd = g.nodesEnd();
498 node != nodeEnd; ++node) {
499 unsigned vreg = problem.getVRegForNode(node);
500 unsigned alloc = solution.getSelection(node);
501
502 if (problem.isPRegOption(vreg, alloc)) {
Andrew Trick16f72dd2012-02-10 04:10:26 +0000503 unsigned preg = problem.getPRegForOption(vreg, alloc);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000504 DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "\n");
505 assert(preg != 0 && "Invalid preg selected.");
Andrew Trick16f72dd2012-02-10 04:10:26 +0000506 vrm->assignVirt2Phys(vreg, preg);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000507 } else if (problem.isSpillOption(vreg, alloc)) {
508 vregsToAlloc.erase(vreg);
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000509 SmallVector<LiveInterval*, 8> newSpills;
510 LiveRangeEdit LRE(lis->getInterval(vreg), newSpills);
511 spiller->spill(LRE);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000512
Lang Hameseb6c8f52010-09-18 09:07:10 +0000513 DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000514 << LRE.getParent().weight << ", New vregs: ");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000515
516 // Copy any newly inserted live intervals into the list of regs to
517 // allocate.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000518 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000519 itr != end; ++itr) {
520 assert(!(*itr)->empty() && "Empty spill range.");
521 DEBUG(dbgs() << (*itr)->reg << " ");
522 vregsToAlloc.insert((*itr)->reg);
523 }
524
525 DEBUG(dbgs() << ")\n");
526
527 // We need another round if spill intervals were added.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000528 anotherRoundNeeded |= !LRE.empty();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000529 } else {
Craig Topper5e25ee82012-02-05 08:31:47 +0000530 llvm_unreachable("Unknown allocation option.");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000531 }
532 }
533
534 return !anotherRoundNeeded;
535}
536
537
538void RegAllocPBQP::finalizeAlloc() const {
Lang Hames27601ef2008-11-16 12:12:54 +0000539 typedef LiveIntervals::iterator LIIterator;
540 typedef LiveInterval::Ranges::const_iterator LRIterator;
541
542 // First allocate registers for the empty intervals.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000543 for (RegSet::const_iterator
544 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames27601ef2008-11-16 12:12:54 +0000545 itr != end; ++itr) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000546 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames27601ef2008-11-16 12:12:54 +0000547
Evan Cheng90f95f82009-06-14 20:22:55 +0000548 unsigned physReg = vrm->getRegAllocPref(li->reg);
Lang Hames6699fb22009-08-06 23:32:48 +0000549
Lang Hames27601ef2008-11-16 12:12:54 +0000550 if (physReg == 0) {
551 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000552 physReg = liRC->getRawAllocationOrder(*mf).front();
Lang Hames27601ef2008-11-16 12:12:54 +0000553 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000554
555 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames27601ef2008-11-16 12:12:54 +0000556 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000557
Lang Hames27601ef2008-11-16 12:12:54 +0000558 // Finally iterate over the basic blocks to compute and set the live-in sets.
559 SmallVector<MachineBasicBlock*, 8> liveInMBBs;
560 MachineBasicBlock *entryMBB = &*mf->begin();
561
562 for (LIIterator liItr = lis->begin(), liEnd = lis->end();
563 liItr != liEnd; ++liItr) {
564
565 const LiveInterval *li = liItr->second;
566 unsigned reg = 0;
Misha Brukman2a835f92009-01-08 15:50:22 +0000567
Lang Hames27601ef2008-11-16 12:12:54 +0000568 // Get the physical register for this interval
569 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
570 reg = li->reg;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000571 } else if (vrm->isAssignedReg(li->reg)) {
Lang Hames27601ef2008-11-16 12:12:54 +0000572 reg = vrm->getPhys(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000573 } else {
Lang Hames27601ef2008-11-16 12:12:54 +0000574 // Ranges which are assigned a stack slot only are ignored.
575 continue;
576 }
577
Lang Hamesb0e519f2009-05-17 23:50:36 +0000578 if (reg == 0) {
Lang Hames6699fb22009-08-06 23:32:48 +0000579 // Filter out zero regs - they're for intervals that were spilled.
Lang Hamesb0e519f2009-05-17 23:50:36 +0000580 continue;
581 }
582
Lang Hames27601ef2008-11-16 12:12:54 +0000583 // Iterate over the ranges of the current interval...
584 for (LRIterator lrItr = li->begin(), lrEnd = li->end();
585 lrItr != lrEnd; ++lrItr) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000586
Lang Hames27601ef2008-11-16 12:12:54 +0000587 // Find the set of basic blocks which this range is live into...
588 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
589 // And add the physreg for this interval to their live-in sets.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000590 for (unsigned i = 0; i != liveInMBBs.size(); ++i) {
Lang Hames27601ef2008-11-16 12:12:54 +0000591 if (liveInMBBs[i] != entryMBB) {
592 if (!liveInMBBs[i]->isLiveIn(reg)) {
593 liveInMBBs[i]->addLiveIn(reg);
594 }
595 }
596 }
597 liveInMBBs.clear();
598 }
599 }
600 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000601
Lang Hames27601ef2008-11-16 12:12:54 +0000602}
603
Lang Hameseb6c8f52010-09-18 09:07:10 +0000604bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames27601ef2008-11-16 12:12:54 +0000605
Evan Chengb1290a62008-10-02 18:29:27 +0000606 mf = &MF;
607 tm = &mf->getTarget();
608 tri = tm->getRegisterInfo();
Lang Hames27601ef2008-11-16 12:12:54 +0000609 tii = tm->getInstrInfo();
Andrew Trick16f72dd2012-02-10 04:10:26 +0000610 mri = &mf->getRegInfo();
Evan Chengb1290a62008-10-02 18:29:27 +0000611
Lang Hames27601ef2008-11-16 12:12:54 +0000612 lis = &getAnalysis<LiveIntervals>();
613 lss = &getAnalysis<LiveStacks>();
Evan Chengb1290a62008-10-02 18:29:27 +0000614 loopInfo = &getAnalysis<MachineLoopInfo>();
Lang Hames33198392010-09-02 08:27:00 +0000615 rmf = &getAnalysis<RenderMachineFunction>();
Evan Chengb1290a62008-10-02 18:29:27 +0000616
Owen Anderson49c8aa02009-03-13 05:55:11 +0000617 vrm = &getAnalysis<VirtRegMap>();
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000618 spiller.reset(createInlineSpiller(*this, MF, *vrm));
Evan Chengb1290a62008-10-02 18:29:27 +0000619
Jakob Stoklund Olesend9e5c762012-01-05 00:26:49 +0000620 mri->freezeReservedRegs(MF);
Lang Hames54cc2ef2010-07-19 15:22:28 +0000621
Lang Hames030c4bf2010-01-26 04:49:58 +0000622 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000623
Evan Chengb1290a62008-10-02 18:29:27 +0000624 // Allocator main loop:
Misha Brukman2a835f92009-01-08 15:50:22 +0000625 //
Evan Chengb1290a62008-10-02 18:29:27 +0000626 // * Map current regalloc problem to a PBQP problem
627 // * Solve the PBQP problem
628 // * Map the solution back to a register allocation
629 // * Spill if necessary
Misha Brukman2a835f92009-01-08 15:50:22 +0000630 //
Evan Chengb1290a62008-10-02 18:29:27 +0000631 // This process is continued till no more spills are generated.
632
Lang Hames27601ef2008-11-16 12:12:54 +0000633 // Find the vreg intervals in need of allocation.
634 findVRegIntervalsToAlloc();
Misha Brukman2a835f92009-01-08 15:50:22 +0000635
Lang Hames27601ef2008-11-16 12:12:54 +0000636 // If there are non-empty intervals allocate them using pbqp.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000637 if (!vregsToAlloc.empty()) {
Evan Chengb1290a62008-10-02 18:29:27 +0000638
Lang Hames27601ef2008-11-16 12:12:54 +0000639 bool pbqpAllocComplete = false;
640 unsigned round = 0;
641
Lang Hamesab62b7e2010-10-04 12:13:07 +0000642 while (!pbqpAllocComplete) {
643 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000644
Lang Hamesab62b7e2010-10-04 12:13:07 +0000645 std::auto_ptr<PBQPRAProblem> problem =
646 builder->build(mf, lis, loopInfo, vregsToAlloc);
647 PBQP::Solution solution =
648 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
649 problem->getGraph());
Lang Hames233fd9c2009-08-18 23:34:50 +0000650
Lang Hamesab62b7e2010-10-04 12:13:07 +0000651 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames27601ef2008-11-16 12:12:54 +0000652
Lang Hamesab62b7e2010-10-04 12:13:07 +0000653 ++round;
Lang Hames27601ef2008-11-16 12:12:54 +0000654 }
Evan Chengb1290a62008-10-02 18:29:27 +0000655 }
656
Lang Hames27601ef2008-11-16 12:12:54 +0000657 // Finalise allocation, allocate empty ranges.
658 finalizeAlloc();
Evan Chengb1290a62008-10-02 18:29:27 +0000659
Lang Hamesc4bcc772010-07-20 07:41:44 +0000660 rmf->renderMachineFunction("After PBQP register allocation.", vrm);
661
Lang Hameseb6c8f52010-09-18 09:07:10 +0000662 vregsToAlloc.clear();
663 emptyIntervalVRegs.clear();
Lang Hames27601ef2008-11-16 12:12:54 +0000664
David Greene30931542010-01-05 01:25:43 +0000665 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000666
Lang Hames87e3bca2009-05-06 02:36:21 +0000667 // Run rewriter
Jakob Stoklund Olesenc3f27222011-11-13 00:02:24 +0000668 vrm->rewrite(lis->getSlotIndexes());
Lang Hames27601ef2008-11-16 12:12:54 +0000669
Andrew Trick19273ae2012-02-21 04:51:23 +0000670 // All machine operands and other references to virtual registers have been
671 // replaced. Remove the virtual registers.
672 vrm->clearAllVirt();
673 mri->clearVirtRegs();
674
Misha Brukman2a835f92009-01-08 15:50:22 +0000675 return true;
Evan Chengb1290a62008-10-02 18:29:27 +0000676}
677
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000678FunctionPass* llvm::createPBQPRegisterAllocator(
Lang Hames8d857662011-06-17 07:09:01 +0000679 std::auto_ptr<PBQPBuilder> builder,
680 char *customPassID) {
681 return new RegAllocPBQP(builder, customPassID);
Evan Chengb1290a62008-10-02 18:29:27 +0000682}
683
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000684FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
685 if (pbqpCoalescing) {
686 return createPBQPRegisterAllocator(
687 std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
688 } // else
689 return createPBQPRegisterAllocator(
690 std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
Lang Hameseb6c8f52010-09-18 09:07:10 +0000691}
Evan Chengb1290a62008-10-02 18:29:27 +0000692
693#undef DEBUG_TYPE