blob: 8a3b53fd08e524abec489a498392a779995e3784 [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"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000049#include "llvm/Support/FileSystem.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000050#include "llvm/Support/raw_ostream.h"
Misha Brukmanda467482009-01-08 15:50:22 +000051#include "llvm/Target/TargetInstrInfo.h"
52#include "llvm/Target/TargetMachine.h"
53#include <limits>
Misha Brukmanda467482009-01-08 15:50:22 +000054#include <memory>
Evan Chengb25f4632008-10-02 18:29:27 +000055#include <set>
Lang Hames95e021f2012-03-26 23:07:23 +000056#include <sstream>
Evan Chengb25f4632008-10-02 18:29:27 +000057#include <vector>
Evan Chengb25f4632008-10-02 18:29:27 +000058
Lang Hamesfd1bc422010-09-23 04:28:54 +000059using namespace llvm;
Lang Hamescb1e1012010-09-18 09:07:10 +000060
Chandler Carruth1b9dde02014-04-22 02:02:50 +000061#define DEBUG_TYPE "regalloc"
62
Evan Chengb25f4632008-10-02 18:29:27 +000063static RegisterRegAlloc
Duncan Sands1804b4f2010-02-18 14:10:41 +000064registerPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesfd1bc422010-09-23 04:28:54 +000065 createDefaultPBQPRegisterAllocator);
Evan Chengb25f4632008-10-02 18:29:27 +000066
Lang Hames11732ad2009-08-19 01:36:14 +000067static cl::opt<bool>
68pbqpCoalescing("pbqp-coalescing",
Lang Hames090c7e82010-01-26 04:49:58 +000069 cl::desc("Attempt coalescing during PBQP register allocation."),
70 cl::init(false), cl::Hidden);
Lang Hames11732ad2009-08-19 01:36:14 +000071
Lang Hames95e021f2012-03-26 23:07:23 +000072#ifndef NDEBUG
73static cl::opt<bool>
74pbqpDumpGraphs("pbqp-dump-graphs",
75 cl::desc("Dump graphs for each function/round in the compilation unit."),
76 cl::init(false), cl::Hidden);
77#endif
78
Lang Hamesfd1bc422010-09-23 04:28:54 +000079namespace {
80
81///
82/// PBQP based allocators solve the register allocation problem by mapping
83/// register allocation problems to Partitioned Boolean Quadratic
84/// Programming problems.
85class RegAllocPBQP : public MachineFunctionPass {
86public:
87
88 static char ID;
89
90 /// Construct a PBQP register allocator.
David Blaikieba80ee32014-07-19 21:19:45 +000091 RegAllocPBQP(std::unique_ptr<PBQPBuilder> b, char *cPassID = nullptr)
92 : MachineFunctionPass(ID), builder(std::move(b)), customPassID(cPassID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +000093 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
94 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000095 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000096 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000097 }
Lang Hamesfd1bc422010-09-23 04:28:54 +000098
99 /// Return the pass name.
Craig Topper4584cd52014-03-07 09:26:03 +0000100 const char* getPassName() const override {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000101 return "PBQP Register Allocator";
102 }
103
104 /// PBQP analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000105 void getAnalysisUsage(AnalysisUsage &au) const override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000106
107 /// Perform register allocation
Craig Topper4584cd52014-03-07 09:26:03 +0000108 bool runOnMachineFunction(MachineFunction &MF) override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000109
110private:
111
112 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
113 typedef std::vector<const LiveInterval*> Node2LIMap;
114 typedef std::vector<unsigned> AllowedSet;
115 typedef std::vector<AllowedSet> AllowedSetMap;
116 typedef std::pair<unsigned, unsigned> RegPair;
117 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000118 typedef std::set<unsigned> RegSet;
119
Ahmed Charles56440fd2014-03-06 05:51:42 +0000120 std::unique_ptr<PBQPBuilder> builder;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000121
Lang Hames934625e2011-06-17 07:09:01 +0000122 char *customPassID;
123
Lang Hamesfd1bc422010-09-23 04:28:54 +0000124 MachineFunction *mf;
125 const TargetMachine *tm;
126 const TargetRegisterInfo *tri;
127 const TargetInstrInfo *tii;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000128 MachineRegisterInfo *mri;
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000129 const MachineBlockFrequencyInfo *mbfi;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000130
Ahmed Charles56440fd2014-03-06 05:51:42 +0000131 std::unique_ptr<Spiller> spiller;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000132 LiveIntervals *lis;
133 LiveStacks *lss;
134 VirtRegMap *vrm;
135
Lang Hamesfd1bc422010-09-23 04:28:54 +0000136 RegSet vregsToAlloc, emptyIntervalVRegs;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000137
138 /// \brief Finds the initial set of vreg intervals to allocate.
139 void findVRegIntervalsToAlloc();
140
Lang Hamesfd1bc422010-09-23 04:28:54 +0000141 /// \brief Given a solved PBQP problem maps this solution back to a register
142 /// assignment.
Lang Hamesfd1bc422010-09-23 04:28:54 +0000143 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
144 const PBQP::Solution &solution);
145
146 /// \brief Postprocessing before final spilling. Sets basic block "live in"
147 /// variables.
148 void finalizeAlloc() const;
149
150};
151
Lang Hamescb1e1012010-09-18 09:07:10 +0000152char RegAllocPBQP::ID = 0;
Evan Chengb25f4632008-10-02 18:29:27 +0000153
Lang Hamesfd1bc422010-09-23 04:28:54 +0000154} // End anonymous namespace.
155
Lang Hames18635822014-03-03 18:50:05 +0000156unsigned PBQPRAProblem::getVRegForNode(PBQPRAGraph::NodeId node) const {
Lang Hamescb1e1012010-09-18 09:07:10 +0000157 Node2VReg::const_iterator vregItr = node2VReg.find(node);
158 assert(vregItr != node2VReg.end() && "No vreg for node.");
159 return vregItr->second;
160}
Evan Chengb25f4632008-10-02 18:29:27 +0000161
Lang Hames18635822014-03-03 18:50:05 +0000162PBQPRAGraph::NodeId PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
Lang Hamescb1e1012010-09-18 09:07:10 +0000163 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
164 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
165 return nodeItr->second;
Andrew Trick9363b592012-02-10 04:10:26 +0000166
Lang Hamescb1e1012010-09-18 09:07:10 +0000167}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000168
Lang Hamescb1e1012010-09-18 09:07:10 +0000169const PBQPRAProblem::AllowedSet&
170 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
171 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
172 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
173 const AllowedSet &allowedSet = allowedSetItr->second;
174 return allowedSet;
175}
Evan Chengb25f4632008-10-02 18:29:27 +0000176
Lang Hamescb1e1012010-09-18 09:07:10 +0000177unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
178 assert(isPRegOption(vreg, option) && "Not a preg option.");
179
180 const AllowedSet& allowedSet = getAllowedSet(vreg);
181 assert(option <= allowedSet.size() && "Option outside allowed set.");
182 return allowedSet[option - 1];
183}
184
Andy Gibbsb23ea722013-04-15 12:06:32 +0000185PBQPRAProblem *PBQPBuilder::build(MachineFunction *mf, const LiveIntervals *lis,
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000186 const MachineBlockFrequencyInfo *mbfi,
Andy Gibbsb23ea722013-04-15 12:06:32 +0000187 const RegSet &vregs) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000188
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000189 LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
Lang Hamescb1e1012010-09-18 09:07:10 +0000190 MachineRegisterInfo *mri = &mf->getRegInfo();
Andrew Trick9363b592012-02-10 04:10:26 +0000191 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
Lang Hamescb1e1012010-09-18 09:07:10 +0000192
Ahmed Charles56440fd2014-03-06 05:51:42 +0000193 std::unique_ptr<PBQPRAProblem> p(new PBQPRAProblem());
Lang Hames18635822014-03-03 18:50:05 +0000194 PBQPRAGraph &g = p->getGraph();
Lang Hamescb1e1012010-09-18 09:07:10 +0000195 RegSet pregs;
196
197 // Collect the set of preg intervals, record that they're used in the MF.
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000198 for (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000199 if (mri->def_empty(Reg))
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000200 continue;
201 pregs.insert(Reg);
202 mri->setPhysRegUsed(Reg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000203 }
Evan Chengb25f4632008-10-02 18:29:27 +0000204
Andrew Trick9363b592012-02-10 04:10:26 +0000205 // Iterate over vregs.
Lang Hamescb1e1012010-09-18 09:07:10 +0000206 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
207 vregItr != vregEnd; ++vregItr) {
208 unsigned vreg = *vregItr;
209 const TargetRegisterClass *trc = mri->getRegClass(vreg);
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000210 LiveInterval *vregLI = &LIS->getInterval(vreg);
211
212 // Record any overlaps with regmask operands.
Lang Hames05fee082012-10-10 06:39:48 +0000213 BitVector regMaskOverlaps;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000214 LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
Evan Chengb25f4632008-10-02 18:29:27 +0000215
Lang Hamescb1e1012010-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 Topper840beec2014-04-04 05:16:06 +0000219 ArrayRef<MCPhysReg> rawOrder = trc->getRawAllocationOrder(*mf);
Jakob Stoklund Olesen08322b72011-06-16 20:37:45 +0000220 for (unsigned i = 0; i != rawOrder.size(); ++i) {
221 unsigned preg = rawOrder[i];
Jakob Stoklund Olesenc30a9af2012-10-15 21:57:41 +0000222 if (mri->isReserved(preg))
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000223 continue;
224
225 // vregLI crosses a regmask operand that clobbers preg.
Lang Hames05fee082012-10-10 06:39:48 +0000226 if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000227 continue;
228
229 // vregLI overlaps fixed regunit interference.
Jakob Stoklund Olesenb1b3e4a2012-06-22 16:46:44 +0000230 bool Interference = false;
231 for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
232 if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
233 Interference = true;
234 break;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000235 }
Lang Hames211e7ce2010-07-17 06:31:41 +0000236 }
Jakob Stoklund Olesenb1b3e4a2012-06-22 16:46:44 +0000237 if (Interference)
238 continue;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000239
240 // preg is usable for this virtual register.
241 vrAllowed.push_back(preg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000242 }
Lang Hames211e7ce2010-07-17 06:31:41 +0000243
Lang Hames18635822014-03-03 18:50:05 +0000244 PBQP::Vector nodeCosts(vrAllowed.size() + 1, 0);
Evan Chengb25f4632008-10-02 18:29:27 +0000245
Lang Hamescb1e1012010-09-18 09:07:10 +0000246 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
247 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb25f4632008-10-02 18:29:27 +0000248
Lang Hames18635822014-03-03 18:50:05 +0000249 addSpillCosts(nodeCosts, spillCost);
250
251 // Construct the node.
252 PBQPRAGraph::NodeId nId = g.addNode(std::move(nodeCosts));
253
254 // Record the mapping and allowed set in the problem.
255 p->recordVReg(vreg, nId, vrAllowed.begin(), vrAllowed.end());
256
Lang Hamescb1e1012010-09-18 09:07:10 +0000257 }
Evan Chengb25f4632008-10-02 18:29:27 +0000258
Lang Hames361de982010-09-18 09:49:08 +0000259 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hamescb1e1012010-09-18 09:07:10 +0000260 vr1Itr != vrEnd; ++vr1Itr) {
261 unsigned vr1 = *vr1Itr;
262 const LiveInterval &l1 = lis->getInterval(vr1);
263 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb25f4632008-10-02 18:29:27 +0000264
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000265 for (RegSet::const_iterator vr2Itr = std::next(vr1Itr); vr2Itr != vrEnd;
266 ++vr2Itr) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000267 unsigned vr2 = *vr2Itr;
268 const LiveInterval &l2 = lis->getInterval(vr2);
269 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb25f4632008-10-02 18:29:27 +0000270
Lang Hamescb1e1012010-09-18 09:07:10 +0000271 assert(!l2.empty() && "Empty interval in vreg set?");
272 if (l1.overlaps(l2)) {
Lang Hames18635822014-03-03 18:50:05 +0000273 PBQP::Matrix edgeCosts(vr1Allowed.size()+1, vr2Allowed.size()+1, 0);
274 addInterferenceCosts(edgeCosts, vr1Allowed, vr2Allowed, tri);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000275
Lang Hames18635822014-03-03 18:50:05 +0000276 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
277 std::move(edgeCosts));
Lang Hamescb1e1012010-09-18 09:07:10 +0000278 }
279 }
280 }
Evan Chengb25f4632008-10-02 18:29:27 +0000281
Ahmed Charles96c9d952014-03-05 10:19:29 +0000282 return p.release();
Lang Hamescb1e1012010-09-18 09:07:10 +0000283}
Lang Hames49ab8bc2008-11-16 12:12:54 +0000284
Lang Hamescb1e1012010-09-18 09:07:10 +0000285void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
286 PBQP::PBQPNum spillCost) {
287 costVec[0] = spillCost;
288}
Evan Chengb25f4632008-10-02 18:29:27 +0000289
Lang Hames0937fc42010-09-21 13:19:36 +0000290void PBQPBuilder::addInterferenceCosts(
291 PBQP::Matrix &costMat,
292 const PBQPRAProblem::AllowedSet &vr1Allowed,
293 const PBQPRAProblem::AllowedSet &vr2Allowed,
294 const TargetRegisterInfo *tri) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000295 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
296 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
297
Lang Hamesc702ba62010-11-12 05:47:21 +0000298 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000299 unsigned preg1 = vr1Allowed[i];
300
Lang Hamesc702ba62010-11-12 05:47:21 +0000301 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000302 unsigned preg2 = vr2Allowed[j];
303
304 if (tri->regsOverlap(preg1, preg2)) {
305 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
306 }
307 }
308 }
Evan Chengb25f4632008-10-02 18:29:27 +0000309}
310
Andy Gibbsb23ea722013-04-15 12:06:32 +0000311PBQPRAProblem *PBQPBuilderWithCoalescing::build(MachineFunction *mf,
Lang Hames0937fc42010-09-21 13:19:36 +0000312 const LiveIntervals *lis,
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000313 const MachineBlockFrequencyInfo *mbfi,
Lang Hames0937fc42010-09-21 13:19:36 +0000314 const RegSet &vregs) {
315
Ahmed Charles56440fd2014-03-06 05:51:42 +0000316 std::unique_ptr<PBQPRAProblem> p(PBQPBuilder::build(mf, lis, mbfi, vregs));
Lang Hames18635822014-03-03 18:50:05 +0000317 PBQPRAGraph &g = p->getGraph();
Lang Hames0937fc42010-09-21 13:19:36 +0000318
319 const TargetMachine &tm = mf->getTarget();
Benjamin Kramer628a39f2012-06-06 18:25:08 +0000320 CoalescerPair cp(*tm.getRegisterInfo());
Lang Hames0937fc42010-09-21 13:19:36 +0000321
322 // Scan the machine function and add a coalescing cost whenever CoalescerPair
323 // gives the Ok.
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000324 for (const auto &mbb : *mf) {
325 for (const auto &mi : mbb) {
326 if (!cp.setRegisters(&mi)) {
Lang Hames0937fc42010-09-21 13:19:36 +0000327 continue; // Not coalescable.
Lang Hamesc702ba62010-11-12 05:47:21 +0000328 }
Lang Hames0937fc42010-09-21 13:19:36 +0000329
Lang Hamesc702ba62010-11-12 05:47:21 +0000330 if (cp.getSrcReg() == cp.getDstReg()) {
Lang Hames0937fc42010-09-21 13:19:36 +0000331 continue; // Already coalesced.
Lang Hamesc702ba62010-11-12 05:47:21 +0000332 }
Lang Hames0937fc42010-09-21 13:19:36 +0000333
Lang Hamesfd1bc422010-09-23 04:28:54 +0000334 unsigned dst = cp.getDstReg(),
335 src = cp.getSrcReg();
Lang Hames0937fc42010-09-21 13:19:36 +0000336
Lang Hamesfd1bc422010-09-23 04:28:54 +0000337 const float copyFactor = 0.5; // Cost of copy relative to load. Current
338 // value plucked randomly out of the air.
Andrew Trick9363b592012-02-10 04:10:26 +0000339
Lang Hamesfd1bc422010-09-23 04:28:54 +0000340 PBQP::PBQPNum cBenefit =
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000341 copyFactor * LiveIntervals::getSpillWeight(false, true, mbfi, &mi);
Lang Hames0937fc42010-09-21 13:19:36 +0000342
Lang Hamesfd1bc422010-09-23 04:28:54 +0000343 if (cp.isPhys()) {
Jakob Stoklund Olesencea596a2012-10-15 22:14:34 +0000344 if (!mf->getRegInfo().isAllocatable(dst)) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000345 continue;
Lang Hamesc702ba62010-11-12 05:47:21 +0000346 }
Lang Hames0937fc42010-09-21 13:19:36 +0000347
Lang Hamesfd1bc422010-09-23 04:28:54 +0000348 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
Andrew Trick9363b592012-02-10 04:10:26 +0000349 unsigned pregOpt = 0;
Lang Hamesc702ba62010-11-12 05:47:21 +0000350 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000351 ++pregOpt;
Lang Hamesc702ba62010-11-12 05:47:21 +0000352 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000353 if (pregOpt < allowed.size()) {
354 ++pregOpt; // +1 to account for spill option.
Lang Hames18635822014-03-03 18:50:05 +0000355 PBQPRAGraph::NodeId node = p->getNodeForVReg(src);
356 llvm::dbgs() << "Reading node costs for node " << node << "\n";
357 llvm::dbgs() << "Source node: " << &g.getNodeCosts(node) << "\n";
358 PBQP::Vector newCosts(g.getNodeCosts(node));
359 addPhysRegCoalesce(newCosts, pregOpt, cBenefit);
360 g.setNodeCosts(node, newCosts);
Lang Hames0937fc42010-09-21 13:19:36 +0000361 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000362 } else {
363 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
364 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
Lang Hames18635822014-03-03 18:50:05 +0000365 PBQPRAGraph::NodeId node1 = p->getNodeForVReg(dst);
366 PBQPRAGraph::NodeId node2 = p->getNodeForVReg(src);
367 PBQPRAGraph::EdgeId edge = g.findEdge(node1, node2);
Lang Hamesfb826302013-11-09 03:08:56 +0000368 if (edge == g.invalidEdgeId()) {
Lang Hames18635822014-03-03 18:50:05 +0000369 PBQP::Matrix costs(allowed1->size() + 1, allowed2->size() + 1, 0);
370 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
371 g.addEdge(node1, node2, costs);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000372 } else {
Lang Hames18635822014-03-03 18:50:05 +0000373 if (g.getEdgeNode1Id(edge) == node2) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000374 std::swap(node1, node2);
375 std::swap(allowed1, allowed2);
376 }
Lang Hames18635822014-03-03 18:50:05 +0000377 PBQP::Matrix costs(g.getEdgeCosts(edge));
378 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
379 g.setEdgeCosts(edge, costs);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000380 }
Lang Hames0937fc42010-09-21 13:19:36 +0000381 }
382 }
383 }
384
Ahmed Charles96c9d952014-03-05 10:19:29 +0000385 return p.release();
Lang Hames0937fc42010-09-21 13:19:36 +0000386}
387
Lang Hames0937fc42010-09-21 13:19:36 +0000388void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
389 unsigned pregOption,
390 PBQP::PBQPNum benefit) {
391 costVec[pregOption] += -benefit;
392}
393
394void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
395 PBQP::Matrix &costMat,
396 const PBQPRAProblem::AllowedSet &vr1Allowed,
397 const PBQPRAProblem::AllowedSet &vr2Allowed,
398 PBQP::PBQPNum benefit) {
399
400 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
401 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
402
Lang Hamesc702ba62010-11-12 05:47:21 +0000403 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hames0937fc42010-09-21 13:19:36 +0000404 unsigned preg1 = vr1Allowed[i];
Lang Hamesc702ba62010-11-12 05:47:21 +0000405 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hames0937fc42010-09-21 13:19:36 +0000406 unsigned preg2 = vr2Allowed[j];
407
408 if (preg1 == preg2) {
409 costMat[i + 1][j + 1] += -benefit;
Andrew Trick9363b592012-02-10 04:10:26 +0000410 }
Lang Hames0937fc42010-09-21 13:19:36 +0000411 }
412 }
413}
Evan Chengb25f4632008-10-02 18:29:27 +0000414
Lang Hamescb1e1012010-09-18 09:07:10 +0000415
416void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hamesb13b6a02011-12-06 01:45:57 +0000417 au.setPreservesCFG();
418 au.addRequired<AliasAnalysis>();
419 au.addPreserved<AliasAnalysis>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000420 au.addRequired<SlotIndexes>();
421 au.addPreserved<SlotIndexes>();
422 au.addRequired<LiveIntervals>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000423 au.addPreserved<LiveIntervals>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000424 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames934625e2011-06-17 07:09:01 +0000425 if (customPassID)
426 au.addRequiredID(*customPassID);
Lang Hamescb1e1012010-09-18 09:07:10 +0000427 au.addRequired<LiveStacks>();
428 au.addPreserved<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000429 au.addRequired<MachineBlockFrequencyInfo>();
430 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames7d99d792013-07-01 20:47:47 +0000431 au.addRequired<MachineLoopInfo>();
432 au.addPreserved<MachineLoopInfo>();
Lang Hamesb13b6a02011-12-06 01:45:57 +0000433 au.addRequired<MachineDominatorTree>();
434 au.addPreserved<MachineDominatorTree>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000435 au.addRequired<VirtRegMap>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000436 au.addPreserved<VirtRegMap>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000437 MachineFunctionPass::getAnalysisUsage(au);
438}
439
Lang Hamescb1e1012010-09-18 09:07:10 +0000440void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000441
442 // Iterate over all live ranges.
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000443 for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
444 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
445 if (mri->reg_nodbg_empty(Reg))
Lang Hames49ab8bc2008-11-16 12:12:54 +0000446 continue;
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000447 LiveInterval *li = &lis->getInterval(Reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000448
449 // If this live interval is non-empty we will use pbqp to allocate it.
450 // Empty intervals we allocate in a simple post-processing stage in
451 // finalizeAlloc.
452 if (!li->empty()) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000453 vregsToAlloc.insert(li->reg);
Lang Hamesc702ba62010-11-12 05:47:21 +0000454 } else {
Lang Hamescb1e1012010-09-18 09:07:10 +0000455 emptyIntervalVRegs.insert(li->reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000456 }
457 }
Evan Chengb25f4632008-10-02 18:29:27 +0000458}
459
Lang Hamesfd1bc422010-09-23 04:28:54 +0000460bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
461 const PBQP::Solution &solution) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000462 // Set to true if we have any spills
463 bool anotherRoundNeeded = false;
464
465 // Clear the existing allocation.
466 vrm->clearAllVirt();
467
Lang Hames18635822014-03-03 18:50:05 +0000468 const PBQPRAGraph &g = problem.getGraph();
Lang Hamescb1e1012010-09-18 09:07:10 +0000469 // Iterate over the nodes mapping the PBQP solution to a register
470 // assignment.
Lang Hames18635822014-03-03 18:50:05 +0000471 for (auto NId : g.nodeIds()) {
472 unsigned vreg = problem.getVRegForNode(NId);
473 unsigned alloc = solution.getSelection(NId);
Lang Hamescb1e1012010-09-18 09:07:10 +0000474
475 if (problem.isPRegOption(vreg, alloc)) {
Andrew Trick9363b592012-02-10 04:10:26 +0000476 unsigned preg = problem.getPRegForOption(vreg, alloc);
Patrik Hägglund94537c22012-05-23 12:12:58 +0000477 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
478 << tri->getName(preg) << "\n");
Lang Hamescb1e1012010-09-18 09:07:10 +0000479 assert(preg != 0 && "Invalid preg selected.");
Andrew Trick9363b592012-02-10 04:10:26 +0000480 vrm->assignVirt2Phys(vreg, preg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000481 } else if (problem.isSpillOption(vreg, alloc)) {
482 vregsToAlloc.erase(vreg);
Mark Laceyf9ea8852013-08-14 23:50:04 +0000483 SmallVector<unsigned, 8> newSpills;
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +0000484 LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000485 spiller->spill(LRE);
Lang Hamescb1e1012010-09-18 09:07:10 +0000486
Patrik Hägglund94537c22012-05-23 12:12:58 +0000487 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000488 << LRE.getParent().weight << ", New vregs: ");
Lang Hamescb1e1012010-09-18 09:07:10 +0000489
490 // Copy any newly inserted live intervals into the list of regs to
491 // allocate.
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000492 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
Lang Hamescb1e1012010-09-18 09:07:10 +0000493 itr != end; ++itr) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000494 LiveInterval &li = lis->getInterval(*itr);
495 assert(!li.empty() && "Empty spill range.");
496 DEBUG(dbgs() << PrintReg(li.reg, tri) << " ");
497 vregsToAlloc.insert(li.reg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000498 }
499
500 DEBUG(dbgs() << ")\n");
501
502 // We need another round if spill intervals were added.
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000503 anotherRoundNeeded |= !LRE.empty();
Lang Hamescb1e1012010-09-18 09:07:10 +0000504 } else {
Craig Topperee4dab52012-02-05 08:31:47 +0000505 llvm_unreachable("Unknown allocation option.");
Lang Hamescb1e1012010-09-18 09:07:10 +0000506 }
507 }
508
509 return !anotherRoundNeeded;
510}
511
512
513void RegAllocPBQP::finalizeAlloc() const {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000514 // First allocate registers for the empty intervals.
Lang Hamescb1e1012010-09-18 09:07:10 +0000515 for (RegSet::const_iterator
516 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000517 itr != end; ++itr) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000518 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000519
Jakob Stoklund Olesen1dd82dd2012-12-04 00:30:22 +0000520 unsigned physReg = mri->getSimpleHint(li->reg);
Lang Hames88fae6f2009-08-06 23:32:48 +0000521
Lang Hames49ab8bc2008-11-16 12:12:54 +0000522 if (physReg == 0) {
523 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Jakob Stoklund Olesen08322b72011-06-16 20:37:45 +0000524 physReg = liRC->getRawAllocationOrder(*mf).front();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000525 }
Misha Brukmanda467482009-01-08 15:50:22 +0000526
527 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000528 }
Lang Hames49ab8bc2008-11-16 12:12:54 +0000529}
530
Lang Hamescb1e1012010-09-18 09:07:10 +0000531bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000532
Evan Chengb25f4632008-10-02 18:29:27 +0000533 mf = &MF;
534 tm = &mf->getTarget();
535 tri = tm->getRegisterInfo();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000536 tii = tm->getInstrInfo();
Andrew Trick9363b592012-02-10 04:10:26 +0000537 mri = &mf->getRegInfo();
Evan Chengb25f4632008-10-02 18:29:27 +0000538
Lang Hames49ab8bc2008-11-16 12:12:54 +0000539 lis = &getAnalysis<LiveIntervals>();
540 lss = &getAnalysis<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000541 mbfi = &getAnalysis<MachineBlockFrequencyInfo>();
Evan Chengb25f4632008-10-02 18:29:27 +0000542
Arnaud A. de Grandmaisonea3ac162013-11-11 19:04:45 +0000543 calculateSpillWeightsAndHints(*lis, MF, getAnalysis<MachineLoopInfo>(),
544 *mbfi);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +0000545
Owen Andersond37ddf52009-03-13 05:55:11 +0000546 vrm = &getAnalysis<VirtRegMap>();
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000547 spiller.reset(createInlineSpiller(*this, MF, *vrm));
Evan Chengb25f4632008-10-02 18:29:27 +0000548
Chad Rosiered119d52012-11-28 00:21:29 +0000549 mri->freezeReservedRegs(MF);
550
Craig Toppera538d832012-08-22 06:07:19 +0000551 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000552
Evan Chengb25f4632008-10-02 18:29:27 +0000553 // Allocator main loop:
Misha Brukmanda467482009-01-08 15:50:22 +0000554 //
Evan Chengb25f4632008-10-02 18:29:27 +0000555 // * Map current regalloc problem to a PBQP problem
556 // * Solve the PBQP problem
557 // * Map the solution back to a register allocation
558 // * Spill if necessary
Misha Brukmanda467482009-01-08 15:50:22 +0000559 //
Evan Chengb25f4632008-10-02 18:29:27 +0000560 // This process is continued till no more spills are generated.
561
Lang Hames49ab8bc2008-11-16 12:12:54 +0000562 // Find the vreg intervals in need of allocation.
563 findVRegIntervalsToAlloc();
Misha Brukmanda467482009-01-08 15:50:22 +0000564
Craig Toppera538d832012-08-22 06:07:19 +0000565#ifndef NDEBUG
Lang Hames95e021f2012-03-26 23:07:23 +0000566 const Function* func = mf->getFunction();
567 std::string fqn =
568 func->getParent()->getModuleIdentifier() + "." +
569 func->getName().str();
Craig Toppera538d832012-08-22 06:07:19 +0000570#endif
Lang Hames95e021f2012-03-26 23:07:23 +0000571
Lang Hames49ab8bc2008-11-16 12:12:54 +0000572 // If there are non-empty intervals allocate them using pbqp.
Lang Hamescb1e1012010-09-18 09:07:10 +0000573 if (!vregsToAlloc.empty()) {
Evan Chengb25f4632008-10-02 18:29:27 +0000574
Lang Hames49ab8bc2008-11-16 12:12:54 +0000575 bool pbqpAllocComplete = false;
576 unsigned round = 0;
577
Lang Hames4108e7e2010-10-04 12:13:07 +0000578 while (!pbqpAllocComplete) {
579 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000580
Ahmed Charles56440fd2014-03-06 05:51:42 +0000581 std::unique_ptr<PBQPRAProblem> problem(
582 builder->build(mf, lis, mbfi, vregsToAlloc));
Lang Hames95e021f2012-03-26 23:07:23 +0000583
584#ifndef NDEBUG
585 if (pbqpDumpGraphs) {
586 std::ostringstream rs;
587 rs << round;
588 std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
589 std::string tmp;
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000590 raw_fd_ostream os(graphFileName.c_str(), tmp, sys::fs::F_Text);
Lang Hames95e021f2012-03-26 23:07:23 +0000591 DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
592 << graphFileName << "\"\n");
593 problem->getGraph().dump(os);
594 }
595#endif
596
Lang Hames4108e7e2010-10-04 12:13:07 +0000597 PBQP::Solution solution =
Lang Hames18635822014-03-03 18:50:05 +0000598 PBQP::RegAlloc::solve(problem->getGraph());
Lang Hames305be0e2009-08-18 23:34:50 +0000599
Lang Hames4108e7e2010-10-04 12:13:07 +0000600 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000601
Lang Hames4108e7e2010-10-04 12:13:07 +0000602 ++round;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000603 }
Evan Chengb25f4632008-10-02 18:29:27 +0000604 }
605
Lang Hames49ab8bc2008-11-16 12:12:54 +0000606 // Finalise allocation, allocate empty ranges.
607 finalizeAlloc();
Lang Hamescb1e1012010-09-18 09:07:10 +0000608 vregsToAlloc.clear();
609 emptyIntervalVRegs.clear();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000610
David Greene7e256f32010-01-05 01:25:43 +0000611 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000612
Misha Brukmanda467482009-01-08 15:50:22 +0000613 return true;
Evan Chengb25f4632008-10-02 18:29:27 +0000614}
615
Ahmed Charles56440fd2014-03-06 05:51:42 +0000616FunctionPass *
David Blaikieba80ee32014-07-19 21:19:45 +0000617llvm::createPBQPRegisterAllocator(std::unique_ptr<PBQPBuilder> builder,
Ahmed Charles56440fd2014-03-06 05:51:42 +0000618 char *customPassID) {
David Blaikieba80ee32014-07-19 21:19:45 +0000619 return new RegAllocPBQP(std::move(builder), customPassID);
Evan Chengb25f4632008-10-02 18:29:27 +0000620}
621
Lang Hamesfd1bc422010-09-23 04:28:54 +0000622FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000623 std::unique_ptr<PBQPBuilder> Builder;
Andy Gibbsb23ea722013-04-15 12:06:32 +0000624 if (pbqpCoalescing)
David Blaikieba80ee32014-07-19 21:19:45 +0000625 Builder = llvm::make_unique<PBQPBuilderWithCoalescing>();
Andy Gibbsb23ea722013-04-15 12:06:32 +0000626 else
David Blaikieba80ee32014-07-19 21:19:45 +0000627 Builder = llvm::make_unique<PBQPBuilder>();
628 return createPBQPRegisterAllocator(std::move(Builder));
Lang Hamescb1e1012010-09-18 09:07:10 +0000629}
Evan Chengb25f4632008-10-02 18:29:27 +0000630
631#undef DEBUG_TYPE