blob: ecfe6ade9b501de1bcbac8e9eb119e62c7e2f5dc [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
Chandler Carruthd04a8d42012-12-03 16:50:05 +000034#include "llvm/CodeGen/RegAllocPBQP.h"
Rafael Espindolafdf16ca2011-06-26 21:41:06 +000035#include "RegisterCoalescer.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000036#include "Spiller.h"
Andy Gibbs604b3572013-04-15 12:06:32 +000037#include "llvm/ADT/OwningPtr.h"
Lang Hames9ad7e072011-12-06 01:45:57 +000038#include "llvm/Analysis/AliasAnalysis.h"
Lang Hamesa937f222009-12-14 06:49:42 +000039#include "llvm/CodeGen/CalcSpillWeights.h"
Evan Chengb1290a62008-10-02 18:29:27 +000040#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000041#include "llvm/CodeGen/LiveRangeEdit.h"
Lang Hames27601ef2008-11-16 12:12:54 +000042#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramer4eed7562013-06-17 19:00:36 +000043#include "llvm/CodeGen/MachineBlockFrequencyInfo.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"
Misha Brukman2a835f92009-01-08 15:50:22 +000046#include "llvm/CodeGen/MachineRegisterInfo.h"
Lang Hameseb6c8f52010-09-18 09:07:10 +000047#include "llvm/CodeGen/PBQP/Graph.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000048#include "llvm/CodeGen/PBQP/HeuristicSolver.h"
Lang Hameseb6c8f52010-09-18 09:07:10 +000049#include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000050#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000051#include "llvm/CodeGen/VirtRegMap.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000052#include "llvm/IR/Module.h"
Evan Chengb1290a62008-10-02 18:29:27 +000053#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000054#include "llvm/Support/raw_ostream.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000055#include "llvm/Target/TargetInstrInfo.h"
56#include "llvm/Target/TargetMachine.h"
57#include <limits>
Misha Brukman2a835f92009-01-08 15:50:22 +000058#include <memory>
Evan Chengb1290a62008-10-02 18:29:27 +000059#include <set>
Lang Hames20df03c2012-03-26 23:07:23 +000060#include <sstream>
Evan Chengb1290a62008-10-02 18:29:27 +000061#include <vector>
Evan Chengb1290a62008-10-02 18:29:27 +000062
Lang Hamesf70e7cc2010-09-23 04:28:54 +000063using namespace llvm;
Lang Hameseb6c8f52010-09-18 09:07:10 +000064
Evan Chengb1290a62008-10-02 18:29:27 +000065static RegisterRegAlloc
Duncan Sands1aecd152010-02-18 14:10:41 +000066registerPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesf70e7cc2010-09-23 04:28:54 +000067 createDefaultPBQPRegisterAllocator);
Evan Chengb1290a62008-10-02 18:29:27 +000068
Lang Hames8481e3b2009-08-19 01:36:14 +000069static cl::opt<bool>
70pbqpCoalescing("pbqp-coalescing",
Lang Hames030c4bf2010-01-26 04:49:58 +000071 cl::desc("Attempt coalescing during PBQP register allocation."),
72 cl::init(false), cl::Hidden);
Lang Hames8481e3b2009-08-19 01:36:14 +000073
Lang Hames20df03c2012-03-26 23:07:23 +000074#ifndef NDEBUG
75static cl::opt<bool>
76pbqpDumpGraphs("pbqp-dump-graphs",
77 cl::desc("Dump graphs for each function/round in the compilation unit."),
78 cl::init(false), cl::Hidden);
79#endif
80
Lang Hamesf70e7cc2010-09-23 04:28:54 +000081namespace {
82
83///
84/// PBQP based allocators solve the register allocation problem by mapping
85/// register allocation problems to Partitioned Boolean Quadratic
86/// Programming problems.
87class RegAllocPBQP : public MachineFunctionPass {
88public:
89
90 static char ID;
91
92 /// Construct a PBQP register allocator.
Andy Gibbs604b3572013-04-15 12:06:32 +000093 RegAllocPBQP(OwningPtr<PBQPBuilder> &b, char *cPassID=0)
94 : MachineFunctionPass(ID), builder(b.take()), customPassID(cPassID) {
Owen Anderson081c34b2010-10-19 17:21:58 +000095 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
96 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +000097 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
98 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +000099 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +0000100 }
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;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000121 typedef std::set<unsigned> RegSet;
122
123
Andy Gibbs604b3572013-04-15 12:06:32 +0000124 OwningPtr<PBQPBuilder> builder;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000125
Lang Hames8d857662011-06-17 07:09:01 +0000126 char *customPassID;
127
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000128 MachineFunction *mf;
129 const TargetMachine *tm;
130 const TargetRegisterInfo *tri;
131 const TargetInstrInfo *tii;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000132 MachineRegisterInfo *mri;
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000133 const MachineBlockFrequencyInfo *mbfi;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000134
Andy Gibbs604b3572013-04-15 12:06:32 +0000135 OwningPtr<Spiller> spiller;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000136 LiveIntervals *lis;
137 LiveStacks *lss;
138 VirtRegMap *vrm;
139
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000140 RegSet vregsToAlloc, emptyIntervalVRegs;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000141
142 /// \brief Finds the initial set of vreg intervals to allocate.
143 void findVRegIntervalsToAlloc();
144
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000145 /// \brief Given a solved PBQP problem maps this solution back to a register
146 /// assignment.
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000147 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
148 const PBQP::Solution &solution);
149
150 /// \brief Postprocessing before final spilling. Sets basic block "live in"
151 /// variables.
152 void finalizeAlloc() const;
153
154};
155
Lang Hameseb6c8f52010-09-18 09:07:10 +0000156char RegAllocPBQP::ID = 0;
Evan Chengb1290a62008-10-02 18:29:27 +0000157
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000158} // End anonymous namespace.
159
Lang Hameseb6c8f52010-09-18 09:07:10 +0000160unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
161 Node2VReg::const_iterator vregItr = node2VReg.find(node);
162 assert(vregItr != node2VReg.end() && "No vreg for node.");
163 return vregItr->second;
164}
Evan Chengb1290a62008-10-02 18:29:27 +0000165
Lang Hameseb6c8f52010-09-18 09:07:10 +0000166PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
167 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
168 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
169 return nodeItr->second;
Andrew Trick16f72dd2012-02-10 04:10:26 +0000170
Lang Hameseb6c8f52010-09-18 09:07:10 +0000171}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000172
Lang Hameseb6c8f52010-09-18 09:07:10 +0000173const PBQPRAProblem::AllowedSet&
174 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
175 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
176 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
177 const AllowedSet &allowedSet = allowedSetItr->second;
178 return allowedSet;
179}
Evan Chengb1290a62008-10-02 18:29:27 +0000180
Lang Hameseb6c8f52010-09-18 09:07:10 +0000181unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
182 assert(isPRegOption(vreg, option) && "Not a preg option.");
183
184 const AllowedSet& allowedSet = getAllowedSet(vreg);
185 assert(option <= allowedSet.size() && "Option outside allowed set.");
186 return allowedSet[option - 1];
187}
188
Andy Gibbs604b3572013-04-15 12:06:32 +0000189PBQPRAProblem *PBQPBuilder::build(MachineFunction *mf, const LiveIntervals *lis,
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000190 const MachineBlockFrequencyInfo *mbfi,
Andy Gibbs604b3572013-04-15 12:06:32 +0000191 const RegSet &vregs) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000192
Jakob Stoklund Olesen3b30bca2012-06-20 22:32:05 +0000193 LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000194 MachineRegisterInfo *mri = &mf->getRegInfo();
Andrew Trick16f72dd2012-02-10 04:10:26 +0000195 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000196
Andy Gibbs604b3572013-04-15 12:06:32 +0000197 OwningPtr<PBQPRAProblem> p(new PBQPRAProblem());
Lang Hameseb6c8f52010-09-18 09:07:10 +0000198 PBQP::Graph &g = p->getGraph();
199 RegSet pregs;
200
201 // Collect the set of preg intervals, record that they're used in the MF.
Jakob Stoklund Olesend67582e2012-06-20 21:25:05 +0000202 for (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
Jakob Stoklund Olesen3b30bca2012-06-20 22:32:05 +0000203 if (mri->def_empty(Reg))
Jakob Stoklund Olesend67582e2012-06-20 21:25:05 +0000204 continue;
205 pregs.insert(Reg);
206 mri->setPhysRegUsed(Reg);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000207 }
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);
Jakob Stoklund Olesen3b30bca2012-06-20 22:32:05 +0000214 LiveInterval *vregLI = &LIS->getInterval(vreg);
215
216 // Record any overlaps with regmask operands.
Lang Hames8a8cf962012-10-10 06:39:48 +0000217 BitVector regMaskOverlaps;
Jakob Stoklund Olesen3b30bca2012-06-20 22:32:05 +0000218 LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
Evan Chengb1290a62008-10-02 18:29:27 +0000219
Lang Hameseb6c8f52010-09-18 09:07:10 +0000220 // Compute an initial allowed set for the current vreg.
221 typedef std::vector<unsigned> VRAllowed;
222 VRAllowed vrAllowed;
Craig Topperb6632ba2012-03-04 10:16:38 +0000223 ArrayRef<uint16_t> rawOrder = trc->getRawAllocationOrder(*mf);
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000224 for (unsigned i = 0; i != rawOrder.size(); ++i) {
225 unsigned preg = rawOrder[i];
Jakob Stoklund Olesenfb9ebbf2012-10-15 21:57:41 +0000226 if (mri->isReserved(preg))
Jakob Stoklund Olesen3b30bca2012-06-20 22:32:05 +0000227 continue;
228
229 // vregLI crosses a regmask operand that clobbers preg.
Lang Hames8a8cf962012-10-10 06:39:48 +0000230 if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
Jakob Stoklund Olesen3b30bca2012-06-20 22:32:05 +0000231 continue;
232
233 // vregLI overlaps fixed regunit interference.
Jakob Stoklund Olesen241d0202012-06-22 16:46:44 +0000234 bool Interference = false;
235 for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
236 if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
237 Interference = true;
238 break;
Jakob Stoklund Olesen3b30bca2012-06-20 22:32:05 +0000239 }
Lang Hamesd0f6f012010-07-17 06:31:41 +0000240 }
Jakob Stoklund Olesen241d0202012-06-22 16:46:44 +0000241 if (Interference)
242 continue;
Jakob Stoklund Olesen3b30bca2012-06-20 22:32:05 +0000243
244 // preg is usable for this virtual register.
245 vrAllowed.push_back(preg);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000246 }
Lang Hamesd0f6f012010-07-17 06:31:41 +0000247
Lang Hameseb6c8f52010-09-18 09:07:10 +0000248 // Construct the node.
Andrew Trick16f72dd2012-02-10 04:10:26 +0000249 PBQP::Graph::NodeItr node =
Lang Hameseb6c8f52010-09-18 09:07:10 +0000250 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
Evan Chengb1290a62008-10-02 18:29:27 +0000251
Lang Hameseb6c8f52010-09-18 09:07:10 +0000252 // Record the mapping and allowed set in the problem.
253 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
Evan Chengb1290a62008-10-02 18:29:27 +0000254
Lang Hameseb6c8f52010-09-18 09:07:10 +0000255 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
256 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb1290a62008-10-02 18:29:27 +0000257
Lang Hameseb6c8f52010-09-18 09:07:10 +0000258 addSpillCosts(g.getNodeCosts(node), spillCost);
259 }
Evan Chengb1290a62008-10-02 18:29:27 +0000260
Lang Hames481630d2010-09-18 09:49:08 +0000261 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000262 vr1Itr != vrEnd; ++vr1Itr) {
263 unsigned vr1 = *vr1Itr;
264 const LiveInterval &l1 = lis->getInterval(vr1);
265 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb1290a62008-10-02 18:29:27 +0000266
Benjamin Kramer9e8d1f92010-09-18 14:41:26 +0000267 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000268 vr2Itr != vrEnd; ++vr2Itr) {
269 unsigned vr2 = *vr2Itr;
270 const LiveInterval &l2 = lis->getInterval(vr2);
271 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb1290a62008-10-02 18:29:27 +0000272
Lang Hameseb6c8f52010-09-18 09:07:10 +0000273 assert(!l2.empty() && "Empty interval in vreg set?");
274 if (l1.overlaps(l2)) {
275 PBQP::Graph::EdgeItr edge =
276 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
277 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
Lang Hames27601ef2008-11-16 12:12:54 +0000278
Lang Hameseb6c8f52010-09-18 09:07:10 +0000279 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
280 }
281 }
282 }
Evan Chengb1290a62008-10-02 18:29:27 +0000283
Andy Gibbs604b3572013-04-15 12:06:32 +0000284 return p.take();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000285}
Lang Hames27601ef2008-11-16 12:12:54 +0000286
Lang Hameseb6c8f52010-09-18 09:07:10 +0000287void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
288 PBQP::PBQPNum spillCost) {
289 costVec[0] = spillCost;
290}
Evan Chengb1290a62008-10-02 18:29:27 +0000291
Lang Hamese9c93562010-09-21 13:19:36 +0000292void PBQPBuilder::addInterferenceCosts(
293 PBQP::Matrix &costMat,
294 const PBQPRAProblem::AllowedSet &vr1Allowed,
295 const PBQPRAProblem::AllowedSet &vr2Allowed,
296 const TargetRegisterInfo *tri) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000297 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
298 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
299
Lang Hames5e77f4b2010-11-12 05:47:21 +0000300 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000301 unsigned preg1 = vr1Allowed[i];
302
Lang Hames5e77f4b2010-11-12 05:47:21 +0000303 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000304 unsigned preg2 = vr2Allowed[j];
305
306 if (tri->regsOverlap(preg1, preg2)) {
307 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
308 }
309 }
310 }
Evan Chengb1290a62008-10-02 18:29:27 +0000311}
312
Andy Gibbs604b3572013-04-15 12:06:32 +0000313PBQPRAProblem *PBQPBuilderWithCoalescing::build(MachineFunction *mf,
Lang Hamese9c93562010-09-21 13:19:36 +0000314 const LiveIntervals *lis,
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000315 const MachineBlockFrequencyInfo *mbfi,
Lang Hamese9c93562010-09-21 13:19:36 +0000316 const RegSet &vregs) {
317
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000318 OwningPtr<PBQPRAProblem> p(PBQPBuilder::build(mf, lis, mbfi, vregs));
Lang Hamese9c93562010-09-21 13:19:36 +0000319 PBQP::Graph &g = p->getGraph();
320
321 const TargetMachine &tm = mf->getTarget();
Benjamin Kramera7542d52012-06-06 18:25:08 +0000322 CoalescerPair cp(*tm.getRegisterInfo());
Lang Hamese9c93562010-09-21 13:19:36 +0000323
324 // Scan the machine function and add a coalescing cost whenever CoalescerPair
325 // gives the Ok.
326 for (MachineFunction::const_iterator mbbItr = mf->begin(),
327 mbbEnd = mf->end();
328 mbbItr != mbbEnd; ++mbbItr) {
329 const MachineBasicBlock *mbb = &*mbbItr;
330
331 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
332 miEnd = mbb->end();
333 miItr != miEnd; ++miItr) {
334 const MachineInstr *mi = &*miItr;
335
Lang Hames5e77f4b2010-11-12 05:47:21 +0000336 if (!cp.setRegisters(mi)) {
Lang Hamese9c93562010-09-21 13:19:36 +0000337 continue; // Not coalescable.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000338 }
Lang Hamese9c93562010-09-21 13:19:36 +0000339
Lang Hames5e77f4b2010-11-12 05:47:21 +0000340 if (cp.getSrcReg() == cp.getDstReg()) {
Lang Hamese9c93562010-09-21 13:19:36 +0000341 continue; // Already coalesced.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000342 }
Lang Hamese9c93562010-09-21 13:19:36 +0000343
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000344 unsigned dst = cp.getDstReg(),
345 src = cp.getSrcReg();
Lang Hamese9c93562010-09-21 13:19:36 +0000346
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000347 const float copyFactor = 0.5; // Cost of copy relative to load. Current
348 // value plucked randomly out of the air.
Andrew Trick16f72dd2012-02-10 04:10:26 +0000349
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000350 PBQP::PBQPNum cBenefit =
351 copyFactor * LiveIntervals::getSpillWeight(false, true,
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000352 mbfi->getBlockFreq(mbb));
Lang Hamese9c93562010-09-21 13:19:36 +0000353
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000354 if (cp.isPhys()) {
Jakob Stoklund Olesen79004762012-10-15 22:14:34 +0000355 if (!mf->getRegInfo().isAllocatable(dst)) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000356 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000357 }
Lang Hamese9c93562010-09-21 13:19:36 +0000358
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000359 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
Andrew Trick16f72dd2012-02-10 04:10:26 +0000360 unsigned pregOpt = 0;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000361 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000362 ++pregOpt;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000363 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000364 if (pregOpt < allowed.size()) {
365 ++pregOpt; // +1 to account for spill option.
366 PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
367 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000368 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000369 } else {
370 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
371 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
372 PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
373 PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
374 PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
375 if (edge == g.edgesEnd()) {
376 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
377 allowed2->size() + 1,
378 0));
379 } else {
380 if (g.getEdgeNode1(edge) == node2) {
381 std::swap(node1, node2);
382 std::swap(allowed1, allowed2);
383 }
384 }
Andrew Trick16f72dd2012-02-10 04:10:26 +0000385
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000386 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
387 cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000388 }
389 }
390 }
391
Andy Gibbs604b3572013-04-15 12:06:32 +0000392 return p.take();
Lang Hamese9c93562010-09-21 13:19:36 +0000393}
394
Lang Hamese9c93562010-09-21 13:19:36 +0000395void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
396 unsigned pregOption,
397 PBQP::PBQPNum benefit) {
398 costVec[pregOption] += -benefit;
399}
400
401void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
402 PBQP::Matrix &costMat,
403 const PBQPRAProblem::AllowedSet &vr1Allowed,
404 const PBQPRAProblem::AllowedSet &vr2Allowed,
405 PBQP::PBQPNum benefit) {
406
407 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
408 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
409
Lang Hames5e77f4b2010-11-12 05:47:21 +0000410 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hamese9c93562010-09-21 13:19:36 +0000411 unsigned preg1 = vr1Allowed[i];
Lang Hames5e77f4b2010-11-12 05:47:21 +0000412 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hamese9c93562010-09-21 13:19:36 +0000413 unsigned preg2 = vr2Allowed[j];
414
415 if (preg1 == preg2) {
416 costMat[i + 1][j + 1] += -benefit;
Andrew Trick16f72dd2012-02-10 04:10:26 +0000417 }
Lang Hamese9c93562010-09-21 13:19:36 +0000418 }
419 }
420}
Evan Chengb1290a62008-10-02 18:29:27 +0000421
Lang Hameseb6c8f52010-09-18 09:07:10 +0000422
423void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hames9ad7e072011-12-06 01:45:57 +0000424 au.setPreservesCFG();
425 au.addRequired<AliasAnalysis>();
426 au.addPreserved<AliasAnalysis>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000427 au.addRequired<SlotIndexes>();
428 au.addPreserved<SlotIndexes>();
429 au.addRequired<LiveIntervals>();
Lang Hames442c59f2012-10-04 04:50:53 +0000430 au.addPreserved<LiveIntervals>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000431 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames8d857662011-06-17 07:09:01 +0000432 if (customPassID)
433 au.addRequiredID(*customPassID);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000434 au.addRequired<CalculateSpillWeights>();
435 au.addRequired<LiveStacks>();
436 au.addPreserved<LiveStacks>();
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000437 au.addRequired<MachineBlockFrequencyInfo>();
438 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames9ad7e072011-12-06 01:45:57 +0000439 au.addRequired<MachineDominatorTree>();
440 au.addPreserved<MachineDominatorTree>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000441 au.addRequired<VirtRegMap>();
Lang Hames442c59f2012-10-04 04:50:53 +0000442 au.addPreserved<VirtRegMap>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000443 MachineFunctionPass::getAnalysisUsage(au);
444}
445
Lang Hameseb6c8f52010-09-18 09:07:10 +0000446void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames27601ef2008-11-16 12:12:54 +0000447
448 // Iterate over all live ranges.
Jakob Stoklund Olesend67582e2012-06-20 21:25:05 +0000449 for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
450 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
451 if (mri->reg_nodbg_empty(Reg))
Lang Hames27601ef2008-11-16 12:12:54 +0000452 continue;
Jakob Stoklund Olesend67582e2012-06-20 21:25:05 +0000453 LiveInterval *li = &lis->getInterval(Reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000454
455 // If this live interval is non-empty we will use pbqp to allocate it.
456 // Empty intervals we allocate in a simple post-processing stage in
457 // finalizeAlloc.
458 if (!li->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000459 vregsToAlloc.insert(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000460 } else {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000461 emptyIntervalVRegs.insert(li->reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000462 }
463 }
Evan Chengb1290a62008-10-02 18:29:27 +0000464}
465
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000466bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
467 const PBQP::Solution &solution) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000468 // Set to true if we have any spills
469 bool anotherRoundNeeded = false;
470
471 // Clear the existing allocation.
472 vrm->clearAllVirt();
473
474 const PBQP::Graph &g = problem.getGraph();
475 // Iterate over the nodes mapping the PBQP solution to a register
476 // assignment.
477 for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
478 nodeEnd = g.nodesEnd();
479 node != nodeEnd; ++node) {
480 unsigned vreg = problem.getVRegForNode(node);
481 unsigned alloc = solution.getSelection(node);
482
483 if (problem.isPRegOption(vreg, alloc)) {
Andrew Trick16f72dd2012-02-10 04:10:26 +0000484 unsigned preg = problem.getPRegForOption(vreg, alloc);
Patrik Hägglundd7693872012-05-23 12:12:58 +0000485 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
486 << tri->getName(preg) << "\n");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000487 assert(preg != 0 && "Invalid preg selected.");
Andrew Trick16f72dd2012-02-10 04:10:26 +0000488 vrm->assignVirt2Phys(vreg, preg);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000489 } else if (problem.isSpillOption(vreg, alloc)) {
490 vregsToAlloc.erase(vreg);
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000491 SmallVector<LiveInterval*, 8> newSpills;
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +0000492 LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000493 spiller->spill(LRE);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000494
Patrik Hägglundd7693872012-05-23 12:12:58 +0000495 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000496 << LRE.getParent().weight << ", New vregs: ");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000497
498 // Copy any newly inserted live intervals into the list of regs to
499 // allocate.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000500 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000501 itr != end; ++itr) {
502 assert(!(*itr)->empty() && "Empty spill range.");
Patrik Hägglundd7693872012-05-23 12:12:58 +0000503 DEBUG(dbgs() << PrintReg((*itr)->reg, tri) << " ");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000504 vregsToAlloc.insert((*itr)->reg);
505 }
506
507 DEBUG(dbgs() << ")\n");
508
509 // We need another round if spill intervals were added.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000510 anotherRoundNeeded |= !LRE.empty();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000511 } else {
Craig Topper5e25ee82012-02-05 08:31:47 +0000512 llvm_unreachable("Unknown allocation option.");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000513 }
514 }
515
516 return !anotherRoundNeeded;
517}
518
519
520void RegAllocPBQP::finalizeAlloc() const {
Lang Hames27601ef2008-11-16 12:12:54 +0000521 // First allocate registers for the empty intervals.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000522 for (RegSet::const_iterator
523 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames27601ef2008-11-16 12:12:54 +0000524 itr != end; ++itr) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000525 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames27601ef2008-11-16 12:12:54 +0000526
Jakob Stoklund Olesen980bddf2012-12-04 00:30:22 +0000527 unsigned physReg = mri->getSimpleHint(li->reg);
Lang Hames6699fb22009-08-06 23:32:48 +0000528
Lang Hames27601ef2008-11-16 12:12:54 +0000529 if (physReg == 0) {
530 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000531 physReg = liRC->getRawAllocationOrder(*mf).front();
Lang Hames27601ef2008-11-16 12:12:54 +0000532 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000533
534 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames27601ef2008-11-16 12:12:54 +0000535 }
Lang Hames27601ef2008-11-16 12:12:54 +0000536}
537
Lang Hameseb6c8f52010-09-18 09:07:10 +0000538bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames27601ef2008-11-16 12:12:54 +0000539
Evan Chengb1290a62008-10-02 18:29:27 +0000540 mf = &MF;
541 tm = &mf->getTarget();
542 tri = tm->getRegisterInfo();
Lang Hames27601ef2008-11-16 12:12:54 +0000543 tii = tm->getInstrInfo();
Andrew Trick16f72dd2012-02-10 04:10:26 +0000544 mri = &mf->getRegInfo();
Evan Chengb1290a62008-10-02 18:29:27 +0000545
Lang Hames27601ef2008-11-16 12:12:54 +0000546 lis = &getAnalysis<LiveIntervals>();
547 lss = &getAnalysis<LiveStacks>();
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000548 mbfi = &getAnalysis<MachineBlockFrequencyInfo>();
Evan Chengb1290a62008-10-02 18:29:27 +0000549
Owen Anderson49c8aa02009-03-13 05:55:11 +0000550 vrm = &getAnalysis<VirtRegMap>();
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000551 spiller.reset(createInlineSpiller(*this, MF, *vrm));
Evan Chengb1290a62008-10-02 18:29:27 +0000552
Chad Rosier18bb0542012-11-28 00:21:29 +0000553 mri->freezeReservedRegs(MF);
554
Craig Topper96601ca2012-08-22 06:07:19 +0000555 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000556
Evan Chengb1290a62008-10-02 18:29:27 +0000557 // Allocator main loop:
Misha Brukman2a835f92009-01-08 15:50:22 +0000558 //
Evan Chengb1290a62008-10-02 18:29:27 +0000559 // * Map current regalloc problem to a PBQP problem
560 // * Solve the PBQP problem
561 // * Map the solution back to a register allocation
562 // * Spill if necessary
Misha Brukman2a835f92009-01-08 15:50:22 +0000563 //
Evan Chengb1290a62008-10-02 18:29:27 +0000564 // This process is continued till no more spills are generated.
565
Lang Hames27601ef2008-11-16 12:12:54 +0000566 // Find the vreg intervals in need of allocation.
567 findVRegIntervalsToAlloc();
Misha Brukman2a835f92009-01-08 15:50:22 +0000568
Craig Topper96601ca2012-08-22 06:07:19 +0000569#ifndef NDEBUG
Lang Hames20df03c2012-03-26 23:07:23 +0000570 const Function* func = mf->getFunction();
571 std::string fqn =
572 func->getParent()->getModuleIdentifier() + "." +
573 func->getName().str();
Craig Topper96601ca2012-08-22 06:07:19 +0000574#endif
Lang Hames20df03c2012-03-26 23:07:23 +0000575
Lang Hames27601ef2008-11-16 12:12:54 +0000576 // If there are non-empty intervals allocate them using pbqp.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000577 if (!vregsToAlloc.empty()) {
Evan Chengb1290a62008-10-02 18:29:27 +0000578
Lang Hames27601ef2008-11-16 12:12:54 +0000579 bool pbqpAllocComplete = false;
580 unsigned round = 0;
581
Lang Hamesab62b7e2010-10-04 12:13:07 +0000582 while (!pbqpAllocComplete) {
583 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000584
Andy Gibbs604b3572013-04-15 12:06:32 +0000585 OwningPtr<PBQPRAProblem> problem(
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000586 builder->build(mf, lis, mbfi, vregsToAlloc));
Lang Hames20df03c2012-03-26 23:07:23 +0000587
588#ifndef NDEBUG
589 if (pbqpDumpGraphs) {
590 std::ostringstream rs;
591 rs << round;
592 std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
593 std::string tmp;
594 raw_fd_ostream os(graphFileName.c_str(), tmp);
595 DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
596 << graphFileName << "\"\n");
597 problem->getGraph().dump(os);
598 }
599#endif
600
Lang Hamesab62b7e2010-10-04 12:13:07 +0000601 PBQP::Solution solution =
602 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
603 problem->getGraph());
Lang Hames233fd9c2009-08-18 23:34:50 +0000604
Lang Hamesab62b7e2010-10-04 12:13:07 +0000605 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames27601ef2008-11-16 12:12:54 +0000606
Lang Hamesab62b7e2010-10-04 12:13:07 +0000607 ++round;
Lang Hames27601ef2008-11-16 12:12:54 +0000608 }
Evan Chengb1290a62008-10-02 18:29:27 +0000609 }
610
Lang Hames27601ef2008-11-16 12:12:54 +0000611 // Finalise allocation, allocate empty ranges.
612 finalizeAlloc();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000613 vregsToAlloc.clear();
614 emptyIntervalVRegs.clear();
Lang Hames27601ef2008-11-16 12:12:54 +0000615
David Greene30931542010-01-05 01:25:43 +0000616 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000617
Misha Brukman2a835f92009-01-08 15:50:22 +0000618 return true;
Evan Chengb1290a62008-10-02 18:29:27 +0000619}
620
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000621FunctionPass* llvm::createPBQPRegisterAllocator(
Andy Gibbs604b3572013-04-15 12:06:32 +0000622 OwningPtr<PBQPBuilder> &builder,
Lang Hames8d857662011-06-17 07:09:01 +0000623 char *customPassID) {
Benjamin Kramer3389e102013-04-12 12:13:51 +0000624 return new RegAllocPBQP(builder, customPassID);
Evan Chengb1290a62008-10-02 18:29:27 +0000625}
626
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000627FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Andy Gibbs604b3572013-04-15 12:06:32 +0000628 OwningPtr<PBQPBuilder> Builder;
629 if (pbqpCoalescing)
630 Builder.reset(new PBQPBuilderWithCoalescing());
631 else
632 Builder.reset(new PBQPBuilder());
633 return createPBQPRegisterAllocator(Builder);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000634}
Evan Chengb1290a62008-10-02 18:29:27 +0000635
636#undef DEBUG_TYPE