blob: c19001c8403df3ab4a9691906a19acc2d83a48d9 [file] [log] [blame]
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +00001//===- RegAllocPBQP.cpp ---- PBQP Register Allocator ----------------------===//
Evan Chengb1290a62008-10-02 18:29:27 +00002//
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 Brukman2a835f92009-01-08 15:50:22 +00009//
Evan Chengb1290a62008-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 Brukman2a835f92009-01-08 15:50:22 +000015// code is inserted and the process repeated.
Evan Chengb1290a62008-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 Brukmance07e992009-01-08 16:40:25 +000019// allocation, see the following papers:
Evan Chengb1290a62008-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 Brukman2a835f92009-01-08 15:50:22 +000029//
Evan Chengb1290a62008-10-02 18:29:27 +000030//===----------------------------------------------------------------------===//
31
Chandler Carruthe3e43d92017-06-06 11:49:48 +000032#include "llvm/CodeGen/RegAllocPBQP.h"
Rafael Espindolafdf16ca2011-06-26 21:41:06 +000033#include "RegisterCoalescer.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000034#include "Spiller.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000035#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/BitVector.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/DenseSet.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000039#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000040#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/SmallVector.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000042#include "llvm/ADT/StringRef.h"
Lang Hames9ad7e072011-12-06 01:45:57 +000043#include "llvm/Analysis/AliasAnalysis.h"
Lang Hamesa937f222009-12-14 06:49:42 +000044#include "llvm/CodeGen/CalcSpillWeights.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000045#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunfa621d22017-12-13 02:51:04 +000046#include "llvm/CodeGen/LiveIntervals.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000047#include "llvm/CodeGen/LiveRangeEdit.h"
Matthias Braun209f0482017-12-18 23:19:44 +000048#include "llvm/CodeGen/LiveStacks.h"
Benjamin Kramer4eed7562013-06-17 19:00:36 +000049#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Lang Hames9ad7e072011-12-06 01:45:57 +000050#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000051#include "llvm/CodeGen/MachineFunction.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000052#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkoff49b832017-06-01 23:25:02 +000053#include "llvm/CodeGen/MachineInstr.h"
Lang Hames781f5b32013-07-01 20:47:47 +000054#include "llvm/CodeGen/MachineLoopInfo.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000055#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000056#include "llvm/CodeGen/PBQP/Graph.h"
Eugene Zelenkoff49b832017-06-01 23:25:02 +000057#include "llvm/CodeGen/PBQP/Math.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000058#include "llvm/CodeGen/PBQP/Solution.h"
59#include "llvm/CodeGen/PBQPRAConstraint.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000060#include "llvm/CodeGen/RegAllocRegistry.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000061#include "llvm/CodeGen/SlotIndexes.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000062#include "llvm/CodeGen/TargetRegisterInfo.h"
63#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000064#include "llvm/CodeGen/VirtRegMap.h"
Nico Weber0f38c602018-04-30 14:59:11 +000065#include "llvm/Config/llvm-config.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000066#include "llvm/IR/Function.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000067#include "llvm/IR/Module.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000068#include "llvm/MC/MCRegisterInfo.h"
69#include "llvm/Pass.h"
70#include "llvm/Support/CommandLine.h"
71#include "llvm/Support/Compiler.h"
Evan Chengb1290a62008-10-02 18:29:27 +000072#include "llvm/Support/Debug.h"
Benjamin Kramer7259f142014-04-29 23:26:49 +000073#include "llvm/Support/FileSystem.h"
Matthias Braunae4aa8b2015-12-04 01:31:59 +000074#include "llvm/Support/Printable.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000075#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000076#include <algorithm>
77#include <cassert>
78#include <cstddef>
Misha Brukman2a835f92009-01-08 15:50:22 +000079#include <limits>
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000080#include <map>
Misha Brukman2a835f92009-01-08 15:50:22 +000081#include <memory>
Lang Hames33ea6f22014-10-18 17:26:07 +000082#include <queue>
Evan Chengb1290a62008-10-02 18:29:27 +000083#include <set>
Lang Hames20df03c2012-03-26 23:07:23 +000084#include <sstream>
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000085#include <string>
86#include <system_error>
87#include <tuple>
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000088#include <utility>
Chandler Carruthe3e43d92017-06-06 11:49:48 +000089#include <vector>
Evan Chengb1290a62008-10-02 18:29:27 +000090
Lang Hamesf70e7cc2010-09-23 04:28:54 +000091using namespace llvm;
Lang Hameseb6c8f52010-09-18 09:07:10 +000092
Chandler Carruth8677f2f2014-04-22 02:02:50 +000093#define DEBUG_TYPE "regalloc"
94
Evan Chengb1290a62008-10-02 18:29:27 +000095static RegisterRegAlloc
Lang Hames54d63b42014-10-09 18:20:51 +000096RegisterPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesf70e7cc2010-09-23 04:28:54 +000097 createDefaultPBQPRegisterAllocator);
Evan Chengb1290a62008-10-02 18:29:27 +000098
Lang Hames8481e3b2009-08-19 01:36:14 +000099static cl::opt<bool>
Lang Hames54d63b42014-10-09 18:20:51 +0000100PBQPCoalescing("pbqp-coalescing",
Lang Hames030c4bf2010-01-26 04:49:58 +0000101 cl::desc("Attempt coalescing during PBQP register allocation."),
102 cl::init(false), cl::Hidden);
Lang Hames8481e3b2009-08-19 01:36:14 +0000103
Lang Hames20df03c2012-03-26 23:07:23 +0000104#ifndef NDEBUG
105static cl::opt<bool>
Lang Hames54d63b42014-10-09 18:20:51 +0000106PBQPDumpGraphs("pbqp-dump-graphs",
Lang Hames20df03c2012-03-26 23:07:23 +0000107 cl::desc("Dump graphs for each function/round in the compilation unit."),
108 cl::init(false), cl::Hidden);
109#endif
110
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000111namespace {
112
113///
114/// PBQP based allocators solve the register allocation problem by mapping
115/// register allocation problems to Partitioned Boolean Quadratic
116/// Programming problems.
117class RegAllocPBQP : public MachineFunctionPass {
118public:
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000119 static char ID;
120
121 /// Construct a PBQP register allocator.
Lang Hames54d63b42014-10-09 18:20:51 +0000122 RegAllocPBQP(char *cPassID = nullptr)
123 : MachineFunctionPass(ID), customPassID(cPassID) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000124 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
125 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +0000126 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +0000127 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +0000128 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000129
130 /// Return the pass name.
Mehdi Amini67f335d2016-10-01 02:56:57 +0000131 StringRef getPassName() const override { return "PBQP Register Allocator"; }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000132
133 /// PBQP analysis usage.
Craig Topper9f998de2014-03-07 09:26:03 +0000134 void getAnalysisUsage(AnalysisUsage &au) const override;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000135
136 /// Perform register allocation
Craig Topper9f998de2014-03-07 09:26:03 +0000137 bool runOnMachineFunction(MachineFunction &MF) override;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000138
Matthias Braundb9ce2f2016-08-23 21:19:49 +0000139 MachineFunctionProperties getRequiredProperties() const override {
140 return MachineFunctionProperties().set(
141 MachineFunctionProperties::Property::NoPHIs);
142 }
143
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000144private:
Eugene Zelenkoff49b832017-06-01 23:25:02 +0000145 using LI2NodeMap = std::map<const LiveInterval *, unsigned>;
146 using Node2LIMap = std::vector<const LiveInterval *>;
147 using AllowedSet = std::vector<unsigned>;
148 using AllowedSetMap = std::vector<AllowedSet>;
149 using RegPair = std::pair<unsigned, unsigned>;
150 using CoalesceMap = std::map<RegPair, PBQP::PBQPNum>;
151 using RegSet = std::set<unsigned>;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000152
Lang Hames8d857662011-06-17 07:09:01 +0000153 char *customPassID;
154
Lang Hames54d63b42014-10-09 18:20:51 +0000155 RegSet VRegsToAlloc, EmptyIntervalVRegs;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000156
Wei Mi815b02e2016-04-13 03:08:27 +0000157 /// Inst which is a def of an original reg and whose defs are already all
158 /// dead after remat is saved in DeadRemats. The deletion of such inst is
159 /// postponed till all the allocations are done, so its remat expr is
160 /// always available for the remat of all the siblings of the original reg.
161 SmallPtrSet<MachineInstr *, 32> DeadRemats;
162
Adrian Prantl26b584c2018-05-01 15:54:18 +0000163 /// Finds the initial set of vreg intervals to allocate.
Lang Hames54d63b42014-10-09 18:20:51 +0000164 void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS);
165
Adrian Prantl26b584c2018-05-01 15:54:18 +0000166 /// Constructs an initial graph.
Lang Hamesd54450e2015-02-03 06:14:06 +0000167 void initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM, Spiller &VRegSpiller);
168
Adrian Prantl26b584c2018-05-01 15:54:18 +0000169 /// Spill the given VReg.
Lang Hamesd54450e2015-02-03 06:14:06 +0000170 void spillVReg(unsigned VReg, SmallVectorImpl<unsigned> &NewIntervals,
171 MachineFunction &MF, LiveIntervals &LIS, VirtRegMap &VRM,
172 Spiller &VRegSpiller);
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000173
Adrian Prantl26b584c2018-05-01 15:54:18 +0000174 /// Given a solved PBQP problem maps this solution back to a register
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000175 /// assignment.
Lang Hames54d63b42014-10-09 18:20:51 +0000176 bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
177 const PBQP::Solution &Solution,
178 VirtRegMap &VRM,
179 Spiller &VRegSpiller);
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000180
Adrian Prantl26b584c2018-05-01 15:54:18 +0000181 /// Postprocessing before final spilling. Sets basic block "live in"
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000182 /// variables.
Lang Hames54d63b42014-10-09 18:20:51 +0000183 void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
184 VirtRegMap &VRM) const;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000185
Wei Mi815b02e2016-04-13 03:08:27 +0000186 void postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS);
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000187};
188
Lang Hameseb6c8f52010-09-18 09:07:10 +0000189char RegAllocPBQP::ID = 0;
Evan Chengb1290a62008-10-02 18:29:27 +0000190
Adrian Prantl0b24b742018-05-01 16:10:38 +0000191/// Set spill costs for each node in the PBQP reg-alloc graph.
Lang Hames54d63b42014-10-09 18:20:51 +0000192class SpillCosts : public PBQPRAConstraint {
193public:
194 void apply(PBQPRAGraph &G) override {
195 LiveIntervals &LIS = G.getMetadata().LIS;
196
Arnaud A. de Grandmaison8025a392014-11-04 20:51:24 +0000197 // A minimum spill costs, so that register constraints can can be set
198 // without normalization in the [0.0:MinSpillCost( interval.
199 const PBQP::PBQPNum MinSpillCost = 10.0;
200
Lang Hames54d63b42014-10-09 18:20:51 +0000201 for (auto NId : G.nodeIds()) {
202 PBQP::PBQPNum SpillCost =
203 LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight;
204 if (SpillCost == 0.0)
205 SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
Arnaud A. de Grandmaison8025a392014-11-04 20:51:24 +0000206 else
207 SpillCost += MinSpillCost;
Lang Hames54d63b42014-10-09 18:20:51 +0000208 PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
209 NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
210 G.setNodeCosts(NId, std::move(NodeCosts));
211 }
212 }
213};
214
Adrian Prantl0b24b742018-05-01 16:10:38 +0000215/// Add interference edges between overlapping vregs.
Lang Hames54d63b42014-10-09 18:20:51 +0000216class Interference : public PBQPRAConstraint {
Lang Hames33ea6f22014-10-18 17:26:07 +0000217private:
Eugene Zelenkoff49b832017-06-01 23:25:02 +0000218 using AllowedRegVecPtr = const PBQP::RegAlloc::AllowedRegVector *;
219 using IKey = std::pair<AllowedRegVecPtr, AllowedRegVecPtr>;
220 using IMatrixCache = DenseMap<IKey, PBQPRAGraph::MatrixPtr>;
221 using DisjointAllowedRegsCache = DenseSet<IKey>;
222 using IEdgeKey = std::pair<PBQP::GraphBase::NodeId, PBQP::GraphBase::NodeId>;
223 using IEdgeCache = DenseSet<IEdgeKey>;
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000224
225 bool haveDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
226 PBQPRAGraph::NodeId MId,
227 const DisjointAllowedRegsCache &D) const {
228 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
229 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
230
231 if (NRegs == MRegs)
232 return false;
233
234 if (NRegs < MRegs)
235 return D.count(IKey(NRegs, MRegs)) > 0;
Arnaud A. de Grandmaison502bb4c2015-03-01 21:22:50 +0000236
237 return D.count(IKey(MRegs, NRegs)) > 0;
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000238 }
239
240 void setDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
241 PBQPRAGraph::NodeId MId,
242 DisjointAllowedRegsCache &D) {
243 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
244 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
245
246 assert(NRegs != MRegs && "AllowedRegs can not be disjoint with itself");
247
248 if (NRegs < MRegs)
249 D.insert(IKey(NRegs, MRegs));
250 else
251 D.insert(IKey(MRegs, NRegs));
252 }
Lang Hames57902cc2014-10-27 17:44:25 +0000253
Lang Hames33ea6f22014-10-18 17:26:07 +0000254 // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
255 // for the fast interference graph construction algorithm. The last is there
256 // to save us from looking up node ids via the VRegToNode map in the graph
257 // metadata.
Eugene Zelenkoff49b832017-06-01 23:25:02 +0000258 using IntervalInfo =
259 std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>;
Lang Hames33ea6f22014-10-18 17:26:07 +0000260
261 static SlotIndex getStartPoint(const IntervalInfo &I) {
262 return std::get<0>(I)->segments[std::get<1>(I)].start;
263 }
264
265 static SlotIndex getEndPoint(const IntervalInfo &I) {
266 return std::get<0>(I)->segments[std::get<1>(I)].end;
267 }
268
269 static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
270 return std::get<2>(I);
271 }
272
273 static bool lowestStartPoint(const IntervalInfo &I1,
274 const IntervalInfo &I2) {
275 // Condition reversed because priority queue has the *highest* element at
276 // the front, rather than the lowest.
277 return getStartPoint(I1) > getStartPoint(I2);
278 }
279
280 static bool lowestEndPoint(const IntervalInfo &I1,
281 const IntervalInfo &I2) {
282 SlotIndex E1 = getEndPoint(I1);
283 SlotIndex E2 = getEndPoint(I2);
284
285 if (E1 < E2)
286 return true;
287
288 if (E1 > E2)
289 return false;
290
291 // If two intervals end at the same point, we need a way to break the tie or
292 // the set will assume they're actually equal and refuse to insert a
293 // "duplicate". Just compare the vregs - fast and guaranteed unique.
294 return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
295 }
296
297 static bool isAtLastSegment(const IntervalInfo &I) {
298 return std::get<1>(I) == std::get<0>(I)->size() - 1;
299 }
300
301 static IntervalInfo nextSegment(const IntervalInfo &I) {
302 return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
303 }
304
Lang Hames54d63b42014-10-09 18:20:51 +0000305public:
Lang Hames54d63b42014-10-09 18:20:51 +0000306 void apply(PBQPRAGraph &G) override {
Lang Hames33ea6f22014-10-18 17:26:07 +0000307 // The following is loosely based on the linear scan algorithm introduced in
308 // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
309 // isn't linear, because the size of the active set isn't bound by the
310 // number of registers, but rather the size of the largest clique in the
311 // graph. Still, we expect this to be better than N^2.
Lang Hames54d63b42014-10-09 18:20:51 +0000312 LiveIntervals &LIS = G.getMetadata().LIS;
Lang Hames57902cc2014-10-27 17:44:25 +0000313
314 // Interferenc matrices are incredibly regular - they're only a function of
315 // the allowed sets, so we cache them to avoid the overhead of constructing
316 // and uniquing them.
317 IMatrixCache C;
Lang Hames54d63b42014-10-09 18:20:51 +0000318
Arnaud A. de Grandmaisond1d594b2015-03-05 09:12:59 +0000319 // Finding an edge is expensive in the worst case (O(max_clique(G))). So
320 // cache locally edges we have already seen.
321 IEdgeCache EC;
322
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000323 // Cache known disjoint allowed registers pairs
324 DisjointAllowedRegsCache D;
325
Eugene Zelenkoff49b832017-06-01 23:25:02 +0000326 using IntervalSet = std::set<IntervalInfo, decltype(&lowestEndPoint)>;
327 using IntervalQueue =
328 std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
329 decltype(&lowestStartPoint)>;
Lang Hames33ea6f22014-10-18 17:26:07 +0000330 IntervalSet Active(lowestEndPoint);
331 IntervalQueue Inactive(lowestStartPoint);
Lang Hames54d63b42014-10-09 18:20:51 +0000332
Lang Hames33ea6f22014-10-18 17:26:07 +0000333 // Start by building the inactive set.
334 for (auto NId : G.nodeIds()) {
335 unsigned VReg = G.getNodeMetadata(NId).getVReg();
336 LiveInterval &LI = LIS.getInterval(VReg);
337 assert(!LI.empty() && "PBQP graph contains node for empty interval");
338 Inactive.push(std::make_tuple(&LI, 0, NId));
339 }
Lang Hames54d63b42014-10-09 18:20:51 +0000340
Lang Hames33ea6f22014-10-18 17:26:07 +0000341 while (!Inactive.empty()) {
342 // Tentatively grab the "next" interval - this choice may be overriden
343 // below.
344 IntervalInfo Cur = Inactive.top();
345
346 // Retire any active intervals that end before Cur starts.
347 IntervalSet::iterator RetireItr = Active.begin();
348 while (RetireItr != Active.end() &&
349 (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
350 // If this interval has subsequent segments, add the next one to the
351 // inactive list.
352 if (!isAtLastSegment(*RetireItr))
353 Inactive.push(nextSegment(*RetireItr));
354
355 ++RetireItr;
Lang Hames54d63b42014-10-09 18:20:51 +0000356 }
Lang Hames33ea6f22014-10-18 17:26:07 +0000357 Active.erase(Active.begin(), RetireItr);
358
359 // One of the newly retired segments may actually start before the
360 // Cur segment, so re-grab the front of the inactive list.
361 Cur = Inactive.top();
362 Inactive.pop();
363
364 // At this point we know that Cur overlaps all active intervals. Add the
365 // interference edges.
366 PBQP::GraphBase::NodeId NId = getNodeId(Cur);
367 for (const auto &A : Active) {
368 PBQP::GraphBase::NodeId MId = getNodeId(A);
369
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000370 // Do not add an edge when the nodes' allowed registers do not
371 // intersect: there is obviously no interference.
372 if (haveDisjointAllowedRegs(G, NId, MId, D))
373 continue;
374
Lang Hames33ea6f22014-10-18 17:26:07 +0000375 // Check that we haven't already added this edge
Arnaud A. de Grandmaisond1d594b2015-03-05 09:12:59 +0000376 IEdgeKey EK(std::min(NId, MId), std::max(NId, MId));
377 if (EC.count(EK))
Lang Hames33ea6f22014-10-18 17:26:07 +0000378 continue;
379
380 // This is a new edge - add it to the graph.
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000381 if (!createInterferenceEdge(G, NId, MId, C))
382 setDisjointAllowedRegs(G, NId, MId, D);
Arnaud A. de Grandmaisond1d594b2015-03-05 09:12:59 +0000383 else
384 EC.insert(EK);
Lang Hames33ea6f22014-10-18 17:26:07 +0000385 }
386
387 // Finally, add Cur to the Active set.
388 Active.insert(Cur);
Lang Hames54d63b42014-10-09 18:20:51 +0000389 }
390 }
391
392private:
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000393 // Create an Interference edge and add it to the graph, unless it is
394 // a null matrix, meaning the nodes' allowed registers do not have any
395 // interference. This case occurs frequently between integer and floating
396 // point registers for example.
397 // return true iff both nodes interferes.
398 bool createInterferenceEdge(PBQPRAGraph &G,
399 PBQPRAGraph::NodeId NId, PBQPRAGraph::NodeId MId,
400 IMatrixCache &C) {
Lang Hames57902cc2014-10-27 17:44:25 +0000401 const TargetRegisterInfo &TRI =
Eric Christopher05935e22015-01-27 08:27:06 +0000402 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames57902cc2014-10-27 17:44:25 +0000403 const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
404 const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
405
406 // Try looking the edge costs up in the IMatrixCache first.
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000407 IKey K(&NRegs, &MRegs);
Lang Hames57902cc2014-10-27 17:44:25 +0000408 IMatrixCache::iterator I = C.find(K);
409 if (I != C.end()) {
410 G.addEdgeBypassingCostAllocator(NId, MId, I->second);
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000411 return true;
Lang Hames57902cc2014-10-27 17:44:25 +0000412 }
413
414 PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000415 bool NodesInterfere = false;
Lang Hames57902cc2014-10-27 17:44:25 +0000416 for (unsigned I = 0; I != NRegs.size(); ++I) {
417 unsigned PRegN = NRegs[I];
418 for (unsigned J = 0; J != MRegs.size(); ++J) {
419 unsigned PRegM = MRegs[J];
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000420 if (TRI.regsOverlap(PRegN, PRegM)) {
Lang Hames54d63b42014-10-09 18:20:51 +0000421 M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000422 NodesInterfere = true;
423 }
Lang Hames54d63b42014-10-09 18:20:51 +0000424 }
425 }
426
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000427 if (!NodesInterfere)
428 return false;
429
Lang Hames57902cc2014-10-27 17:44:25 +0000430 PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
431 C[K] = G.getEdgeCostsPtr(EId);
Arnaud A. de Grandmaisone2557d92015-03-01 20:39:34 +0000432
433 return true;
Lang Hames54d63b42014-10-09 18:20:51 +0000434 }
435};
436
Lang Hames54d63b42014-10-09 18:20:51 +0000437class Coalescing : public PBQPRAConstraint {
438public:
439 void apply(PBQPRAGraph &G) override {
440 MachineFunction &MF = G.getMetadata().MF;
441 MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
Eric Christopher05935e22015-01-27 08:27:06 +0000442 CoalescerPair CP(*MF.getSubtarget().getRegisterInfo());
Lang Hames54d63b42014-10-09 18:20:51 +0000443
444 // Scan the machine function and add a coalescing cost whenever CoalescerPair
445 // gives the Ok.
446 for (const auto &MBB : MF) {
447 for (const auto &MI : MBB) {
Lang Hames54d63b42014-10-09 18:20:51 +0000448 // Skip not-coalescable or already coalesced copies.
449 if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
450 continue;
451
452 unsigned DstReg = CP.getDstReg();
453 unsigned SrcReg = CP.getSrcReg();
454
Arnaud A. de Grandmaison8025a392014-11-04 20:51:24 +0000455 const float Scale = 1.0f / MBFI.getEntryFreq();
456 PBQP::PBQPNum CBenefit = MBFI.getBlockFreq(&MBB).getFrequency() * Scale;
Lang Hames54d63b42014-10-09 18:20:51 +0000457
458 if (CP.isPhys()) {
459 if (!MF.getRegInfo().isAllocatable(DstReg))
460 continue;
461
462 PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
463
Lang Hames57902cc2014-10-27 17:44:25 +0000464 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
465 G.getNodeMetadata(NId).getAllowedRegs();
Lang Hames54d63b42014-10-09 18:20:51 +0000466
467 unsigned PRegOpt = 0;
468 while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
469 ++PRegOpt;
470
471 if (PRegOpt < Allowed.size()) {
472 PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
Arnaud A. de Grandmaisona5d0ebd2014-10-21 16:24:15 +0000473 NewCosts[PRegOpt + 1] -= CBenefit;
Lang Hames54d63b42014-10-09 18:20:51 +0000474 G.setNodeCosts(NId, std::move(NewCosts));
475 }
476 } else {
477 PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
478 PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
Lang Hames57902cc2014-10-27 17:44:25 +0000479 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
480 &G.getNodeMetadata(N1Id).getAllowedRegs();
481 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
482 &G.getNodeMetadata(N2Id).getAllowedRegs();
Lang Hames54d63b42014-10-09 18:20:51 +0000483
484 PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
485 if (EId == G.invalidEdgeId()) {
486 PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
487 Allowed2->size() + 1, 0);
488 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
489 G.addEdge(N1Id, N2Id, std::move(Costs));
490 } else {
491 if (G.getEdgeNode1Id(EId) == N2Id) {
492 std::swap(N1Id, N2Id);
493 std::swap(Allowed1, Allowed2);
494 }
495 PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
496 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
Arnaud A. de Grandmaison8ee1b652015-02-11 08:25:36 +0000497 G.updateEdgeCosts(EId, std::move(Costs));
Lang Hames54d63b42014-10-09 18:20:51 +0000498 }
499 }
500 }
501 }
502 }
503
504private:
Lang Hames54d63b42014-10-09 18:20:51 +0000505 void addVirtRegCoalesce(
Lang Hames57902cc2014-10-27 17:44:25 +0000506 PBQPRAGraph::RawMatrix &CostMat,
507 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
508 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
509 PBQP::PBQPNum Benefit) {
Lang Hames54d63b42014-10-09 18:20:51 +0000510 assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
511 assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
512 for (unsigned I = 0; I != Allowed1.size(); ++I) {
513 unsigned PReg1 = Allowed1[I];
514 for (unsigned J = 0; J != Allowed2.size(); ++J) {
515 unsigned PReg2 = Allowed2[J];
516 if (PReg1 == PReg2)
Arnaud A. de Grandmaisona5d0ebd2014-10-21 16:24:15 +0000517 CostMat[I + 1][J + 1] -= Benefit;
Lang Hames54d63b42014-10-09 18:20:51 +0000518 }
519 }
520 }
Lang Hames54d63b42014-10-09 18:20:51 +0000521};
522
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000523} // end anonymous namespace
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000524
Lang Hames54d63b42014-10-09 18:20:51 +0000525// Out-of-line destructor/anchor for PBQPRAConstraint.
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000526PBQPRAConstraint::~PBQPRAConstraint() = default;
527
Lang Hames54d63b42014-10-09 18:20:51 +0000528void PBQPRAConstraint::anchor() {}
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000529
Lang Hames54d63b42014-10-09 18:20:51 +0000530void PBQPRAConstraintList::anchor() {}
Lang Hameseb6c8f52010-09-18 09:07:10 +0000531
532void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hames9ad7e072011-12-06 01:45:57 +0000533 au.setPreservesCFG();
Chandler Carruth91468332015-09-09 17:55:00 +0000534 au.addRequired<AAResultsWrapperPass>();
535 au.addPreserved<AAResultsWrapperPass>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000536 au.addRequired<SlotIndexes>();
537 au.addPreserved<SlotIndexes>();
538 au.addRequired<LiveIntervals>();
Lang Hames442c59f2012-10-04 04:50:53 +0000539 au.addPreserved<LiveIntervals>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000540 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames8d857662011-06-17 07:09:01 +0000541 if (customPassID)
542 au.addRequiredID(*customPassID);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000543 au.addRequired<LiveStacks>();
544 au.addPreserved<LiveStacks>();
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000545 au.addRequired<MachineBlockFrequencyInfo>();
546 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames781f5b32013-07-01 20:47:47 +0000547 au.addRequired<MachineLoopInfo>();
548 au.addPreserved<MachineLoopInfo>();
Lang Hames9ad7e072011-12-06 01:45:57 +0000549 au.addRequired<MachineDominatorTree>();
550 au.addPreserved<MachineDominatorTree>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000551 au.addRequired<VirtRegMap>();
Lang Hames442c59f2012-10-04 04:50:53 +0000552 au.addPreserved<VirtRegMap>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000553 MachineFunctionPass::getAnalysisUsage(au);
554}
555
Lang Hames54d63b42014-10-09 18:20:51 +0000556void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
557 LiveIntervals &LIS) {
558 const MachineRegisterInfo &MRI = MF.getRegInfo();
Lang Hames27601ef2008-11-16 12:12:54 +0000559
560 // Iterate over all live ranges.
Lang Hames54d63b42014-10-09 18:20:51 +0000561 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
562 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
563 if (MRI.reg_nodbg_empty(Reg))
Lang Hames27601ef2008-11-16 12:12:54 +0000564 continue;
Lang Hames2e9f9262018-02-20 22:15:09 +0000565 VRegsToAlloc.insert(Reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000566 }
Evan Chengb1290a62008-10-02 18:29:27 +0000567}
568
Arnaud A. de Grandmaisone1bec752014-11-04 20:51:29 +0000569static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI,
570 const MachineFunction &MF) {
Oren Ben Simhon6095a792017-03-14 09:09:26 +0000571 const MCPhysReg *CSR = MF.getRegInfo().getCalleeSavedRegs();
Arnaud A. de Grandmaisone1bec752014-11-04 20:51:29 +0000572 for (unsigned i = 0; CSR[i] != 0; ++i)
573 if (TRI.regsOverlap(reg, CSR[i]))
574 return true;
575 return false;
576}
577
Lang Hamesd54450e2015-02-03 06:14:06 +0000578void RegAllocPBQP::initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM,
579 Spiller &VRegSpiller) {
Lang Hames54d63b42014-10-09 18:20:51 +0000580 MachineFunction &MF = G.getMetadata().MF;
581
582 LiveIntervals &LIS = G.getMetadata().LIS;
583 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
584 const TargetRegisterInfo &TRI =
Eric Christopher05935e22015-01-27 08:27:06 +0000585 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames54d63b42014-10-09 18:20:51 +0000586
Lang Hamesd54450e2015-02-03 06:14:06 +0000587 std::vector<unsigned> Worklist(VRegsToAlloc.begin(), VRegsToAlloc.end());
588
Lang Hames2e9f9262018-02-20 22:15:09 +0000589 std::map<unsigned, std::vector<unsigned>> VRegAllowedMap;
590
Lang Hamesd54450e2015-02-03 06:14:06 +0000591 while (!Worklist.empty()) {
592 unsigned VReg = Worklist.back();
593 Worklist.pop_back();
594
Lang Hames54d63b42014-10-09 18:20:51 +0000595 LiveInterval &VRegLI = LIS.getInterval(VReg);
596
Lang Hames2e9f9262018-02-20 22:15:09 +0000597 // If this is an empty interval move it to the EmptyIntervalVRegs set then
598 // continue.
599 if (VRegLI.empty()) {
600 EmptyIntervalVRegs.insert(VRegLI.reg);
601 VRegsToAlloc.erase(VRegLI.reg);
602 continue;
603 }
604
605 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
606
Lang Hames54d63b42014-10-09 18:20:51 +0000607 // Record any overlaps with regmask operands.
608 BitVector RegMaskOverlaps;
609 LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
610
611 // Compute an initial allowed set for the current vreg.
612 std::vector<unsigned> VRegAllowed;
613 ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
614 for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
615 unsigned PReg = RawPRegOrder[I];
616 if (MRI.isReserved(PReg))
617 continue;
618
619 // vregLI crosses a regmask operand that clobbers preg.
620 if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
621 continue;
622
623 // vregLI overlaps fixed regunit interference.
624 bool Interference = false;
625 for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
626 if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
627 Interference = true;
628 break;
629 }
630 }
631 if (Interference)
632 continue;
633
634 // preg is usable for this virtual register.
635 VRegAllowed.push_back(PReg);
636 }
637
Lang Hamesd54450e2015-02-03 06:14:06 +0000638 // Check for vregs that have no allowed registers. These should be
639 // pre-spilled and the new vregs added to the worklist.
640 if (VRegAllowed.empty()) {
641 SmallVector<unsigned, 8> NewVRegs;
642 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
Benjamin Kramer1a50a122015-02-17 15:29:18 +0000643 Worklist.insert(Worklist.end(), NewVRegs.begin(), NewVRegs.end());
Lang Hamesd54450e2015-02-03 06:14:06 +0000644 continue;
Lang Hames2e9f9262018-02-20 22:15:09 +0000645 } else
646 VRegAllowedMap[VReg] = std::move(VRegAllowed);
647 }
648
649 for (auto &KV : VRegAllowedMap) {
650 auto VReg = KV.first;
651
652 // Move empty intervals to the EmptyIntervalVReg set.
653 if (LIS.getInterval(VReg).empty()) {
654 EmptyIntervalVRegs.insert(VReg);
655 VRegsToAlloc.erase(VReg);
656 continue;
Lang Hamesd54450e2015-02-03 06:14:06 +0000657 }
658
Lang Hames2e9f9262018-02-20 22:15:09 +0000659 auto &VRegAllowed = KV.second;
660
Lang Hames54d63b42014-10-09 18:20:51 +0000661 PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
Arnaud A. de Grandmaisone1bec752014-11-04 20:51:29 +0000662
663 // Tweak cost of callee saved registers, as using then force spilling and
664 // restoring them. This would only happen in the prologue / epilogue though.
665 for (unsigned i = 0; i != VRegAllowed.size(); ++i)
666 if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF))
667 NodeCosts[1 + i] += 1.0;
668
Lang Hames54d63b42014-10-09 18:20:51 +0000669 PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
670 G.getNodeMetadata(NId).setVReg(VReg);
Lang Hames57902cc2014-10-27 17:44:25 +0000671 G.getNodeMetadata(NId).setAllowedRegs(
672 G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
Lang Hames54d63b42014-10-09 18:20:51 +0000673 G.getMetadata().setNodeIdForVReg(VReg, NId);
674 }
675}
676
Lang Hamesd54450e2015-02-03 06:14:06 +0000677void RegAllocPBQP::spillVReg(unsigned VReg,
678 SmallVectorImpl<unsigned> &NewIntervals,
679 MachineFunction &MF, LiveIntervals &LIS,
680 VirtRegMap &VRM, Spiller &VRegSpiller) {
Lang Hamesd54450e2015-02-03 06:14:06 +0000681 VRegsToAlloc.erase(VReg);
Wei Mi815b02e2016-04-13 03:08:27 +0000682 LiveRangeEdit LRE(&LIS.getInterval(VReg), NewIntervals, MF, LIS, &VRM,
683 nullptr, &DeadRemats);
Lang Hamesd54450e2015-02-03 06:14:06 +0000684 VRegSpiller.spill(LRE);
685
686 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
687 (void)TRI;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000688 LLVM_DEBUG(dbgs() << "VREG " << printReg(VReg, &TRI) << " -> SPILLED (Cost: "
689 << LRE.getParent().weight << ", New vregs: ");
Lang Hamesd54450e2015-02-03 06:14:06 +0000690
691 // Copy any newly inserted live intervals into the list of regs to
692 // allocate.
693 for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
694 I != E; ++I) {
695 const LiveInterval &LI = LIS.getInterval(*I);
696 assert(!LI.empty() && "Empty spill range.");
Nicola Zaghen0818e782018-05-14 12:53:11 +0000697 LLVM_DEBUG(dbgs() << printReg(LI.reg, &TRI) << " ");
Lang Hamesd54450e2015-02-03 06:14:06 +0000698 VRegsToAlloc.insert(LI.reg);
699 }
700
Nicola Zaghen0818e782018-05-14 12:53:11 +0000701 LLVM_DEBUG(dbgs() << ")\n");
Lang Hamesd54450e2015-02-03 06:14:06 +0000702}
703
Lang Hames54d63b42014-10-09 18:20:51 +0000704bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
705 const PBQP::Solution &Solution,
706 VirtRegMap &VRM,
707 Spiller &VRegSpiller) {
708 MachineFunction &MF = G.getMetadata().MF;
709 LiveIntervals &LIS = G.getMetadata().LIS;
Eric Christopher05935e22015-01-27 08:27:06 +0000710 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
Lang Hames54d63b42014-10-09 18:20:51 +0000711 (void)TRI;
712
Lang Hameseb6c8f52010-09-18 09:07:10 +0000713 // Set to true if we have any spills
Lang Hames54d63b42014-10-09 18:20:51 +0000714 bool AnotherRoundNeeded = false;
Lang Hameseb6c8f52010-09-18 09:07:10 +0000715
716 // Clear the existing allocation.
Lang Hames54d63b42014-10-09 18:20:51 +0000717 VRM.clearAllVirt();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000718
Lang Hameseb6c8f52010-09-18 09:07:10 +0000719 // Iterate over the nodes mapping the PBQP solution to a register
720 // assignment.
Lang Hames54d63b42014-10-09 18:20:51 +0000721 for (auto NId : G.nodeIds()) {
722 unsigned VReg = G.getNodeMetadata(NId).getVReg();
723 unsigned AllocOption = Solution.getSelection(NId);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000724
Lang Hames54d63b42014-10-09 18:20:51 +0000725 if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
Lang Hames57902cc2014-10-27 17:44:25 +0000726 unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
Nicola Zaghen0818e782018-05-14 12:53:11 +0000727 LLVM_DEBUG(dbgs() << "VREG " << printReg(VReg, &TRI) << " -> "
728 << TRI.getName(PReg) << "\n");
Lang Hames54d63b42014-10-09 18:20:51 +0000729 assert(PReg != 0 && "Invalid preg selected.");
730 VRM.assignVirt2Phys(VReg, PReg);
731 } else {
Lang Hamesd54450e2015-02-03 06:14:06 +0000732 // Spill VReg. If this introduces new intervals we'll need another round
733 // of allocation.
734 SmallVector<unsigned, 8> NewVRegs;
735 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
736 AnotherRoundNeeded |= !NewVRegs.empty();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000737 }
738 }
739
Lang Hames54d63b42014-10-09 18:20:51 +0000740 return !AnotherRoundNeeded;
Lang Hameseb6c8f52010-09-18 09:07:10 +0000741}
742
Lang Hames54d63b42014-10-09 18:20:51 +0000743void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
744 LiveIntervals &LIS,
745 VirtRegMap &VRM) const {
746 MachineRegisterInfo &MRI = MF.getRegInfo();
747
Lang Hames27601ef2008-11-16 12:12:54 +0000748 // First allocate registers for the empty intervals.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000749 for (RegSet::const_iterator
Lang Hames54d63b42014-10-09 18:20:51 +0000750 I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
751 I != E; ++I) {
752 LiveInterval &LI = LIS.getInterval(*I);
Lang Hames27601ef2008-11-16 12:12:54 +0000753
Lang Hames54d63b42014-10-09 18:20:51 +0000754 unsigned PReg = MRI.getSimpleHint(LI.reg);
Lang Hames6699fb22009-08-06 23:32:48 +0000755
Lang Hames54d63b42014-10-09 18:20:51 +0000756 if (PReg == 0) {
757 const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg);
Matthias Braun9b4cf762017-06-08 21:30:54 +0000758 const ArrayRef<MCPhysReg> RawPRegOrder = RC.getRawAllocationOrder(MF);
759 for (unsigned CandidateReg : RawPRegOrder) {
760 if (!VRM.getRegInfo().isReserved(CandidateReg)) {
761 PReg = CandidateReg;
762 break;
763 }
764 }
765 assert(PReg &&
766 "No un-reserved physical registers in this register class");
Lang Hames27601ef2008-11-16 12:12:54 +0000767 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000768
Lang Hames54d63b42014-10-09 18:20:51 +0000769 VRM.assignVirt2Phys(LI.reg, PReg);
Lang Hames27601ef2008-11-16 12:12:54 +0000770 }
Lang Hames27601ef2008-11-16 12:12:54 +0000771}
772
Wei Mi815b02e2016-04-13 03:08:27 +0000773void RegAllocPBQP::postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS) {
774 VRegSpiller.postOptimization();
775 /// Remove dead defs because of rematerialization.
776 for (auto DeadInst : DeadRemats) {
777 LIS.RemoveMachineInstrFromMaps(*DeadInst);
778 DeadInst->eraseFromParent();
779 }
780 DeadRemats.clear();
781}
782
Arnaud A. de Grandmaison8025a392014-11-04 20:51:24 +0000783static inline float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size,
784 unsigned NumInstr) {
785 // All intervals have a spill weight that is mostly proportional to the number
786 // of uses, with uses in loops having a bigger weight.
787 return NumInstr * normalizeSpillWeight(UseDefFreq, Size, 1);
788}
789
Lang Hameseb6c8f52010-09-18 09:07:10 +0000790bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames54d63b42014-10-09 18:20:51 +0000791 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
792 MachineBlockFrequencyInfo &MBFI =
793 getAnalysis<MachineBlockFrequencyInfo>();
Lang Hames27601ef2008-11-16 12:12:54 +0000794
Lang Hames54d63b42014-10-09 18:20:51 +0000795 VirtRegMap &VRM = getAnalysis<VirtRegMap>();
Evan Chengb1290a62008-10-02 18:29:27 +0000796
Robert Lougher0d87d632015-08-10 11:59:44 +0000797 calculateSpillWeightsAndHints(LIS, MF, &VRM, getAnalysis<MachineLoopInfo>(),
798 MBFI, normalizePBQPSpillWeight);
799
Lang Hames54d63b42014-10-09 18:20:51 +0000800 std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
Arnaud A. de Grandmaisona77da052013-11-10 17:46:31 +0000801
Lang Hames54d63b42014-10-09 18:20:51 +0000802 MF.getRegInfo().freezeReservedRegs(MF);
Evan Chengb1290a62008-10-02 18:29:27 +0000803
Nicola Zaghen0818e782018-05-14 12:53:11 +0000804 LLVM_DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000805
Evan Chengb1290a62008-10-02 18:29:27 +0000806 // Allocator main loop:
Misha Brukman2a835f92009-01-08 15:50:22 +0000807 //
Evan Chengb1290a62008-10-02 18:29:27 +0000808 // * Map current regalloc problem to a PBQP problem
809 // * Solve the PBQP problem
810 // * Map the solution back to a register allocation
811 // * Spill if necessary
Misha Brukman2a835f92009-01-08 15:50:22 +0000812 //
Evan Chengb1290a62008-10-02 18:29:27 +0000813 // This process is continued till no more spills are generated.
814
Lang Hames27601ef2008-11-16 12:12:54 +0000815 // Find the vreg intervals in need of allocation.
Lang Hames54d63b42014-10-09 18:20:51 +0000816 findVRegIntervalsToAlloc(MF, LIS);
Misha Brukman2a835f92009-01-08 15:50:22 +0000817
Craig Topper96601ca2012-08-22 06:07:19 +0000818#ifndef NDEBUG
Matthias Braund3181392017-12-15 22:22:58 +0000819 const Function &F = MF.getFunction();
Lang Hames54d63b42014-10-09 18:20:51 +0000820 std::string FullyQualifiedName =
821 F.getParent()->getModuleIdentifier() + "." + F.getName().str();
Craig Topper96601ca2012-08-22 06:07:19 +0000822#endif
Lang Hames20df03c2012-03-26 23:07:23 +0000823
Lang Hames27601ef2008-11-16 12:12:54 +0000824 // If there are non-empty intervals allocate them using pbqp.
Lang Hames54d63b42014-10-09 18:20:51 +0000825 if (!VRegsToAlloc.empty()) {
Eric Christopher05935e22015-01-27 08:27:06 +0000826 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
Lang Hames54d63b42014-10-09 18:20:51 +0000827 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
828 llvm::make_unique<PBQPRAConstraintList>();
829 ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
830 ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
831 if (PBQPCoalescing)
832 ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
833 ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
Lang Hames27601ef2008-11-16 12:12:54 +0000834
Lang Hames54d63b42014-10-09 18:20:51 +0000835 bool PBQPAllocComplete = false;
836 unsigned Round = 0;
Lang Hames27601ef2008-11-16 12:12:54 +0000837
Lang Hames54d63b42014-10-09 18:20:51 +0000838 while (!PBQPAllocComplete) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000839 LLVM_DEBUG(dbgs() << " PBQP Regalloc round " << Round << ":\n");
Lang Hames54d63b42014-10-09 18:20:51 +0000840
841 PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
Lang Hamesd54450e2015-02-03 06:14:06 +0000842 initializeGraph(G, VRM, *VRegSpiller);
Lang Hames54d63b42014-10-09 18:20:51 +0000843 ConstraintsRoot->apply(G);
Lang Hames20df03c2012-03-26 23:07:23 +0000844
845#ifndef NDEBUG
Lang Hames54d63b42014-10-09 18:20:51 +0000846 if (PBQPDumpGraphs) {
847 std::ostringstream RS;
848 RS << Round;
849 std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
850 ".pbqpgraph";
Rafael Espindola8c968622014-08-25 18:16:47 +0000851 std::error_code EC;
Lang Hames54d63b42014-10-09 18:20:51 +0000852 raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000853 LLVM_DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
854 << GraphFileName << "\"\n");
Arnaud A. de Grandmaisonf0418612015-02-03 23:40:24 +0000855 G.dump(OS);
Lang Hames20df03c2012-03-26 23:07:23 +0000856 }
857#endif
858
Lang Hames54d63b42014-10-09 18:20:51 +0000859 PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
860 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
861 ++Round;
Lang Hames27601ef2008-11-16 12:12:54 +0000862 }
Evan Chengb1290a62008-10-02 18:29:27 +0000863 }
864
Lang Hames27601ef2008-11-16 12:12:54 +0000865 // Finalise allocation, allocate empty ranges.
Lang Hames54d63b42014-10-09 18:20:51 +0000866 finalizeAlloc(MF, LIS, VRM);
Wei Mi815b02e2016-04-13 03:08:27 +0000867 postOptimization(*VRegSpiller, LIS);
Lang Hames54d63b42014-10-09 18:20:51 +0000868 VRegsToAlloc.clear();
869 EmptyIntervalVRegs.clear();
Lang Hames27601ef2008-11-16 12:12:54 +0000870
Nicola Zaghen0818e782018-05-14 12:53:11 +0000871 LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000872
Misha Brukman2a835f92009-01-08 15:50:22 +0000873 return true;
Evan Chengb1290a62008-10-02 18:29:27 +0000874}
875
Matthias Braunae4aa8b2015-12-04 01:31:59 +0000876/// Create Printable object for node and register info.
877static Printable PrintNodeInfo(PBQP::RegAlloc::PBQPRAGraph::NodeId NId,
878 const PBQP::RegAlloc::PBQPRAGraph &G) {
879 return Printable([NId, &G](raw_ostream &OS) {
Arnaud A. de Grandmaisonf0418612015-02-03 23:40:24 +0000880 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
881 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
882 unsigned VReg = G.getNodeMetadata(NId).getVReg();
883 const char *RegClassName = TRI->getRegClassName(MRI.getRegClass(VReg));
Francis Visoiu Mistrihaccb3372017-11-28 12:42:37 +0000884 OS << NId << " (" << RegClassName << ':' << printReg(VReg, TRI) << ')';
Matthias Braunae4aa8b2015-12-04 01:31:59 +0000885 });
Arnaud A. de Grandmaisonf0418612015-02-03 23:40:24 +0000886}
Arnaud A. de Grandmaisonf0418612015-02-03 23:40:24 +0000887
Aaron Ballman1d03d382017-10-15 14:32:27 +0000888#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun88d20752017-01-28 02:02:38 +0000889LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump(raw_ostream &OS) const {
Arnaud A. de Grandmaisonf0418612015-02-03 23:40:24 +0000890 for (auto NId : nodeIds()) {
891 const Vector &Costs = getNodeCosts(NId);
892 assert(Costs.getLength() != 0 && "Empty vector in graph.");
893 OS << PrintNodeInfo(NId, *this) << ": " << Costs << '\n';
894 }
895 OS << '\n';
896
897 for (auto EId : edgeIds()) {
898 NodeId N1Id = getEdgeNode1Id(EId);
899 NodeId N2Id = getEdgeNode2Id(EId);
900 assert(N1Id != N2Id && "PBQP graphs should not have self-edges.");
901 const Matrix &M = getEdgeCosts(EId);
902 assert(M.getRows() != 0 && "No rows in matrix.");
903 assert(M.getCols() != 0 && "No cols in matrix.");
904 OS << PrintNodeInfo(N1Id, *this) << ' ' << M.getRows() << " rows / ";
905 OS << PrintNodeInfo(N2Id, *this) << ' ' << M.getCols() << " cols:\n";
906 OS << M << '\n';
907 }
908}
909
Matthias Braun88d20752017-01-28 02:02:38 +0000910LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump() const {
911 dump(dbgs());
912}
913#endif
Arnaud A. de Grandmaisonf0418612015-02-03 23:40:24 +0000914
915void PBQP::RegAlloc::PBQPRAGraph::printDot(raw_ostream &OS) const {
916 OS << "graph {\n";
917 for (auto NId : nodeIds()) {
918 OS << " node" << NId << " [ label=\""
919 << PrintNodeInfo(NId, *this) << "\\n"
920 << getNodeCosts(NId) << "\" ]\n";
921 }
922
923 OS << " edge [ len=" << nodeIds().size() << " ]\n";
924 for (auto EId : edgeIds()) {
925 OS << " node" << getEdgeNode1Id(EId)
926 << " -- node" << getEdgeNode2Id(EId)
927 << " [ label=\"";
928 const Matrix &EdgeCosts = getEdgeCosts(EId);
929 for (unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
930 OS << EdgeCosts.getRowAsVector(i) << "\\n";
931 }
932 OS << "\" ]\n";
933 }
934 OS << "}\n";
935}
936
Lang Hames54d63b42014-10-09 18:20:51 +0000937FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
938 return new RegAllocPBQP(customPassID);
Evan Chengb1290a62008-10-02 18:29:27 +0000939}
940
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000941FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Lang Hames54d63b42014-10-09 18:20:51 +0000942 return createPBQPRegisterAllocator();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000943}