blob: 5bd33743db0dc618bdec0cb5d39809f7e2b053b2 [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
153 for (auto NId : G.nodeIds()) {
154 PBQP::PBQPNum SpillCost =
155 LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight;
156 if (SpillCost == 0.0)
157 SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
158 PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
159 NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
160 G.setNodeCosts(NId, std::move(NodeCosts));
161 }
162 }
163};
164
165/// @brief Add interference edges between overlapping vregs.
166class Interference : public PBQPRAConstraint {
Lang Hamesad0962a2014-10-18 17:26:07 +0000167private:
168
169 // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
170 // for the fast interference graph construction algorithm. The last is there
171 // to save us from looking up node ids via the VRegToNode map in the graph
172 // metadata.
173 typedef std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>
174 IntervalInfo;
175
176 static SlotIndex getStartPoint(const IntervalInfo &I) {
177 return std::get<0>(I)->segments[std::get<1>(I)].start;
178 }
179
180 static SlotIndex getEndPoint(const IntervalInfo &I) {
181 return std::get<0>(I)->segments[std::get<1>(I)].end;
182 }
183
184 static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
185 return std::get<2>(I);
186 }
187
188 static bool lowestStartPoint(const IntervalInfo &I1,
189 const IntervalInfo &I2) {
190 // Condition reversed because priority queue has the *highest* element at
191 // the front, rather than the lowest.
192 return getStartPoint(I1) > getStartPoint(I2);
193 }
194
195 static bool lowestEndPoint(const IntervalInfo &I1,
196 const IntervalInfo &I2) {
197 SlotIndex E1 = getEndPoint(I1);
198 SlotIndex E2 = getEndPoint(I2);
199
200 if (E1 < E2)
201 return true;
202
203 if (E1 > E2)
204 return false;
205
206 // If two intervals end at the same point, we need a way to break the tie or
207 // the set will assume they're actually equal and refuse to insert a
208 // "duplicate". Just compare the vregs - fast and guaranteed unique.
209 return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
210 }
211
212 static bool isAtLastSegment(const IntervalInfo &I) {
213 return std::get<1>(I) == std::get<0>(I)->size() - 1;
214 }
215
216 static IntervalInfo nextSegment(const IntervalInfo &I) {
217 return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
218 }
219
Lang Hames8f31f442014-10-09 18:20:51 +0000220public:
221
222 void apply(PBQPRAGraph &G) override {
Lang Hamesad0962a2014-10-18 17:26:07 +0000223 // The following is loosely based on the linear scan algorithm introduced in
224 // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
225 // isn't linear, because the size of the active set isn't bound by the
226 // number of registers, but rather the size of the largest clique in the
227 // graph. Still, we expect this to be better than N^2.
Lang Hames8f31f442014-10-09 18:20:51 +0000228 LiveIntervals &LIS = G.getMetadata().LIS;
229 const TargetRegisterInfo &TRI =
230 *G.getMetadata().MF.getTarget().getSubtargetImpl()->getRegisterInfo();
231
Lang Hamesad0962a2014-10-18 17:26:07 +0000232 typedef std::set<IntervalInfo, decltype(&lowestEndPoint)> IntervalSet;
233 typedef std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
234 decltype(&lowestStartPoint)> IntervalQueue;
235 IntervalSet Active(lowestEndPoint);
236 IntervalQueue Inactive(lowestStartPoint);
Lang Hames8f31f442014-10-09 18:20:51 +0000237
Lang Hamesad0962a2014-10-18 17:26:07 +0000238 // Start by building the inactive set.
239 for (auto NId : G.nodeIds()) {
240 unsigned VReg = G.getNodeMetadata(NId).getVReg();
241 LiveInterval &LI = LIS.getInterval(VReg);
242 assert(!LI.empty() && "PBQP graph contains node for empty interval");
243 Inactive.push(std::make_tuple(&LI, 0, NId));
244 }
Lang Hames8f31f442014-10-09 18:20:51 +0000245
Lang Hamesad0962a2014-10-18 17:26:07 +0000246 while (!Inactive.empty()) {
247 // Tentatively grab the "next" interval - this choice may be overriden
248 // below.
249 IntervalInfo Cur = Inactive.top();
250
251 // Retire any active intervals that end before Cur starts.
252 IntervalSet::iterator RetireItr = Active.begin();
253 while (RetireItr != Active.end() &&
254 (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
255 // If this interval has subsequent segments, add the next one to the
256 // inactive list.
257 if (!isAtLastSegment(*RetireItr))
258 Inactive.push(nextSegment(*RetireItr));
259
260 ++RetireItr;
Lang Hames8f31f442014-10-09 18:20:51 +0000261 }
Lang Hamesad0962a2014-10-18 17:26:07 +0000262 Active.erase(Active.begin(), RetireItr);
263
264 // One of the newly retired segments may actually start before the
265 // Cur segment, so re-grab the front of the inactive list.
266 Cur = Inactive.top();
267 Inactive.pop();
268
269 // At this point we know that Cur overlaps all active intervals. Add the
270 // interference edges.
271 PBQP::GraphBase::NodeId NId = getNodeId(Cur);
272 for (const auto &A : Active) {
273 PBQP::GraphBase::NodeId MId = getNodeId(A);
274
275 // Check that we haven't already added this edge
276 // FIXME: findEdge is expensive in the worst case (O(max_clique(G))).
277 // It might be better to replace this with a local bit-matrix.
278 if (G.findEdge(NId, MId) != PBQP::GraphBase::invalidEdgeId())
279 continue;
280
281 // This is a new edge - add it to the graph.
282 const auto &NOpts = G.getNodeMetadata(NId).getOptionRegs();
283 const auto &MOpts = G.getNodeMetadata(MId).getOptionRegs();
284 G.addEdge(NId, MId, createInterferenceMatrix(TRI, NOpts, MOpts));
285 }
286
287 // Finally, add Cur to the Active set.
288 Active.insert(Cur);
Lang Hames8f31f442014-10-09 18:20:51 +0000289 }
290 }
291
292private:
293
294 PBQPRAGraph::RawMatrix createInterferenceMatrix(
295 const TargetRegisterInfo &TRI,
296 const PBQPRAGraph::NodeMetadata::OptionToRegMap &NOpts,
297 const PBQPRAGraph::NodeMetadata::OptionToRegMap &MOpts) {
298 PBQPRAGraph::RawMatrix M(NOpts.size() + 1, MOpts.size() + 1, 0);
299 for (unsigned I = 0; I != NOpts.size(); ++I) {
300 unsigned PRegN = NOpts[I];
301 for (unsigned J = 0; J != MOpts.size(); ++J) {
302 unsigned PRegM = MOpts[J];
303 if (TRI.regsOverlap(PRegN, PRegM))
304 M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
305 }
306 }
307
308 return M;
309 }
310};
311
312
313class Coalescing : public PBQPRAConstraint {
314public:
315 void apply(PBQPRAGraph &G) override {
316 MachineFunction &MF = G.getMetadata().MF;
317 MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
318 CoalescerPair CP(*MF.getTarget().getSubtargetImpl()->getRegisterInfo());
319
320 // Scan the machine function and add a coalescing cost whenever CoalescerPair
321 // gives the Ok.
322 for (const auto &MBB : MF) {
323 for (const auto &MI : MBB) {
324
325 // Skip not-coalescable or already coalesced copies.
326 if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
327 continue;
328
329 unsigned DstReg = CP.getDstReg();
330 unsigned SrcReg = CP.getSrcReg();
331
332 const float CopyFactor = 0.5; // Cost of copy relative to load. Current
333 // value plucked randomly out of the air.
334
335 PBQP::PBQPNum CBenefit =
336 CopyFactor * LiveIntervals::getSpillWeight(false, true, &MBFI, &MI);
337
338 if (CP.isPhys()) {
339 if (!MF.getRegInfo().isAllocatable(DstReg))
340 continue;
341
342 PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
343
344 const PBQPRAGraph::NodeMetadata::OptionToRegMap &Allowed =
345 G.getNodeMetadata(NId).getOptionRegs();
346
347 unsigned PRegOpt = 0;
348 while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
349 ++PRegOpt;
350
351 if (PRegOpt < Allowed.size()) {
352 PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000353 NewCosts[PRegOpt + 1] -= CBenefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000354 G.setNodeCosts(NId, std::move(NewCosts));
355 }
356 } else {
357 PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
358 PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
359 const PBQPRAGraph::NodeMetadata::OptionToRegMap *Allowed1 =
360 &G.getNodeMetadata(N1Id).getOptionRegs();
361 const PBQPRAGraph::NodeMetadata::OptionToRegMap *Allowed2 =
362 &G.getNodeMetadata(N2Id).getOptionRegs();
363
364 PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
365 if (EId == G.invalidEdgeId()) {
366 PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
367 Allowed2->size() + 1, 0);
368 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
369 G.addEdge(N1Id, N2Id, std::move(Costs));
370 } else {
371 if (G.getEdgeNode1Id(EId) == N2Id) {
372 std::swap(N1Id, N2Id);
373 std::swap(Allowed1, Allowed2);
374 }
375 PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
376 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
377 G.setEdgeCosts(EId, std::move(Costs));
378 }
379 }
380 }
381 }
382 }
383
384private:
385
386 void addVirtRegCoalesce(
387 PBQPRAGraph::RawMatrix &CostMat,
388 const PBQPRAGraph::NodeMetadata::OptionToRegMap &Allowed1,
389 const PBQPRAGraph::NodeMetadata::OptionToRegMap &Allowed2,
390 PBQP::PBQPNum Benefit) {
391 assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
392 assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
393 for (unsigned I = 0; I != Allowed1.size(); ++I) {
394 unsigned PReg1 = Allowed1[I];
395 for (unsigned J = 0; J != Allowed2.size(); ++J) {
396 unsigned PReg2 = Allowed2[J];
397 if (PReg1 == PReg2)
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000398 CostMat[I + 1][J + 1] -= Benefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000399 }
400 }
401 }
402
403};
404
Lang Hamesfd1bc422010-09-23 04:28:54 +0000405} // End anonymous namespace.
406
Lang Hames8f31f442014-10-09 18:20:51 +0000407// Out-of-line destructor/anchor for PBQPRAConstraint.
408PBQPRAConstraint::~PBQPRAConstraint() {}
409void PBQPRAConstraint::anchor() {}
410void PBQPRAConstraintList::anchor() {}
Lang Hamescb1e1012010-09-18 09:07:10 +0000411
412void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hamesb13b6a02011-12-06 01:45:57 +0000413 au.setPreservesCFG();
414 au.addRequired<AliasAnalysis>();
415 au.addPreserved<AliasAnalysis>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000416 au.addRequired<SlotIndexes>();
417 au.addPreserved<SlotIndexes>();
418 au.addRequired<LiveIntervals>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000419 au.addPreserved<LiveIntervals>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000420 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames934625e2011-06-17 07:09:01 +0000421 if (customPassID)
422 au.addRequiredID(*customPassID);
Lang Hamescb1e1012010-09-18 09:07:10 +0000423 au.addRequired<LiveStacks>();
424 au.addPreserved<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000425 au.addRequired<MachineBlockFrequencyInfo>();
426 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames7d99d792013-07-01 20:47:47 +0000427 au.addRequired<MachineLoopInfo>();
428 au.addPreserved<MachineLoopInfo>();
Lang Hamesb13b6a02011-12-06 01:45:57 +0000429 au.addRequired<MachineDominatorTree>();
430 au.addPreserved<MachineDominatorTree>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000431 au.addRequired<VirtRegMap>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000432 au.addPreserved<VirtRegMap>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000433 MachineFunctionPass::getAnalysisUsage(au);
434}
435
Lang Hames8f31f442014-10-09 18:20:51 +0000436void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
437 LiveIntervals &LIS) {
438 const MachineRegisterInfo &MRI = MF.getRegInfo();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000439
440 // Iterate over all live ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000441 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
442 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
443 if (MRI.reg_nodbg_empty(Reg))
Lang Hames49ab8bc2008-11-16 12:12:54 +0000444 continue;
Lang Hames8f31f442014-10-09 18:20:51 +0000445 LiveInterval &LI = LIS.getInterval(Reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000446
447 // If this live interval is non-empty we will use pbqp to allocate it.
448 // Empty intervals we allocate in a simple post-processing stage in
449 // finalizeAlloc.
Lang Hames8f31f442014-10-09 18:20:51 +0000450 if (!LI.empty()) {
451 VRegsToAlloc.insert(LI.reg);
Lang Hamesc702ba62010-11-12 05:47:21 +0000452 } else {
Lang Hames8f31f442014-10-09 18:20:51 +0000453 EmptyIntervalVRegs.insert(LI.reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000454 }
455 }
Evan Chengb25f4632008-10-02 18:29:27 +0000456}
457
Lang Hames8f31f442014-10-09 18:20:51 +0000458void RegAllocPBQP::initializeGraph(PBQPRAGraph &G) {
459 MachineFunction &MF = G.getMetadata().MF;
460
461 LiveIntervals &LIS = G.getMetadata().LIS;
462 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
463 const TargetRegisterInfo &TRI =
464 *G.getMetadata().MF.getTarget().getSubtargetImpl()->getRegisterInfo();
465
466 for (auto VReg : VRegsToAlloc) {
467 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
468 LiveInterval &VRegLI = LIS.getInterval(VReg);
469
470 // Record any overlaps with regmask operands.
471 BitVector RegMaskOverlaps;
472 LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
473
474 // Compute an initial allowed set for the current vreg.
475 std::vector<unsigned> VRegAllowed;
476 ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
477 for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
478 unsigned PReg = RawPRegOrder[I];
479 if (MRI.isReserved(PReg))
480 continue;
481
482 // vregLI crosses a regmask operand that clobbers preg.
483 if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
484 continue;
485
486 // vregLI overlaps fixed regunit interference.
487 bool Interference = false;
488 for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
489 if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
490 Interference = true;
491 break;
492 }
493 }
494 if (Interference)
495 continue;
496
497 // preg is usable for this virtual register.
498 VRegAllowed.push_back(PReg);
499 }
500
501 PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
502 PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
503 G.getNodeMetadata(NId).setVReg(VReg);
504 G.getNodeMetadata(NId).setOptionRegs(std::move(VRegAllowed));
505 G.getMetadata().setNodeIdForVReg(VReg, NId);
506 }
507}
508
509bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
510 const PBQP::Solution &Solution,
511 VirtRegMap &VRM,
512 Spiller &VRegSpiller) {
513 MachineFunction &MF = G.getMetadata().MF;
514 LiveIntervals &LIS = G.getMetadata().LIS;
515 const TargetRegisterInfo &TRI =
516 *MF.getTarget().getSubtargetImpl()->getRegisterInfo();
517 (void)TRI;
518
Lang Hamescb1e1012010-09-18 09:07:10 +0000519 // Set to true if we have any spills
Lang Hames8f31f442014-10-09 18:20:51 +0000520 bool AnotherRoundNeeded = false;
Lang Hamescb1e1012010-09-18 09:07:10 +0000521
522 // Clear the existing allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000523 VRM.clearAllVirt();
Lang Hamescb1e1012010-09-18 09:07:10 +0000524
Lang Hamescb1e1012010-09-18 09:07:10 +0000525 // Iterate over the nodes mapping the PBQP solution to a register
526 // assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000527 for (auto NId : G.nodeIds()) {
528 unsigned VReg = G.getNodeMetadata(NId).getVReg();
529 unsigned AllocOption = Solution.getSelection(NId);
Lang Hamescb1e1012010-09-18 09:07:10 +0000530
Lang Hames8f31f442014-10-09 18:20:51 +0000531 if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
532 unsigned PReg = G.getNodeMetadata(NId).getOptionRegs()[AllocOption - 1];
533 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> "
534 << TRI.getName(PReg) << "\n");
535 assert(PReg != 0 && "Invalid preg selected.");
536 VRM.assignVirt2Phys(VReg, PReg);
537 } else {
538 VRegsToAlloc.erase(VReg);
539 SmallVector<unsigned, 8> NewSpills;
540 LiveRangeEdit LRE(&LIS.getInterval(VReg), NewSpills, MF, LIS, &VRM);
541 VRegSpiller.spill(LRE);
Lang Hamescb1e1012010-09-18 09:07:10 +0000542
Lang Hames8f31f442014-10-09 18:20:51 +0000543 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> SPILLED (Cost: "
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000544 << LRE.getParent().weight << ", New vregs: ");
Lang Hamescb1e1012010-09-18 09:07:10 +0000545
546 // Copy any newly inserted live intervals into the list of regs to
547 // allocate.
Lang Hames8f31f442014-10-09 18:20:51 +0000548 for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
549 I != E; ++I) {
550 LiveInterval &LI = LIS.getInterval(*I);
551 assert(!LI.empty() && "Empty spill range.");
552 DEBUG(dbgs() << PrintReg(LI.reg, &TRI) << " ");
553 VRegsToAlloc.insert(LI.reg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000554 }
555
556 DEBUG(dbgs() << ")\n");
557
558 // We need another round if spill intervals were added.
Lang Hames8f31f442014-10-09 18:20:51 +0000559 AnotherRoundNeeded |= !LRE.empty();
Lang Hamescb1e1012010-09-18 09:07:10 +0000560 }
561 }
562
Lang Hames8f31f442014-10-09 18:20:51 +0000563 return !AnotherRoundNeeded;
Lang Hamescb1e1012010-09-18 09:07:10 +0000564}
565
566
Lang Hames8f31f442014-10-09 18:20:51 +0000567void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
568 LiveIntervals &LIS,
569 VirtRegMap &VRM) const {
570 MachineRegisterInfo &MRI = MF.getRegInfo();
571
Lang Hames49ab8bc2008-11-16 12:12:54 +0000572 // First allocate registers for the empty intervals.
Lang Hamescb1e1012010-09-18 09:07:10 +0000573 for (RegSet::const_iterator
Lang Hames8f31f442014-10-09 18:20:51 +0000574 I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
575 I != E; ++I) {
576 LiveInterval &LI = LIS.getInterval(*I);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000577
Lang Hames8f31f442014-10-09 18:20:51 +0000578 unsigned PReg = MRI.getSimpleHint(LI.reg);
Lang Hames88fae6f2009-08-06 23:32:48 +0000579
Lang Hames8f31f442014-10-09 18:20:51 +0000580 if (PReg == 0) {
581 const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg);
582 PReg = RC.getRawAllocationOrder(MF).front();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000583 }
Misha Brukmanda467482009-01-08 15:50:22 +0000584
Lang Hames8f31f442014-10-09 18:20:51 +0000585 VRM.assignVirt2Phys(LI.reg, PReg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000586 }
Lang Hames49ab8bc2008-11-16 12:12:54 +0000587}
588
Lang Hamescb1e1012010-09-18 09:07:10 +0000589bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames8f31f442014-10-09 18:20:51 +0000590 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
591 MachineBlockFrequencyInfo &MBFI =
592 getAnalysis<MachineBlockFrequencyInfo>();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000593
Lang Hames8f31f442014-10-09 18:20:51 +0000594 calculateSpillWeightsAndHints(LIS, MF, getAnalysis<MachineLoopInfo>(), MBFI);
Evan Chengb25f4632008-10-02 18:29:27 +0000595
Lang Hames8f31f442014-10-09 18:20:51 +0000596 VirtRegMap &VRM = getAnalysis<VirtRegMap>();
Evan Chengb25f4632008-10-02 18:29:27 +0000597
Lang Hames8f31f442014-10-09 18:20:51 +0000598 std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +0000599
Lang Hames8f31f442014-10-09 18:20:51 +0000600 MF.getRegInfo().freezeReservedRegs(MF);
Evan Chengb25f4632008-10-02 18:29:27 +0000601
Lang Hames8f31f442014-10-09 18:20:51 +0000602 DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000603
Evan Chengb25f4632008-10-02 18:29:27 +0000604 // Allocator main loop:
Misha Brukmanda467482009-01-08 15:50:22 +0000605 //
Evan Chengb25f4632008-10-02 18:29:27 +0000606 // * Map current regalloc problem to a PBQP problem
607 // * Solve the PBQP problem
608 // * Map the solution back to a register allocation
609 // * Spill if necessary
Misha Brukmanda467482009-01-08 15:50:22 +0000610 //
Evan Chengb25f4632008-10-02 18:29:27 +0000611 // This process is continued till no more spills are generated.
612
Lang Hames49ab8bc2008-11-16 12:12:54 +0000613 // Find the vreg intervals in need of allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000614 findVRegIntervalsToAlloc(MF, LIS);
Misha Brukmanda467482009-01-08 15:50:22 +0000615
Craig Toppera538d832012-08-22 06:07:19 +0000616#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000617 const Function &F = *MF.getFunction();
618 std::string FullyQualifiedName =
619 F.getParent()->getModuleIdentifier() + "." + F.getName().str();
Craig Toppera538d832012-08-22 06:07:19 +0000620#endif
Lang Hames95e021f2012-03-26 23:07:23 +0000621
Lang Hames49ab8bc2008-11-16 12:12:54 +0000622 // If there are non-empty intervals allocate them using pbqp.
Lang Hames8f31f442014-10-09 18:20:51 +0000623 if (!VRegsToAlloc.empty()) {
Evan Chengb25f4632008-10-02 18:29:27 +0000624
Lang Hames8f31f442014-10-09 18:20:51 +0000625 const TargetSubtargetInfo &Subtarget = *MF.getTarget().getSubtargetImpl();
626 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
627 llvm::make_unique<PBQPRAConstraintList>();
628 ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
629 ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
630 if (PBQPCoalescing)
631 ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
632 ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
Lang Hames49ab8bc2008-11-16 12:12:54 +0000633
Lang Hames8f31f442014-10-09 18:20:51 +0000634 bool PBQPAllocComplete = false;
635 unsigned Round = 0;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000636
Lang Hames8f31f442014-10-09 18:20:51 +0000637 while (!PBQPAllocComplete) {
638 DEBUG(dbgs() << " PBQP Regalloc round " << Round << ":\n");
639
640 PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
641 initializeGraph(G);
642 ConstraintsRoot->apply(G);
Lang Hames95e021f2012-03-26 23:07:23 +0000643
644#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000645 if (PBQPDumpGraphs) {
646 std::ostringstream RS;
647 RS << Round;
648 std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
649 ".pbqpgraph";
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000650 std::error_code EC;
Lang Hames8f31f442014-10-09 18:20:51 +0000651 raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text);
652 DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
653 << GraphFileName << "\"\n");
654 G.dumpToStream(OS);
Lang Hames95e021f2012-03-26 23:07:23 +0000655 }
656#endif
657
Lang Hames8f31f442014-10-09 18:20:51 +0000658 PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
659 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
660 ++Round;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000661 }
Evan Chengb25f4632008-10-02 18:29:27 +0000662 }
663
Lang Hames49ab8bc2008-11-16 12:12:54 +0000664 // Finalise allocation, allocate empty ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000665 finalizeAlloc(MF, LIS, VRM);
666 VRegsToAlloc.clear();
667 EmptyIntervalVRegs.clear();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000668
Lang Hames8f31f442014-10-09 18:20:51 +0000669 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000670
Misha Brukmanda467482009-01-08 15:50:22 +0000671 return true;
Evan Chengb25f4632008-10-02 18:29:27 +0000672}
673
Lang Hames8f31f442014-10-09 18:20:51 +0000674FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
675 return new RegAllocPBQP(customPassID);
Evan Chengb25f4632008-10-02 18:29:27 +0000676}
677
Lang Hamesfd1bc422010-09-23 04:28:54 +0000678FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Lang Hames8f31f442014-10-09 18:20:51 +0000679 return createPBQPRegisterAllocator();
Lang Hamescb1e1012010-09-18 09:07:10 +0000680}
Evan Chengb25f4632008-10-02 18:29:27 +0000681
682#undef DEBUG_TYPE