blob: 73f78e2a8d96caf8f34e9c12dab2cb5add56f38d [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;
Lang Hamesf1113ef2012-03-23 17:33:42 +0000190 ArrayRef<SlotIndex> regMaskSlots = lis->getRegMaskSlots();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000191 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 Hamesf1113ef2012-03-23 17:33:42 +0000227 RegSet overlappingPRegs;
228
229 // Record physical registers whose ranges overlap.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000230 for (RegSet::const_iterator pregItr = pregs.begin(),
231 pregEnd = pregs.end();
232 pregItr != pregEnd; ++pregItr) {
233 unsigned preg = *pregItr;
234 const LiveInterval *pregLI = &lis->getInterval(preg);
Lang Hames27601ef2008-11-16 12:12:54 +0000235
Lang Hames5e77f4b2010-11-12 05:47:21 +0000236 if (pregLI->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000237 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000238 }
Evan Chengb1290a62008-10-02 18:29:27 +0000239
Lang Hamesf1113ef2012-03-23 17:33:42 +0000240 if (vregLI->overlaps(*pregLI))
241 overlappingPRegs.insert(preg);
242 }
243
244 // Record any overlaps with regmask operands.
245 BitVector regMaskOverlaps(tri->getNumRegs());
246 for (ArrayRef<SlotIndex>::iterator rmItr = regMaskSlots.begin(),
247 rmEnd = regMaskSlots.end();
248 rmItr != rmEnd; ++rmItr) {
249 SlotIndex rmIdx = *rmItr;
250 if (vregLI->liveAt(rmIdx)) {
251 MachineInstr *rmMI = lis->getInstructionFromIndex(rmIdx);
252 const uint32_t* regMask = 0;
253 for (MachineInstr::mop_iterator mopItr = rmMI->operands_begin(),
254 mopEnd = rmMI->operands_end();
255 mopItr != mopEnd; ++mopItr) {
256 if (mopItr->isRegMask()) {
257 regMask = mopItr->getRegMask();
258 break;
259 }
260 }
261 assert(regMask != 0 && "Couldn't find register mask.");
262 regMaskOverlaps.setBitsNotInMask(regMask);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000263 }
Lang Hamesf1113ef2012-03-23 17:33:42 +0000264 }
265
266 for (unsigned preg = 0; preg < tri->getNumRegs(); ++preg) {
267 if (regMaskOverlaps.test(preg))
268 overlappingPRegs.insert(preg);
269 }
270
271 for (RegSet::const_iterator pregItr = overlappingPRegs.begin(),
272 pregEnd = overlappingPRegs.end();
273 pregItr != pregEnd; ++pregItr) {
274 unsigned preg = *pregItr;
Lang Hames030c4bf2010-01-26 04:49:58 +0000275
Lang Hameseb6c8f52010-09-18 09:07:10 +0000276 // Remove the register from the allowed set.
277 VRAllowed::iterator eraseItr =
278 std::find(vrAllowed.begin(), vrAllowed.end(), preg);
Evan Chengb1290a62008-10-02 18:29:27 +0000279
Lang Hameseb6c8f52010-09-18 09:07:10 +0000280 if (eraseItr != vrAllowed.end()) {
281 vrAllowed.erase(eraseItr);
282 }
Evan Chengb1290a62008-10-02 18:29:27 +0000283
Lang Hameseb6c8f52010-09-18 09:07:10 +0000284 // Also remove any aliases.
Craig Toppere4fd9072012-03-04 10:43:23 +0000285 const uint16_t *aliasItr = tri->getAliasSet(preg);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000286 if (aliasItr != 0) {
287 for (; *aliasItr != 0; ++aliasItr) {
288 VRAllowed::iterator eraseItr =
289 std::find(vrAllowed.begin(), vrAllowed.end(), *aliasItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000290
Lang Hameseb6c8f52010-09-18 09:07:10 +0000291 if (eraseItr != vrAllowed.end()) {
292 vrAllowed.erase(eraseItr);
293 }
294 }
295 }
296 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000297
Lang Hameseb6c8f52010-09-18 09:07:10 +0000298 // Construct the node.
Andrew Trick16f72dd2012-02-10 04:10:26 +0000299 PBQP::Graph::NodeItr node =
Lang Hameseb6c8f52010-09-18 09:07:10 +0000300 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
Evan Chengb1290a62008-10-02 18:29:27 +0000301
Lang Hameseb6c8f52010-09-18 09:07:10 +0000302 // Record the mapping and allowed set in the problem.
303 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
Evan Chengb1290a62008-10-02 18:29:27 +0000304
Lang Hameseb6c8f52010-09-18 09:07:10 +0000305 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
306 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb1290a62008-10-02 18:29:27 +0000307
Lang Hameseb6c8f52010-09-18 09:07:10 +0000308 addSpillCosts(g.getNodeCosts(node), spillCost);
309 }
Evan Chengb1290a62008-10-02 18:29:27 +0000310
Lang Hames481630d2010-09-18 09:49:08 +0000311 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000312 vr1Itr != vrEnd; ++vr1Itr) {
313 unsigned vr1 = *vr1Itr;
314 const LiveInterval &l1 = lis->getInterval(vr1);
315 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb1290a62008-10-02 18:29:27 +0000316
Benjamin Kramer9e8d1f92010-09-18 14:41:26 +0000317 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000318 vr2Itr != vrEnd; ++vr2Itr) {
319 unsigned vr2 = *vr2Itr;
320 const LiveInterval &l2 = lis->getInterval(vr2);
321 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb1290a62008-10-02 18:29:27 +0000322
Lang Hameseb6c8f52010-09-18 09:07:10 +0000323 assert(!l2.empty() && "Empty interval in vreg set?");
324 if (l1.overlaps(l2)) {
325 PBQP::Graph::EdgeItr edge =
326 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
327 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
Lang Hames27601ef2008-11-16 12:12:54 +0000328
Lang Hameseb6c8f52010-09-18 09:07:10 +0000329 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
330 }
331 }
332 }
Evan Chengb1290a62008-10-02 18:29:27 +0000333
Lang Hameseb6c8f52010-09-18 09:07:10 +0000334 return p;
335}
Lang Hames27601ef2008-11-16 12:12:54 +0000336
Lang Hameseb6c8f52010-09-18 09:07:10 +0000337void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
338 PBQP::PBQPNum spillCost) {
339 costVec[0] = spillCost;
340}
Evan Chengb1290a62008-10-02 18:29:27 +0000341
Lang Hamese9c93562010-09-21 13:19:36 +0000342void PBQPBuilder::addInterferenceCosts(
343 PBQP::Matrix &costMat,
344 const PBQPRAProblem::AllowedSet &vr1Allowed,
345 const PBQPRAProblem::AllowedSet &vr2Allowed,
346 const TargetRegisterInfo *tri) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000347 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
348 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
349
Lang Hames5e77f4b2010-11-12 05:47:21 +0000350 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000351 unsigned preg1 = vr1Allowed[i];
352
Lang Hames5e77f4b2010-11-12 05:47:21 +0000353 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000354 unsigned preg2 = vr2Allowed[j];
355
356 if (tri->regsOverlap(preg1, preg2)) {
357 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
358 }
359 }
360 }
Evan Chengb1290a62008-10-02 18:29:27 +0000361}
362
Lang Hamese9c93562010-09-21 13:19:36 +0000363std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
364 MachineFunction *mf,
365 const LiveIntervals *lis,
366 const MachineLoopInfo *loopInfo,
367 const RegSet &vregs) {
368
369 std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
370 PBQP::Graph &g = p->getGraph();
371
372 const TargetMachine &tm = mf->getTarget();
373 CoalescerPair cp(*tm.getInstrInfo(), *tm.getRegisterInfo());
374
375 // Scan the machine function and add a coalescing cost whenever CoalescerPair
376 // gives the Ok.
377 for (MachineFunction::const_iterator mbbItr = mf->begin(),
378 mbbEnd = mf->end();
379 mbbItr != mbbEnd; ++mbbItr) {
380 const MachineBasicBlock *mbb = &*mbbItr;
381
382 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
383 miEnd = mbb->end();
384 miItr != miEnd; ++miItr) {
385 const MachineInstr *mi = &*miItr;
386
Lang Hames5e77f4b2010-11-12 05:47:21 +0000387 if (!cp.setRegisters(mi)) {
Lang Hamese9c93562010-09-21 13:19:36 +0000388 continue; // Not coalescable.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000389 }
Lang Hamese9c93562010-09-21 13:19:36 +0000390
Lang Hames5e77f4b2010-11-12 05:47:21 +0000391 if (cp.getSrcReg() == cp.getDstReg()) {
Lang Hamese9c93562010-09-21 13:19:36 +0000392 continue; // Already coalesced.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000393 }
Lang Hamese9c93562010-09-21 13:19:36 +0000394
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000395 unsigned dst = cp.getDstReg(),
396 src = cp.getSrcReg();
Lang Hamese9c93562010-09-21 13:19:36 +0000397
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000398 const float copyFactor = 0.5; // Cost of copy relative to load. Current
399 // value plucked randomly out of the air.
Andrew Trick16f72dd2012-02-10 04:10:26 +0000400
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000401 PBQP::PBQPNum cBenefit =
402 copyFactor * LiveIntervals::getSpillWeight(false, true,
403 loopInfo->getLoopDepth(mbb));
Lang Hamese9c93562010-09-21 13:19:36 +0000404
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000405 if (cp.isPhys()) {
Lang Hames5e77f4b2010-11-12 05:47:21 +0000406 if (!lis->isAllocatable(dst)) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000407 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000408 }
Lang Hamese9c93562010-09-21 13:19:36 +0000409
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000410 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
Andrew Trick16f72dd2012-02-10 04:10:26 +0000411 unsigned pregOpt = 0;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000412 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000413 ++pregOpt;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000414 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000415 if (pregOpt < allowed.size()) {
416 ++pregOpt; // +1 to account for spill option.
417 PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
418 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000419 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000420 } else {
421 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
422 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
423 PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
424 PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
425 PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
426 if (edge == g.edgesEnd()) {
427 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
428 allowed2->size() + 1,
429 0));
430 } else {
431 if (g.getEdgeNode1(edge) == node2) {
432 std::swap(node1, node2);
433 std::swap(allowed1, allowed2);
434 }
435 }
Andrew Trick16f72dd2012-02-10 04:10:26 +0000436
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000437 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
438 cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000439 }
440 }
441 }
442
443 return p;
444}
445
Lang Hamese9c93562010-09-21 13:19:36 +0000446void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
447 unsigned pregOption,
448 PBQP::PBQPNum benefit) {
449 costVec[pregOption] += -benefit;
450}
451
452void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
453 PBQP::Matrix &costMat,
454 const PBQPRAProblem::AllowedSet &vr1Allowed,
455 const PBQPRAProblem::AllowedSet &vr2Allowed,
456 PBQP::PBQPNum benefit) {
457
458 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
459 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
460
Lang Hames5e77f4b2010-11-12 05:47:21 +0000461 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hamese9c93562010-09-21 13:19:36 +0000462 unsigned preg1 = vr1Allowed[i];
Lang Hames5e77f4b2010-11-12 05:47:21 +0000463 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hamese9c93562010-09-21 13:19:36 +0000464 unsigned preg2 = vr2Allowed[j];
465
466 if (preg1 == preg2) {
467 costMat[i + 1][j + 1] += -benefit;
Andrew Trick16f72dd2012-02-10 04:10:26 +0000468 }
Lang Hamese9c93562010-09-21 13:19:36 +0000469 }
470 }
471}
Evan Chengb1290a62008-10-02 18:29:27 +0000472
Lang Hameseb6c8f52010-09-18 09:07:10 +0000473
474void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hames9ad7e072011-12-06 01:45:57 +0000475 au.setPreservesCFG();
476 au.addRequired<AliasAnalysis>();
477 au.addPreserved<AliasAnalysis>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000478 au.addRequired<SlotIndexes>();
479 au.addPreserved<SlotIndexes>();
480 au.addRequired<LiveIntervals>();
481 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames8d857662011-06-17 07:09:01 +0000482 if (customPassID)
483 au.addRequiredID(*customPassID);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000484 au.addRequired<CalculateSpillWeights>();
485 au.addRequired<LiveStacks>();
486 au.addPreserved<LiveStacks>();
Lang Hames9ad7e072011-12-06 01:45:57 +0000487 au.addRequired<MachineDominatorTree>();
488 au.addPreserved<MachineDominatorTree>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000489 au.addRequired<MachineLoopInfo>();
490 au.addPreserved<MachineLoopInfo>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000491 au.addRequired<VirtRegMap>();
492 au.addRequired<RenderMachineFunction>();
493 MachineFunctionPass::getAnalysisUsage(au);
494}
495
Lang Hameseb6c8f52010-09-18 09:07:10 +0000496void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames27601ef2008-11-16 12:12:54 +0000497
498 // Iterate over all live ranges.
499 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
500 itr != end; ++itr) {
501
502 // Ignore physical ones.
503 if (TargetRegisterInfo::isPhysicalRegister(itr->first))
504 continue;
505
506 LiveInterval *li = itr->second;
507
508 // If this live interval is non-empty we will use pbqp to allocate it.
509 // Empty intervals we allocate in a simple post-processing stage in
510 // finalizeAlloc.
511 if (!li->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000512 vregsToAlloc.insert(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000513 } else {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000514 emptyIntervalVRegs.insert(li->reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000515 }
516 }
Evan Chengb1290a62008-10-02 18:29:27 +0000517}
518
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000519bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
520 const PBQP::Solution &solution) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000521 // Set to true if we have any spills
522 bool anotherRoundNeeded = false;
523
524 // Clear the existing allocation.
525 vrm->clearAllVirt();
526
527 const PBQP::Graph &g = problem.getGraph();
528 // Iterate over the nodes mapping the PBQP solution to a register
529 // assignment.
530 for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
531 nodeEnd = g.nodesEnd();
532 node != nodeEnd; ++node) {
533 unsigned vreg = problem.getVRegForNode(node);
534 unsigned alloc = solution.getSelection(node);
535
536 if (problem.isPRegOption(vreg, alloc)) {
Andrew Trick16f72dd2012-02-10 04:10:26 +0000537 unsigned preg = problem.getPRegForOption(vreg, alloc);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000538 DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "\n");
539 assert(preg != 0 && "Invalid preg selected.");
Andrew Trick16f72dd2012-02-10 04:10:26 +0000540 vrm->assignVirt2Phys(vreg, preg);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000541 } else if (problem.isSpillOption(vreg, alloc)) {
542 vregsToAlloc.erase(vreg);
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000543 SmallVector<LiveInterval*, 8> newSpills;
544 LiveRangeEdit LRE(lis->getInterval(vreg), newSpills);
545 spiller->spill(LRE);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000546
Lang Hameseb6c8f52010-09-18 09:07:10 +0000547 DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000548 << LRE.getParent().weight << ", New vregs: ");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000549
550 // Copy any newly inserted live intervals into the list of regs to
551 // allocate.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000552 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000553 itr != end; ++itr) {
554 assert(!(*itr)->empty() && "Empty spill range.");
555 DEBUG(dbgs() << (*itr)->reg << " ");
556 vregsToAlloc.insert((*itr)->reg);
557 }
558
559 DEBUG(dbgs() << ")\n");
560
561 // We need another round if spill intervals were added.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000562 anotherRoundNeeded |= !LRE.empty();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000563 } else {
Craig Topper5e25ee82012-02-05 08:31:47 +0000564 llvm_unreachable("Unknown allocation option.");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000565 }
566 }
567
568 return !anotherRoundNeeded;
569}
570
571
572void RegAllocPBQP::finalizeAlloc() const {
Lang Hames27601ef2008-11-16 12:12:54 +0000573 typedef LiveIntervals::iterator LIIterator;
574 typedef LiveInterval::Ranges::const_iterator LRIterator;
575
576 // First allocate registers for the empty intervals.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000577 for (RegSet::const_iterator
578 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames27601ef2008-11-16 12:12:54 +0000579 itr != end; ++itr) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000580 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames27601ef2008-11-16 12:12:54 +0000581
Evan Cheng90f95f82009-06-14 20:22:55 +0000582 unsigned physReg = vrm->getRegAllocPref(li->reg);
Lang Hames6699fb22009-08-06 23:32:48 +0000583
Lang Hames27601ef2008-11-16 12:12:54 +0000584 if (physReg == 0) {
585 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000586 physReg = liRC->getRawAllocationOrder(*mf).front();
Lang Hames27601ef2008-11-16 12:12:54 +0000587 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000588
589 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames27601ef2008-11-16 12:12:54 +0000590 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000591
Lang Hames27601ef2008-11-16 12:12:54 +0000592 // Finally iterate over the basic blocks to compute and set the live-in sets.
593 SmallVector<MachineBasicBlock*, 8> liveInMBBs;
594 MachineBasicBlock *entryMBB = &*mf->begin();
595
596 for (LIIterator liItr = lis->begin(), liEnd = lis->end();
597 liItr != liEnd; ++liItr) {
598
599 const LiveInterval *li = liItr->second;
600 unsigned reg = 0;
Misha Brukman2a835f92009-01-08 15:50:22 +0000601
Lang Hames27601ef2008-11-16 12:12:54 +0000602 // Get the physical register for this interval
603 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
604 reg = li->reg;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000605 } else if (vrm->isAssignedReg(li->reg)) {
Lang Hames27601ef2008-11-16 12:12:54 +0000606 reg = vrm->getPhys(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000607 } else {
Lang Hames27601ef2008-11-16 12:12:54 +0000608 // Ranges which are assigned a stack slot only are ignored.
609 continue;
610 }
611
Lang Hamesb0e519f2009-05-17 23:50:36 +0000612 if (reg == 0) {
Lang Hames6699fb22009-08-06 23:32:48 +0000613 // Filter out zero regs - they're for intervals that were spilled.
Lang Hamesb0e519f2009-05-17 23:50:36 +0000614 continue;
615 }
616
Lang Hames27601ef2008-11-16 12:12:54 +0000617 // Iterate over the ranges of the current interval...
618 for (LRIterator lrItr = li->begin(), lrEnd = li->end();
619 lrItr != lrEnd; ++lrItr) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000620
Lang Hames27601ef2008-11-16 12:12:54 +0000621 // Find the set of basic blocks which this range is live into...
622 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
623 // And add the physreg for this interval to their live-in sets.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000624 for (unsigned i = 0; i != liveInMBBs.size(); ++i) {
Lang Hames27601ef2008-11-16 12:12:54 +0000625 if (liveInMBBs[i] != entryMBB) {
626 if (!liveInMBBs[i]->isLiveIn(reg)) {
627 liveInMBBs[i]->addLiveIn(reg);
628 }
629 }
630 }
631 liveInMBBs.clear();
632 }
633 }
634 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000635
Lang Hames27601ef2008-11-16 12:12:54 +0000636}
637
Lang Hameseb6c8f52010-09-18 09:07:10 +0000638bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames27601ef2008-11-16 12:12:54 +0000639
Evan Chengb1290a62008-10-02 18:29:27 +0000640 mf = &MF;
641 tm = &mf->getTarget();
642 tri = tm->getRegisterInfo();
Lang Hames27601ef2008-11-16 12:12:54 +0000643 tii = tm->getInstrInfo();
Andrew Trick16f72dd2012-02-10 04:10:26 +0000644 mri = &mf->getRegInfo();
Evan Chengb1290a62008-10-02 18:29:27 +0000645
Lang Hames27601ef2008-11-16 12:12:54 +0000646 lis = &getAnalysis<LiveIntervals>();
647 lss = &getAnalysis<LiveStacks>();
Evan Chengb1290a62008-10-02 18:29:27 +0000648 loopInfo = &getAnalysis<MachineLoopInfo>();
Lang Hames33198392010-09-02 08:27:00 +0000649 rmf = &getAnalysis<RenderMachineFunction>();
Evan Chengb1290a62008-10-02 18:29:27 +0000650
Owen Anderson49c8aa02009-03-13 05:55:11 +0000651 vrm = &getAnalysis<VirtRegMap>();
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000652 spiller.reset(createInlineSpiller(*this, MF, *vrm));
Evan Chengb1290a62008-10-02 18:29:27 +0000653
Jakob Stoklund Olesend9e5c762012-01-05 00:26:49 +0000654 mri->freezeReservedRegs(MF);
Lang Hames54cc2ef2010-07-19 15:22:28 +0000655
Lang Hames030c4bf2010-01-26 04:49:58 +0000656 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000657
Evan Chengb1290a62008-10-02 18:29:27 +0000658 // Allocator main loop:
Misha Brukman2a835f92009-01-08 15:50:22 +0000659 //
Evan Chengb1290a62008-10-02 18:29:27 +0000660 // * Map current regalloc problem to a PBQP problem
661 // * Solve the PBQP problem
662 // * Map the solution back to a register allocation
663 // * Spill if necessary
Misha Brukman2a835f92009-01-08 15:50:22 +0000664 //
Evan Chengb1290a62008-10-02 18:29:27 +0000665 // This process is continued till no more spills are generated.
666
Lang Hames27601ef2008-11-16 12:12:54 +0000667 // Find the vreg intervals in need of allocation.
668 findVRegIntervalsToAlloc();
Misha Brukman2a835f92009-01-08 15:50:22 +0000669
Lang Hames27601ef2008-11-16 12:12:54 +0000670 // If there are non-empty intervals allocate them using pbqp.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000671 if (!vregsToAlloc.empty()) {
Evan Chengb1290a62008-10-02 18:29:27 +0000672
Lang Hames27601ef2008-11-16 12:12:54 +0000673 bool pbqpAllocComplete = false;
674 unsigned round = 0;
675
Lang Hamesab62b7e2010-10-04 12:13:07 +0000676 while (!pbqpAllocComplete) {
677 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000678
Lang Hamesab62b7e2010-10-04 12:13:07 +0000679 std::auto_ptr<PBQPRAProblem> problem =
680 builder->build(mf, lis, loopInfo, vregsToAlloc);
681 PBQP::Solution solution =
682 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
683 problem->getGraph());
Lang Hames233fd9c2009-08-18 23:34:50 +0000684
Lang Hamesab62b7e2010-10-04 12:13:07 +0000685 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames27601ef2008-11-16 12:12:54 +0000686
Lang Hamesab62b7e2010-10-04 12:13:07 +0000687 ++round;
Lang Hames27601ef2008-11-16 12:12:54 +0000688 }
Evan Chengb1290a62008-10-02 18:29:27 +0000689 }
690
Lang Hames27601ef2008-11-16 12:12:54 +0000691 // Finalise allocation, allocate empty ranges.
692 finalizeAlloc();
Evan Chengb1290a62008-10-02 18:29:27 +0000693
Lang Hamesc4bcc772010-07-20 07:41:44 +0000694 rmf->renderMachineFunction("After PBQP register allocation.", vrm);
695
Lang Hameseb6c8f52010-09-18 09:07:10 +0000696 vregsToAlloc.clear();
697 emptyIntervalVRegs.clear();
Lang Hames27601ef2008-11-16 12:12:54 +0000698
David Greene30931542010-01-05 01:25:43 +0000699 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000700
Lang Hames87e3bca2009-05-06 02:36:21 +0000701 // Run rewriter
Jakob Stoklund Olesenc3f27222011-11-13 00:02:24 +0000702 vrm->rewrite(lis->getSlotIndexes());
Lang Hames27601ef2008-11-16 12:12:54 +0000703
Andrew Trick19273ae2012-02-21 04:51:23 +0000704 // All machine operands and other references to virtual registers have been
705 // replaced. Remove the virtual registers.
706 vrm->clearAllVirt();
707 mri->clearVirtRegs();
708
Misha Brukman2a835f92009-01-08 15:50:22 +0000709 return true;
Evan Chengb1290a62008-10-02 18:29:27 +0000710}
711
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000712FunctionPass* llvm::createPBQPRegisterAllocator(
Lang Hames8d857662011-06-17 07:09:01 +0000713 std::auto_ptr<PBQPBuilder> builder,
714 char *customPassID) {
715 return new RegAllocPBQP(builder, customPassID);
Evan Chengb1290a62008-10-02 18:29:27 +0000716}
717
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000718FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
719 if (pbqpCoalescing) {
720 return createPBQPRegisterAllocator(
721 std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
722 } // else
723 return createPBQPRegisterAllocator(
724 std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
Lang Hameseb6c8f52010-09-18 09:07:10 +0000725}
Evan Chengb1290a62008-10-02 18:29:27 +0000726
727#undef DEBUG_TYPE