blob: fa45dd236545865b70b87403f747a8c0913e40c1 [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.
129 void initializeGraph(PBQPRAGraph &G);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000130
Lang Hamesfd1bc422010-09-23 04:28:54 +0000131 /// \brief Given a solved PBQP problem maps this solution back to a register
132 /// assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000133 bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
134 const PBQP::Solution &Solution,
135 VirtRegMap &VRM,
136 Spiller &VRegSpiller);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000137
138 /// \brief Postprocessing before final spilling. Sets basic block "live in"
139 /// variables.
Lang Hames8f31f442014-10-09 18:20:51 +0000140 void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
141 VirtRegMap &VRM) const;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000142
143};
144
Lang Hamescb1e1012010-09-18 09:07:10 +0000145char RegAllocPBQP::ID = 0;
Evan Chengb25f4632008-10-02 18:29:27 +0000146
Lang Hames8f31f442014-10-09 18:20:51 +0000147/// @brief Set spill costs for each node in the PBQP reg-alloc graph.
148class SpillCosts : public PBQPRAConstraint {
149public:
150 void apply(PBQPRAGraph &G) override {
151 LiveIntervals &LIS = G.getMetadata().LIS;
152
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000153 // A minimum spill costs, so that register constraints can can be set
154 // without normalization in the [0.0:MinSpillCost( interval.
155 const PBQP::PBQPNum MinSpillCost = 10.0;
156
Lang Hames8f31f442014-10-09 18:20:51 +0000157 for (auto NId : G.nodeIds()) {
158 PBQP::PBQPNum SpillCost =
159 LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight;
160 if (SpillCost == 0.0)
161 SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000162 else
163 SpillCost += MinSpillCost;
Lang Hames8f31f442014-10-09 18:20:51 +0000164 PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
165 NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
166 G.setNodeCosts(NId, std::move(NodeCosts));
167 }
168 }
169};
170
171/// @brief Add interference edges between overlapping vregs.
172class Interference : public PBQPRAConstraint {
Lang Hamesad0962a2014-10-18 17:26:07 +0000173private:
174
Lang Hames5fe30ca2014-10-27 17:44:25 +0000175private:
176
177 typedef const PBQP::RegAlloc::AllowedRegVector* AllowedRegVecPtr;
178 typedef std::pair<AllowedRegVecPtr, AllowedRegVecPtr> IMatrixKey;
179 typedef DenseMap<IMatrixKey, PBQPRAGraph::MatrixPtr> IMatrixCache;
180
Lang Hamesad0962a2014-10-18 17:26:07 +0000181 // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
182 // for the fast interference graph construction algorithm. The last is there
183 // to save us from looking up node ids via the VRegToNode map in the graph
184 // metadata.
185 typedef std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>
186 IntervalInfo;
187
188 static SlotIndex getStartPoint(const IntervalInfo &I) {
189 return std::get<0>(I)->segments[std::get<1>(I)].start;
190 }
191
192 static SlotIndex getEndPoint(const IntervalInfo &I) {
193 return std::get<0>(I)->segments[std::get<1>(I)].end;
194 }
195
196 static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
197 return std::get<2>(I);
198 }
199
200 static bool lowestStartPoint(const IntervalInfo &I1,
201 const IntervalInfo &I2) {
202 // Condition reversed because priority queue has the *highest* element at
203 // the front, rather than the lowest.
204 return getStartPoint(I1) > getStartPoint(I2);
205 }
206
207 static bool lowestEndPoint(const IntervalInfo &I1,
208 const IntervalInfo &I2) {
209 SlotIndex E1 = getEndPoint(I1);
210 SlotIndex E2 = getEndPoint(I2);
211
212 if (E1 < E2)
213 return true;
214
215 if (E1 > E2)
216 return false;
217
218 // If two intervals end at the same point, we need a way to break the tie or
219 // the set will assume they're actually equal and refuse to insert a
220 // "duplicate". Just compare the vregs - fast and guaranteed unique.
221 return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
222 }
223
224 static bool isAtLastSegment(const IntervalInfo &I) {
225 return std::get<1>(I) == std::get<0>(I)->size() - 1;
226 }
227
228 static IntervalInfo nextSegment(const IntervalInfo &I) {
229 return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
230 }
231
Lang Hames8f31f442014-10-09 18:20:51 +0000232public:
233
234 void apply(PBQPRAGraph &G) override {
Lang Hamesad0962a2014-10-18 17:26:07 +0000235 // The following is loosely based on the linear scan algorithm introduced in
236 // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
237 // isn't linear, because the size of the active set isn't bound by the
238 // number of registers, but rather the size of the largest clique in the
239 // graph. Still, we expect this to be better than N^2.
Lang Hames8f31f442014-10-09 18:20:51 +0000240 LiveIntervals &LIS = G.getMetadata().LIS;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000241
242 // Interferenc matrices are incredibly regular - they're only a function of
243 // the allowed sets, so we cache them to avoid the overhead of constructing
244 // and uniquing them.
245 IMatrixCache C;
Lang Hames8f31f442014-10-09 18:20:51 +0000246
Lang Hamesad0962a2014-10-18 17:26:07 +0000247 typedef std::set<IntervalInfo, decltype(&lowestEndPoint)> IntervalSet;
248 typedef std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
249 decltype(&lowestStartPoint)> IntervalQueue;
250 IntervalSet Active(lowestEndPoint);
251 IntervalQueue Inactive(lowestStartPoint);
Lang Hames8f31f442014-10-09 18:20:51 +0000252
Lang Hamesad0962a2014-10-18 17:26:07 +0000253 // Start by building the inactive set.
254 for (auto NId : G.nodeIds()) {
255 unsigned VReg = G.getNodeMetadata(NId).getVReg();
256 LiveInterval &LI = LIS.getInterval(VReg);
257 assert(!LI.empty() && "PBQP graph contains node for empty interval");
258 Inactive.push(std::make_tuple(&LI, 0, NId));
259 }
Lang Hames8f31f442014-10-09 18:20:51 +0000260
Lang Hamesad0962a2014-10-18 17:26:07 +0000261 while (!Inactive.empty()) {
262 // Tentatively grab the "next" interval - this choice may be overriden
263 // below.
264 IntervalInfo Cur = Inactive.top();
265
266 // Retire any active intervals that end before Cur starts.
267 IntervalSet::iterator RetireItr = Active.begin();
268 while (RetireItr != Active.end() &&
269 (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
270 // If this interval has subsequent segments, add the next one to the
271 // inactive list.
272 if (!isAtLastSegment(*RetireItr))
273 Inactive.push(nextSegment(*RetireItr));
274
275 ++RetireItr;
Lang Hames8f31f442014-10-09 18:20:51 +0000276 }
Lang Hamesad0962a2014-10-18 17:26:07 +0000277 Active.erase(Active.begin(), RetireItr);
278
279 // One of the newly retired segments may actually start before the
280 // Cur segment, so re-grab the front of the inactive list.
281 Cur = Inactive.top();
282 Inactive.pop();
283
284 // At this point we know that Cur overlaps all active intervals. Add the
285 // interference edges.
286 PBQP::GraphBase::NodeId NId = getNodeId(Cur);
287 for (const auto &A : Active) {
288 PBQP::GraphBase::NodeId MId = getNodeId(A);
289
290 // Check that we haven't already added this edge
291 // FIXME: findEdge is expensive in the worst case (O(max_clique(G))).
292 // It might be better to replace this with a local bit-matrix.
Lang Hames5fe30ca2014-10-27 17:44:25 +0000293 if (G.findEdge(NId, MId) != PBQPRAGraph::invalidEdgeId())
Lang Hamesad0962a2014-10-18 17:26:07 +0000294 continue;
295
296 // This is a new edge - add it to the graph.
Lang Hames5fe30ca2014-10-27 17:44:25 +0000297 createInterferenceEdge(G, NId, MId, C);
Lang Hamesad0962a2014-10-18 17:26:07 +0000298 }
299
300 // Finally, add Cur to the Active set.
301 Active.insert(Cur);
Lang Hames8f31f442014-10-09 18:20:51 +0000302 }
303 }
304
305private:
306
Lang Hames5fe30ca2014-10-27 17:44:25 +0000307 void createInterferenceEdge(PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
308 PBQPRAGraph::NodeId MId, IMatrixCache &C) {
309
310 const TargetRegisterInfo &TRI =
311 *G.getMetadata().MF.getTarget().getSubtargetImpl()->getRegisterInfo();
312
313 const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
314 const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
315
316 // Try looking the edge costs up in the IMatrixCache first.
317 IMatrixKey K(&NRegs, &MRegs);
318 IMatrixCache::iterator I = C.find(K);
319 if (I != C.end()) {
320 G.addEdgeBypassingCostAllocator(NId, MId, I->second);
321 return;
322 }
323
324 PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
325 for (unsigned I = 0; I != NRegs.size(); ++I) {
326 unsigned PRegN = NRegs[I];
327 for (unsigned J = 0; J != MRegs.size(); ++J) {
328 unsigned PRegM = MRegs[J];
Lang Hames8f31f442014-10-09 18:20:51 +0000329 if (TRI.regsOverlap(PRegN, PRegM))
330 M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
331 }
332 }
333
Lang Hames5fe30ca2014-10-27 17:44:25 +0000334 PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
335 C[K] = G.getEdgeCostsPtr(EId);
Lang Hames8f31f442014-10-09 18:20:51 +0000336 }
337};
338
339
340class Coalescing : public PBQPRAConstraint {
341public:
342 void apply(PBQPRAGraph &G) override {
343 MachineFunction &MF = G.getMetadata().MF;
344 MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
345 CoalescerPair CP(*MF.getTarget().getSubtargetImpl()->getRegisterInfo());
346
347 // Scan the machine function and add a coalescing cost whenever CoalescerPair
348 // gives the Ok.
349 for (const auto &MBB : MF) {
350 for (const auto &MI : MBB) {
351
352 // Skip not-coalescable or already coalesced copies.
353 if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
354 continue;
355
356 unsigned DstReg = CP.getDstReg();
357 unsigned SrcReg = CP.getSrcReg();
358
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000359 const float Scale = 1.0f / MBFI.getEntryFreq();
360 PBQP::PBQPNum CBenefit = MBFI.getBlockFreq(&MBB).getFrequency() * Scale;
Lang Hames8f31f442014-10-09 18:20:51 +0000361
362 if (CP.isPhys()) {
363 if (!MF.getRegInfo().isAllocatable(DstReg))
364 continue;
365
366 PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
367
Lang Hames5fe30ca2014-10-27 17:44:25 +0000368 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
369 G.getNodeMetadata(NId).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000370
371 unsigned PRegOpt = 0;
372 while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
373 ++PRegOpt;
374
375 if (PRegOpt < Allowed.size()) {
376 PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000377 NewCosts[PRegOpt + 1] -= CBenefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000378 G.setNodeCosts(NId, std::move(NewCosts));
379 }
380 } else {
381 PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
382 PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000383 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
384 &G.getNodeMetadata(N1Id).getAllowedRegs();
385 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
386 &G.getNodeMetadata(N2Id).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000387
388 PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
389 if (EId == G.invalidEdgeId()) {
390 PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
391 Allowed2->size() + 1, 0);
392 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
393 G.addEdge(N1Id, N2Id, std::move(Costs));
394 } else {
395 if (G.getEdgeNode1Id(EId) == N2Id) {
396 std::swap(N1Id, N2Id);
397 std::swap(Allowed1, Allowed2);
398 }
399 PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
400 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
401 G.setEdgeCosts(EId, std::move(Costs));
402 }
403 }
404 }
405 }
406 }
407
408private:
409
410 void addVirtRegCoalesce(
Lang Hames5fe30ca2014-10-27 17:44:25 +0000411 PBQPRAGraph::RawMatrix &CostMat,
412 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
413 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
414 PBQP::PBQPNum Benefit) {
Lang Hames8f31f442014-10-09 18:20:51 +0000415 assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
416 assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
417 for (unsigned I = 0; I != Allowed1.size(); ++I) {
418 unsigned PReg1 = Allowed1[I];
419 for (unsigned J = 0; J != Allowed2.size(); ++J) {
420 unsigned PReg2 = Allowed2[J];
421 if (PReg1 == PReg2)
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000422 CostMat[I + 1][J + 1] -= Benefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000423 }
424 }
425 }
426
427};
428
Lang Hamesfd1bc422010-09-23 04:28:54 +0000429} // End anonymous namespace.
430
Lang Hames8f31f442014-10-09 18:20:51 +0000431// Out-of-line destructor/anchor for PBQPRAConstraint.
432PBQPRAConstraint::~PBQPRAConstraint() {}
433void PBQPRAConstraint::anchor() {}
434void PBQPRAConstraintList::anchor() {}
Lang Hamescb1e1012010-09-18 09:07:10 +0000435
436void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hamesb13b6a02011-12-06 01:45:57 +0000437 au.setPreservesCFG();
438 au.addRequired<AliasAnalysis>();
439 au.addPreserved<AliasAnalysis>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000440 au.addRequired<SlotIndexes>();
441 au.addPreserved<SlotIndexes>();
442 au.addRequired<LiveIntervals>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000443 au.addPreserved<LiveIntervals>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000444 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames934625e2011-06-17 07:09:01 +0000445 if (customPassID)
446 au.addRequiredID(*customPassID);
Lang Hamescb1e1012010-09-18 09:07:10 +0000447 au.addRequired<LiveStacks>();
448 au.addPreserved<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000449 au.addRequired<MachineBlockFrequencyInfo>();
450 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames7d99d792013-07-01 20:47:47 +0000451 au.addRequired<MachineLoopInfo>();
452 au.addPreserved<MachineLoopInfo>();
Lang Hamesb13b6a02011-12-06 01:45:57 +0000453 au.addRequired<MachineDominatorTree>();
454 au.addPreserved<MachineDominatorTree>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000455 au.addRequired<VirtRegMap>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000456 au.addPreserved<VirtRegMap>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000457 MachineFunctionPass::getAnalysisUsage(au);
458}
459
Lang Hames8f31f442014-10-09 18:20:51 +0000460void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
461 LiveIntervals &LIS) {
462 const MachineRegisterInfo &MRI = MF.getRegInfo();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000463
464 // Iterate over all live ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000465 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
466 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
467 if (MRI.reg_nodbg_empty(Reg))
Lang Hames49ab8bc2008-11-16 12:12:54 +0000468 continue;
Lang Hames8f31f442014-10-09 18:20:51 +0000469 LiveInterval &LI = LIS.getInterval(Reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000470
471 // If this live interval is non-empty we will use pbqp to allocate it.
472 // Empty intervals we allocate in a simple post-processing stage in
473 // finalizeAlloc.
Lang Hames8f31f442014-10-09 18:20:51 +0000474 if (!LI.empty()) {
475 VRegsToAlloc.insert(LI.reg);
Lang Hamesc702ba62010-11-12 05:47:21 +0000476 } else {
Lang Hames8f31f442014-10-09 18:20:51 +0000477 EmptyIntervalVRegs.insert(LI.reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000478 }
479 }
Evan Chengb25f4632008-10-02 18:29:27 +0000480}
481
Lang Hames8f31f442014-10-09 18:20:51 +0000482void RegAllocPBQP::initializeGraph(PBQPRAGraph &G) {
483 MachineFunction &MF = G.getMetadata().MF;
484
485 LiveIntervals &LIS = G.getMetadata().LIS;
486 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
487 const TargetRegisterInfo &TRI =
488 *G.getMetadata().MF.getTarget().getSubtargetImpl()->getRegisterInfo();
489
490 for (auto VReg : VRegsToAlloc) {
491 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
492 LiveInterval &VRegLI = LIS.getInterval(VReg);
493
494 // Record any overlaps with regmask operands.
495 BitVector RegMaskOverlaps;
496 LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
497
498 // Compute an initial allowed set for the current vreg.
499 std::vector<unsigned> VRegAllowed;
500 ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
501 for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
502 unsigned PReg = RawPRegOrder[I];
503 if (MRI.isReserved(PReg))
504 continue;
505
506 // vregLI crosses a regmask operand that clobbers preg.
507 if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
508 continue;
509
510 // vregLI overlaps fixed regunit interference.
511 bool Interference = false;
512 for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
513 if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
514 Interference = true;
515 break;
516 }
517 }
518 if (Interference)
519 continue;
520
521 // preg is usable for this virtual register.
522 VRegAllowed.push_back(PReg);
523 }
524
525 PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
526 PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
527 G.getNodeMetadata(NId).setVReg(VReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000528 G.getNodeMetadata(NId).setAllowedRegs(
529 G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
Lang Hames8f31f442014-10-09 18:20:51 +0000530 G.getMetadata().setNodeIdForVReg(VReg, NId);
531 }
532}
533
534bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
535 const PBQP::Solution &Solution,
536 VirtRegMap &VRM,
537 Spiller &VRegSpiller) {
538 MachineFunction &MF = G.getMetadata().MF;
539 LiveIntervals &LIS = G.getMetadata().LIS;
540 const TargetRegisterInfo &TRI =
541 *MF.getTarget().getSubtargetImpl()->getRegisterInfo();
542 (void)TRI;
543
Lang Hamescb1e1012010-09-18 09:07:10 +0000544 // Set to true if we have any spills
Lang Hames8f31f442014-10-09 18:20:51 +0000545 bool AnotherRoundNeeded = false;
Lang Hamescb1e1012010-09-18 09:07:10 +0000546
547 // Clear the existing allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000548 VRM.clearAllVirt();
Lang Hamescb1e1012010-09-18 09:07:10 +0000549
Lang Hamescb1e1012010-09-18 09:07:10 +0000550 // Iterate over the nodes mapping the PBQP solution to a register
551 // assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000552 for (auto NId : G.nodeIds()) {
553 unsigned VReg = G.getNodeMetadata(NId).getVReg();
554 unsigned AllocOption = Solution.getSelection(NId);
Lang Hamescb1e1012010-09-18 09:07:10 +0000555
Lang Hames8f31f442014-10-09 18:20:51 +0000556 if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
Lang Hames5fe30ca2014-10-27 17:44:25 +0000557 unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
Lang Hames8f31f442014-10-09 18:20:51 +0000558 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> "
559 << TRI.getName(PReg) << "\n");
560 assert(PReg != 0 && "Invalid preg selected.");
561 VRM.assignVirt2Phys(VReg, PReg);
562 } else {
563 VRegsToAlloc.erase(VReg);
564 SmallVector<unsigned, 8> NewSpills;
565 LiveRangeEdit LRE(&LIS.getInterval(VReg), NewSpills, MF, LIS, &VRM);
566 VRegSpiller.spill(LRE);
Lang Hamescb1e1012010-09-18 09:07:10 +0000567
Lang Hames8f31f442014-10-09 18:20:51 +0000568 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> SPILLED (Cost: "
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000569 << LRE.getParent().weight << ", New vregs: ");
Lang Hamescb1e1012010-09-18 09:07:10 +0000570
571 // Copy any newly inserted live intervals into the list of regs to
572 // allocate.
Lang Hames8f31f442014-10-09 18:20:51 +0000573 for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
574 I != E; ++I) {
575 LiveInterval &LI = LIS.getInterval(*I);
576 assert(!LI.empty() && "Empty spill range.");
577 DEBUG(dbgs() << PrintReg(LI.reg, &TRI) << " ");
578 VRegsToAlloc.insert(LI.reg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000579 }
580
581 DEBUG(dbgs() << ")\n");
582
583 // We need another round if spill intervals were added.
Lang Hames8f31f442014-10-09 18:20:51 +0000584 AnotherRoundNeeded |= !LRE.empty();
Lang Hamescb1e1012010-09-18 09:07:10 +0000585 }
586 }
587
Lang Hames8f31f442014-10-09 18:20:51 +0000588 return !AnotherRoundNeeded;
Lang Hamescb1e1012010-09-18 09:07:10 +0000589}
590
Lang Hames8f31f442014-10-09 18:20:51 +0000591void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
592 LiveIntervals &LIS,
593 VirtRegMap &VRM) const {
594 MachineRegisterInfo &MRI = MF.getRegInfo();
595
Lang Hames49ab8bc2008-11-16 12:12:54 +0000596 // First allocate registers for the empty intervals.
Lang Hamescb1e1012010-09-18 09:07:10 +0000597 for (RegSet::const_iterator
Lang Hames8f31f442014-10-09 18:20:51 +0000598 I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
599 I != E; ++I) {
600 LiveInterval &LI = LIS.getInterval(*I);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000601
Lang Hames8f31f442014-10-09 18:20:51 +0000602 unsigned PReg = MRI.getSimpleHint(LI.reg);
Lang Hames88fae6f2009-08-06 23:32:48 +0000603
Lang Hames8f31f442014-10-09 18:20:51 +0000604 if (PReg == 0) {
605 const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg);
606 PReg = RC.getRawAllocationOrder(MF).front();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000607 }
Misha Brukmanda467482009-01-08 15:50:22 +0000608
Lang Hames8f31f442014-10-09 18:20:51 +0000609 VRM.assignVirt2Phys(LI.reg, PReg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000610 }
Lang Hames49ab8bc2008-11-16 12:12:54 +0000611}
612
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000613static inline float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size,
614 unsigned NumInstr) {
615 // All intervals have a spill weight that is mostly proportional to the number
616 // of uses, with uses in loops having a bigger weight.
617 return NumInstr * normalizeSpillWeight(UseDefFreq, Size, 1);
618}
619
Lang Hamescb1e1012010-09-18 09:07:10 +0000620bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames8f31f442014-10-09 18:20:51 +0000621 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
622 MachineBlockFrequencyInfo &MBFI =
623 getAnalysis<MachineBlockFrequencyInfo>();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000624
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000625 calculateSpillWeightsAndHints(LIS, MF, getAnalysis<MachineLoopInfo>(), MBFI,
626 normalizePBQPSpillWeight);
Evan Chengb25f4632008-10-02 18:29:27 +0000627
Lang Hames8f31f442014-10-09 18:20:51 +0000628 VirtRegMap &VRM = getAnalysis<VirtRegMap>();
Evan Chengb25f4632008-10-02 18:29:27 +0000629
Lang Hames8f31f442014-10-09 18:20:51 +0000630 std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +0000631
Lang Hames8f31f442014-10-09 18:20:51 +0000632 MF.getRegInfo().freezeReservedRegs(MF);
Evan Chengb25f4632008-10-02 18:29:27 +0000633
Lang Hames8f31f442014-10-09 18:20:51 +0000634 DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000635
Evan Chengb25f4632008-10-02 18:29:27 +0000636 // Allocator main loop:
Misha Brukmanda467482009-01-08 15:50:22 +0000637 //
Evan Chengb25f4632008-10-02 18:29:27 +0000638 // * Map current regalloc problem to a PBQP problem
639 // * Solve the PBQP problem
640 // * Map the solution back to a register allocation
641 // * Spill if necessary
Misha Brukmanda467482009-01-08 15:50:22 +0000642 //
Evan Chengb25f4632008-10-02 18:29:27 +0000643 // This process is continued till no more spills are generated.
644
Lang Hames49ab8bc2008-11-16 12:12:54 +0000645 // Find the vreg intervals in need of allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000646 findVRegIntervalsToAlloc(MF, LIS);
Misha Brukmanda467482009-01-08 15:50:22 +0000647
Craig Toppera538d832012-08-22 06:07:19 +0000648#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000649 const Function &F = *MF.getFunction();
650 std::string FullyQualifiedName =
651 F.getParent()->getModuleIdentifier() + "." + F.getName().str();
Craig Toppera538d832012-08-22 06:07:19 +0000652#endif
Lang Hames95e021f2012-03-26 23:07:23 +0000653
Lang Hames49ab8bc2008-11-16 12:12:54 +0000654 // If there are non-empty intervals allocate them using pbqp.
Lang Hames8f31f442014-10-09 18:20:51 +0000655 if (!VRegsToAlloc.empty()) {
Evan Chengb25f4632008-10-02 18:29:27 +0000656
Lang Hames8f31f442014-10-09 18:20:51 +0000657 const TargetSubtargetInfo &Subtarget = *MF.getTarget().getSubtargetImpl();
658 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
659 llvm::make_unique<PBQPRAConstraintList>();
660 ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
661 ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
662 if (PBQPCoalescing)
663 ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
664 ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
Lang Hames49ab8bc2008-11-16 12:12:54 +0000665
Lang Hames8f31f442014-10-09 18:20:51 +0000666 bool PBQPAllocComplete = false;
667 unsigned Round = 0;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000668
Lang Hames8f31f442014-10-09 18:20:51 +0000669 while (!PBQPAllocComplete) {
670 DEBUG(dbgs() << " PBQP Regalloc round " << Round << ":\n");
671
672 PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
673 initializeGraph(G);
674 ConstraintsRoot->apply(G);
Lang Hames95e021f2012-03-26 23:07:23 +0000675
676#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000677 if (PBQPDumpGraphs) {
678 std::ostringstream RS;
679 RS << Round;
680 std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
681 ".pbqpgraph";
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000682 std::error_code EC;
Lang Hames8f31f442014-10-09 18:20:51 +0000683 raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text);
684 DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
685 << GraphFileName << "\"\n");
686 G.dumpToStream(OS);
Lang Hames95e021f2012-03-26 23:07:23 +0000687 }
688#endif
689
Lang Hames8f31f442014-10-09 18:20:51 +0000690 PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
691 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
692 ++Round;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000693 }
Evan Chengb25f4632008-10-02 18:29:27 +0000694 }
695
Lang Hames49ab8bc2008-11-16 12:12:54 +0000696 // Finalise allocation, allocate empty ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000697 finalizeAlloc(MF, LIS, VRM);
698 VRegsToAlloc.clear();
699 EmptyIntervalVRegs.clear();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000700
Lang Hames8f31f442014-10-09 18:20:51 +0000701 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000702
Misha Brukmanda467482009-01-08 15:50:22 +0000703 return true;
Evan Chengb25f4632008-10-02 18:29:27 +0000704}
705
Lang Hames8f31f442014-10-09 18:20:51 +0000706FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
707 return new RegAllocPBQP(customPassID);
Evan Chengb25f4632008-10-02 18:29:27 +0000708}
709
Lang Hamesfd1bc422010-09-23 04:28:54 +0000710FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Lang Hames8f31f442014-10-09 18:20:51 +0000711 return createPBQPRegisterAllocator();
Lang Hamescb1e1012010-09-18 09:07:10 +0000712}
Evan Chengb25f4632008-10-02 18:29:27 +0000713
714#undef DEBUG_TYPE