blob: 83dbcecab0f4b695683b008de9ffc4d1a2334c0c [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
Evan Chengb25f4632008-10-02 18:29:27 +000032#define DEBUG_TYPE "regalloc"
33
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/CodeGen/RegAllocPBQP.h"
Rafael Espindolafef3c642011-06-26 21:41:06 +000035#include "RegisterCoalescer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "Spiller.h"
Andy Gibbsb23ea722013-04-15 12:06:32 +000037#include "llvm/ADT/OwningPtr.h"
Lang Hamesb13b6a02011-12-06 01:45:57 +000038#include "llvm/Analysis/AliasAnalysis.h"
Lang Hamesd17e2962009-12-14 06:49:42 +000039#include "llvm/CodeGen/CalcSpillWeights.h"
Evan Chengb25f4632008-10-02 18:29:27 +000040#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000041#include "llvm/CodeGen/LiveRangeEdit.h"
Lang Hames49ab8bc2008-11-16 12:12:54 +000042#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000043#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Lang Hamesb13b6a02011-12-06 01:45:57 +000044#include "llvm/CodeGen/MachineDominators.h"
Misha Brukmanda467482009-01-08 15:50:22 +000045#include "llvm/CodeGen/MachineFunctionPass.h"
Lang Hames7d99d792013-07-01 20:47:47 +000046#include "llvm/CodeGen/MachineLoopInfo.h"
Misha Brukmanda467482009-01-08 15:50:22 +000047#include "llvm/CodeGen/MachineRegisterInfo.h"
48#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000049#include "llvm/CodeGen/VirtRegMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/Module.h"
Evan Chengb25f4632008-10-02 18:29:27 +000051#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000052#include "llvm/Support/raw_ostream.h"
Misha Brukmanda467482009-01-08 15:50:22 +000053#include "llvm/Target/TargetInstrInfo.h"
54#include "llvm/Target/TargetMachine.h"
55#include <limits>
Misha Brukmanda467482009-01-08 15:50:22 +000056#include <memory>
Evan Chengb25f4632008-10-02 18:29:27 +000057#include <set>
Lang Hames95e021f2012-03-26 23:07:23 +000058#include <sstream>
Evan Chengb25f4632008-10-02 18:29:27 +000059#include <vector>
Evan Chengb25f4632008-10-02 18:29:27 +000060
Lang Hamesfd1bc422010-09-23 04:28:54 +000061using namespace llvm;
Lang Hamescb1e1012010-09-18 09:07:10 +000062
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.
Andy Gibbsb23ea722013-04-15 12:06:32 +000091 RegAllocPBQP(OwningPtr<PBQPBuilder> &b, char *cPassID=0)
92 : MachineFunctionPass(ID), builder(b.take()), 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.
100 virtual const char* getPassName() const {
101 return "PBQP Register Allocator";
102 }
103
104 /// PBQP analysis usage.
105 virtual void getAnalysisUsage(AnalysisUsage &au) const;
106
107 /// Perform register allocation
108 virtual bool runOnMachineFunction(MachineFunction &MF);
109
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
120
Andy Gibbsb23ea722013-04-15 12:06:32 +0000121 OwningPtr<PBQPBuilder> builder;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000122
Lang Hames934625e2011-06-17 07:09:01 +0000123 char *customPassID;
124
Lang Hamesfd1bc422010-09-23 04:28:54 +0000125 MachineFunction *mf;
126 const TargetMachine *tm;
127 const TargetRegisterInfo *tri;
128 const TargetInstrInfo *tii;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000129 MachineRegisterInfo *mri;
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000130 const MachineBlockFrequencyInfo *mbfi;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000131
Andy Gibbsb23ea722013-04-15 12:06:32 +0000132 OwningPtr<Spiller> spiller;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000133 LiveIntervals *lis;
134 LiveStacks *lss;
135 VirtRegMap *vrm;
136
Lang Hamesfd1bc422010-09-23 04:28:54 +0000137 RegSet vregsToAlloc, emptyIntervalVRegs;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000138
139 /// \brief Finds the initial set of vreg intervals to allocate.
140 void findVRegIntervalsToAlloc();
141
Lang Hamesfd1bc422010-09-23 04:28:54 +0000142 /// \brief Given a solved PBQP problem maps this solution back to a register
143 /// assignment.
Lang Hamesfd1bc422010-09-23 04:28:54 +0000144 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
145 const PBQP::Solution &solution);
146
147 /// \brief Postprocessing before final spilling. Sets basic block "live in"
148 /// variables.
149 void finalizeAlloc() const;
150
151};
152
Lang Hamescb1e1012010-09-18 09:07:10 +0000153char RegAllocPBQP::ID = 0;
Evan Chengb25f4632008-10-02 18:29:27 +0000154
Lang Hamesfd1bc422010-09-23 04:28:54 +0000155} // End anonymous namespace.
156
Lang Hames18635822014-03-03 18:50:05 +0000157unsigned PBQPRAProblem::getVRegForNode(PBQPRAGraph::NodeId node) const {
Lang Hamescb1e1012010-09-18 09:07:10 +0000158 Node2VReg::const_iterator vregItr = node2VReg.find(node);
159 assert(vregItr != node2VReg.end() && "No vreg for node.");
160 return vregItr->second;
161}
Evan Chengb25f4632008-10-02 18:29:27 +0000162
Lang Hames18635822014-03-03 18:50:05 +0000163PBQPRAGraph::NodeId PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
Lang Hamescb1e1012010-09-18 09:07:10 +0000164 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
165 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
166 return nodeItr->second;
Andrew Trick9363b592012-02-10 04:10:26 +0000167
Lang Hamescb1e1012010-09-18 09:07:10 +0000168}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000169
Lang Hamescb1e1012010-09-18 09:07:10 +0000170const PBQPRAProblem::AllowedSet&
171 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
172 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
173 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
174 const AllowedSet &allowedSet = allowedSetItr->second;
175 return allowedSet;
176}
Evan Chengb25f4632008-10-02 18:29:27 +0000177
Lang Hamescb1e1012010-09-18 09:07:10 +0000178unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
179 assert(isPRegOption(vreg, option) && "Not a preg option.");
180
181 const AllowedSet& allowedSet = getAllowedSet(vreg);
182 assert(option <= allowedSet.size() && "Option outside allowed set.");
183 return allowedSet[option - 1];
184}
185
Andy Gibbsb23ea722013-04-15 12:06:32 +0000186PBQPRAProblem *PBQPBuilder::build(MachineFunction *mf, const LiveIntervals *lis,
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000187 const MachineBlockFrequencyInfo *mbfi,
Andy Gibbsb23ea722013-04-15 12:06:32 +0000188 const RegSet &vregs) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000189
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000190 LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
Lang Hamescb1e1012010-09-18 09:07:10 +0000191 MachineRegisterInfo *mri = &mf->getRegInfo();
Andrew Trick9363b592012-02-10 04:10:26 +0000192 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
Lang Hamescb1e1012010-09-18 09:07:10 +0000193
Andy Gibbsb23ea722013-04-15 12:06:32 +0000194 OwningPtr<PBQPRAProblem> p(new PBQPRAProblem());
Lang Hames18635822014-03-03 18:50:05 +0000195 PBQPRAGraph &g = p->getGraph();
Lang Hamescb1e1012010-09-18 09:07:10 +0000196 RegSet pregs;
197
198 // Collect the set of preg intervals, record that they're used in the MF.
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000199 for (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000200 if (mri->def_empty(Reg))
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000201 continue;
202 pregs.insert(Reg);
203 mri->setPhysRegUsed(Reg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000204 }
Evan Chengb25f4632008-10-02 18:29:27 +0000205
Andrew Trick9363b592012-02-10 04:10:26 +0000206 // Iterate over vregs.
Lang Hamescb1e1012010-09-18 09:07:10 +0000207 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
208 vregItr != vregEnd; ++vregItr) {
209 unsigned vreg = *vregItr;
210 const TargetRegisterClass *trc = mri->getRegClass(vreg);
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000211 LiveInterval *vregLI = &LIS->getInterval(vreg);
212
213 // Record any overlaps with regmask operands.
Lang Hames05fee082012-10-10 06:39:48 +0000214 BitVector regMaskOverlaps;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000215 LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
Evan Chengb25f4632008-10-02 18:29:27 +0000216
Lang Hamescb1e1012010-09-18 09:07:10 +0000217 // Compute an initial allowed set for the current vreg.
218 typedef std::vector<unsigned> VRAllowed;
219 VRAllowed vrAllowed;
Craig Topperb35eacb2012-03-04 10:16:38 +0000220 ArrayRef<uint16_t> rawOrder = trc->getRawAllocationOrder(*mf);
Jakob Stoklund Olesen08322b72011-06-16 20:37:45 +0000221 for (unsigned i = 0; i != rawOrder.size(); ++i) {
222 unsigned preg = rawOrder[i];
Jakob Stoklund Olesenc30a9af2012-10-15 21:57:41 +0000223 if (mri->isReserved(preg))
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000224 continue;
225
226 // vregLI crosses a regmask operand that clobbers preg.
Lang Hames05fee082012-10-10 06:39:48 +0000227 if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000228 continue;
229
230 // vregLI overlaps fixed regunit interference.
Jakob Stoklund Olesenb1b3e4a2012-06-22 16:46:44 +0000231 bool Interference = false;
232 for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
233 if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
234 Interference = true;
235 break;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000236 }
Lang Hames211e7ce2010-07-17 06:31:41 +0000237 }
Jakob Stoklund Olesenb1b3e4a2012-06-22 16:46:44 +0000238 if (Interference)
239 continue;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000240
241 // preg is usable for this virtual register.
242 vrAllowed.push_back(preg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000243 }
Lang Hames211e7ce2010-07-17 06:31:41 +0000244
Lang Hames18635822014-03-03 18:50:05 +0000245 PBQP::Vector nodeCosts(vrAllowed.size() + 1, 0);
Evan Chengb25f4632008-10-02 18:29:27 +0000246
Lang Hamescb1e1012010-09-18 09:07:10 +0000247 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
248 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb25f4632008-10-02 18:29:27 +0000249
Lang Hames18635822014-03-03 18:50:05 +0000250 addSpillCosts(nodeCosts, spillCost);
251
252 // Construct the node.
253 PBQPRAGraph::NodeId nId = g.addNode(std::move(nodeCosts));
254
255 // Record the mapping and allowed set in the problem.
256 p->recordVReg(vreg, nId, vrAllowed.begin(), vrAllowed.end());
257
Lang Hamescb1e1012010-09-18 09:07:10 +0000258 }
Evan Chengb25f4632008-10-02 18:29:27 +0000259
Lang Hames361de982010-09-18 09:49:08 +0000260 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hamescb1e1012010-09-18 09:07:10 +0000261 vr1Itr != vrEnd; ++vr1Itr) {
262 unsigned vr1 = *vr1Itr;
263 const LiveInterval &l1 = lis->getInterval(vr1);
264 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb25f4632008-10-02 18:29:27 +0000265
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000266 for (RegSet::const_iterator vr2Itr = std::next(vr1Itr); vr2Itr != vrEnd;
267 ++vr2Itr) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000268 unsigned vr2 = *vr2Itr;
269 const LiveInterval &l2 = lis->getInterval(vr2);
270 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb25f4632008-10-02 18:29:27 +0000271
Lang Hamescb1e1012010-09-18 09:07:10 +0000272 assert(!l2.empty() && "Empty interval in vreg set?");
273 if (l1.overlaps(l2)) {
Lang Hames18635822014-03-03 18:50:05 +0000274 PBQP::Matrix edgeCosts(vr1Allowed.size()+1, vr2Allowed.size()+1, 0);
275 addInterferenceCosts(edgeCosts, vr1Allowed, vr2Allowed, tri);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000276
Lang Hames18635822014-03-03 18:50:05 +0000277 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
278 std::move(edgeCosts));
Lang Hamescb1e1012010-09-18 09:07:10 +0000279 }
280 }
281 }
Evan Chengb25f4632008-10-02 18:29:27 +0000282
Andy Gibbsb23ea722013-04-15 12:06:32 +0000283 return p.take();
Lang Hamescb1e1012010-09-18 09:07:10 +0000284}
Lang Hames49ab8bc2008-11-16 12:12:54 +0000285
Lang Hamescb1e1012010-09-18 09:07:10 +0000286void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
287 PBQP::PBQPNum spillCost) {
288 costVec[0] = spillCost;
289}
Evan Chengb25f4632008-10-02 18:29:27 +0000290
Lang Hames0937fc42010-09-21 13:19:36 +0000291void PBQPBuilder::addInterferenceCosts(
292 PBQP::Matrix &costMat,
293 const PBQPRAProblem::AllowedSet &vr1Allowed,
294 const PBQPRAProblem::AllowedSet &vr2Allowed,
295 const TargetRegisterInfo *tri) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000296 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
297 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
298
Lang Hamesc702ba62010-11-12 05:47:21 +0000299 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000300 unsigned preg1 = vr1Allowed[i];
301
Lang Hamesc702ba62010-11-12 05:47:21 +0000302 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000303 unsigned preg2 = vr2Allowed[j];
304
305 if (tri->regsOverlap(preg1, preg2)) {
306 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
307 }
308 }
309 }
Evan Chengb25f4632008-10-02 18:29:27 +0000310}
311
Andy Gibbsb23ea722013-04-15 12:06:32 +0000312PBQPRAProblem *PBQPBuilderWithCoalescing::build(MachineFunction *mf,
Lang Hames0937fc42010-09-21 13:19:36 +0000313 const LiveIntervals *lis,
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000314 const MachineBlockFrequencyInfo *mbfi,
Lang Hames0937fc42010-09-21 13:19:36 +0000315 const RegSet &vregs) {
316
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000317 OwningPtr<PBQPRAProblem> p(PBQPBuilder::build(mf, lis, mbfi, vregs));
Lang Hames18635822014-03-03 18:50:05 +0000318 PBQPRAGraph &g = p->getGraph();
Lang Hames0937fc42010-09-21 13:19:36 +0000319
320 const TargetMachine &tm = mf->getTarget();
Benjamin Kramer628a39f2012-06-06 18:25:08 +0000321 CoalescerPair cp(*tm.getRegisterInfo());
Lang Hames0937fc42010-09-21 13:19:36 +0000322
323 // Scan the machine function and add a coalescing cost whenever CoalescerPair
324 // gives the Ok.
325 for (MachineFunction::const_iterator mbbItr = mf->begin(),
326 mbbEnd = mf->end();
327 mbbItr != mbbEnd; ++mbbItr) {
328 const MachineBasicBlock *mbb = &*mbbItr;
329
330 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
331 miEnd = mbb->end();
332 miItr != miEnd; ++miItr) {
333 const MachineInstr *mi = &*miItr;
334
Lang Hamesc702ba62010-11-12 05:47:21 +0000335 if (!cp.setRegisters(mi)) {
Lang Hames0937fc42010-09-21 13:19:36 +0000336 continue; // Not coalescable.
Lang Hamesc702ba62010-11-12 05:47:21 +0000337 }
Lang Hames0937fc42010-09-21 13:19:36 +0000338
Lang Hamesc702ba62010-11-12 05:47:21 +0000339 if (cp.getSrcReg() == cp.getDstReg()) {
Lang Hames0937fc42010-09-21 13:19:36 +0000340 continue; // Already coalesced.
Lang Hamesc702ba62010-11-12 05:47:21 +0000341 }
Lang Hames0937fc42010-09-21 13:19:36 +0000342
Lang Hamesfd1bc422010-09-23 04:28:54 +0000343 unsigned dst = cp.getDstReg(),
344 src = cp.getSrcReg();
Lang Hames0937fc42010-09-21 13:19:36 +0000345
Lang Hamesfd1bc422010-09-23 04:28:54 +0000346 const float copyFactor = 0.5; // Cost of copy relative to load. Current
347 // value plucked randomly out of the air.
Andrew Trick9363b592012-02-10 04:10:26 +0000348
Lang Hamesfd1bc422010-09-23 04:28:54 +0000349 PBQP::PBQPNum cBenefit =
Michael Gottesman9f49d742013-12-14 00:53:32 +0000350 copyFactor * LiveIntervals::getSpillWeight(false, true, mbfi, mi);
Lang Hames0937fc42010-09-21 13:19:36 +0000351
Lang Hamesfd1bc422010-09-23 04:28:54 +0000352 if (cp.isPhys()) {
Jakob Stoklund Olesencea596a2012-10-15 22:14:34 +0000353 if (!mf->getRegInfo().isAllocatable(dst)) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000354 continue;
Lang Hamesc702ba62010-11-12 05:47:21 +0000355 }
Lang Hames0937fc42010-09-21 13:19:36 +0000356
Lang Hamesfd1bc422010-09-23 04:28:54 +0000357 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
Andrew Trick9363b592012-02-10 04:10:26 +0000358 unsigned pregOpt = 0;
Lang Hamesc702ba62010-11-12 05:47:21 +0000359 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000360 ++pregOpt;
Lang Hamesc702ba62010-11-12 05:47:21 +0000361 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000362 if (pregOpt < allowed.size()) {
363 ++pregOpt; // +1 to account for spill option.
Lang Hames18635822014-03-03 18:50:05 +0000364 PBQPRAGraph::NodeId node = p->getNodeForVReg(src);
365 llvm::dbgs() << "Reading node costs for node " << node << "\n";
366 llvm::dbgs() << "Source node: " << &g.getNodeCosts(node) << "\n";
367 PBQP::Vector newCosts(g.getNodeCosts(node));
368 addPhysRegCoalesce(newCosts, pregOpt, cBenefit);
369 g.setNodeCosts(node, newCosts);
Lang Hames0937fc42010-09-21 13:19:36 +0000370 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000371 } else {
372 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
373 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
Lang Hames18635822014-03-03 18:50:05 +0000374 PBQPRAGraph::NodeId node1 = p->getNodeForVReg(dst);
375 PBQPRAGraph::NodeId node2 = p->getNodeForVReg(src);
376 PBQPRAGraph::EdgeId edge = g.findEdge(node1, node2);
Lang Hamesfb826302013-11-09 03:08:56 +0000377 if (edge == g.invalidEdgeId()) {
Lang Hames18635822014-03-03 18:50:05 +0000378 PBQP::Matrix costs(allowed1->size() + 1, allowed2->size() + 1, 0);
379 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
380 g.addEdge(node1, node2, costs);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000381 } else {
Lang Hames18635822014-03-03 18:50:05 +0000382 if (g.getEdgeNode1Id(edge) == node2) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000383 std::swap(node1, node2);
384 std::swap(allowed1, allowed2);
385 }
Lang Hames18635822014-03-03 18:50:05 +0000386 PBQP::Matrix costs(g.getEdgeCosts(edge));
387 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
388 g.setEdgeCosts(edge, costs);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000389 }
Lang Hames0937fc42010-09-21 13:19:36 +0000390 }
391 }
392 }
393
Andy Gibbsb23ea722013-04-15 12:06:32 +0000394 return p.take();
Lang Hames0937fc42010-09-21 13:19:36 +0000395}
396
Lang Hames0937fc42010-09-21 13:19:36 +0000397void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
398 unsigned pregOption,
399 PBQP::PBQPNum benefit) {
400 costVec[pregOption] += -benefit;
401}
402
403void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
404 PBQP::Matrix &costMat,
405 const PBQPRAProblem::AllowedSet &vr1Allowed,
406 const PBQPRAProblem::AllowedSet &vr2Allowed,
407 PBQP::PBQPNum benefit) {
408
409 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
410 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
411
Lang Hamesc702ba62010-11-12 05:47:21 +0000412 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hames0937fc42010-09-21 13:19:36 +0000413 unsigned preg1 = vr1Allowed[i];
Lang Hamesc702ba62010-11-12 05:47:21 +0000414 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hames0937fc42010-09-21 13:19:36 +0000415 unsigned preg2 = vr2Allowed[j];
416
417 if (preg1 == preg2) {
418 costMat[i + 1][j + 1] += -benefit;
Andrew Trick9363b592012-02-10 04:10:26 +0000419 }
Lang Hames0937fc42010-09-21 13:19:36 +0000420 }
421 }
422}
Evan Chengb25f4632008-10-02 18:29:27 +0000423
Lang Hamescb1e1012010-09-18 09:07:10 +0000424
425void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hamesb13b6a02011-12-06 01:45:57 +0000426 au.setPreservesCFG();
427 au.addRequired<AliasAnalysis>();
428 au.addPreserved<AliasAnalysis>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000429 au.addRequired<SlotIndexes>();
430 au.addPreserved<SlotIndexes>();
431 au.addRequired<LiveIntervals>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000432 au.addPreserved<LiveIntervals>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000433 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames934625e2011-06-17 07:09:01 +0000434 if (customPassID)
435 au.addRequiredID(*customPassID);
Lang Hamescb1e1012010-09-18 09:07:10 +0000436 au.addRequired<LiveStacks>();
437 au.addPreserved<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000438 au.addRequired<MachineBlockFrequencyInfo>();
439 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames7d99d792013-07-01 20:47:47 +0000440 au.addRequired<MachineLoopInfo>();
441 au.addPreserved<MachineLoopInfo>();
Lang Hamesb13b6a02011-12-06 01:45:57 +0000442 au.addRequired<MachineDominatorTree>();
443 au.addPreserved<MachineDominatorTree>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000444 au.addRequired<VirtRegMap>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000445 au.addPreserved<VirtRegMap>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000446 MachineFunctionPass::getAnalysisUsage(au);
447}
448
Lang Hamescb1e1012010-09-18 09:07:10 +0000449void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000450
451 // Iterate over all live ranges.
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000452 for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
453 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
454 if (mri->reg_nodbg_empty(Reg))
Lang Hames49ab8bc2008-11-16 12:12:54 +0000455 continue;
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000456 LiveInterval *li = &lis->getInterval(Reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000457
458 // If this live interval is non-empty we will use pbqp to allocate it.
459 // Empty intervals we allocate in a simple post-processing stage in
460 // finalizeAlloc.
461 if (!li->empty()) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000462 vregsToAlloc.insert(li->reg);
Lang Hamesc702ba62010-11-12 05:47:21 +0000463 } else {
Lang Hamescb1e1012010-09-18 09:07:10 +0000464 emptyIntervalVRegs.insert(li->reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000465 }
466 }
Evan Chengb25f4632008-10-02 18:29:27 +0000467}
468
Lang Hamesfd1bc422010-09-23 04:28:54 +0000469bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
470 const PBQP::Solution &solution) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000471 // Set to true if we have any spills
472 bool anotherRoundNeeded = false;
473
474 // Clear the existing allocation.
475 vrm->clearAllVirt();
476
Lang Hames18635822014-03-03 18:50:05 +0000477 const PBQPRAGraph &g = problem.getGraph();
Lang Hamescb1e1012010-09-18 09:07:10 +0000478 // Iterate over the nodes mapping the PBQP solution to a register
479 // assignment.
Lang Hames18635822014-03-03 18:50:05 +0000480 for (auto NId : g.nodeIds()) {
481 unsigned vreg = problem.getVRegForNode(NId);
482 unsigned alloc = solution.getSelection(NId);
Lang Hamescb1e1012010-09-18 09:07:10 +0000483
484 if (problem.isPRegOption(vreg, alloc)) {
Andrew Trick9363b592012-02-10 04:10:26 +0000485 unsigned preg = problem.getPRegForOption(vreg, alloc);
Patrik Hägglund94537c22012-05-23 12:12:58 +0000486 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
487 << tri->getName(preg) << "\n");
Lang Hamescb1e1012010-09-18 09:07:10 +0000488 assert(preg != 0 && "Invalid preg selected.");
Andrew Trick9363b592012-02-10 04:10:26 +0000489 vrm->assignVirt2Phys(vreg, preg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000490 } else if (problem.isSpillOption(vreg, alloc)) {
491 vregsToAlloc.erase(vreg);
Mark Laceyf9ea8852013-08-14 23:50:04 +0000492 SmallVector<unsigned, 8> newSpills;
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +0000493 LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000494 spiller->spill(LRE);
Lang Hamescb1e1012010-09-18 09:07:10 +0000495
Patrik Hägglund94537c22012-05-23 12:12:58 +0000496 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000497 << LRE.getParent().weight << ", New vregs: ");
Lang Hamescb1e1012010-09-18 09:07:10 +0000498
499 // Copy any newly inserted live intervals into the list of regs to
500 // allocate.
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000501 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
Lang Hamescb1e1012010-09-18 09:07:10 +0000502 itr != end; ++itr) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000503 LiveInterval &li = lis->getInterval(*itr);
504 assert(!li.empty() && "Empty spill range.");
505 DEBUG(dbgs() << PrintReg(li.reg, tri) << " ");
506 vregsToAlloc.insert(li.reg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000507 }
508
509 DEBUG(dbgs() << ")\n");
510
511 // We need another round if spill intervals were added.
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000512 anotherRoundNeeded |= !LRE.empty();
Lang Hamescb1e1012010-09-18 09:07:10 +0000513 } else {
Craig Topperee4dab52012-02-05 08:31:47 +0000514 llvm_unreachable("Unknown allocation option.");
Lang Hamescb1e1012010-09-18 09:07:10 +0000515 }
516 }
517
518 return !anotherRoundNeeded;
519}
520
521
522void RegAllocPBQP::finalizeAlloc() const {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000523 // First allocate registers for the empty intervals.
Lang Hamescb1e1012010-09-18 09:07:10 +0000524 for (RegSet::const_iterator
525 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000526 itr != end; ++itr) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000527 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000528
Jakob Stoklund Olesen1dd82dd2012-12-04 00:30:22 +0000529 unsigned physReg = mri->getSimpleHint(li->reg);
Lang Hames88fae6f2009-08-06 23:32:48 +0000530
Lang Hames49ab8bc2008-11-16 12:12:54 +0000531 if (physReg == 0) {
532 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Jakob Stoklund Olesen08322b72011-06-16 20:37:45 +0000533 physReg = liRC->getRawAllocationOrder(*mf).front();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000534 }
Misha Brukmanda467482009-01-08 15:50:22 +0000535
536 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000537 }
Lang Hames49ab8bc2008-11-16 12:12:54 +0000538}
539
Lang Hamescb1e1012010-09-18 09:07:10 +0000540bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000541
Evan Chengb25f4632008-10-02 18:29:27 +0000542 mf = &MF;
543 tm = &mf->getTarget();
544 tri = tm->getRegisterInfo();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000545 tii = tm->getInstrInfo();
Andrew Trick9363b592012-02-10 04:10:26 +0000546 mri = &mf->getRegInfo();
Evan Chengb25f4632008-10-02 18:29:27 +0000547
Lang Hames49ab8bc2008-11-16 12:12:54 +0000548 lis = &getAnalysis<LiveIntervals>();
549 lss = &getAnalysis<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000550 mbfi = &getAnalysis<MachineBlockFrequencyInfo>();
Evan Chengb25f4632008-10-02 18:29:27 +0000551
Arnaud A. de Grandmaisonea3ac162013-11-11 19:04:45 +0000552 calculateSpillWeightsAndHints(*lis, MF, getAnalysis<MachineLoopInfo>(),
553 *mbfi);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +0000554
Owen Andersond37ddf52009-03-13 05:55:11 +0000555 vrm = &getAnalysis<VirtRegMap>();
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000556 spiller.reset(createInlineSpiller(*this, MF, *vrm));
Evan Chengb25f4632008-10-02 18:29:27 +0000557
Chad Rosiered119d52012-11-28 00:21:29 +0000558 mri->freezeReservedRegs(MF);
559
Craig Toppera538d832012-08-22 06:07:19 +0000560 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000561
Evan Chengb25f4632008-10-02 18:29:27 +0000562 // Allocator main loop:
Misha Brukmanda467482009-01-08 15:50:22 +0000563 //
Evan Chengb25f4632008-10-02 18:29:27 +0000564 // * Map current regalloc problem to a PBQP problem
565 // * Solve the PBQP problem
566 // * Map the solution back to a register allocation
567 // * Spill if necessary
Misha Brukmanda467482009-01-08 15:50:22 +0000568 //
Evan Chengb25f4632008-10-02 18:29:27 +0000569 // This process is continued till no more spills are generated.
570
Lang Hames49ab8bc2008-11-16 12:12:54 +0000571 // Find the vreg intervals in need of allocation.
572 findVRegIntervalsToAlloc();
Misha Brukmanda467482009-01-08 15:50:22 +0000573
Craig Toppera538d832012-08-22 06:07:19 +0000574#ifndef NDEBUG
Lang Hames95e021f2012-03-26 23:07:23 +0000575 const Function* func = mf->getFunction();
576 std::string fqn =
577 func->getParent()->getModuleIdentifier() + "." +
578 func->getName().str();
Craig Toppera538d832012-08-22 06:07:19 +0000579#endif
Lang Hames95e021f2012-03-26 23:07:23 +0000580
Lang Hames49ab8bc2008-11-16 12:12:54 +0000581 // If there are non-empty intervals allocate them using pbqp.
Lang Hamescb1e1012010-09-18 09:07:10 +0000582 if (!vregsToAlloc.empty()) {
Evan Chengb25f4632008-10-02 18:29:27 +0000583
Lang Hames49ab8bc2008-11-16 12:12:54 +0000584 bool pbqpAllocComplete = false;
585 unsigned round = 0;
586
Lang Hames4108e7e2010-10-04 12:13:07 +0000587 while (!pbqpAllocComplete) {
588 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000589
Andy Gibbsb23ea722013-04-15 12:06:32 +0000590 OwningPtr<PBQPRAProblem> problem(
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000591 builder->build(mf, lis, mbfi, vregsToAlloc));
Lang Hames95e021f2012-03-26 23:07:23 +0000592
593#ifndef NDEBUG
594 if (pbqpDumpGraphs) {
595 std::ostringstream rs;
596 rs << round;
597 std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
598 std::string tmp;
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000599 raw_fd_ostream os(graphFileName.c_str(), tmp, sys::fs::F_Text);
Lang Hames95e021f2012-03-26 23:07:23 +0000600 DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
601 << graphFileName << "\"\n");
602 problem->getGraph().dump(os);
603 }
604#endif
605
Lang Hames4108e7e2010-10-04 12:13:07 +0000606 PBQP::Solution solution =
Lang Hames18635822014-03-03 18:50:05 +0000607 PBQP::RegAlloc::solve(problem->getGraph());
Lang Hames305be0e2009-08-18 23:34:50 +0000608
Lang Hames4108e7e2010-10-04 12:13:07 +0000609 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000610
Lang Hames4108e7e2010-10-04 12:13:07 +0000611 ++round;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000612 }
Evan Chengb25f4632008-10-02 18:29:27 +0000613 }
614
Lang Hames49ab8bc2008-11-16 12:12:54 +0000615 // Finalise allocation, allocate empty ranges.
616 finalizeAlloc();
Lang Hamescb1e1012010-09-18 09:07:10 +0000617 vregsToAlloc.clear();
618 emptyIntervalVRegs.clear();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000619
David Greene7e256f32010-01-05 01:25:43 +0000620 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000621
Misha Brukmanda467482009-01-08 15:50:22 +0000622 return true;
Evan Chengb25f4632008-10-02 18:29:27 +0000623}
624
Lang Hamesfd1bc422010-09-23 04:28:54 +0000625FunctionPass* llvm::createPBQPRegisterAllocator(
Andy Gibbsb23ea722013-04-15 12:06:32 +0000626 OwningPtr<PBQPBuilder> &builder,
Lang Hames934625e2011-06-17 07:09:01 +0000627 char *customPassID) {
Benjamin Kramerdae08512013-04-12 12:13:51 +0000628 return new RegAllocPBQP(builder, customPassID);
Evan Chengb25f4632008-10-02 18:29:27 +0000629}
630
Lang Hamesfd1bc422010-09-23 04:28:54 +0000631FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Andy Gibbsb23ea722013-04-15 12:06:32 +0000632 OwningPtr<PBQPBuilder> Builder;
633 if (pbqpCoalescing)
634 Builder.reset(new PBQPBuilderWithCoalescing());
635 else
636 Builder.reset(new PBQPBuilder());
637 return createPBQPRegisterAllocator(Builder);
Lang Hamescb1e1012010-09-18 09:07:10 +0000638}
Evan Chengb25f4632008-10-02 18:29:27 +0000639
640#undef DEBUG_TYPE