blob: 54b67abd7df0af7f69fd3cf5fe28768bade240a9 [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"
Eric Christopherd9134482014-08-04 21:25:23 +000052#include "llvm/Target/TargetSubtargetInfo.h"
Misha Brukmanda467482009-01-08 15:50:22 +000053#include <limits>
Misha Brukmanda467482009-01-08 15:50:22 +000054#include <memory>
Lang Hamesad0962a2014-10-18 17:26:07 +000055#include <queue>
Evan Chengb25f4632008-10-02 18:29:27 +000056#include <set>
Lang Hames95e021f2012-03-26 23:07:23 +000057#include <sstream>
Evan Chengb25f4632008-10-02 18:29:27 +000058#include <vector>
Evan Chengb25f4632008-10-02 18:29:27 +000059
Lang Hamesfd1bc422010-09-23 04:28:54 +000060using namespace llvm;
Lang Hamescb1e1012010-09-18 09:07:10 +000061
Chandler Carruth1b9dde02014-04-22 02:02:50 +000062#define DEBUG_TYPE "regalloc"
63
Evan Chengb25f4632008-10-02 18:29:27 +000064static RegisterRegAlloc
Lang Hames8f31f442014-10-09 18:20:51 +000065RegisterPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesfd1bc422010-09-23 04:28:54 +000066 createDefaultPBQPRegisterAllocator);
Evan Chengb25f4632008-10-02 18:29:27 +000067
Lang Hames11732ad2009-08-19 01:36:14 +000068static cl::opt<bool>
Lang Hames8f31f442014-10-09 18:20:51 +000069PBQPCoalescing("pbqp-coalescing",
Lang Hames090c7e82010-01-26 04:49:58 +000070 cl::desc("Attempt coalescing during PBQP register allocation."),
71 cl::init(false), cl::Hidden);
Lang Hames11732ad2009-08-19 01:36:14 +000072
Lang Hames95e021f2012-03-26 23:07:23 +000073#ifndef NDEBUG
74static cl::opt<bool>
Lang Hames8f31f442014-10-09 18:20:51 +000075PBQPDumpGraphs("pbqp-dump-graphs",
Lang Hames95e021f2012-03-26 23:07:23 +000076 cl::desc("Dump graphs for each function/round in the compilation unit."),
77 cl::init(false), cl::Hidden);
78#endif
79
Lang Hamesfd1bc422010-09-23 04:28:54 +000080namespace {
81
82///
83/// PBQP based allocators solve the register allocation problem by mapping
84/// register allocation problems to Partitioned Boolean Quadratic
85/// Programming problems.
86class RegAllocPBQP : public MachineFunctionPass {
87public:
88
89 static char ID;
90
91 /// Construct a PBQP register allocator.
Lang Hames8f31f442014-10-09 18:20:51 +000092 RegAllocPBQP(char *cPassID = nullptr)
93 : MachineFunctionPass(ID), customPassID(cPassID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +000094 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
95 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000096 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000097 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000098 }
Lang Hamesfd1bc422010-09-23 04:28:54 +000099
100 /// Return the pass name.
Craig Topper4584cd52014-03-07 09:26:03 +0000101 const char* getPassName() const override {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000102 return "PBQP Register Allocator";
103 }
104
105 /// PBQP analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000106 void getAnalysisUsage(AnalysisUsage &au) const override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000107
108 /// Perform register allocation
Craig Topper4584cd52014-03-07 09:26:03 +0000109 bool runOnMachineFunction(MachineFunction &MF) override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000110
111private:
112
113 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
114 typedef std::vector<const LiveInterval*> Node2LIMap;
115 typedef std::vector<unsigned> AllowedSet;
116 typedef std::vector<AllowedSet> AllowedSetMap;
117 typedef std::pair<unsigned, unsigned> RegPair;
118 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000119 typedef std::set<unsigned> RegSet;
120
Lang Hames934625e2011-06-17 07:09:01 +0000121 char *customPassID;
122
Lang Hames8f31f442014-10-09 18:20:51 +0000123 RegSet VRegsToAlloc, EmptyIntervalVRegs;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000124
125 /// \brief Finds the initial set of vreg intervals to allocate.
Lang Hames8f31f442014-10-09 18:20:51 +0000126 void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS);
127
128 /// \brief Constructs an initial graph.
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000129 void initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM, Spiller &VRegSpiller);
130
131 /// \brief Spill the given VReg.
132 void spillVReg(unsigned VReg, SmallVectorImpl<unsigned> &NewIntervals,
133 MachineFunction &MF, LiveIntervals &LIS, VirtRegMap &VRM,
134 Spiller &VRegSpiller);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000135
Lang Hamesfd1bc422010-09-23 04:28:54 +0000136 /// \brief Given a solved PBQP problem maps this solution back to a register
137 /// assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000138 bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
139 const PBQP::Solution &Solution,
140 VirtRegMap &VRM,
141 Spiller &VRegSpiller);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000142
143 /// \brief Postprocessing before final spilling. Sets basic block "live in"
144 /// variables.
Lang Hames8f31f442014-10-09 18:20:51 +0000145 void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
146 VirtRegMap &VRM) const;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000147
148};
149
Lang Hamescb1e1012010-09-18 09:07:10 +0000150char RegAllocPBQP::ID = 0;
Evan Chengb25f4632008-10-02 18:29:27 +0000151
Lang Hames8f31f442014-10-09 18:20:51 +0000152/// @brief Set spill costs for each node in the PBQP reg-alloc graph.
153class SpillCosts : public PBQPRAConstraint {
154public:
155 void apply(PBQPRAGraph &G) override {
156 LiveIntervals &LIS = G.getMetadata().LIS;
157
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000158 // A minimum spill costs, so that register constraints can can be set
159 // without normalization in the [0.0:MinSpillCost( interval.
160 const PBQP::PBQPNum MinSpillCost = 10.0;
161
Lang Hames8f31f442014-10-09 18:20:51 +0000162 for (auto NId : G.nodeIds()) {
163 PBQP::PBQPNum SpillCost =
164 LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight;
165 if (SpillCost == 0.0)
166 SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000167 else
168 SpillCost += MinSpillCost;
Lang Hames8f31f442014-10-09 18:20:51 +0000169 PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
170 NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
171 G.setNodeCosts(NId, std::move(NodeCosts));
172 }
173 }
174};
175
176/// @brief Add interference edges between overlapping vregs.
177class Interference : public PBQPRAConstraint {
Lang Hamesad0962a2014-10-18 17:26:07 +0000178private:
179
Lang Hames5fe30ca2014-10-27 17:44:25 +0000180 typedef const PBQP::RegAlloc::AllowedRegVector* AllowedRegVecPtr;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000181 typedef std::pair<AllowedRegVecPtr, AllowedRegVecPtr> IKey;
182 typedef DenseMap<IKey, PBQPRAGraph::MatrixPtr> IMatrixCache;
183 typedef DenseSet<IKey> DisjointAllowedRegsCache;
184
185 bool haveDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
186 PBQPRAGraph::NodeId MId,
187 const DisjointAllowedRegsCache &D) const {
188 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
189 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
190
191 if (NRegs == MRegs)
192 return false;
193
194 if (NRegs < MRegs)
195 return D.count(IKey(NRegs, MRegs)) > 0;
Arnaud A. de Grandmaisona57ca812015-03-01 21:22:50 +0000196
197 return D.count(IKey(MRegs, NRegs)) > 0;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000198 }
199
200 void setDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
201 PBQPRAGraph::NodeId MId,
202 DisjointAllowedRegsCache &D) {
203 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
204 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
205
206 assert(NRegs != MRegs && "AllowedRegs can not be disjoint with itself");
207
208 if (NRegs < MRegs)
209 D.insert(IKey(NRegs, MRegs));
210 else
211 D.insert(IKey(MRegs, NRegs));
212 }
Lang Hames5fe30ca2014-10-27 17:44:25 +0000213
Lang Hamesad0962a2014-10-18 17:26:07 +0000214 // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
215 // for the fast interference graph construction algorithm. The last is there
216 // to save us from looking up node ids via the VRegToNode map in the graph
217 // metadata.
218 typedef std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>
219 IntervalInfo;
220
221 static SlotIndex getStartPoint(const IntervalInfo &I) {
222 return std::get<0>(I)->segments[std::get<1>(I)].start;
223 }
224
225 static SlotIndex getEndPoint(const IntervalInfo &I) {
226 return std::get<0>(I)->segments[std::get<1>(I)].end;
227 }
228
229 static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
230 return std::get<2>(I);
231 }
232
233 static bool lowestStartPoint(const IntervalInfo &I1,
234 const IntervalInfo &I2) {
235 // Condition reversed because priority queue has the *highest* element at
236 // the front, rather than the lowest.
237 return getStartPoint(I1) > getStartPoint(I2);
238 }
239
240 static bool lowestEndPoint(const IntervalInfo &I1,
241 const IntervalInfo &I2) {
242 SlotIndex E1 = getEndPoint(I1);
243 SlotIndex E2 = getEndPoint(I2);
244
245 if (E1 < E2)
246 return true;
247
248 if (E1 > E2)
249 return false;
250
251 // If two intervals end at the same point, we need a way to break the tie or
252 // the set will assume they're actually equal and refuse to insert a
253 // "duplicate". Just compare the vregs - fast and guaranteed unique.
254 return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
255 }
256
257 static bool isAtLastSegment(const IntervalInfo &I) {
258 return std::get<1>(I) == std::get<0>(I)->size() - 1;
259 }
260
261 static IntervalInfo nextSegment(const IntervalInfo &I) {
262 return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
263 }
264
Lang Hames8f31f442014-10-09 18:20:51 +0000265public:
266
267 void apply(PBQPRAGraph &G) override {
Lang Hamesad0962a2014-10-18 17:26:07 +0000268 // The following is loosely based on the linear scan algorithm introduced in
269 // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
270 // isn't linear, because the size of the active set isn't bound by the
271 // number of registers, but rather the size of the largest clique in the
272 // graph. Still, we expect this to be better than N^2.
Lang Hames8f31f442014-10-09 18:20:51 +0000273 LiveIntervals &LIS = G.getMetadata().LIS;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000274
275 // Interferenc matrices are incredibly regular - they're only a function of
276 // the allowed sets, so we cache them to avoid the overhead of constructing
277 // and uniquing them.
278 IMatrixCache C;
Lang Hames8f31f442014-10-09 18:20:51 +0000279
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000280 // Cache known disjoint allowed registers pairs
281 DisjointAllowedRegsCache D;
282
Lang Hamesad0962a2014-10-18 17:26:07 +0000283 typedef std::set<IntervalInfo, decltype(&lowestEndPoint)> IntervalSet;
284 typedef std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
285 decltype(&lowestStartPoint)> IntervalQueue;
286 IntervalSet Active(lowestEndPoint);
287 IntervalQueue Inactive(lowestStartPoint);
Lang Hames8f31f442014-10-09 18:20:51 +0000288
Lang Hamesad0962a2014-10-18 17:26:07 +0000289 // Start by building the inactive set.
290 for (auto NId : G.nodeIds()) {
291 unsigned VReg = G.getNodeMetadata(NId).getVReg();
292 LiveInterval &LI = LIS.getInterval(VReg);
293 assert(!LI.empty() && "PBQP graph contains node for empty interval");
294 Inactive.push(std::make_tuple(&LI, 0, NId));
295 }
Lang Hames8f31f442014-10-09 18:20:51 +0000296
Lang Hamesad0962a2014-10-18 17:26:07 +0000297 while (!Inactive.empty()) {
298 // Tentatively grab the "next" interval - this choice may be overriden
299 // below.
300 IntervalInfo Cur = Inactive.top();
301
302 // Retire any active intervals that end before Cur starts.
303 IntervalSet::iterator RetireItr = Active.begin();
304 while (RetireItr != Active.end() &&
305 (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
306 // If this interval has subsequent segments, add the next one to the
307 // inactive list.
308 if (!isAtLastSegment(*RetireItr))
309 Inactive.push(nextSegment(*RetireItr));
310
311 ++RetireItr;
Lang Hames8f31f442014-10-09 18:20:51 +0000312 }
Lang Hamesad0962a2014-10-18 17:26:07 +0000313 Active.erase(Active.begin(), RetireItr);
314
315 // One of the newly retired segments may actually start before the
316 // Cur segment, so re-grab the front of the inactive list.
317 Cur = Inactive.top();
318 Inactive.pop();
319
320 // At this point we know that Cur overlaps all active intervals. Add the
321 // interference edges.
322 PBQP::GraphBase::NodeId NId = getNodeId(Cur);
323 for (const auto &A : Active) {
324 PBQP::GraphBase::NodeId MId = getNodeId(A);
325
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000326 // Do not add an edge when the nodes' allowed registers do not
327 // intersect: there is obviously no interference.
328 if (haveDisjointAllowedRegs(G, NId, MId, D))
329 continue;
330
Lang Hamesad0962a2014-10-18 17:26:07 +0000331 // Check that we haven't already added this edge
332 // FIXME: findEdge is expensive in the worst case (O(max_clique(G))).
333 // It might be better to replace this with a local bit-matrix.
Lang Hames5fe30ca2014-10-27 17:44:25 +0000334 if (G.findEdge(NId, MId) != PBQPRAGraph::invalidEdgeId())
Lang Hamesad0962a2014-10-18 17:26:07 +0000335 continue;
336
337 // This is a new edge - add it to the graph.
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000338 if (!createInterferenceEdge(G, NId, MId, C))
339 setDisjointAllowedRegs(G, NId, MId, D);
Lang Hamesad0962a2014-10-18 17:26:07 +0000340 }
341
342 // Finally, add Cur to the Active set.
343 Active.insert(Cur);
Lang Hames8f31f442014-10-09 18:20:51 +0000344 }
345 }
346
347private:
348
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000349 // Create an Interference edge and add it to the graph, unless it is
350 // a null matrix, meaning the nodes' allowed registers do not have any
351 // interference. This case occurs frequently between integer and floating
352 // point registers for example.
353 // return true iff both nodes interferes.
354 bool createInterferenceEdge(PBQPRAGraph &G,
355 PBQPRAGraph::NodeId NId, PBQPRAGraph::NodeId MId,
356 IMatrixCache &C) {
Lang Hames5fe30ca2014-10-27 17:44:25 +0000357
358 const TargetRegisterInfo &TRI =
Eric Christopher7592b0c2015-01-27 08:27:06 +0000359 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames5fe30ca2014-10-27 17:44:25 +0000360 const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
361 const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
362
363 // Try looking the edge costs up in the IMatrixCache first.
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000364 IKey K(&NRegs, &MRegs);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000365 IMatrixCache::iterator I = C.find(K);
366 if (I != C.end()) {
367 G.addEdgeBypassingCostAllocator(NId, MId, I->second);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000368 return true;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000369 }
370
371 PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000372 bool NodesInterfere = false;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000373 for (unsigned I = 0; I != NRegs.size(); ++I) {
374 unsigned PRegN = NRegs[I];
375 for (unsigned J = 0; J != MRegs.size(); ++J) {
376 unsigned PRegM = MRegs[J];
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000377 if (TRI.regsOverlap(PRegN, PRegM)) {
Lang Hames8f31f442014-10-09 18:20:51 +0000378 M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000379 NodesInterfere = true;
380 }
Lang Hames8f31f442014-10-09 18:20:51 +0000381 }
382 }
383
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000384 if (!NodesInterfere)
385 return false;
386
Lang Hames5fe30ca2014-10-27 17:44:25 +0000387 PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
388 C[K] = G.getEdgeCostsPtr(EId);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000389
390 return true;
Lang Hames8f31f442014-10-09 18:20:51 +0000391 }
392};
393
394
395class Coalescing : public PBQPRAConstraint {
396public:
397 void apply(PBQPRAGraph &G) override {
398 MachineFunction &MF = G.getMetadata().MF;
399 MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
Eric Christopher7592b0c2015-01-27 08:27:06 +0000400 CoalescerPair CP(*MF.getSubtarget().getRegisterInfo());
Lang Hames8f31f442014-10-09 18:20:51 +0000401
402 // Scan the machine function and add a coalescing cost whenever CoalescerPair
403 // gives the Ok.
404 for (const auto &MBB : MF) {
405 for (const auto &MI : MBB) {
406
407 // Skip not-coalescable or already coalesced copies.
408 if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
409 continue;
410
411 unsigned DstReg = CP.getDstReg();
412 unsigned SrcReg = CP.getSrcReg();
413
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000414 const float Scale = 1.0f / MBFI.getEntryFreq();
415 PBQP::PBQPNum CBenefit = MBFI.getBlockFreq(&MBB).getFrequency() * Scale;
Lang Hames8f31f442014-10-09 18:20:51 +0000416
417 if (CP.isPhys()) {
418 if (!MF.getRegInfo().isAllocatable(DstReg))
419 continue;
420
421 PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
422
Lang Hames5fe30ca2014-10-27 17:44:25 +0000423 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
424 G.getNodeMetadata(NId).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000425
426 unsigned PRegOpt = 0;
427 while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
428 ++PRegOpt;
429
430 if (PRegOpt < Allowed.size()) {
431 PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000432 NewCosts[PRegOpt + 1] -= CBenefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000433 G.setNodeCosts(NId, std::move(NewCosts));
434 }
435 } else {
436 PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
437 PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000438 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
439 &G.getNodeMetadata(N1Id).getAllowedRegs();
440 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
441 &G.getNodeMetadata(N2Id).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000442
443 PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
444 if (EId == G.invalidEdgeId()) {
445 PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
446 Allowed2->size() + 1, 0);
447 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
448 G.addEdge(N1Id, N2Id, std::move(Costs));
449 } else {
450 if (G.getEdgeNode1Id(EId) == N2Id) {
451 std::swap(N1Id, N2Id);
452 std::swap(Allowed1, Allowed2);
453 }
454 PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
455 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
Arnaud A. de Grandmaisonde790262015-02-11 08:25:36 +0000456 G.updateEdgeCosts(EId, std::move(Costs));
Lang Hames8f31f442014-10-09 18:20:51 +0000457 }
458 }
459 }
460 }
461 }
462
463private:
464
465 void addVirtRegCoalesce(
Lang Hames5fe30ca2014-10-27 17:44:25 +0000466 PBQPRAGraph::RawMatrix &CostMat,
467 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
468 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
469 PBQP::PBQPNum Benefit) {
Lang Hames8f31f442014-10-09 18:20:51 +0000470 assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
471 assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
472 for (unsigned I = 0; I != Allowed1.size(); ++I) {
473 unsigned PReg1 = Allowed1[I];
474 for (unsigned J = 0; J != Allowed2.size(); ++J) {
475 unsigned PReg2 = Allowed2[J];
476 if (PReg1 == PReg2)
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000477 CostMat[I + 1][J + 1] -= Benefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000478 }
479 }
480 }
481
482};
483
Lang Hamesfd1bc422010-09-23 04:28:54 +0000484} // End anonymous namespace.
485
Lang Hames8f31f442014-10-09 18:20:51 +0000486// Out-of-line destructor/anchor for PBQPRAConstraint.
487PBQPRAConstraint::~PBQPRAConstraint() {}
488void PBQPRAConstraint::anchor() {}
489void PBQPRAConstraintList::anchor() {}
Lang Hamescb1e1012010-09-18 09:07:10 +0000490
491void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hamesb13b6a02011-12-06 01:45:57 +0000492 au.setPreservesCFG();
493 au.addRequired<AliasAnalysis>();
494 au.addPreserved<AliasAnalysis>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000495 au.addRequired<SlotIndexes>();
496 au.addPreserved<SlotIndexes>();
497 au.addRequired<LiveIntervals>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000498 au.addPreserved<LiveIntervals>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000499 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames934625e2011-06-17 07:09:01 +0000500 if (customPassID)
501 au.addRequiredID(*customPassID);
Lang Hamescb1e1012010-09-18 09:07:10 +0000502 au.addRequired<LiveStacks>();
503 au.addPreserved<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000504 au.addRequired<MachineBlockFrequencyInfo>();
505 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames7d99d792013-07-01 20:47:47 +0000506 au.addRequired<MachineLoopInfo>();
507 au.addPreserved<MachineLoopInfo>();
Lang Hamesb13b6a02011-12-06 01:45:57 +0000508 au.addRequired<MachineDominatorTree>();
509 au.addPreserved<MachineDominatorTree>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000510 au.addRequired<VirtRegMap>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000511 au.addPreserved<VirtRegMap>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000512 MachineFunctionPass::getAnalysisUsage(au);
513}
514
Lang Hames8f31f442014-10-09 18:20:51 +0000515void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
516 LiveIntervals &LIS) {
517 const MachineRegisterInfo &MRI = MF.getRegInfo();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000518
519 // Iterate over all live ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000520 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
521 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
522 if (MRI.reg_nodbg_empty(Reg))
Lang Hames49ab8bc2008-11-16 12:12:54 +0000523 continue;
Lang Hames8f31f442014-10-09 18:20:51 +0000524 LiveInterval &LI = LIS.getInterval(Reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000525
526 // If this live interval is non-empty we will use pbqp to allocate it.
527 // Empty intervals we allocate in a simple post-processing stage in
528 // finalizeAlloc.
Lang Hames8f31f442014-10-09 18:20:51 +0000529 if (!LI.empty()) {
530 VRegsToAlloc.insert(LI.reg);
Lang Hamesc702ba62010-11-12 05:47:21 +0000531 } else {
Lang Hames8f31f442014-10-09 18:20:51 +0000532 EmptyIntervalVRegs.insert(LI.reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000533 }
534 }
Evan Chengb25f4632008-10-02 18:29:27 +0000535}
536
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000537static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI,
538 const MachineFunction &MF) {
539 const MCPhysReg *CSR = TRI.getCalleeSavedRegs(&MF);
540 for (unsigned i = 0; CSR[i] != 0; ++i)
541 if (TRI.regsOverlap(reg, CSR[i]))
542 return true;
543 return false;
544}
545
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000546void RegAllocPBQP::initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM,
547 Spiller &VRegSpiller) {
Lang Hames8f31f442014-10-09 18:20:51 +0000548 MachineFunction &MF = G.getMetadata().MF;
549
550 LiveIntervals &LIS = G.getMetadata().LIS;
551 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
552 const TargetRegisterInfo &TRI =
Eric Christopher7592b0c2015-01-27 08:27:06 +0000553 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames8f31f442014-10-09 18:20:51 +0000554
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000555 std::vector<unsigned> Worklist(VRegsToAlloc.begin(), VRegsToAlloc.end());
556
557 while (!Worklist.empty()) {
558 unsigned VReg = Worklist.back();
559 Worklist.pop_back();
560
Lang Hames8f31f442014-10-09 18:20:51 +0000561 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
562 LiveInterval &VRegLI = LIS.getInterval(VReg);
563
564 // Record any overlaps with regmask operands.
565 BitVector RegMaskOverlaps;
566 LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
567
568 // Compute an initial allowed set for the current vreg.
569 std::vector<unsigned> VRegAllowed;
570 ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
571 for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
572 unsigned PReg = RawPRegOrder[I];
573 if (MRI.isReserved(PReg))
574 continue;
575
576 // vregLI crosses a regmask operand that clobbers preg.
577 if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
578 continue;
579
580 // vregLI overlaps fixed regunit interference.
581 bool Interference = false;
582 for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
583 if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
584 Interference = true;
585 break;
586 }
587 }
588 if (Interference)
589 continue;
590
591 // preg is usable for this virtual register.
592 VRegAllowed.push_back(PReg);
593 }
594
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000595 // Check for vregs that have no allowed registers. These should be
596 // pre-spilled and the new vregs added to the worklist.
597 if (VRegAllowed.empty()) {
598 SmallVector<unsigned, 8> NewVRegs;
599 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000600 Worklist.insert(Worklist.end(), NewVRegs.begin(), NewVRegs.end());
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000601 continue;
602 }
603
Lang Hames8f31f442014-10-09 18:20:51 +0000604 PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000605
606 // Tweak cost of callee saved registers, as using then force spilling and
607 // restoring them. This would only happen in the prologue / epilogue though.
608 for (unsigned i = 0; i != VRegAllowed.size(); ++i)
609 if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF))
610 NodeCosts[1 + i] += 1.0;
611
Lang Hames8f31f442014-10-09 18:20:51 +0000612 PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
613 G.getNodeMetadata(NId).setVReg(VReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000614 G.getNodeMetadata(NId).setAllowedRegs(
615 G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
Lang Hames8f31f442014-10-09 18:20:51 +0000616 G.getMetadata().setNodeIdForVReg(VReg, NId);
617 }
618}
619
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000620void RegAllocPBQP::spillVReg(unsigned VReg,
621 SmallVectorImpl<unsigned> &NewIntervals,
622 MachineFunction &MF, LiveIntervals &LIS,
623 VirtRegMap &VRM, Spiller &VRegSpiller) {
624
625 VRegsToAlloc.erase(VReg);
626 LiveRangeEdit LRE(&LIS.getInterval(VReg), NewIntervals, MF, LIS, &VRM);
627 VRegSpiller.spill(LRE);
628
629 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
630 (void)TRI;
631 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> SPILLED (Cost: "
632 << LRE.getParent().weight << ", New vregs: ");
633
634 // Copy any newly inserted live intervals into the list of regs to
635 // allocate.
636 for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
637 I != E; ++I) {
638 const LiveInterval &LI = LIS.getInterval(*I);
639 assert(!LI.empty() && "Empty spill range.");
640 DEBUG(dbgs() << PrintReg(LI.reg, &TRI) << " ");
641 VRegsToAlloc.insert(LI.reg);
642 }
643
644 DEBUG(dbgs() << ")\n");
645}
646
Lang Hames8f31f442014-10-09 18:20:51 +0000647bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
648 const PBQP::Solution &Solution,
649 VirtRegMap &VRM,
650 Spiller &VRegSpiller) {
651 MachineFunction &MF = G.getMetadata().MF;
652 LiveIntervals &LIS = G.getMetadata().LIS;
Eric Christopher7592b0c2015-01-27 08:27:06 +0000653 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
Lang Hames8f31f442014-10-09 18:20:51 +0000654 (void)TRI;
655
Lang Hamescb1e1012010-09-18 09:07:10 +0000656 // Set to true if we have any spills
Lang Hames8f31f442014-10-09 18:20:51 +0000657 bool AnotherRoundNeeded = false;
Lang Hamescb1e1012010-09-18 09:07:10 +0000658
659 // Clear the existing allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000660 VRM.clearAllVirt();
Lang Hamescb1e1012010-09-18 09:07:10 +0000661
Lang Hamescb1e1012010-09-18 09:07:10 +0000662 // Iterate over the nodes mapping the PBQP solution to a register
663 // assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000664 for (auto NId : G.nodeIds()) {
665 unsigned VReg = G.getNodeMetadata(NId).getVReg();
666 unsigned AllocOption = Solution.getSelection(NId);
Lang Hamescb1e1012010-09-18 09:07:10 +0000667
Lang Hames8f31f442014-10-09 18:20:51 +0000668 if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
Lang Hames5fe30ca2014-10-27 17:44:25 +0000669 unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
Lang Hames8f31f442014-10-09 18:20:51 +0000670 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> "
671 << TRI.getName(PReg) << "\n");
672 assert(PReg != 0 && "Invalid preg selected.");
673 VRM.assignVirt2Phys(VReg, PReg);
674 } else {
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000675 // Spill VReg. If this introduces new intervals we'll need another round
676 // of allocation.
677 SmallVector<unsigned, 8> NewVRegs;
678 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
679 AnotherRoundNeeded |= !NewVRegs.empty();
Lang Hamescb1e1012010-09-18 09:07:10 +0000680 }
681 }
682
Lang Hames8f31f442014-10-09 18:20:51 +0000683 return !AnotherRoundNeeded;
Lang Hamescb1e1012010-09-18 09:07:10 +0000684}
685
Lang Hames8f31f442014-10-09 18:20:51 +0000686void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
687 LiveIntervals &LIS,
688 VirtRegMap &VRM) const {
689 MachineRegisterInfo &MRI = MF.getRegInfo();
690
Lang Hames49ab8bc2008-11-16 12:12:54 +0000691 // First allocate registers for the empty intervals.
Lang Hamescb1e1012010-09-18 09:07:10 +0000692 for (RegSet::const_iterator
Lang Hames8f31f442014-10-09 18:20:51 +0000693 I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
694 I != E; ++I) {
695 LiveInterval &LI = LIS.getInterval(*I);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000696
Lang Hames8f31f442014-10-09 18:20:51 +0000697 unsigned PReg = MRI.getSimpleHint(LI.reg);
Lang Hames88fae6f2009-08-06 23:32:48 +0000698
Lang Hames8f31f442014-10-09 18:20:51 +0000699 if (PReg == 0) {
700 const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg);
701 PReg = RC.getRawAllocationOrder(MF).front();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000702 }
Misha Brukmanda467482009-01-08 15:50:22 +0000703
Lang Hames8f31f442014-10-09 18:20:51 +0000704 VRM.assignVirt2Phys(LI.reg, PReg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000705 }
Lang Hames49ab8bc2008-11-16 12:12:54 +0000706}
707
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000708static inline float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size,
709 unsigned NumInstr) {
710 // All intervals have a spill weight that is mostly proportional to the number
711 // of uses, with uses in loops having a bigger weight.
712 return NumInstr * normalizeSpillWeight(UseDefFreq, Size, 1);
713}
714
Lang Hamescb1e1012010-09-18 09:07:10 +0000715bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames8f31f442014-10-09 18:20:51 +0000716 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
717 MachineBlockFrequencyInfo &MBFI =
718 getAnalysis<MachineBlockFrequencyInfo>();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000719
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000720 calculateSpillWeightsAndHints(LIS, MF, getAnalysis<MachineLoopInfo>(), MBFI,
721 normalizePBQPSpillWeight);
Evan Chengb25f4632008-10-02 18:29:27 +0000722
Lang Hames8f31f442014-10-09 18:20:51 +0000723 VirtRegMap &VRM = getAnalysis<VirtRegMap>();
Evan Chengb25f4632008-10-02 18:29:27 +0000724
Lang Hames8f31f442014-10-09 18:20:51 +0000725 std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +0000726
Lang Hames8f31f442014-10-09 18:20:51 +0000727 MF.getRegInfo().freezeReservedRegs(MF);
Evan Chengb25f4632008-10-02 18:29:27 +0000728
Lang Hames8f31f442014-10-09 18:20:51 +0000729 DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000730
Evan Chengb25f4632008-10-02 18:29:27 +0000731 // Allocator main loop:
Misha Brukmanda467482009-01-08 15:50:22 +0000732 //
Evan Chengb25f4632008-10-02 18:29:27 +0000733 // * Map current regalloc problem to a PBQP problem
734 // * Solve the PBQP problem
735 // * Map the solution back to a register allocation
736 // * Spill if necessary
Misha Brukmanda467482009-01-08 15:50:22 +0000737 //
Evan Chengb25f4632008-10-02 18:29:27 +0000738 // This process is continued till no more spills are generated.
739
Lang Hames49ab8bc2008-11-16 12:12:54 +0000740 // Find the vreg intervals in need of allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000741 findVRegIntervalsToAlloc(MF, LIS);
Misha Brukmanda467482009-01-08 15:50:22 +0000742
Craig Toppera538d832012-08-22 06:07:19 +0000743#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000744 const Function &F = *MF.getFunction();
745 std::string FullyQualifiedName =
746 F.getParent()->getModuleIdentifier() + "." + F.getName().str();
Craig Toppera538d832012-08-22 06:07:19 +0000747#endif
Lang Hames95e021f2012-03-26 23:07:23 +0000748
Lang Hames49ab8bc2008-11-16 12:12:54 +0000749 // If there are non-empty intervals allocate them using pbqp.
Lang Hames8f31f442014-10-09 18:20:51 +0000750 if (!VRegsToAlloc.empty()) {
Evan Chengb25f4632008-10-02 18:29:27 +0000751
Eric Christopher7592b0c2015-01-27 08:27:06 +0000752 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
Lang Hames8f31f442014-10-09 18:20:51 +0000753 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
754 llvm::make_unique<PBQPRAConstraintList>();
755 ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
756 ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
757 if (PBQPCoalescing)
758 ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
759 ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
Lang Hames49ab8bc2008-11-16 12:12:54 +0000760
Lang Hames8f31f442014-10-09 18:20:51 +0000761 bool PBQPAllocComplete = false;
762 unsigned Round = 0;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000763
Lang Hames8f31f442014-10-09 18:20:51 +0000764 while (!PBQPAllocComplete) {
765 DEBUG(dbgs() << " PBQP Regalloc round " << Round << ":\n");
766
767 PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000768 initializeGraph(G, VRM, *VRegSpiller);
Lang Hames8f31f442014-10-09 18:20:51 +0000769 ConstraintsRoot->apply(G);
Lang Hames95e021f2012-03-26 23:07:23 +0000770
771#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000772 if (PBQPDumpGraphs) {
773 std::ostringstream RS;
774 RS << Round;
775 std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
776 ".pbqpgraph";
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000777 std::error_code EC;
Lang Hames8f31f442014-10-09 18:20:51 +0000778 raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text);
779 DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
780 << GraphFileName << "\"\n");
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000781 G.dump(OS);
Lang Hames95e021f2012-03-26 23:07:23 +0000782 }
783#endif
784
Lang Hames8f31f442014-10-09 18:20:51 +0000785 PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
786 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
787 ++Round;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000788 }
Evan Chengb25f4632008-10-02 18:29:27 +0000789 }
790
Lang Hames49ab8bc2008-11-16 12:12:54 +0000791 // Finalise allocation, allocate empty ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000792 finalizeAlloc(MF, LIS, VRM);
793 VRegsToAlloc.clear();
794 EmptyIntervalVRegs.clear();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000795
Lang Hames8f31f442014-10-09 18:20:51 +0000796 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000797
Misha Brukmanda467482009-01-08 15:50:22 +0000798 return true;
Evan Chengb25f4632008-10-02 18:29:27 +0000799}
800
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000801namespace {
Arnaud A. de Grandmaison77f62d42015-02-06 11:28:16 +0000802// A helper class for printing node and register info in a consistent way
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000803class PrintNodeInfo {
804public:
805 typedef PBQP::RegAlloc::PBQPRAGraph Graph;
806 typedef PBQP::RegAlloc::PBQPRAGraph::NodeId NodeId;
807
808 PrintNodeInfo(NodeId NId, const Graph &G) : G(G), NId(NId) {}
809
810 void print(raw_ostream &OS) const {
811 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
812 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
813 unsigned VReg = G.getNodeMetadata(NId).getVReg();
814 const char *RegClassName = TRI->getRegClassName(MRI.getRegClass(VReg));
815 OS << NId << " (" << RegClassName << ':' << PrintReg(VReg, TRI) << ')';
816 }
817
818private:
819 const Graph &G;
820 NodeId NId;
821};
822
823inline raw_ostream &operator<<(raw_ostream &OS, const PrintNodeInfo &PR) {
824 PR.print(OS);
825 return OS;
826}
827} // anonymous namespace
828
829void PBQP::RegAlloc::PBQPRAGraph::dump(raw_ostream &OS) const {
830 for (auto NId : nodeIds()) {
831 const Vector &Costs = getNodeCosts(NId);
832 assert(Costs.getLength() != 0 && "Empty vector in graph.");
833 OS << PrintNodeInfo(NId, *this) << ": " << Costs << '\n';
834 }
835 OS << '\n';
836
837 for (auto EId : edgeIds()) {
838 NodeId N1Id = getEdgeNode1Id(EId);
839 NodeId N2Id = getEdgeNode2Id(EId);
840 assert(N1Id != N2Id && "PBQP graphs should not have self-edges.");
841 const Matrix &M = getEdgeCosts(EId);
842 assert(M.getRows() != 0 && "No rows in matrix.");
843 assert(M.getCols() != 0 && "No cols in matrix.");
844 OS << PrintNodeInfo(N1Id, *this) << ' ' << M.getRows() << " rows / ";
845 OS << PrintNodeInfo(N2Id, *this) << ' ' << M.getCols() << " cols:\n";
846 OS << M << '\n';
847 }
848}
849
850void PBQP::RegAlloc::PBQPRAGraph::dump() const { dump(dbgs()); }
851
852void PBQP::RegAlloc::PBQPRAGraph::printDot(raw_ostream &OS) const {
853 OS << "graph {\n";
854 for (auto NId : nodeIds()) {
855 OS << " node" << NId << " [ label=\""
856 << PrintNodeInfo(NId, *this) << "\\n"
857 << getNodeCosts(NId) << "\" ]\n";
858 }
859
860 OS << " edge [ len=" << nodeIds().size() << " ]\n";
861 for (auto EId : edgeIds()) {
862 OS << " node" << getEdgeNode1Id(EId)
863 << " -- node" << getEdgeNode2Id(EId)
864 << " [ label=\"";
865 const Matrix &EdgeCosts = getEdgeCosts(EId);
866 for (unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
867 OS << EdgeCosts.getRowAsVector(i) << "\\n";
868 }
869 OS << "\" ]\n";
870 }
871 OS << "}\n";
872}
873
Lang Hames8f31f442014-10-09 18:20:51 +0000874FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
875 return new RegAllocPBQP(customPassID);
Evan Chengb25f4632008-10-02 18:29:27 +0000876}
877
Lang Hamesfd1bc422010-09-23 04:28:54 +0000878FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Lang Hames8f31f442014-10-09 18:20:51 +0000879 return createPBQPRegisterAllocator();
Lang Hamescb1e1012010-09-18 09:07:10 +0000880}
Evan Chengb25f4632008-10-02 18:29:27 +0000881
882#undef DEBUG_TYPE