blob: 64ef0084c1bbc7ca87ea709eb4457fe0d981c130 [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"
Matthias Braunc07cbc82015-12-04 01:31:59 +000050#include "llvm/Support/Printable.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000051#include "llvm/Support/raw_ostream.h"
Misha Brukmanda467482009-01-08 15:50:22 +000052#include "llvm/Target/TargetInstrInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000053#include "llvm/Target/TargetSubtargetInfo.h"
Misha Brukmanda467482009-01-08 15:50:22 +000054#include <limits>
Misha Brukmanda467482009-01-08 15:50:22 +000055#include <memory>
Lang Hamesad0962a2014-10-18 17:26:07 +000056#include <queue>
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
Chandler Carruth1b9dde02014-04-22 02:02:50 +000063#define DEBUG_TYPE "regalloc"
64
Evan Chengb25f4632008-10-02 18:29:27 +000065static RegisterRegAlloc
Lang Hames8f31f442014-10-09 18:20:51 +000066RegisterPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesfd1bc422010-09-23 04:28:54 +000067 createDefaultPBQPRegisterAllocator);
Evan Chengb25f4632008-10-02 18:29:27 +000068
Lang Hames11732ad2009-08-19 01:36:14 +000069static cl::opt<bool>
Lang Hames8f31f442014-10-09 18:20:51 +000070PBQPCoalescing("pbqp-coalescing",
Lang Hames090c7e82010-01-26 04:49:58 +000071 cl::desc("Attempt coalescing during PBQP register allocation."),
72 cl::init(false), cl::Hidden);
Lang Hames11732ad2009-08-19 01:36:14 +000073
Lang Hames95e021f2012-03-26 23:07:23 +000074#ifndef NDEBUG
75static cl::opt<bool>
Lang Hames8f31f442014-10-09 18:20:51 +000076PBQPDumpGraphs("pbqp-dump-graphs",
Lang Hames95e021f2012-03-26 23:07:23 +000077 cl::desc("Dump graphs for each function/round in the compilation unit."),
78 cl::init(false), cl::Hidden);
79#endif
80
Lang Hamesfd1bc422010-09-23 04:28:54 +000081namespace {
82
83///
84/// PBQP based allocators solve the register allocation problem by mapping
85/// register allocation problems to Partitioned Boolean Quadratic
86/// Programming problems.
87class RegAllocPBQP : public MachineFunctionPass {
88public:
89
90 static char ID;
91
92 /// Construct a PBQP register allocator.
Lang Hames8f31f442014-10-09 18:20:51 +000093 RegAllocPBQP(char *cPassID = nullptr)
94 : MachineFunctionPass(ID), customPassID(cPassID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +000095 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
96 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000097 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000098 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000099 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000100
101 /// Return the pass name.
Craig Topper4584cd52014-03-07 09:26:03 +0000102 const char* getPassName() const override {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000103 return "PBQP Register Allocator";
104 }
105
106 /// PBQP analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000107 void getAnalysisUsage(AnalysisUsage &au) const override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000108
109 /// Perform register allocation
Craig Topper4584cd52014-03-07 09:26:03 +0000110 bool runOnMachineFunction(MachineFunction &MF) override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000111
Matthias Braun90799ce2016-08-23 21:19:49 +0000112 MachineFunctionProperties getRequiredProperties() const override {
113 return MachineFunctionProperties().set(
114 MachineFunctionProperties::Property::NoPHIs);
115 }
116
Lang Hamesfd1bc422010-09-23 04:28:54 +0000117private:
118
119 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
120 typedef std::vector<const LiveInterval*> Node2LIMap;
121 typedef std::vector<unsigned> AllowedSet;
122 typedef std::vector<AllowedSet> AllowedSetMap;
123 typedef std::pair<unsigned, unsigned> RegPair;
124 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000125 typedef std::set<unsigned> RegSet;
126
Lang Hames934625e2011-06-17 07:09:01 +0000127 char *customPassID;
128
Lang Hames8f31f442014-10-09 18:20:51 +0000129 RegSet VRegsToAlloc, EmptyIntervalVRegs;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000130
Wei Mi9a16d652016-04-13 03:08:27 +0000131 /// Inst which is a def of an original reg and whose defs are already all
132 /// dead after remat is saved in DeadRemats. The deletion of such inst is
133 /// postponed till all the allocations are done, so its remat expr is
134 /// always available for the remat of all the siblings of the original reg.
135 SmallPtrSet<MachineInstr *, 32> DeadRemats;
136
Lang Hamesfd1bc422010-09-23 04:28:54 +0000137 /// \brief Finds the initial set of vreg intervals to allocate.
Lang Hames8f31f442014-10-09 18:20:51 +0000138 void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS);
139
140 /// \brief Constructs an initial graph.
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000141 void initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM, Spiller &VRegSpiller);
142
143 /// \brief Spill the given VReg.
144 void spillVReg(unsigned VReg, SmallVectorImpl<unsigned> &NewIntervals,
145 MachineFunction &MF, LiveIntervals &LIS, VirtRegMap &VRM,
146 Spiller &VRegSpiller);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000147
Lang Hamesfd1bc422010-09-23 04:28:54 +0000148 /// \brief Given a solved PBQP problem maps this solution back to a register
149 /// assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000150 bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
151 const PBQP::Solution &Solution,
152 VirtRegMap &VRM,
153 Spiller &VRegSpiller);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000154
155 /// \brief Postprocessing before final spilling. Sets basic block "live in"
156 /// variables.
Lang Hames8f31f442014-10-09 18:20:51 +0000157 void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
158 VirtRegMap &VRM) const;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000159
Wei Mi9a16d652016-04-13 03:08:27 +0000160 void postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000161};
162
Lang Hamescb1e1012010-09-18 09:07:10 +0000163char RegAllocPBQP::ID = 0;
Evan Chengb25f4632008-10-02 18:29:27 +0000164
Lang Hames8f31f442014-10-09 18:20:51 +0000165/// @brief Set spill costs for each node in the PBQP reg-alloc graph.
166class SpillCosts : public PBQPRAConstraint {
167public:
168 void apply(PBQPRAGraph &G) override {
169 LiveIntervals &LIS = G.getMetadata().LIS;
170
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000171 // A minimum spill costs, so that register constraints can can be set
172 // without normalization in the [0.0:MinSpillCost( interval.
173 const PBQP::PBQPNum MinSpillCost = 10.0;
174
Lang Hames8f31f442014-10-09 18:20:51 +0000175 for (auto NId : G.nodeIds()) {
176 PBQP::PBQPNum SpillCost =
177 LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight;
178 if (SpillCost == 0.0)
179 SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000180 else
181 SpillCost += MinSpillCost;
Lang Hames8f31f442014-10-09 18:20:51 +0000182 PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
183 NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
184 G.setNodeCosts(NId, std::move(NodeCosts));
185 }
186 }
187};
188
189/// @brief Add interference edges between overlapping vregs.
190class Interference : public PBQPRAConstraint {
Lang Hamesad0962a2014-10-18 17:26:07 +0000191private:
192
Lang Hames5fe30ca2014-10-27 17:44:25 +0000193 typedef const PBQP::RegAlloc::AllowedRegVector* AllowedRegVecPtr;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000194 typedef std::pair<AllowedRegVecPtr, AllowedRegVecPtr> IKey;
195 typedef DenseMap<IKey, PBQPRAGraph::MatrixPtr> IMatrixCache;
196 typedef DenseSet<IKey> DisjointAllowedRegsCache;
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000197 typedef std::pair<PBQP::GraphBase::NodeId, PBQP::GraphBase::NodeId> IEdgeKey;
198 typedef DenseSet<IEdgeKey> IEdgeCache;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000199
200 bool haveDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
201 PBQPRAGraph::NodeId MId,
202 const DisjointAllowedRegsCache &D) const {
203 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
204 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
205
206 if (NRegs == MRegs)
207 return false;
208
209 if (NRegs < MRegs)
210 return D.count(IKey(NRegs, MRegs)) > 0;
Arnaud A. de Grandmaisona57ca812015-03-01 21:22:50 +0000211
212 return D.count(IKey(MRegs, NRegs)) > 0;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000213 }
214
215 void setDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
216 PBQPRAGraph::NodeId MId,
217 DisjointAllowedRegsCache &D) {
218 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
219 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
220
221 assert(NRegs != MRegs && "AllowedRegs can not be disjoint with itself");
222
223 if (NRegs < MRegs)
224 D.insert(IKey(NRegs, MRegs));
225 else
226 D.insert(IKey(MRegs, NRegs));
227 }
Lang Hames5fe30ca2014-10-27 17:44:25 +0000228
Lang Hamesad0962a2014-10-18 17:26:07 +0000229 // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
230 // for the fast interference graph construction algorithm. The last is there
231 // to save us from looking up node ids via the VRegToNode map in the graph
232 // metadata.
233 typedef std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>
234 IntervalInfo;
235
236 static SlotIndex getStartPoint(const IntervalInfo &I) {
237 return std::get<0>(I)->segments[std::get<1>(I)].start;
238 }
239
240 static SlotIndex getEndPoint(const IntervalInfo &I) {
241 return std::get<0>(I)->segments[std::get<1>(I)].end;
242 }
243
244 static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
245 return std::get<2>(I);
246 }
247
248 static bool lowestStartPoint(const IntervalInfo &I1,
249 const IntervalInfo &I2) {
250 // Condition reversed because priority queue has the *highest* element at
251 // the front, rather than the lowest.
252 return getStartPoint(I1) > getStartPoint(I2);
253 }
254
255 static bool lowestEndPoint(const IntervalInfo &I1,
256 const IntervalInfo &I2) {
257 SlotIndex E1 = getEndPoint(I1);
258 SlotIndex E2 = getEndPoint(I2);
259
260 if (E1 < E2)
261 return true;
262
263 if (E1 > E2)
264 return false;
265
266 // If two intervals end at the same point, we need a way to break the tie or
267 // the set will assume they're actually equal and refuse to insert a
268 // "duplicate". Just compare the vregs - fast and guaranteed unique.
269 return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
270 }
271
272 static bool isAtLastSegment(const IntervalInfo &I) {
273 return std::get<1>(I) == std::get<0>(I)->size() - 1;
274 }
275
276 static IntervalInfo nextSegment(const IntervalInfo &I) {
277 return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
278 }
279
Lang Hames8f31f442014-10-09 18:20:51 +0000280public:
281
282 void apply(PBQPRAGraph &G) override {
Lang Hamesad0962a2014-10-18 17:26:07 +0000283 // The following is loosely based on the linear scan algorithm introduced in
284 // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
285 // isn't linear, because the size of the active set isn't bound by the
286 // number of registers, but rather the size of the largest clique in the
287 // graph. Still, we expect this to be better than N^2.
Lang Hames8f31f442014-10-09 18:20:51 +0000288 LiveIntervals &LIS = G.getMetadata().LIS;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000289
290 // Interferenc matrices are incredibly regular - they're only a function of
291 // the allowed sets, so we cache them to avoid the overhead of constructing
292 // and uniquing them.
293 IMatrixCache C;
Lang Hames8f31f442014-10-09 18:20:51 +0000294
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000295 // Finding an edge is expensive in the worst case (O(max_clique(G))). So
296 // cache locally edges we have already seen.
297 IEdgeCache EC;
298
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000299 // Cache known disjoint allowed registers pairs
300 DisjointAllowedRegsCache D;
301
Lang Hamesad0962a2014-10-18 17:26:07 +0000302 typedef std::set<IntervalInfo, decltype(&lowestEndPoint)> IntervalSet;
303 typedef std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
304 decltype(&lowestStartPoint)> IntervalQueue;
305 IntervalSet Active(lowestEndPoint);
306 IntervalQueue Inactive(lowestStartPoint);
Lang Hames8f31f442014-10-09 18:20:51 +0000307
Lang Hamesad0962a2014-10-18 17:26:07 +0000308 // Start by building the inactive set.
309 for (auto NId : G.nodeIds()) {
310 unsigned VReg = G.getNodeMetadata(NId).getVReg();
311 LiveInterval &LI = LIS.getInterval(VReg);
312 assert(!LI.empty() && "PBQP graph contains node for empty interval");
313 Inactive.push(std::make_tuple(&LI, 0, NId));
314 }
Lang Hames8f31f442014-10-09 18:20:51 +0000315
Lang Hamesad0962a2014-10-18 17:26:07 +0000316 while (!Inactive.empty()) {
317 // Tentatively grab the "next" interval - this choice may be overriden
318 // below.
319 IntervalInfo Cur = Inactive.top();
320
321 // Retire any active intervals that end before Cur starts.
322 IntervalSet::iterator RetireItr = Active.begin();
323 while (RetireItr != Active.end() &&
324 (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
325 // If this interval has subsequent segments, add the next one to the
326 // inactive list.
327 if (!isAtLastSegment(*RetireItr))
328 Inactive.push(nextSegment(*RetireItr));
329
330 ++RetireItr;
Lang Hames8f31f442014-10-09 18:20:51 +0000331 }
Lang Hamesad0962a2014-10-18 17:26:07 +0000332 Active.erase(Active.begin(), RetireItr);
333
334 // One of the newly retired segments may actually start before the
335 // Cur segment, so re-grab the front of the inactive list.
336 Cur = Inactive.top();
337 Inactive.pop();
338
339 // At this point we know that Cur overlaps all active intervals. Add the
340 // interference edges.
341 PBQP::GraphBase::NodeId NId = getNodeId(Cur);
342 for (const auto &A : Active) {
343 PBQP::GraphBase::NodeId MId = getNodeId(A);
344
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000345 // Do not add an edge when the nodes' allowed registers do not
346 // intersect: there is obviously no interference.
347 if (haveDisjointAllowedRegs(G, NId, MId, D))
348 continue;
349
Lang Hamesad0962a2014-10-18 17:26:07 +0000350 // Check that we haven't already added this edge
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000351 IEdgeKey EK(std::min(NId, MId), std::max(NId, MId));
352 if (EC.count(EK))
Lang Hamesad0962a2014-10-18 17:26:07 +0000353 continue;
354
355 // This is a new edge - add it to the graph.
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000356 if (!createInterferenceEdge(G, NId, MId, C))
357 setDisjointAllowedRegs(G, NId, MId, D);
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000358 else
359 EC.insert(EK);
Lang Hamesad0962a2014-10-18 17:26:07 +0000360 }
361
362 // Finally, add Cur to the Active set.
363 Active.insert(Cur);
Lang Hames8f31f442014-10-09 18:20:51 +0000364 }
365 }
366
367private:
368
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000369 // Create an Interference edge and add it to the graph, unless it is
370 // a null matrix, meaning the nodes' allowed registers do not have any
371 // interference. This case occurs frequently between integer and floating
372 // point registers for example.
373 // return true iff both nodes interferes.
374 bool createInterferenceEdge(PBQPRAGraph &G,
375 PBQPRAGraph::NodeId NId, PBQPRAGraph::NodeId MId,
376 IMatrixCache &C) {
Lang Hames5fe30ca2014-10-27 17:44:25 +0000377
378 const TargetRegisterInfo &TRI =
Eric Christopher7592b0c2015-01-27 08:27:06 +0000379 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames5fe30ca2014-10-27 17:44:25 +0000380 const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
381 const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
382
383 // Try looking the edge costs up in the IMatrixCache first.
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000384 IKey K(&NRegs, &MRegs);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000385 IMatrixCache::iterator I = C.find(K);
386 if (I != C.end()) {
387 G.addEdgeBypassingCostAllocator(NId, MId, I->second);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000388 return true;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000389 }
390
391 PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000392 bool NodesInterfere = false;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000393 for (unsigned I = 0; I != NRegs.size(); ++I) {
394 unsigned PRegN = NRegs[I];
395 for (unsigned J = 0; J != MRegs.size(); ++J) {
396 unsigned PRegM = MRegs[J];
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000397 if (TRI.regsOverlap(PRegN, PRegM)) {
Lang Hames8f31f442014-10-09 18:20:51 +0000398 M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000399 NodesInterfere = true;
400 }
Lang Hames8f31f442014-10-09 18:20:51 +0000401 }
402 }
403
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000404 if (!NodesInterfere)
405 return false;
406
Lang Hames5fe30ca2014-10-27 17:44:25 +0000407 PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
408 C[K] = G.getEdgeCostsPtr(EId);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000409
410 return true;
Lang Hames8f31f442014-10-09 18:20:51 +0000411 }
412};
413
414
415class Coalescing : public PBQPRAConstraint {
416public:
417 void apply(PBQPRAGraph &G) override {
418 MachineFunction &MF = G.getMetadata().MF;
419 MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
Eric Christopher7592b0c2015-01-27 08:27:06 +0000420 CoalescerPair CP(*MF.getSubtarget().getRegisterInfo());
Lang Hames8f31f442014-10-09 18:20:51 +0000421
422 // Scan the machine function and add a coalescing cost whenever CoalescerPair
423 // gives the Ok.
424 for (const auto &MBB : MF) {
425 for (const auto &MI : MBB) {
426
427 // Skip not-coalescable or already coalesced copies.
428 if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
429 continue;
430
431 unsigned DstReg = CP.getDstReg();
432 unsigned SrcReg = CP.getSrcReg();
433
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000434 const float Scale = 1.0f / MBFI.getEntryFreq();
435 PBQP::PBQPNum CBenefit = MBFI.getBlockFreq(&MBB).getFrequency() * Scale;
Lang Hames8f31f442014-10-09 18:20:51 +0000436
437 if (CP.isPhys()) {
438 if (!MF.getRegInfo().isAllocatable(DstReg))
439 continue;
440
441 PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
442
Lang Hames5fe30ca2014-10-27 17:44:25 +0000443 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
444 G.getNodeMetadata(NId).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000445
446 unsigned PRegOpt = 0;
447 while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
448 ++PRegOpt;
449
450 if (PRegOpt < Allowed.size()) {
451 PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000452 NewCosts[PRegOpt + 1] -= CBenefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000453 G.setNodeCosts(NId, std::move(NewCosts));
454 }
455 } else {
456 PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
457 PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000458 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
459 &G.getNodeMetadata(N1Id).getAllowedRegs();
460 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
461 &G.getNodeMetadata(N2Id).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000462
463 PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
464 if (EId == G.invalidEdgeId()) {
465 PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
466 Allowed2->size() + 1, 0);
467 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
468 G.addEdge(N1Id, N2Id, std::move(Costs));
469 } else {
470 if (G.getEdgeNode1Id(EId) == N2Id) {
471 std::swap(N1Id, N2Id);
472 std::swap(Allowed1, Allowed2);
473 }
474 PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
475 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
Arnaud A. de Grandmaisonde790262015-02-11 08:25:36 +0000476 G.updateEdgeCosts(EId, std::move(Costs));
Lang Hames8f31f442014-10-09 18:20:51 +0000477 }
478 }
479 }
480 }
481 }
482
483private:
484
485 void addVirtRegCoalesce(
Lang Hames5fe30ca2014-10-27 17:44:25 +0000486 PBQPRAGraph::RawMatrix &CostMat,
487 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
488 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
489 PBQP::PBQPNum Benefit) {
Lang Hames8f31f442014-10-09 18:20:51 +0000490 assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
491 assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
492 for (unsigned I = 0; I != Allowed1.size(); ++I) {
493 unsigned PReg1 = Allowed1[I];
494 for (unsigned J = 0; J != Allowed2.size(); ++J) {
495 unsigned PReg2 = Allowed2[J];
496 if (PReg1 == PReg2)
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000497 CostMat[I + 1][J + 1] -= Benefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000498 }
499 }
500 }
501
502};
503
Lang Hamesfd1bc422010-09-23 04:28:54 +0000504} // End anonymous namespace.
505
Lang Hames8f31f442014-10-09 18:20:51 +0000506// Out-of-line destructor/anchor for PBQPRAConstraint.
507PBQPRAConstraint::~PBQPRAConstraint() {}
508void PBQPRAConstraint::anchor() {}
509void PBQPRAConstraintList::anchor() {}
Lang Hamescb1e1012010-09-18 09:07:10 +0000510
511void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hamesb13b6a02011-12-06 01:45:57 +0000512 au.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000513 au.addRequired<AAResultsWrapperPass>();
514 au.addPreserved<AAResultsWrapperPass>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000515 au.addRequired<SlotIndexes>();
516 au.addPreserved<SlotIndexes>();
517 au.addRequired<LiveIntervals>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000518 au.addPreserved<LiveIntervals>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000519 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames934625e2011-06-17 07:09:01 +0000520 if (customPassID)
521 au.addRequiredID(*customPassID);
Lang Hamescb1e1012010-09-18 09:07:10 +0000522 au.addRequired<LiveStacks>();
523 au.addPreserved<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000524 au.addRequired<MachineBlockFrequencyInfo>();
525 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames7d99d792013-07-01 20:47:47 +0000526 au.addRequired<MachineLoopInfo>();
527 au.addPreserved<MachineLoopInfo>();
Lang Hamesb13b6a02011-12-06 01:45:57 +0000528 au.addRequired<MachineDominatorTree>();
529 au.addPreserved<MachineDominatorTree>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000530 au.addRequired<VirtRegMap>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000531 au.addPreserved<VirtRegMap>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000532 MachineFunctionPass::getAnalysisUsage(au);
533}
534
Lang Hames8f31f442014-10-09 18:20:51 +0000535void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
536 LiveIntervals &LIS) {
537 const MachineRegisterInfo &MRI = MF.getRegInfo();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000538
539 // Iterate over all live ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000540 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
541 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
542 if (MRI.reg_nodbg_empty(Reg))
Lang Hames49ab8bc2008-11-16 12:12:54 +0000543 continue;
Lang Hames8f31f442014-10-09 18:20:51 +0000544 LiveInterval &LI = LIS.getInterval(Reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000545
546 // If this live interval is non-empty we will use pbqp to allocate it.
547 // Empty intervals we allocate in a simple post-processing stage in
548 // finalizeAlloc.
Lang Hames8f31f442014-10-09 18:20:51 +0000549 if (!LI.empty()) {
550 VRegsToAlloc.insert(LI.reg);
Lang Hamesc702ba62010-11-12 05:47:21 +0000551 } else {
Lang Hames8f31f442014-10-09 18:20:51 +0000552 EmptyIntervalVRegs.insert(LI.reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000553 }
554 }
Evan Chengb25f4632008-10-02 18:29:27 +0000555}
556
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000557static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI,
558 const MachineFunction &MF) {
559 const MCPhysReg *CSR = TRI.getCalleeSavedRegs(&MF);
560 for (unsigned i = 0; CSR[i] != 0; ++i)
561 if (TRI.regsOverlap(reg, CSR[i]))
562 return true;
563 return false;
564}
565
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000566void RegAllocPBQP::initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM,
567 Spiller &VRegSpiller) {
Lang Hames8f31f442014-10-09 18:20:51 +0000568 MachineFunction &MF = G.getMetadata().MF;
569
570 LiveIntervals &LIS = G.getMetadata().LIS;
571 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
572 const TargetRegisterInfo &TRI =
Eric Christopher7592b0c2015-01-27 08:27:06 +0000573 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames8f31f442014-10-09 18:20:51 +0000574
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000575 std::vector<unsigned> Worklist(VRegsToAlloc.begin(), VRegsToAlloc.end());
576
577 while (!Worklist.empty()) {
578 unsigned VReg = Worklist.back();
579 Worklist.pop_back();
580
Lang Hames8f31f442014-10-09 18:20:51 +0000581 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
582 LiveInterval &VRegLI = LIS.getInterval(VReg);
583
584 // Record any overlaps with regmask operands.
585 BitVector RegMaskOverlaps;
586 LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
587
588 // Compute an initial allowed set for the current vreg.
589 std::vector<unsigned> VRegAllowed;
590 ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
591 for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
592 unsigned PReg = RawPRegOrder[I];
593 if (MRI.isReserved(PReg))
594 continue;
595
596 // vregLI crosses a regmask operand that clobbers preg.
597 if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
598 continue;
599
600 // vregLI overlaps fixed regunit interference.
601 bool Interference = false;
602 for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
603 if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
604 Interference = true;
605 break;
606 }
607 }
608 if (Interference)
609 continue;
610
611 // preg is usable for this virtual register.
612 VRegAllowed.push_back(PReg);
613 }
614
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000615 // Check for vregs that have no allowed registers. These should be
616 // pre-spilled and the new vregs added to the worklist.
617 if (VRegAllowed.empty()) {
618 SmallVector<unsigned, 8> NewVRegs;
619 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000620 Worklist.insert(Worklist.end(), NewVRegs.begin(), NewVRegs.end());
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000621 continue;
622 }
623
Lang Hames8f31f442014-10-09 18:20:51 +0000624 PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000625
626 // Tweak cost of callee saved registers, as using then force spilling and
627 // restoring them. This would only happen in the prologue / epilogue though.
628 for (unsigned i = 0; i != VRegAllowed.size(); ++i)
629 if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF))
630 NodeCosts[1 + i] += 1.0;
631
Lang Hames8f31f442014-10-09 18:20:51 +0000632 PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
633 G.getNodeMetadata(NId).setVReg(VReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000634 G.getNodeMetadata(NId).setAllowedRegs(
635 G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
Lang Hames8f31f442014-10-09 18:20:51 +0000636 G.getMetadata().setNodeIdForVReg(VReg, NId);
637 }
638}
639
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000640void RegAllocPBQP::spillVReg(unsigned VReg,
641 SmallVectorImpl<unsigned> &NewIntervals,
642 MachineFunction &MF, LiveIntervals &LIS,
643 VirtRegMap &VRM, Spiller &VRegSpiller) {
644
645 VRegsToAlloc.erase(VReg);
Wei Mi9a16d652016-04-13 03:08:27 +0000646 LiveRangeEdit LRE(&LIS.getInterval(VReg), NewIntervals, MF, LIS, &VRM,
647 nullptr, &DeadRemats);
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000648 VRegSpiller.spill(LRE);
649
650 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
651 (void)TRI;
652 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> SPILLED (Cost: "
653 << LRE.getParent().weight << ", New vregs: ");
654
655 // Copy any newly inserted live intervals into the list of regs to
656 // allocate.
657 for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
658 I != E; ++I) {
659 const LiveInterval &LI = LIS.getInterval(*I);
660 assert(!LI.empty() && "Empty spill range.");
661 DEBUG(dbgs() << PrintReg(LI.reg, &TRI) << " ");
662 VRegsToAlloc.insert(LI.reg);
663 }
664
665 DEBUG(dbgs() << ")\n");
666}
667
Lang Hames8f31f442014-10-09 18:20:51 +0000668bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
669 const PBQP::Solution &Solution,
670 VirtRegMap &VRM,
671 Spiller &VRegSpiller) {
672 MachineFunction &MF = G.getMetadata().MF;
673 LiveIntervals &LIS = G.getMetadata().LIS;
Eric Christopher7592b0c2015-01-27 08:27:06 +0000674 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
Lang Hames8f31f442014-10-09 18:20:51 +0000675 (void)TRI;
676
Lang Hamescb1e1012010-09-18 09:07:10 +0000677 // Set to true if we have any spills
Lang Hames8f31f442014-10-09 18:20:51 +0000678 bool AnotherRoundNeeded = false;
Lang Hamescb1e1012010-09-18 09:07:10 +0000679
680 // Clear the existing allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000681 VRM.clearAllVirt();
Lang Hamescb1e1012010-09-18 09:07:10 +0000682
Lang Hamescb1e1012010-09-18 09:07:10 +0000683 // Iterate over the nodes mapping the PBQP solution to a register
684 // assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000685 for (auto NId : G.nodeIds()) {
686 unsigned VReg = G.getNodeMetadata(NId).getVReg();
687 unsigned AllocOption = Solution.getSelection(NId);
Lang Hamescb1e1012010-09-18 09:07:10 +0000688
Lang Hames8f31f442014-10-09 18:20:51 +0000689 if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
Lang Hames5fe30ca2014-10-27 17:44:25 +0000690 unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
Lang Hames8f31f442014-10-09 18:20:51 +0000691 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> "
692 << TRI.getName(PReg) << "\n");
693 assert(PReg != 0 && "Invalid preg selected.");
694 VRM.assignVirt2Phys(VReg, PReg);
695 } else {
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000696 // Spill VReg. If this introduces new intervals we'll need another round
697 // of allocation.
698 SmallVector<unsigned, 8> NewVRegs;
699 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
700 AnotherRoundNeeded |= !NewVRegs.empty();
Lang Hamescb1e1012010-09-18 09:07:10 +0000701 }
702 }
703
Lang Hames8f31f442014-10-09 18:20:51 +0000704 return !AnotherRoundNeeded;
Lang Hamescb1e1012010-09-18 09:07:10 +0000705}
706
Lang Hames8f31f442014-10-09 18:20:51 +0000707void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
708 LiveIntervals &LIS,
709 VirtRegMap &VRM) const {
710 MachineRegisterInfo &MRI = MF.getRegInfo();
711
Lang Hames49ab8bc2008-11-16 12:12:54 +0000712 // First allocate registers for the empty intervals.
Lang Hamescb1e1012010-09-18 09:07:10 +0000713 for (RegSet::const_iterator
Lang Hames8f31f442014-10-09 18:20:51 +0000714 I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
715 I != E; ++I) {
716 LiveInterval &LI = LIS.getInterval(*I);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000717
Lang Hames8f31f442014-10-09 18:20:51 +0000718 unsigned PReg = MRI.getSimpleHint(LI.reg);
Lang Hames88fae6f2009-08-06 23:32:48 +0000719
Lang Hames8f31f442014-10-09 18:20:51 +0000720 if (PReg == 0) {
721 const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg);
722 PReg = RC.getRawAllocationOrder(MF).front();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000723 }
Misha Brukmanda467482009-01-08 15:50:22 +0000724
Lang Hames8f31f442014-10-09 18:20:51 +0000725 VRM.assignVirt2Phys(LI.reg, PReg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000726 }
Lang Hames49ab8bc2008-11-16 12:12:54 +0000727}
728
Wei Mi9a16d652016-04-13 03:08:27 +0000729void RegAllocPBQP::postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS) {
730 VRegSpiller.postOptimization();
731 /// Remove dead defs because of rematerialization.
732 for (auto DeadInst : DeadRemats) {
733 LIS.RemoveMachineInstrFromMaps(*DeadInst);
734 DeadInst->eraseFromParent();
735 }
736 DeadRemats.clear();
737}
738
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000739static inline float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size,
740 unsigned NumInstr) {
741 // All intervals have a spill weight that is mostly proportional to the number
742 // of uses, with uses in loops having a bigger weight.
743 return NumInstr * normalizeSpillWeight(UseDefFreq, Size, 1);
744}
745
Lang Hamescb1e1012010-09-18 09:07:10 +0000746bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames8f31f442014-10-09 18:20:51 +0000747 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
748 MachineBlockFrequencyInfo &MBFI =
749 getAnalysis<MachineBlockFrequencyInfo>();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000750
Lang Hames8f31f442014-10-09 18:20:51 +0000751 VirtRegMap &VRM = getAnalysis<VirtRegMap>();
Evan Chengb25f4632008-10-02 18:29:27 +0000752
Robert Lougher11a44b72015-08-10 11:59:44 +0000753 calculateSpillWeightsAndHints(LIS, MF, &VRM, getAnalysis<MachineLoopInfo>(),
754 MBFI, normalizePBQPSpillWeight);
755
Lang Hames8f31f442014-10-09 18:20:51 +0000756 std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +0000757
Lang Hames8f31f442014-10-09 18:20:51 +0000758 MF.getRegInfo().freezeReservedRegs(MF);
Evan Chengb25f4632008-10-02 18:29:27 +0000759
Lang Hames8f31f442014-10-09 18:20:51 +0000760 DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000761
Evan Chengb25f4632008-10-02 18:29:27 +0000762 // Allocator main loop:
Misha Brukmanda467482009-01-08 15:50:22 +0000763 //
Evan Chengb25f4632008-10-02 18:29:27 +0000764 // * Map current regalloc problem to a PBQP problem
765 // * Solve the PBQP problem
766 // * Map the solution back to a register allocation
767 // * Spill if necessary
Misha Brukmanda467482009-01-08 15:50:22 +0000768 //
Evan Chengb25f4632008-10-02 18:29:27 +0000769 // This process is continued till no more spills are generated.
770
Lang Hames49ab8bc2008-11-16 12:12:54 +0000771 // Find the vreg intervals in need of allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000772 findVRegIntervalsToAlloc(MF, LIS);
Misha Brukmanda467482009-01-08 15:50:22 +0000773
Craig Toppera538d832012-08-22 06:07:19 +0000774#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000775 const Function &F = *MF.getFunction();
776 std::string FullyQualifiedName =
777 F.getParent()->getModuleIdentifier() + "." + F.getName().str();
Craig Toppera538d832012-08-22 06:07:19 +0000778#endif
Lang Hames95e021f2012-03-26 23:07:23 +0000779
Lang Hames49ab8bc2008-11-16 12:12:54 +0000780 // If there are non-empty intervals allocate them using pbqp.
Lang Hames8f31f442014-10-09 18:20:51 +0000781 if (!VRegsToAlloc.empty()) {
Evan Chengb25f4632008-10-02 18:29:27 +0000782
Eric Christopher7592b0c2015-01-27 08:27:06 +0000783 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
Lang Hames8f31f442014-10-09 18:20:51 +0000784 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
785 llvm::make_unique<PBQPRAConstraintList>();
786 ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
787 ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
788 if (PBQPCoalescing)
789 ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
790 ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
Lang Hames49ab8bc2008-11-16 12:12:54 +0000791
Lang Hames8f31f442014-10-09 18:20:51 +0000792 bool PBQPAllocComplete = false;
793 unsigned Round = 0;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000794
Lang Hames8f31f442014-10-09 18:20:51 +0000795 while (!PBQPAllocComplete) {
796 DEBUG(dbgs() << " PBQP Regalloc round " << Round << ":\n");
797
798 PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000799 initializeGraph(G, VRM, *VRegSpiller);
Lang Hames8f31f442014-10-09 18:20:51 +0000800 ConstraintsRoot->apply(G);
Lang Hames95e021f2012-03-26 23:07:23 +0000801
802#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000803 if (PBQPDumpGraphs) {
804 std::ostringstream RS;
805 RS << Round;
806 std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
807 ".pbqpgraph";
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000808 std::error_code EC;
Lang Hames8f31f442014-10-09 18:20:51 +0000809 raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text);
810 DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
811 << GraphFileName << "\"\n");
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000812 G.dump(OS);
Lang Hames95e021f2012-03-26 23:07:23 +0000813 }
814#endif
815
Lang Hames8f31f442014-10-09 18:20:51 +0000816 PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
817 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
818 ++Round;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000819 }
Evan Chengb25f4632008-10-02 18:29:27 +0000820 }
821
Lang Hames49ab8bc2008-11-16 12:12:54 +0000822 // Finalise allocation, allocate empty ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000823 finalizeAlloc(MF, LIS, VRM);
Wei Mi9a16d652016-04-13 03:08:27 +0000824 postOptimization(*VRegSpiller, LIS);
Lang Hames8f31f442014-10-09 18:20:51 +0000825 VRegsToAlloc.clear();
826 EmptyIntervalVRegs.clear();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000827
Lang Hames8f31f442014-10-09 18:20:51 +0000828 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000829
Misha Brukmanda467482009-01-08 15:50:22 +0000830 return true;
Evan Chengb25f4632008-10-02 18:29:27 +0000831}
832
Matthias Braunc07cbc82015-12-04 01:31:59 +0000833/// Create Printable object for node and register info.
834static Printable PrintNodeInfo(PBQP::RegAlloc::PBQPRAGraph::NodeId NId,
835 const PBQP::RegAlloc::PBQPRAGraph &G) {
836 return Printable([NId, &G](raw_ostream &OS) {
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000837 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
838 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
839 unsigned VReg = G.getNodeMetadata(NId).getVReg();
840 const char *RegClassName = TRI->getRegClassName(MRI.getRegClass(VReg));
841 OS << NId << " (" << RegClassName << ':' << PrintReg(VReg, TRI) << ')';
Matthias Braunc07cbc82015-12-04 01:31:59 +0000842 });
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000843}
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000844
845void PBQP::RegAlloc::PBQPRAGraph::dump(raw_ostream &OS) const {
846 for (auto NId : nodeIds()) {
847 const Vector &Costs = getNodeCosts(NId);
848 assert(Costs.getLength() != 0 && "Empty vector in graph.");
849 OS << PrintNodeInfo(NId, *this) << ": " << Costs << '\n';
850 }
851 OS << '\n';
852
853 for (auto EId : edgeIds()) {
854 NodeId N1Id = getEdgeNode1Id(EId);
855 NodeId N2Id = getEdgeNode2Id(EId);
856 assert(N1Id != N2Id && "PBQP graphs should not have self-edges.");
857 const Matrix &M = getEdgeCosts(EId);
858 assert(M.getRows() != 0 && "No rows in matrix.");
859 assert(M.getCols() != 0 && "No cols in matrix.");
860 OS << PrintNodeInfo(N1Id, *this) << ' ' << M.getRows() << " rows / ";
861 OS << PrintNodeInfo(N2Id, *this) << ' ' << M.getCols() << " cols:\n";
862 OS << M << '\n';
863 }
864}
865
Yaron Kereneb2a2542016-01-29 20:50:44 +0000866LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump() const { dump(dbgs()); }
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000867
868void PBQP::RegAlloc::PBQPRAGraph::printDot(raw_ostream &OS) const {
869 OS << "graph {\n";
870 for (auto NId : nodeIds()) {
871 OS << " node" << NId << " [ label=\""
872 << PrintNodeInfo(NId, *this) << "\\n"
873 << getNodeCosts(NId) << "\" ]\n";
874 }
875
876 OS << " edge [ len=" << nodeIds().size() << " ]\n";
877 for (auto EId : edgeIds()) {
878 OS << " node" << getEdgeNode1Id(EId)
879 << " -- node" << getEdgeNode2Id(EId)
880 << " [ label=\"";
881 const Matrix &EdgeCosts = getEdgeCosts(EId);
882 for (unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
883 OS << EdgeCosts.getRowAsVector(i) << "\\n";
884 }
885 OS << "\" ]\n";
886 }
887 OS << "}\n";
888}
889
Lang Hames8f31f442014-10-09 18:20:51 +0000890FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
891 return new RegAllocPBQP(customPassID);
Evan Chengb25f4632008-10-02 18:29:27 +0000892}
893
Lang Hamesfd1bc422010-09-23 04:28:54 +0000894FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Lang Hames8f31f442014-10-09 18:20:51 +0000895 return createPBQPRegisterAllocator();
Lang Hamescb1e1012010-09-18 09:07:10 +0000896}
Evan Chengb25f4632008-10-02 18:29:27 +0000897
898#undef DEBUG_TYPE