blob: 9f8b401a81f13868f0b2570f1ce45b0b30b5d82f [file] [log] [blame]
Evan Chengb25f4632008-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 Brukmanda467482009-01-08 15:50:22 +00009//
Evan Chengb25f4632008-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 Brukmanda467482009-01-08 15:50:22 +000015// code is inserted and the process repeated.
Evan Chengb25f4632008-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 Brukman572f2642009-01-08 16:40:25 +000019// allocation, see the following papers:
Evan Chengb25f4632008-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 Brukmanda467482009-01-08 15:50:22 +000029//
Evan Chengb25f4632008-10-02 18:29:27 +000030//===----------------------------------------------------------------------===//
31
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/CodeGen/RegAllocPBQP.h"
Rafael Espindolafef3c642011-06-26 21:41:06 +000033#include "RegisterCoalescer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "Spiller.h"
Lang Hamesb13b6a02011-12-06 01:45:57 +000035#include "llvm/Analysis/AliasAnalysis.h"
Lang Hamesd17e2962009-12-14 06:49:42 +000036#include "llvm/CodeGen/CalcSpillWeights.h"
Evan Chengb25f4632008-10-02 18:29:27 +000037#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000038#include "llvm/CodeGen/LiveRangeEdit.h"
Lang Hames49ab8bc2008-11-16 12:12:54 +000039#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000040#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Lang Hamesb13b6a02011-12-06 01:45:57 +000041#include "llvm/CodeGen/MachineDominators.h"
Misha Brukmanda467482009-01-08 15:50:22 +000042#include "llvm/CodeGen/MachineFunctionPass.h"
Lang Hames7d99d792013-07-01 20:47:47 +000043#include "llvm/CodeGen/MachineLoopInfo.h"
Misha Brukmanda467482009-01-08 15:50:22 +000044#include "llvm/CodeGen/MachineRegisterInfo.h"
45#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000046#include "llvm/CodeGen/VirtRegMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Module.h"
Evan Chengb25f4632008-10-02 18:29:27 +000048#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000049#include "llvm/Support/raw_ostream.h"
Misha Brukmanda467482009-01-08 15:50:22 +000050#include "llvm/Target/TargetInstrInfo.h"
51#include "llvm/Target/TargetMachine.h"
52#include <limits>
Misha Brukmanda467482009-01-08 15:50:22 +000053#include <memory>
Evan Chengb25f4632008-10-02 18:29:27 +000054#include <set>
Lang Hames95e021f2012-03-26 23:07:23 +000055#include <sstream>
Evan Chengb25f4632008-10-02 18:29:27 +000056#include <vector>
Evan Chengb25f4632008-10-02 18:29:27 +000057
Lang Hamesfd1bc422010-09-23 04:28:54 +000058using namespace llvm;
Lang Hamescb1e1012010-09-18 09:07:10 +000059
Chandler Carruth1b9dde02014-04-22 02:02:50 +000060#define DEBUG_TYPE "regalloc"
61
Evan Chengb25f4632008-10-02 18:29:27 +000062static RegisterRegAlloc
Duncan Sands1804b4f2010-02-18 14:10:41 +000063registerPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesfd1bc422010-09-23 04:28:54 +000064 createDefaultPBQPRegisterAllocator);
Evan Chengb25f4632008-10-02 18:29:27 +000065
Lang Hames11732ad2009-08-19 01:36:14 +000066static cl::opt<bool>
67pbqpCoalescing("pbqp-coalescing",
Lang Hames090c7e82010-01-26 04:49:58 +000068 cl::desc("Attempt coalescing during PBQP register allocation."),
69 cl::init(false), cl::Hidden);
Lang Hames11732ad2009-08-19 01:36:14 +000070
Lang Hames95e021f2012-03-26 23:07:23 +000071#ifndef NDEBUG
72static cl::opt<bool>
73pbqpDumpGraphs("pbqp-dump-graphs",
74 cl::desc("Dump graphs for each function/round in the compilation unit."),
75 cl::init(false), cl::Hidden);
76#endif
77
Lang Hamesfd1bc422010-09-23 04:28:54 +000078namespace {
79
80///
81/// PBQP based allocators solve the register allocation problem by mapping
82/// register allocation problems to Partitioned Boolean Quadratic
83/// Programming problems.
84class RegAllocPBQP : public MachineFunctionPass {
85public:
86
87 static char ID;
88
89 /// Construct a PBQP register allocator.
Craig Topperc0196b12014-04-14 00:51:57 +000090 RegAllocPBQP(std::unique_ptr<PBQPBuilder> &b, char *cPassID=nullptr)
Ahmed Charles96c9d952014-03-05 10:19:29 +000091 : MachineFunctionPass(ID), builder(b.release()), customPassID(cPassID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +000092 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
93 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000094 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000095 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000096 }
Lang Hamesfd1bc422010-09-23 04:28:54 +000097
98 /// Return the pass name.
Craig Topper4584cd52014-03-07 09:26:03 +000099 const char* getPassName() const override {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000100 return "PBQP Register Allocator";
101 }
102
103 /// PBQP analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000104 void getAnalysisUsage(AnalysisUsage &au) const override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000105
106 /// Perform register allocation
Craig Topper4584cd52014-03-07 09:26:03 +0000107 bool runOnMachineFunction(MachineFunction &MF) override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000108
109private:
110
111 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
112 typedef std::vector<const LiveInterval*> Node2LIMap;
113 typedef std::vector<unsigned> AllowedSet;
114 typedef std::vector<AllowedSet> AllowedSetMap;
115 typedef std::pair<unsigned, unsigned> RegPair;
116 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000117 typedef std::set<unsigned> RegSet;
118
Ahmed Charles56440fd2014-03-06 05:51:42 +0000119 std::unique_ptr<PBQPBuilder> builder;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000120
Lang Hames934625e2011-06-17 07:09:01 +0000121 char *customPassID;
122
Lang Hamesfd1bc422010-09-23 04:28:54 +0000123 MachineFunction *mf;
124 const TargetMachine *tm;
125 const TargetRegisterInfo *tri;
126 const TargetInstrInfo *tii;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000127 MachineRegisterInfo *mri;
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000128 const MachineBlockFrequencyInfo *mbfi;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000129
Ahmed Charles56440fd2014-03-06 05:51:42 +0000130 std::unique_ptr<Spiller> spiller;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000131 LiveIntervals *lis;
132 LiveStacks *lss;
133 VirtRegMap *vrm;
134
Lang Hamesfd1bc422010-09-23 04:28:54 +0000135 RegSet vregsToAlloc, emptyIntervalVRegs;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000136
137 /// \brief Finds the initial set of vreg intervals to allocate.
138 void findVRegIntervalsToAlloc();
139
Lang Hamesfd1bc422010-09-23 04:28:54 +0000140 /// \brief Given a solved PBQP problem maps this solution back to a register
141 /// assignment.
Lang Hamesfd1bc422010-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 Hamescb1e1012010-09-18 09:07:10 +0000151char RegAllocPBQP::ID = 0;
Evan Chengb25f4632008-10-02 18:29:27 +0000152
Lang Hamesfd1bc422010-09-23 04:28:54 +0000153} // End anonymous namespace.
154
Lang Hames18635822014-03-03 18:50:05 +0000155unsigned PBQPRAProblem::getVRegForNode(PBQPRAGraph::NodeId node) const {
Lang Hamescb1e1012010-09-18 09:07:10 +0000156 Node2VReg::const_iterator vregItr = node2VReg.find(node);
157 assert(vregItr != node2VReg.end() && "No vreg for node.");
158 return vregItr->second;
159}
Evan Chengb25f4632008-10-02 18:29:27 +0000160
Lang Hames18635822014-03-03 18:50:05 +0000161PBQPRAGraph::NodeId PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
Lang Hamescb1e1012010-09-18 09:07:10 +0000162 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
163 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
164 return nodeItr->second;
Andrew Trick9363b592012-02-10 04:10:26 +0000165
Lang Hamescb1e1012010-09-18 09:07:10 +0000166}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000167
Lang Hamescb1e1012010-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 Chengb25f4632008-10-02 18:29:27 +0000175
Lang Hamescb1e1012010-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
Andy Gibbsb23ea722013-04-15 12:06:32 +0000184PBQPRAProblem *PBQPBuilder::build(MachineFunction *mf, const LiveIntervals *lis,
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000185 const MachineBlockFrequencyInfo *mbfi,
Andy Gibbsb23ea722013-04-15 12:06:32 +0000186 const RegSet &vregs) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000187
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000188 LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
Lang Hamescb1e1012010-09-18 09:07:10 +0000189 MachineRegisterInfo *mri = &mf->getRegInfo();
Andrew Trick9363b592012-02-10 04:10:26 +0000190 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
Lang Hamescb1e1012010-09-18 09:07:10 +0000191
Ahmed Charles56440fd2014-03-06 05:51:42 +0000192 std::unique_ptr<PBQPRAProblem> p(new PBQPRAProblem());
Lang Hames18635822014-03-03 18:50:05 +0000193 PBQPRAGraph &g = p->getGraph();
Lang Hamescb1e1012010-09-18 09:07:10 +0000194 RegSet pregs;
195
196 // Collect the set of preg intervals, record that they're used in the MF.
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000197 for (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000198 if (mri->def_empty(Reg))
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000199 continue;
200 pregs.insert(Reg);
201 mri->setPhysRegUsed(Reg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000202 }
Evan Chengb25f4632008-10-02 18:29:27 +0000203
Andrew Trick9363b592012-02-10 04:10:26 +0000204 // Iterate over vregs.
Lang Hamescb1e1012010-09-18 09:07:10 +0000205 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
206 vregItr != vregEnd; ++vregItr) {
207 unsigned vreg = *vregItr;
208 const TargetRegisterClass *trc = mri->getRegClass(vreg);
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000209 LiveInterval *vregLI = &LIS->getInterval(vreg);
210
211 // Record any overlaps with regmask operands.
Lang Hames05fee082012-10-10 06:39:48 +0000212 BitVector regMaskOverlaps;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000213 LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
Evan Chengb25f4632008-10-02 18:29:27 +0000214
Lang Hamescb1e1012010-09-18 09:07:10 +0000215 // Compute an initial allowed set for the current vreg.
216 typedef std::vector<unsigned> VRAllowed;
217 VRAllowed vrAllowed;
Craig Topper840beec2014-04-04 05:16:06 +0000218 ArrayRef<MCPhysReg> rawOrder = trc->getRawAllocationOrder(*mf);
Jakob Stoklund Olesen08322b72011-06-16 20:37:45 +0000219 for (unsigned i = 0; i != rawOrder.size(); ++i) {
220 unsigned preg = rawOrder[i];
Jakob Stoklund Olesenc30a9af2012-10-15 21:57:41 +0000221 if (mri->isReserved(preg))
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000222 continue;
223
224 // vregLI crosses a regmask operand that clobbers preg.
Lang Hames05fee082012-10-10 06:39:48 +0000225 if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000226 continue;
227
228 // vregLI overlaps fixed regunit interference.
Jakob Stoklund Olesenb1b3e4a2012-06-22 16:46:44 +0000229 bool Interference = false;
230 for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
231 if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
232 Interference = true;
233 break;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000234 }
Lang Hames211e7ce2010-07-17 06:31:41 +0000235 }
Jakob Stoklund Olesenb1b3e4a2012-06-22 16:46:44 +0000236 if (Interference)
237 continue;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000238
239 // preg is usable for this virtual register.
240 vrAllowed.push_back(preg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000241 }
Lang Hames211e7ce2010-07-17 06:31:41 +0000242
Lang Hames18635822014-03-03 18:50:05 +0000243 PBQP::Vector nodeCosts(vrAllowed.size() + 1, 0);
Evan Chengb25f4632008-10-02 18:29:27 +0000244
Lang Hamescb1e1012010-09-18 09:07:10 +0000245 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
246 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb25f4632008-10-02 18:29:27 +0000247
Lang Hames18635822014-03-03 18:50:05 +0000248 addSpillCosts(nodeCosts, spillCost);
249
250 // Construct the node.
251 PBQPRAGraph::NodeId nId = g.addNode(std::move(nodeCosts));
252
253 // Record the mapping and allowed set in the problem.
254 p->recordVReg(vreg, nId, vrAllowed.begin(), vrAllowed.end());
255
Lang Hamescb1e1012010-09-18 09:07:10 +0000256 }
Evan Chengb25f4632008-10-02 18:29:27 +0000257
Lang Hames361de982010-09-18 09:49:08 +0000258 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hamescb1e1012010-09-18 09:07:10 +0000259 vr1Itr != vrEnd; ++vr1Itr) {
260 unsigned vr1 = *vr1Itr;
261 const LiveInterval &l1 = lis->getInterval(vr1);
262 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb25f4632008-10-02 18:29:27 +0000263
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000264 for (RegSet::const_iterator vr2Itr = std::next(vr1Itr); vr2Itr != vrEnd;
265 ++vr2Itr) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000266 unsigned vr2 = *vr2Itr;
267 const LiveInterval &l2 = lis->getInterval(vr2);
268 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb25f4632008-10-02 18:29:27 +0000269
Lang Hamescb1e1012010-09-18 09:07:10 +0000270 assert(!l2.empty() && "Empty interval in vreg set?");
271 if (l1.overlaps(l2)) {
Lang Hames18635822014-03-03 18:50:05 +0000272 PBQP::Matrix edgeCosts(vr1Allowed.size()+1, vr2Allowed.size()+1, 0);
273 addInterferenceCosts(edgeCosts, vr1Allowed, vr2Allowed, tri);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000274
Lang Hames18635822014-03-03 18:50:05 +0000275 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
276 std::move(edgeCosts));
Lang Hamescb1e1012010-09-18 09:07:10 +0000277 }
278 }
279 }
Evan Chengb25f4632008-10-02 18:29:27 +0000280
Ahmed Charles96c9d952014-03-05 10:19:29 +0000281 return p.release();
Lang Hamescb1e1012010-09-18 09:07:10 +0000282}
Lang Hames49ab8bc2008-11-16 12:12:54 +0000283
Lang Hamescb1e1012010-09-18 09:07:10 +0000284void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
285 PBQP::PBQPNum spillCost) {
286 costVec[0] = spillCost;
287}
Evan Chengb25f4632008-10-02 18:29:27 +0000288
Lang Hames0937fc42010-09-21 13:19:36 +0000289void PBQPBuilder::addInterferenceCosts(
290 PBQP::Matrix &costMat,
291 const PBQPRAProblem::AllowedSet &vr1Allowed,
292 const PBQPRAProblem::AllowedSet &vr2Allowed,
293 const TargetRegisterInfo *tri) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000294 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
295 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
296
Lang Hamesc702ba62010-11-12 05:47:21 +0000297 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000298 unsigned preg1 = vr1Allowed[i];
299
Lang Hamesc702ba62010-11-12 05:47:21 +0000300 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000301 unsigned preg2 = vr2Allowed[j];
302
303 if (tri->regsOverlap(preg1, preg2)) {
304 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
305 }
306 }
307 }
Evan Chengb25f4632008-10-02 18:29:27 +0000308}
309
Andy Gibbsb23ea722013-04-15 12:06:32 +0000310PBQPRAProblem *PBQPBuilderWithCoalescing::build(MachineFunction *mf,
Lang Hames0937fc42010-09-21 13:19:36 +0000311 const LiveIntervals *lis,
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000312 const MachineBlockFrequencyInfo *mbfi,
Lang Hames0937fc42010-09-21 13:19:36 +0000313 const RegSet &vregs) {
314
Ahmed Charles56440fd2014-03-06 05:51:42 +0000315 std::unique_ptr<PBQPRAProblem> p(PBQPBuilder::build(mf, lis, mbfi, vregs));
Lang Hames18635822014-03-03 18:50:05 +0000316 PBQPRAGraph &g = p->getGraph();
Lang Hames0937fc42010-09-21 13:19:36 +0000317
318 const TargetMachine &tm = mf->getTarget();
Benjamin Kramer628a39f2012-06-06 18:25:08 +0000319 CoalescerPair cp(*tm.getRegisterInfo());
Lang Hames0937fc42010-09-21 13:19:36 +0000320
321 // Scan the machine function and add a coalescing cost whenever CoalescerPair
322 // gives the Ok.
323 for (MachineFunction::const_iterator mbbItr = mf->begin(),
324 mbbEnd = mf->end();
325 mbbItr != mbbEnd; ++mbbItr) {
326 const MachineBasicBlock *mbb = &*mbbItr;
327
328 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
329 miEnd = mbb->end();
330 miItr != miEnd; ++miItr) {
331 const MachineInstr *mi = &*miItr;
332
Lang Hamesc702ba62010-11-12 05:47:21 +0000333 if (!cp.setRegisters(mi)) {
Lang Hames0937fc42010-09-21 13:19:36 +0000334 continue; // Not coalescable.
Lang Hamesc702ba62010-11-12 05:47:21 +0000335 }
Lang Hames0937fc42010-09-21 13:19:36 +0000336
Lang Hamesc702ba62010-11-12 05:47:21 +0000337 if (cp.getSrcReg() == cp.getDstReg()) {
Lang Hames0937fc42010-09-21 13:19:36 +0000338 continue; // Already coalesced.
Lang Hamesc702ba62010-11-12 05:47:21 +0000339 }
Lang Hames0937fc42010-09-21 13:19:36 +0000340
Lang Hamesfd1bc422010-09-23 04:28:54 +0000341 unsigned dst = cp.getDstReg(),
342 src = cp.getSrcReg();
Lang Hames0937fc42010-09-21 13:19:36 +0000343
Lang Hamesfd1bc422010-09-23 04:28:54 +0000344 const float copyFactor = 0.5; // Cost of copy relative to load. Current
345 // value plucked randomly out of the air.
Andrew Trick9363b592012-02-10 04:10:26 +0000346
Lang Hamesfd1bc422010-09-23 04:28:54 +0000347 PBQP::PBQPNum cBenefit =
Michael Gottesman9f49d742013-12-14 00:53:32 +0000348 copyFactor * LiveIntervals::getSpillWeight(false, true, mbfi, mi);
Lang Hames0937fc42010-09-21 13:19:36 +0000349
Lang Hamesfd1bc422010-09-23 04:28:54 +0000350 if (cp.isPhys()) {
Jakob Stoklund Olesencea596a2012-10-15 22:14:34 +0000351 if (!mf->getRegInfo().isAllocatable(dst)) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000352 continue;
Lang Hamesc702ba62010-11-12 05:47:21 +0000353 }
Lang Hames0937fc42010-09-21 13:19:36 +0000354
Lang Hamesfd1bc422010-09-23 04:28:54 +0000355 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
Andrew Trick9363b592012-02-10 04:10:26 +0000356 unsigned pregOpt = 0;
Lang Hamesc702ba62010-11-12 05:47:21 +0000357 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000358 ++pregOpt;
Lang Hamesc702ba62010-11-12 05:47:21 +0000359 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000360 if (pregOpt < allowed.size()) {
361 ++pregOpt; // +1 to account for spill option.
Lang Hames18635822014-03-03 18:50:05 +0000362 PBQPRAGraph::NodeId node = p->getNodeForVReg(src);
363 llvm::dbgs() << "Reading node costs for node " << node << "\n";
364 llvm::dbgs() << "Source node: " << &g.getNodeCosts(node) << "\n";
365 PBQP::Vector newCosts(g.getNodeCosts(node));
366 addPhysRegCoalesce(newCosts, pregOpt, cBenefit);
367 g.setNodeCosts(node, newCosts);
Lang Hames0937fc42010-09-21 13:19:36 +0000368 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000369 } else {
370 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
371 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
Lang Hames18635822014-03-03 18:50:05 +0000372 PBQPRAGraph::NodeId node1 = p->getNodeForVReg(dst);
373 PBQPRAGraph::NodeId node2 = p->getNodeForVReg(src);
374 PBQPRAGraph::EdgeId edge = g.findEdge(node1, node2);
Lang Hamesfb826302013-11-09 03:08:56 +0000375 if (edge == g.invalidEdgeId()) {
Lang Hames18635822014-03-03 18:50:05 +0000376 PBQP::Matrix costs(allowed1->size() + 1, allowed2->size() + 1, 0);
377 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
378 g.addEdge(node1, node2, costs);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000379 } else {
Lang Hames18635822014-03-03 18:50:05 +0000380 if (g.getEdgeNode1Id(edge) == node2) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000381 std::swap(node1, node2);
382 std::swap(allowed1, allowed2);
383 }
Lang Hames18635822014-03-03 18:50:05 +0000384 PBQP::Matrix costs(g.getEdgeCosts(edge));
385 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
386 g.setEdgeCosts(edge, costs);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000387 }
Lang Hames0937fc42010-09-21 13:19:36 +0000388 }
389 }
390 }
391
Ahmed Charles96c9d952014-03-05 10:19:29 +0000392 return p.release();
Lang Hames0937fc42010-09-21 13:19:36 +0000393}
394
Lang Hames0937fc42010-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 Hamesc702ba62010-11-12 05:47:21 +0000410 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hames0937fc42010-09-21 13:19:36 +0000411 unsigned preg1 = vr1Allowed[i];
Lang Hamesc702ba62010-11-12 05:47:21 +0000412 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hames0937fc42010-09-21 13:19:36 +0000413 unsigned preg2 = vr2Allowed[j];
414
415 if (preg1 == preg2) {
416 costMat[i + 1][j + 1] += -benefit;
Andrew Trick9363b592012-02-10 04:10:26 +0000417 }
Lang Hames0937fc42010-09-21 13:19:36 +0000418 }
419 }
420}
Evan Chengb25f4632008-10-02 18:29:27 +0000421
Lang Hamescb1e1012010-09-18 09:07:10 +0000422
423void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hamesb13b6a02011-12-06 01:45:57 +0000424 au.setPreservesCFG();
425 au.addRequired<AliasAnalysis>();
426 au.addPreserved<AliasAnalysis>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000427 au.addRequired<SlotIndexes>();
428 au.addPreserved<SlotIndexes>();
429 au.addRequired<LiveIntervals>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000430 au.addPreserved<LiveIntervals>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000431 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames934625e2011-06-17 07:09:01 +0000432 if (customPassID)
433 au.addRequiredID(*customPassID);
Lang Hamescb1e1012010-09-18 09:07:10 +0000434 au.addRequired<LiveStacks>();
435 au.addPreserved<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000436 au.addRequired<MachineBlockFrequencyInfo>();
437 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames7d99d792013-07-01 20:47:47 +0000438 au.addRequired<MachineLoopInfo>();
439 au.addPreserved<MachineLoopInfo>();
Lang Hamesb13b6a02011-12-06 01:45:57 +0000440 au.addRequired<MachineDominatorTree>();
441 au.addPreserved<MachineDominatorTree>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000442 au.addRequired<VirtRegMap>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000443 au.addPreserved<VirtRegMap>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000444 MachineFunctionPass::getAnalysisUsage(au);
445}
446
Lang Hamescb1e1012010-09-18 09:07:10 +0000447void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000448
449 // Iterate over all live ranges.
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000450 for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
451 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
452 if (mri->reg_nodbg_empty(Reg))
Lang Hames49ab8bc2008-11-16 12:12:54 +0000453 continue;
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000454 LiveInterval *li = &lis->getInterval(Reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000455
456 // If this live interval is non-empty we will use pbqp to allocate it.
457 // Empty intervals we allocate in a simple post-processing stage in
458 // finalizeAlloc.
459 if (!li->empty()) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000460 vregsToAlloc.insert(li->reg);
Lang Hamesc702ba62010-11-12 05:47:21 +0000461 } else {
Lang Hamescb1e1012010-09-18 09:07:10 +0000462 emptyIntervalVRegs.insert(li->reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000463 }
464 }
Evan Chengb25f4632008-10-02 18:29:27 +0000465}
466
Lang Hamesfd1bc422010-09-23 04:28:54 +0000467bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
468 const PBQP::Solution &solution) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000469 // Set to true if we have any spills
470 bool anotherRoundNeeded = false;
471
472 // Clear the existing allocation.
473 vrm->clearAllVirt();
474
Lang Hames18635822014-03-03 18:50:05 +0000475 const PBQPRAGraph &g = problem.getGraph();
Lang Hamescb1e1012010-09-18 09:07:10 +0000476 // Iterate over the nodes mapping the PBQP solution to a register
477 // assignment.
Lang Hames18635822014-03-03 18:50:05 +0000478 for (auto NId : g.nodeIds()) {
479 unsigned vreg = problem.getVRegForNode(NId);
480 unsigned alloc = solution.getSelection(NId);
Lang Hamescb1e1012010-09-18 09:07:10 +0000481
482 if (problem.isPRegOption(vreg, alloc)) {
Andrew Trick9363b592012-02-10 04:10:26 +0000483 unsigned preg = problem.getPRegForOption(vreg, alloc);
Patrik Hägglund94537c22012-05-23 12:12:58 +0000484 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
485 << tri->getName(preg) << "\n");
Lang Hamescb1e1012010-09-18 09:07:10 +0000486 assert(preg != 0 && "Invalid preg selected.");
Andrew Trick9363b592012-02-10 04:10:26 +0000487 vrm->assignVirt2Phys(vreg, preg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000488 } else if (problem.isSpillOption(vreg, alloc)) {
489 vregsToAlloc.erase(vreg);
Mark Laceyf9ea8852013-08-14 23:50:04 +0000490 SmallVector<unsigned, 8> newSpills;
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +0000491 LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000492 spiller->spill(LRE);
Lang Hamescb1e1012010-09-18 09:07:10 +0000493
Patrik Hägglund94537c22012-05-23 12:12:58 +0000494 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000495 << LRE.getParent().weight << ", New vregs: ");
Lang Hamescb1e1012010-09-18 09:07:10 +0000496
497 // Copy any newly inserted live intervals into the list of regs to
498 // allocate.
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000499 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
Lang Hamescb1e1012010-09-18 09:07:10 +0000500 itr != end; ++itr) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000501 LiveInterval &li = lis->getInterval(*itr);
502 assert(!li.empty() && "Empty spill range.");
503 DEBUG(dbgs() << PrintReg(li.reg, tri) << " ");
504 vregsToAlloc.insert(li.reg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000505 }
506
507 DEBUG(dbgs() << ")\n");
508
509 // We need another round if spill intervals were added.
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000510 anotherRoundNeeded |= !LRE.empty();
Lang Hamescb1e1012010-09-18 09:07:10 +0000511 } else {
Craig Topperee4dab52012-02-05 08:31:47 +0000512 llvm_unreachable("Unknown allocation option.");
Lang Hamescb1e1012010-09-18 09:07:10 +0000513 }
514 }
515
516 return !anotherRoundNeeded;
517}
518
519
520void RegAllocPBQP::finalizeAlloc() const {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000521 // First allocate registers for the empty intervals.
Lang Hamescb1e1012010-09-18 09:07:10 +0000522 for (RegSet::const_iterator
523 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000524 itr != end; ++itr) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000525 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000526
Jakob Stoklund Olesen1dd82dd2012-12-04 00:30:22 +0000527 unsigned physReg = mri->getSimpleHint(li->reg);
Lang Hames88fae6f2009-08-06 23:32:48 +0000528
Lang Hames49ab8bc2008-11-16 12:12:54 +0000529 if (physReg == 0) {
530 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Jakob Stoklund Olesen08322b72011-06-16 20:37:45 +0000531 physReg = liRC->getRawAllocationOrder(*mf).front();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000532 }
Misha Brukmanda467482009-01-08 15:50:22 +0000533
534 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000535 }
Lang Hames49ab8bc2008-11-16 12:12:54 +0000536}
537
Lang Hamescb1e1012010-09-18 09:07:10 +0000538bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000539
Evan Chengb25f4632008-10-02 18:29:27 +0000540 mf = &MF;
541 tm = &mf->getTarget();
542 tri = tm->getRegisterInfo();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000543 tii = tm->getInstrInfo();
Andrew Trick9363b592012-02-10 04:10:26 +0000544 mri = &mf->getRegInfo();
Evan Chengb25f4632008-10-02 18:29:27 +0000545
Lang Hames49ab8bc2008-11-16 12:12:54 +0000546 lis = &getAnalysis<LiveIntervals>();
547 lss = &getAnalysis<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000548 mbfi = &getAnalysis<MachineBlockFrequencyInfo>();
Evan Chengb25f4632008-10-02 18:29:27 +0000549
Arnaud A. de Grandmaisonea3ac162013-11-11 19:04:45 +0000550 calculateSpillWeightsAndHints(*lis, MF, getAnalysis<MachineLoopInfo>(),
551 *mbfi);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +0000552
Owen Andersond37ddf52009-03-13 05:55:11 +0000553 vrm = &getAnalysis<VirtRegMap>();
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000554 spiller.reset(createInlineSpiller(*this, MF, *vrm));
Evan Chengb25f4632008-10-02 18:29:27 +0000555
Chad Rosiered119d52012-11-28 00:21:29 +0000556 mri->freezeReservedRegs(MF);
557
Craig Toppera538d832012-08-22 06:07:19 +0000558 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000559
Evan Chengb25f4632008-10-02 18:29:27 +0000560 // Allocator main loop:
Misha Brukmanda467482009-01-08 15:50:22 +0000561 //
Evan Chengb25f4632008-10-02 18:29:27 +0000562 // * Map current regalloc problem to a PBQP problem
563 // * Solve the PBQP problem
564 // * Map the solution back to a register allocation
565 // * Spill if necessary
Misha Brukmanda467482009-01-08 15:50:22 +0000566 //
Evan Chengb25f4632008-10-02 18:29:27 +0000567 // This process is continued till no more spills are generated.
568
Lang Hames49ab8bc2008-11-16 12:12:54 +0000569 // Find the vreg intervals in need of allocation.
570 findVRegIntervalsToAlloc();
Misha Brukmanda467482009-01-08 15:50:22 +0000571
Craig Toppera538d832012-08-22 06:07:19 +0000572#ifndef NDEBUG
Lang Hames95e021f2012-03-26 23:07:23 +0000573 const Function* func = mf->getFunction();
574 std::string fqn =
575 func->getParent()->getModuleIdentifier() + "." +
576 func->getName().str();
Craig Toppera538d832012-08-22 06:07:19 +0000577#endif
Lang Hames95e021f2012-03-26 23:07:23 +0000578
Lang Hames49ab8bc2008-11-16 12:12:54 +0000579 // If there are non-empty intervals allocate them using pbqp.
Lang Hamescb1e1012010-09-18 09:07:10 +0000580 if (!vregsToAlloc.empty()) {
Evan Chengb25f4632008-10-02 18:29:27 +0000581
Lang Hames49ab8bc2008-11-16 12:12:54 +0000582 bool pbqpAllocComplete = false;
583 unsigned round = 0;
584
Lang Hames4108e7e2010-10-04 12:13:07 +0000585 while (!pbqpAllocComplete) {
586 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000587
Ahmed Charles56440fd2014-03-06 05:51:42 +0000588 std::unique_ptr<PBQPRAProblem> problem(
589 builder->build(mf, lis, mbfi, vregsToAlloc));
Lang Hames95e021f2012-03-26 23:07:23 +0000590
591#ifndef NDEBUG
592 if (pbqpDumpGraphs) {
593 std::ostringstream rs;
594 rs << round;
595 std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
596 std::string tmp;
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000597 raw_fd_ostream os(graphFileName.c_str(), tmp, sys::fs::F_Text);
Lang Hames95e021f2012-03-26 23:07:23 +0000598 DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
599 << graphFileName << "\"\n");
600 problem->getGraph().dump(os);
601 }
602#endif
603
Lang Hames4108e7e2010-10-04 12:13:07 +0000604 PBQP::Solution solution =
Lang Hames18635822014-03-03 18:50:05 +0000605 PBQP::RegAlloc::solve(problem->getGraph());
Lang Hames305be0e2009-08-18 23:34:50 +0000606
Lang Hames4108e7e2010-10-04 12:13:07 +0000607 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000608
Lang Hames4108e7e2010-10-04 12:13:07 +0000609 ++round;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000610 }
Evan Chengb25f4632008-10-02 18:29:27 +0000611 }
612
Lang Hames49ab8bc2008-11-16 12:12:54 +0000613 // Finalise allocation, allocate empty ranges.
614 finalizeAlloc();
Lang Hamescb1e1012010-09-18 09:07:10 +0000615 vregsToAlloc.clear();
616 emptyIntervalVRegs.clear();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000617
David Greene7e256f32010-01-05 01:25:43 +0000618 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000619
Misha Brukmanda467482009-01-08 15:50:22 +0000620 return true;
Evan Chengb25f4632008-10-02 18:29:27 +0000621}
622
Ahmed Charles56440fd2014-03-06 05:51:42 +0000623FunctionPass *
624llvm::createPBQPRegisterAllocator(std::unique_ptr<PBQPBuilder> &builder,
625 char *customPassID) {
Benjamin Kramerdae08512013-04-12 12:13:51 +0000626 return new RegAllocPBQP(builder, customPassID);
Evan Chengb25f4632008-10-02 18:29:27 +0000627}
628
Lang Hamesfd1bc422010-09-23 04:28:54 +0000629FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000630 std::unique_ptr<PBQPBuilder> Builder;
Andy Gibbsb23ea722013-04-15 12:06:32 +0000631 if (pbqpCoalescing)
632 Builder.reset(new PBQPBuilderWithCoalescing());
633 else
634 Builder.reset(new PBQPBuilder());
635 return createPBQPRegisterAllocator(Builder);
Lang Hamescb1e1012010-09-18 09:07:10 +0000636}
Evan Chengb25f4632008-10-02 18:29:27 +0000637
638#undef DEBUG_TYPE