blob: 3b5964eef55e4960fa563ec0c29279ed5e74412e [file] [log] [blame]
Eugene Zelenko49e2fc42017-02-21 22:07:52 +00001//===- RegAllocPBQP.cpp ---- PBQP Register Allocator ----------------------===//
Evan Chengb25f4632008-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 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
Rafael Espindolafef3c642011-06-26 21:41:06 +000032#include "RegisterCoalescer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "Spiller.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000034#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/BitVector.h"
36#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/StringRef.h"
Lang Hamesb13b6a02011-12-06 01:45:57 +000042#include "llvm/Analysis/AliasAnalysis.h"
Lang Hamesd17e2962009-12-14 06:49:42 +000043#include "llvm/CodeGen/CalcSpillWeights.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000044#include "llvm/CodeGen/LiveInterval.h"
Evan Chengb25f4632008-10-02 18:29:27 +000045#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000046#include "llvm/CodeGen/LiveRangeEdit.h"
Lang Hames49ab8bc2008-11-16 12:12:54 +000047#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000048#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Lang Hamesb13b6a02011-12-06 01:45:57 +000049#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000050#include "llvm/CodeGen/MachineFunction.h"
Misha Brukmanda467482009-01-08 15:50:22 +000051#include "llvm/CodeGen/MachineFunctionPass.h"
Lang Hames7d99d792013-07-01 20:47:47 +000052#include "llvm/CodeGen/MachineLoopInfo.h"
Misha Brukmanda467482009-01-08 15:50:22 +000053#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000054#include "llvm/CodeGen/PBQP/Graph.h"
55#include "llvm/CodeGen/PBQP/Solution.h"
56#include "llvm/CodeGen/PBQPRAConstraint.h"
57#include "llvm/CodeGen/RegAllocPBQP.h"
Misha Brukmanda467482009-01-08 15:50:22 +000058#include "llvm/CodeGen/RegAllocRegistry.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000059#include "llvm/CodeGen/SlotIndexes.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000060#include "llvm/CodeGen/VirtRegMap.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000061#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000062#include "llvm/IR/Module.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000063#include "llvm/MC/MCRegisterInfo.h"
64#include "llvm/Pass.h"
65#include "llvm/Support/CommandLine.h"
66#include "llvm/Support/Compiler.h"
Evan Chengb25f4632008-10-02 18:29:27 +000067#include "llvm/Support/Debug.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000068#include "llvm/Support/FileSystem.h"
Matthias Braunc07cbc82015-12-04 01:31:59 +000069#include "llvm/Support/Printable.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000070#include "llvm/Support/raw_ostream.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000071#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000072#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000073#include <algorithm>
74#include <cassert>
75#include <cstddef>
Misha Brukmanda467482009-01-08 15:50:22 +000076#include <limits>
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000077#include <map>
Misha Brukmanda467482009-01-08 15:50:22 +000078#include <memory>
Lang Hamesad0962a2014-10-18 17:26:07 +000079#include <queue>
Evan Chengb25f4632008-10-02 18:29:27 +000080#include <set>
Lang Hames95e021f2012-03-26 23:07:23 +000081#include <sstream>
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000082#include <string>
83#include <system_error>
84#include <tuple>
Evan Chengb25f4632008-10-02 18:29:27 +000085#include <vector>
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000086#include <utility>
Evan Chengb25f4632008-10-02 18:29:27 +000087
Lang Hamesfd1bc422010-09-23 04:28:54 +000088using namespace llvm;
Lang Hamescb1e1012010-09-18 09:07:10 +000089
Chandler Carruth1b9dde02014-04-22 02:02:50 +000090#define DEBUG_TYPE "regalloc"
91
Evan Chengb25f4632008-10-02 18:29:27 +000092static RegisterRegAlloc
Lang Hames8f31f442014-10-09 18:20:51 +000093RegisterPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesfd1bc422010-09-23 04:28:54 +000094 createDefaultPBQPRegisterAllocator);
Evan Chengb25f4632008-10-02 18:29:27 +000095
Lang Hames11732ad2009-08-19 01:36:14 +000096static cl::opt<bool>
Lang Hames8f31f442014-10-09 18:20:51 +000097PBQPCoalescing("pbqp-coalescing",
Lang Hames090c7e82010-01-26 04:49:58 +000098 cl::desc("Attempt coalescing during PBQP register allocation."),
99 cl::init(false), cl::Hidden);
Lang Hames11732ad2009-08-19 01:36:14 +0000100
Lang Hames95e021f2012-03-26 23:07:23 +0000101#ifndef NDEBUG
102static cl::opt<bool>
Lang Hames8f31f442014-10-09 18:20:51 +0000103PBQPDumpGraphs("pbqp-dump-graphs",
Lang Hames95e021f2012-03-26 23:07:23 +0000104 cl::desc("Dump graphs for each function/round in the compilation unit."),
105 cl::init(false), cl::Hidden);
106#endif
107
Lang Hamesfd1bc422010-09-23 04:28:54 +0000108namespace {
109
110///
111/// PBQP based allocators solve the register allocation problem by mapping
112/// register allocation problems to Partitioned Boolean Quadratic
113/// Programming problems.
114class RegAllocPBQP : public MachineFunctionPass {
115public:
Lang Hamesfd1bc422010-09-23 04:28:54 +0000116 static char ID;
117
118 /// Construct a PBQP register allocator.
Lang Hames8f31f442014-10-09 18:20:51 +0000119 RegAllocPBQP(char *cPassID = nullptr)
120 : MachineFunctionPass(ID), customPassID(cPassID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000121 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
122 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000123 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000124 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000125 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000126
127 /// Return the pass name.
Mehdi Amini117296c2016-10-01 02:56:57 +0000128 StringRef getPassName() const override { return "PBQP Register Allocator"; }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000129
130 /// PBQP analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000131 void getAnalysisUsage(AnalysisUsage &au) const override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000132
133 /// Perform register allocation
Craig Topper4584cd52014-03-07 09:26:03 +0000134 bool runOnMachineFunction(MachineFunction &MF) override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000135
Matthias Braun90799ce2016-08-23 21:19:49 +0000136 MachineFunctionProperties getRequiredProperties() const override {
137 return MachineFunctionProperties().set(
138 MachineFunctionProperties::Property::NoPHIs);
139 }
140
Lang Hamesfd1bc422010-09-23 04:28:54 +0000141private:
Lang Hamesfd1bc422010-09-23 04:28:54 +0000142 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
143 typedef std::vector<const LiveInterval*> Node2LIMap;
144 typedef std::vector<unsigned> AllowedSet;
145 typedef std::vector<AllowedSet> AllowedSetMap;
146 typedef std::pair<unsigned, unsigned> RegPair;
147 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000148 typedef std::set<unsigned> RegSet;
149
Lang Hames934625e2011-06-17 07:09:01 +0000150 char *customPassID;
151
Lang Hames8f31f442014-10-09 18:20:51 +0000152 RegSet VRegsToAlloc, EmptyIntervalVRegs;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000153
Wei Mi9a16d652016-04-13 03:08:27 +0000154 /// Inst which is a def of an original reg and whose defs are already all
155 /// dead after remat is saved in DeadRemats. The deletion of such inst is
156 /// postponed till all the allocations are done, so its remat expr is
157 /// always available for the remat of all the siblings of the original reg.
158 SmallPtrSet<MachineInstr *, 32> DeadRemats;
159
Lang Hamesfd1bc422010-09-23 04:28:54 +0000160 /// \brief Finds the initial set of vreg intervals to allocate.
Lang Hames8f31f442014-10-09 18:20:51 +0000161 void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS);
162
163 /// \brief Constructs an initial graph.
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000164 void initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM, Spiller &VRegSpiller);
165
166 /// \brief Spill the given VReg.
167 void spillVReg(unsigned VReg, SmallVectorImpl<unsigned> &NewIntervals,
168 MachineFunction &MF, LiveIntervals &LIS, VirtRegMap &VRM,
169 Spiller &VRegSpiller);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000170
Lang Hamesfd1bc422010-09-23 04:28:54 +0000171 /// \brief Given a solved PBQP problem maps this solution back to a register
172 /// assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000173 bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
174 const PBQP::Solution &Solution,
175 VirtRegMap &VRM,
176 Spiller &VRegSpiller);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000177
178 /// \brief Postprocessing before final spilling. Sets basic block "live in"
179 /// variables.
Lang Hames8f31f442014-10-09 18:20:51 +0000180 void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
181 VirtRegMap &VRM) const;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000182
Wei Mi9a16d652016-04-13 03:08:27 +0000183 void postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000184};
185
Lang Hamescb1e1012010-09-18 09:07:10 +0000186char RegAllocPBQP::ID = 0;
Evan Chengb25f4632008-10-02 18:29:27 +0000187
Lang Hames8f31f442014-10-09 18:20:51 +0000188/// @brief Set spill costs for each node in the PBQP reg-alloc graph.
189class SpillCosts : public PBQPRAConstraint {
190public:
191 void apply(PBQPRAGraph &G) override {
192 LiveIntervals &LIS = G.getMetadata().LIS;
193
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000194 // A minimum spill costs, so that register constraints can can be set
195 // without normalization in the [0.0:MinSpillCost( interval.
196 const PBQP::PBQPNum MinSpillCost = 10.0;
197
Lang Hames8f31f442014-10-09 18:20:51 +0000198 for (auto NId : G.nodeIds()) {
199 PBQP::PBQPNum SpillCost =
200 LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight;
201 if (SpillCost == 0.0)
202 SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000203 else
204 SpillCost += MinSpillCost;
Lang Hames8f31f442014-10-09 18:20:51 +0000205 PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
206 NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
207 G.setNodeCosts(NId, std::move(NodeCosts));
208 }
209 }
210};
211
212/// @brief Add interference edges between overlapping vregs.
213class Interference : public PBQPRAConstraint {
Lang Hamesad0962a2014-10-18 17:26:07 +0000214private:
Lang Hames5fe30ca2014-10-27 17:44:25 +0000215 typedef const PBQP::RegAlloc::AllowedRegVector* AllowedRegVecPtr;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000216 typedef std::pair<AllowedRegVecPtr, AllowedRegVecPtr> IKey;
217 typedef DenseMap<IKey, PBQPRAGraph::MatrixPtr> IMatrixCache;
218 typedef DenseSet<IKey> DisjointAllowedRegsCache;
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000219 typedef std::pair<PBQP::GraphBase::NodeId, PBQP::GraphBase::NodeId> IEdgeKey;
220 typedef DenseSet<IEdgeKey> IEdgeCache;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000221
222 bool haveDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
223 PBQPRAGraph::NodeId MId,
224 const DisjointAllowedRegsCache &D) const {
225 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
226 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
227
228 if (NRegs == MRegs)
229 return false;
230
231 if (NRegs < MRegs)
232 return D.count(IKey(NRegs, MRegs)) > 0;
Arnaud A. de Grandmaisona57ca812015-03-01 21:22:50 +0000233
234 return D.count(IKey(MRegs, NRegs)) > 0;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000235 }
236
237 void setDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
238 PBQPRAGraph::NodeId MId,
239 DisjointAllowedRegsCache &D) {
240 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
241 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
242
243 assert(NRegs != MRegs && "AllowedRegs can not be disjoint with itself");
244
245 if (NRegs < MRegs)
246 D.insert(IKey(NRegs, MRegs));
247 else
248 D.insert(IKey(MRegs, NRegs));
249 }
Lang Hames5fe30ca2014-10-27 17:44:25 +0000250
Lang Hamesad0962a2014-10-18 17:26:07 +0000251 // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
252 // for the fast interference graph construction algorithm. The last is there
253 // to save us from looking up node ids via the VRegToNode map in the graph
254 // metadata.
255 typedef std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>
256 IntervalInfo;
257
258 static SlotIndex getStartPoint(const IntervalInfo &I) {
259 return std::get<0>(I)->segments[std::get<1>(I)].start;
260 }
261
262 static SlotIndex getEndPoint(const IntervalInfo &I) {
263 return std::get<0>(I)->segments[std::get<1>(I)].end;
264 }
265
266 static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
267 return std::get<2>(I);
268 }
269
270 static bool lowestStartPoint(const IntervalInfo &I1,
271 const IntervalInfo &I2) {
272 // Condition reversed because priority queue has the *highest* element at
273 // the front, rather than the lowest.
274 return getStartPoint(I1) > getStartPoint(I2);
275 }
276
277 static bool lowestEndPoint(const IntervalInfo &I1,
278 const IntervalInfo &I2) {
279 SlotIndex E1 = getEndPoint(I1);
280 SlotIndex E2 = getEndPoint(I2);
281
282 if (E1 < E2)
283 return true;
284
285 if (E1 > E2)
286 return false;
287
288 // If two intervals end at the same point, we need a way to break the tie or
289 // the set will assume they're actually equal and refuse to insert a
290 // "duplicate". Just compare the vregs - fast and guaranteed unique.
291 return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
292 }
293
294 static bool isAtLastSegment(const IntervalInfo &I) {
295 return std::get<1>(I) == std::get<0>(I)->size() - 1;
296 }
297
298 static IntervalInfo nextSegment(const IntervalInfo &I) {
299 return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
300 }
301
Lang Hames8f31f442014-10-09 18:20:51 +0000302public:
Lang Hames8f31f442014-10-09 18:20:51 +0000303 void apply(PBQPRAGraph &G) override {
Lang Hamesad0962a2014-10-18 17:26:07 +0000304 // The following is loosely based on the linear scan algorithm introduced in
305 // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
306 // isn't linear, because the size of the active set isn't bound by the
307 // number of registers, but rather the size of the largest clique in the
308 // graph. Still, we expect this to be better than N^2.
Lang Hames8f31f442014-10-09 18:20:51 +0000309 LiveIntervals &LIS = G.getMetadata().LIS;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000310
311 // Interferenc matrices are incredibly regular - they're only a function of
312 // the allowed sets, so we cache them to avoid the overhead of constructing
313 // and uniquing them.
314 IMatrixCache C;
Lang Hames8f31f442014-10-09 18:20:51 +0000315
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000316 // Finding an edge is expensive in the worst case (O(max_clique(G))). So
317 // cache locally edges we have already seen.
318 IEdgeCache EC;
319
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000320 // Cache known disjoint allowed registers pairs
321 DisjointAllowedRegsCache D;
322
Lang Hamesad0962a2014-10-18 17:26:07 +0000323 typedef std::set<IntervalInfo, decltype(&lowestEndPoint)> IntervalSet;
324 typedef std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
325 decltype(&lowestStartPoint)> IntervalQueue;
326 IntervalSet Active(lowestEndPoint);
327 IntervalQueue Inactive(lowestStartPoint);
Lang Hames8f31f442014-10-09 18:20:51 +0000328
Lang Hamesad0962a2014-10-18 17:26:07 +0000329 // Start by building the inactive set.
330 for (auto NId : G.nodeIds()) {
331 unsigned VReg = G.getNodeMetadata(NId).getVReg();
332 LiveInterval &LI = LIS.getInterval(VReg);
333 assert(!LI.empty() && "PBQP graph contains node for empty interval");
334 Inactive.push(std::make_tuple(&LI, 0, NId));
335 }
Lang Hames8f31f442014-10-09 18:20:51 +0000336
Lang Hamesad0962a2014-10-18 17:26:07 +0000337 while (!Inactive.empty()) {
338 // Tentatively grab the "next" interval - this choice may be overriden
339 // below.
340 IntervalInfo Cur = Inactive.top();
341
342 // Retire any active intervals that end before Cur starts.
343 IntervalSet::iterator RetireItr = Active.begin();
344 while (RetireItr != Active.end() &&
345 (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
346 // If this interval has subsequent segments, add the next one to the
347 // inactive list.
348 if (!isAtLastSegment(*RetireItr))
349 Inactive.push(nextSegment(*RetireItr));
350
351 ++RetireItr;
Lang Hames8f31f442014-10-09 18:20:51 +0000352 }
Lang Hamesad0962a2014-10-18 17:26:07 +0000353 Active.erase(Active.begin(), RetireItr);
354
355 // One of the newly retired segments may actually start before the
356 // Cur segment, so re-grab the front of the inactive list.
357 Cur = Inactive.top();
358 Inactive.pop();
359
360 // At this point we know that Cur overlaps all active intervals. Add the
361 // interference edges.
362 PBQP::GraphBase::NodeId NId = getNodeId(Cur);
363 for (const auto &A : Active) {
364 PBQP::GraphBase::NodeId MId = getNodeId(A);
365
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000366 // Do not add an edge when the nodes' allowed registers do not
367 // intersect: there is obviously no interference.
368 if (haveDisjointAllowedRegs(G, NId, MId, D))
369 continue;
370
Lang Hamesad0962a2014-10-18 17:26:07 +0000371 // Check that we haven't already added this edge
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000372 IEdgeKey EK(std::min(NId, MId), std::max(NId, MId));
373 if (EC.count(EK))
Lang Hamesad0962a2014-10-18 17:26:07 +0000374 continue;
375
376 // This is a new edge - add it to the graph.
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000377 if (!createInterferenceEdge(G, NId, MId, C))
378 setDisjointAllowedRegs(G, NId, MId, D);
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000379 else
380 EC.insert(EK);
Lang Hamesad0962a2014-10-18 17:26:07 +0000381 }
382
383 // Finally, add Cur to the Active set.
384 Active.insert(Cur);
Lang Hames8f31f442014-10-09 18:20:51 +0000385 }
386 }
387
388private:
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000389 // Create an Interference edge and add it to the graph, unless it is
390 // a null matrix, meaning the nodes' allowed registers do not have any
391 // interference. This case occurs frequently between integer and floating
392 // point registers for example.
393 // return true iff both nodes interferes.
394 bool createInterferenceEdge(PBQPRAGraph &G,
395 PBQPRAGraph::NodeId NId, PBQPRAGraph::NodeId MId,
396 IMatrixCache &C) {
Lang Hames5fe30ca2014-10-27 17:44:25 +0000397 const TargetRegisterInfo &TRI =
Eric Christopher7592b0c2015-01-27 08:27:06 +0000398 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames5fe30ca2014-10-27 17:44:25 +0000399 const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
400 const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
401
402 // Try looking the edge costs up in the IMatrixCache first.
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000403 IKey K(&NRegs, &MRegs);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000404 IMatrixCache::iterator I = C.find(K);
405 if (I != C.end()) {
406 G.addEdgeBypassingCostAllocator(NId, MId, I->second);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000407 return true;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000408 }
409
410 PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000411 bool NodesInterfere = false;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000412 for (unsigned I = 0; I != NRegs.size(); ++I) {
413 unsigned PRegN = NRegs[I];
414 for (unsigned J = 0; J != MRegs.size(); ++J) {
415 unsigned PRegM = MRegs[J];
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000416 if (TRI.regsOverlap(PRegN, PRegM)) {
Lang Hames8f31f442014-10-09 18:20:51 +0000417 M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000418 NodesInterfere = true;
419 }
Lang Hames8f31f442014-10-09 18:20:51 +0000420 }
421 }
422
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000423 if (!NodesInterfere)
424 return false;
425
Lang Hames5fe30ca2014-10-27 17:44:25 +0000426 PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
427 C[K] = G.getEdgeCostsPtr(EId);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000428
429 return true;
Lang Hames8f31f442014-10-09 18:20:51 +0000430 }
431};
432
Lang Hames8f31f442014-10-09 18:20:51 +0000433class Coalescing : public PBQPRAConstraint {
434public:
435 void apply(PBQPRAGraph &G) override {
436 MachineFunction &MF = G.getMetadata().MF;
437 MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
Eric Christopher7592b0c2015-01-27 08:27:06 +0000438 CoalescerPair CP(*MF.getSubtarget().getRegisterInfo());
Lang Hames8f31f442014-10-09 18:20:51 +0000439
440 // Scan the machine function and add a coalescing cost whenever CoalescerPair
441 // gives the Ok.
442 for (const auto &MBB : MF) {
443 for (const auto &MI : MBB) {
Lang Hames8f31f442014-10-09 18:20:51 +0000444 // Skip not-coalescable or already coalesced copies.
445 if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
446 continue;
447
448 unsigned DstReg = CP.getDstReg();
449 unsigned SrcReg = CP.getSrcReg();
450
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000451 const float Scale = 1.0f / MBFI.getEntryFreq();
452 PBQP::PBQPNum CBenefit = MBFI.getBlockFreq(&MBB).getFrequency() * Scale;
Lang Hames8f31f442014-10-09 18:20:51 +0000453
454 if (CP.isPhys()) {
455 if (!MF.getRegInfo().isAllocatable(DstReg))
456 continue;
457
458 PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
459
Lang Hames5fe30ca2014-10-27 17:44:25 +0000460 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
461 G.getNodeMetadata(NId).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000462
463 unsigned PRegOpt = 0;
464 while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
465 ++PRegOpt;
466
467 if (PRegOpt < Allowed.size()) {
468 PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000469 NewCosts[PRegOpt + 1] -= CBenefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000470 G.setNodeCosts(NId, std::move(NewCosts));
471 }
472 } else {
473 PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
474 PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000475 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
476 &G.getNodeMetadata(N1Id).getAllowedRegs();
477 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
478 &G.getNodeMetadata(N2Id).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000479
480 PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
481 if (EId == G.invalidEdgeId()) {
482 PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
483 Allowed2->size() + 1, 0);
484 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
485 G.addEdge(N1Id, N2Id, std::move(Costs));
486 } else {
487 if (G.getEdgeNode1Id(EId) == N2Id) {
488 std::swap(N1Id, N2Id);
489 std::swap(Allowed1, Allowed2);
490 }
491 PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
492 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
Arnaud A. de Grandmaisonde790262015-02-11 08:25:36 +0000493 G.updateEdgeCosts(EId, std::move(Costs));
Lang Hames8f31f442014-10-09 18:20:51 +0000494 }
495 }
496 }
497 }
498 }
499
500private:
Lang Hames8f31f442014-10-09 18:20:51 +0000501 void addVirtRegCoalesce(
Lang Hames5fe30ca2014-10-27 17:44:25 +0000502 PBQPRAGraph::RawMatrix &CostMat,
503 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
504 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
505 PBQP::PBQPNum Benefit) {
Lang Hames8f31f442014-10-09 18:20:51 +0000506 assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
507 assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
508 for (unsigned I = 0; I != Allowed1.size(); ++I) {
509 unsigned PReg1 = Allowed1[I];
510 for (unsigned J = 0; J != Allowed2.size(); ++J) {
511 unsigned PReg2 = Allowed2[J];
512 if (PReg1 == PReg2)
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000513 CostMat[I + 1][J + 1] -= Benefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000514 }
515 }
516 }
Lang Hames8f31f442014-10-09 18:20:51 +0000517};
518
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000519} // end anonymous namespace
Lang Hamesfd1bc422010-09-23 04:28:54 +0000520
Lang Hames8f31f442014-10-09 18:20:51 +0000521// Out-of-line destructor/anchor for PBQPRAConstraint.
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000522PBQPRAConstraint::~PBQPRAConstraint() = default;
523
Lang Hames8f31f442014-10-09 18:20:51 +0000524void PBQPRAConstraint::anchor() {}
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000525
Lang Hames8f31f442014-10-09 18:20:51 +0000526void PBQPRAConstraintList::anchor() {}
Lang Hamescb1e1012010-09-18 09:07:10 +0000527
528void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hamesb13b6a02011-12-06 01:45:57 +0000529 au.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000530 au.addRequired<AAResultsWrapperPass>();
531 au.addPreserved<AAResultsWrapperPass>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000532 au.addRequired<SlotIndexes>();
533 au.addPreserved<SlotIndexes>();
534 au.addRequired<LiveIntervals>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000535 au.addPreserved<LiveIntervals>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000536 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames934625e2011-06-17 07:09:01 +0000537 if (customPassID)
538 au.addRequiredID(*customPassID);
Lang Hamescb1e1012010-09-18 09:07:10 +0000539 au.addRequired<LiveStacks>();
540 au.addPreserved<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000541 au.addRequired<MachineBlockFrequencyInfo>();
542 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames7d99d792013-07-01 20:47:47 +0000543 au.addRequired<MachineLoopInfo>();
544 au.addPreserved<MachineLoopInfo>();
Lang Hamesb13b6a02011-12-06 01:45:57 +0000545 au.addRequired<MachineDominatorTree>();
546 au.addPreserved<MachineDominatorTree>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000547 au.addRequired<VirtRegMap>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000548 au.addPreserved<VirtRegMap>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000549 MachineFunctionPass::getAnalysisUsage(au);
550}
551
Lang Hames8f31f442014-10-09 18:20:51 +0000552void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
553 LiveIntervals &LIS) {
554 const MachineRegisterInfo &MRI = MF.getRegInfo();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000555
556 // Iterate over all live ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000557 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
558 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
559 if (MRI.reg_nodbg_empty(Reg))
Lang Hames49ab8bc2008-11-16 12:12:54 +0000560 continue;
Lang Hames8f31f442014-10-09 18:20:51 +0000561 LiveInterval &LI = LIS.getInterval(Reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000562
563 // If this live interval is non-empty we will use pbqp to allocate it.
564 // Empty intervals we allocate in a simple post-processing stage in
565 // finalizeAlloc.
Lang Hames8f31f442014-10-09 18:20:51 +0000566 if (!LI.empty()) {
567 VRegsToAlloc.insert(LI.reg);
Lang Hamesc702ba62010-11-12 05:47:21 +0000568 } else {
Lang Hames8f31f442014-10-09 18:20:51 +0000569 EmptyIntervalVRegs.insert(LI.reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000570 }
571 }
Evan Chengb25f4632008-10-02 18:29:27 +0000572}
573
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000574static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI,
575 const MachineFunction &MF) {
Oren Ben Simhonfe34c5e2017-03-14 09:09:26 +0000576 const MCPhysReg *CSR = MF.getRegInfo().getCalleeSavedRegs();
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000577 for (unsigned i = 0; CSR[i] != 0; ++i)
578 if (TRI.regsOverlap(reg, CSR[i]))
579 return true;
580 return false;
581}
582
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000583void RegAllocPBQP::initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM,
584 Spiller &VRegSpiller) {
Lang Hames8f31f442014-10-09 18:20:51 +0000585 MachineFunction &MF = G.getMetadata().MF;
586
587 LiveIntervals &LIS = G.getMetadata().LIS;
588 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
589 const TargetRegisterInfo &TRI =
Eric Christopher7592b0c2015-01-27 08:27:06 +0000590 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames8f31f442014-10-09 18:20:51 +0000591
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000592 std::vector<unsigned> Worklist(VRegsToAlloc.begin(), VRegsToAlloc.end());
593
594 while (!Worklist.empty()) {
595 unsigned VReg = Worklist.back();
596 Worklist.pop_back();
597
Lang Hames8f31f442014-10-09 18:20:51 +0000598 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
599 LiveInterval &VRegLI = LIS.getInterval(VReg);
600
601 // Record any overlaps with regmask operands.
602 BitVector RegMaskOverlaps;
603 LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
604
605 // Compute an initial allowed set for the current vreg.
606 std::vector<unsigned> VRegAllowed;
607 ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
608 for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
609 unsigned PReg = RawPRegOrder[I];
610 if (MRI.isReserved(PReg))
611 continue;
612
613 // vregLI crosses a regmask operand that clobbers preg.
614 if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
615 continue;
616
617 // vregLI overlaps fixed regunit interference.
618 bool Interference = false;
619 for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
620 if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
621 Interference = true;
622 break;
623 }
624 }
625 if (Interference)
626 continue;
627
628 // preg is usable for this virtual register.
629 VRegAllowed.push_back(PReg);
630 }
631
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000632 // Check for vregs that have no allowed registers. These should be
633 // pre-spilled and the new vregs added to the worklist.
634 if (VRegAllowed.empty()) {
635 SmallVector<unsigned, 8> NewVRegs;
636 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000637 Worklist.insert(Worklist.end(), NewVRegs.begin(), NewVRegs.end());
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000638 continue;
639 }
640
Lang Hames8f31f442014-10-09 18:20:51 +0000641 PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000642
643 // Tweak cost of callee saved registers, as using then force spilling and
644 // restoring them. This would only happen in the prologue / epilogue though.
645 for (unsigned i = 0; i != VRegAllowed.size(); ++i)
646 if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF))
647 NodeCosts[1 + i] += 1.0;
648
Lang Hames8f31f442014-10-09 18:20:51 +0000649 PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
650 G.getNodeMetadata(NId).setVReg(VReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000651 G.getNodeMetadata(NId).setAllowedRegs(
652 G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
Lang Hames8f31f442014-10-09 18:20:51 +0000653 G.getMetadata().setNodeIdForVReg(VReg, NId);
654 }
655}
656
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000657void RegAllocPBQP::spillVReg(unsigned VReg,
658 SmallVectorImpl<unsigned> &NewIntervals,
659 MachineFunction &MF, LiveIntervals &LIS,
660 VirtRegMap &VRM, Spiller &VRegSpiller) {
661
662 VRegsToAlloc.erase(VReg);
Wei Mi9a16d652016-04-13 03:08:27 +0000663 LiveRangeEdit LRE(&LIS.getInterval(VReg), NewIntervals, MF, LIS, &VRM,
664 nullptr, &DeadRemats);
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000665 VRegSpiller.spill(LRE);
666
667 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
668 (void)TRI;
669 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> SPILLED (Cost: "
670 << LRE.getParent().weight << ", New vregs: ");
671
672 // Copy any newly inserted live intervals into the list of regs to
673 // allocate.
674 for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
675 I != E; ++I) {
676 const LiveInterval &LI = LIS.getInterval(*I);
677 assert(!LI.empty() && "Empty spill range.");
678 DEBUG(dbgs() << PrintReg(LI.reg, &TRI) << " ");
679 VRegsToAlloc.insert(LI.reg);
680 }
681
682 DEBUG(dbgs() << ")\n");
683}
684
Lang Hames8f31f442014-10-09 18:20:51 +0000685bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
686 const PBQP::Solution &Solution,
687 VirtRegMap &VRM,
688 Spiller &VRegSpiller) {
689 MachineFunction &MF = G.getMetadata().MF;
690 LiveIntervals &LIS = G.getMetadata().LIS;
Eric Christopher7592b0c2015-01-27 08:27:06 +0000691 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
Lang Hames8f31f442014-10-09 18:20:51 +0000692 (void)TRI;
693
Lang Hamescb1e1012010-09-18 09:07:10 +0000694 // Set to true if we have any spills
Lang Hames8f31f442014-10-09 18:20:51 +0000695 bool AnotherRoundNeeded = false;
Lang Hamescb1e1012010-09-18 09:07:10 +0000696
697 // Clear the existing allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000698 VRM.clearAllVirt();
Lang Hamescb1e1012010-09-18 09:07:10 +0000699
Lang Hamescb1e1012010-09-18 09:07:10 +0000700 // Iterate over the nodes mapping the PBQP solution to a register
701 // assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000702 for (auto NId : G.nodeIds()) {
703 unsigned VReg = G.getNodeMetadata(NId).getVReg();
704 unsigned AllocOption = Solution.getSelection(NId);
Lang Hamescb1e1012010-09-18 09:07:10 +0000705
Lang Hames8f31f442014-10-09 18:20:51 +0000706 if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
Lang Hames5fe30ca2014-10-27 17:44:25 +0000707 unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
Lang Hames8f31f442014-10-09 18:20:51 +0000708 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> "
709 << TRI.getName(PReg) << "\n");
710 assert(PReg != 0 && "Invalid preg selected.");
711 VRM.assignVirt2Phys(VReg, PReg);
712 } else {
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000713 // Spill VReg. If this introduces new intervals we'll need another round
714 // of allocation.
715 SmallVector<unsigned, 8> NewVRegs;
716 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
717 AnotherRoundNeeded |= !NewVRegs.empty();
Lang Hamescb1e1012010-09-18 09:07:10 +0000718 }
719 }
720
Lang Hames8f31f442014-10-09 18:20:51 +0000721 return !AnotherRoundNeeded;
Lang Hamescb1e1012010-09-18 09:07:10 +0000722}
723
Lang Hames8f31f442014-10-09 18:20:51 +0000724void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
725 LiveIntervals &LIS,
726 VirtRegMap &VRM) const {
727 MachineRegisterInfo &MRI = MF.getRegInfo();
728
Lang Hames49ab8bc2008-11-16 12:12:54 +0000729 // First allocate registers for the empty intervals.
Lang Hamescb1e1012010-09-18 09:07:10 +0000730 for (RegSet::const_iterator
Lang Hames8f31f442014-10-09 18:20:51 +0000731 I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
732 I != E; ++I) {
733 LiveInterval &LI = LIS.getInterval(*I);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000734
Lang Hames8f31f442014-10-09 18:20:51 +0000735 unsigned PReg = MRI.getSimpleHint(LI.reg);
Lang Hames88fae6f2009-08-06 23:32:48 +0000736
Lang Hames8f31f442014-10-09 18:20:51 +0000737 if (PReg == 0) {
738 const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg);
739 PReg = RC.getRawAllocationOrder(MF).front();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000740 }
Misha Brukmanda467482009-01-08 15:50:22 +0000741
Lang Hames8f31f442014-10-09 18:20:51 +0000742 VRM.assignVirt2Phys(LI.reg, PReg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000743 }
Lang Hames49ab8bc2008-11-16 12:12:54 +0000744}
745
Wei Mi9a16d652016-04-13 03:08:27 +0000746void RegAllocPBQP::postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS) {
747 VRegSpiller.postOptimization();
748 /// Remove dead defs because of rematerialization.
749 for (auto DeadInst : DeadRemats) {
750 LIS.RemoveMachineInstrFromMaps(*DeadInst);
751 DeadInst->eraseFromParent();
752 }
753 DeadRemats.clear();
754}
755
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000756static inline float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size,
757 unsigned NumInstr) {
758 // All intervals have a spill weight that is mostly proportional to the number
759 // of uses, with uses in loops having a bigger weight.
760 return NumInstr * normalizeSpillWeight(UseDefFreq, Size, 1);
761}
762
Lang Hamescb1e1012010-09-18 09:07:10 +0000763bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames8f31f442014-10-09 18:20:51 +0000764 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
765 MachineBlockFrequencyInfo &MBFI =
766 getAnalysis<MachineBlockFrequencyInfo>();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000767
Lang Hames8f31f442014-10-09 18:20:51 +0000768 VirtRegMap &VRM = getAnalysis<VirtRegMap>();
Evan Chengb25f4632008-10-02 18:29:27 +0000769
Robert Lougher11a44b72015-08-10 11:59:44 +0000770 calculateSpillWeightsAndHints(LIS, MF, &VRM, getAnalysis<MachineLoopInfo>(),
771 MBFI, normalizePBQPSpillWeight);
772
Lang Hames8f31f442014-10-09 18:20:51 +0000773 std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +0000774
Lang Hames8f31f442014-10-09 18:20:51 +0000775 MF.getRegInfo().freezeReservedRegs(MF);
Evan Chengb25f4632008-10-02 18:29:27 +0000776
Lang Hames8f31f442014-10-09 18:20:51 +0000777 DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000778
Evan Chengb25f4632008-10-02 18:29:27 +0000779 // Allocator main loop:
Misha Brukmanda467482009-01-08 15:50:22 +0000780 //
Evan Chengb25f4632008-10-02 18:29:27 +0000781 // * Map current regalloc problem to a PBQP problem
782 // * Solve the PBQP problem
783 // * Map the solution back to a register allocation
784 // * Spill if necessary
Misha Brukmanda467482009-01-08 15:50:22 +0000785 //
Evan Chengb25f4632008-10-02 18:29:27 +0000786 // This process is continued till no more spills are generated.
787
Lang Hames49ab8bc2008-11-16 12:12:54 +0000788 // Find the vreg intervals in need of allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000789 findVRegIntervalsToAlloc(MF, LIS);
Misha Brukmanda467482009-01-08 15:50:22 +0000790
Craig Toppera538d832012-08-22 06:07:19 +0000791#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000792 const Function &F = *MF.getFunction();
793 std::string FullyQualifiedName =
794 F.getParent()->getModuleIdentifier() + "." + F.getName().str();
Craig Toppera538d832012-08-22 06:07:19 +0000795#endif
Lang Hames95e021f2012-03-26 23:07:23 +0000796
Lang Hames49ab8bc2008-11-16 12:12:54 +0000797 // If there are non-empty intervals allocate them using pbqp.
Lang Hames8f31f442014-10-09 18:20:51 +0000798 if (!VRegsToAlloc.empty()) {
Eric Christopher7592b0c2015-01-27 08:27:06 +0000799 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
Lang Hames8f31f442014-10-09 18:20:51 +0000800 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
801 llvm::make_unique<PBQPRAConstraintList>();
802 ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
803 ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
804 if (PBQPCoalescing)
805 ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
806 ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
Lang Hames49ab8bc2008-11-16 12:12:54 +0000807
Lang Hames8f31f442014-10-09 18:20:51 +0000808 bool PBQPAllocComplete = false;
809 unsigned Round = 0;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000810
Lang Hames8f31f442014-10-09 18:20:51 +0000811 while (!PBQPAllocComplete) {
812 DEBUG(dbgs() << " PBQP Regalloc round " << Round << ":\n");
813
814 PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000815 initializeGraph(G, VRM, *VRegSpiller);
Lang Hames8f31f442014-10-09 18:20:51 +0000816 ConstraintsRoot->apply(G);
Lang Hames95e021f2012-03-26 23:07:23 +0000817
818#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000819 if (PBQPDumpGraphs) {
820 std::ostringstream RS;
821 RS << Round;
822 std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
823 ".pbqpgraph";
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000824 std::error_code EC;
Lang Hames8f31f442014-10-09 18:20:51 +0000825 raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text);
826 DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
827 << GraphFileName << "\"\n");
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000828 G.dump(OS);
Lang Hames95e021f2012-03-26 23:07:23 +0000829 }
830#endif
831
Lang Hames8f31f442014-10-09 18:20:51 +0000832 PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
833 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
834 ++Round;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000835 }
Evan Chengb25f4632008-10-02 18:29:27 +0000836 }
837
Lang Hames49ab8bc2008-11-16 12:12:54 +0000838 // Finalise allocation, allocate empty ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000839 finalizeAlloc(MF, LIS, VRM);
Wei Mi9a16d652016-04-13 03:08:27 +0000840 postOptimization(*VRegSpiller, LIS);
Lang Hames8f31f442014-10-09 18:20:51 +0000841 VRegsToAlloc.clear();
842 EmptyIntervalVRegs.clear();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000843
Lang Hames8f31f442014-10-09 18:20:51 +0000844 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000845
Misha Brukmanda467482009-01-08 15:50:22 +0000846 return true;
Evan Chengb25f4632008-10-02 18:29:27 +0000847}
848
Matthias Braunc07cbc82015-12-04 01:31:59 +0000849/// Create Printable object for node and register info.
850static Printable PrintNodeInfo(PBQP::RegAlloc::PBQPRAGraph::NodeId NId,
851 const PBQP::RegAlloc::PBQPRAGraph &G) {
852 return Printable([NId, &G](raw_ostream &OS) {
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000853 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
854 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
855 unsigned VReg = G.getNodeMetadata(NId).getVReg();
856 const char *RegClassName = TRI->getRegClassName(MRI.getRegClass(VReg));
857 OS << NId << " (" << RegClassName << ':' << PrintReg(VReg, TRI) << ')';
Matthias Braunc07cbc82015-12-04 01:31:59 +0000858 });
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000859}
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000860
Matthias Braun8c209aa2017-01-28 02:02:38 +0000861#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
862LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump(raw_ostream &OS) const {
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000863 for (auto NId : nodeIds()) {
864 const Vector &Costs = getNodeCosts(NId);
865 assert(Costs.getLength() != 0 && "Empty vector in graph.");
866 OS << PrintNodeInfo(NId, *this) << ": " << Costs << '\n';
867 }
868 OS << '\n';
869
870 for (auto EId : edgeIds()) {
871 NodeId N1Id = getEdgeNode1Id(EId);
872 NodeId N2Id = getEdgeNode2Id(EId);
873 assert(N1Id != N2Id && "PBQP graphs should not have self-edges.");
874 const Matrix &M = getEdgeCosts(EId);
875 assert(M.getRows() != 0 && "No rows in matrix.");
876 assert(M.getCols() != 0 && "No cols in matrix.");
877 OS << PrintNodeInfo(N1Id, *this) << ' ' << M.getRows() << " rows / ";
878 OS << PrintNodeInfo(N2Id, *this) << ' ' << M.getCols() << " cols:\n";
879 OS << M << '\n';
880 }
881}
882
Matthias Braun8c209aa2017-01-28 02:02:38 +0000883LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump() const {
884 dump(dbgs());
885}
886#endif
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000887
888void PBQP::RegAlloc::PBQPRAGraph::printDot(raw_ostream &OS) const {
889 OS << "graph {\n";
890 for (auto NId : nodeIds()) {
891 OS << " node" << NId << " [ label=\""
892 << PrintNodeInfo(NId, *this) << "\\n"
893 << getNodeCosts(NId) << "\" ]\n";
894 }
895
896 OS << " edge [ len=" << nodeIds().size() << " ]\n";
897 for (auto EId : edgeIds()) {
898 OS << " node" << getEdgeNode1Id(EId)
899 << " -- node" << getEdgeNode2Id(EId)
900 << " [ label=\"";
901 const Matrix &EdgeCosts = getEdgeCosts(EId);
902 for (unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
903 OS << EdgeCosts.getRowAsVector(i) << "\\n";
904 }
905 OS << "\" ]\n";
906 }
907 OS << "}\n";
908}
909
Lang Hames8f31f442014-10-09 18:20:51 +0000910FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
911 return new RegAllocPBQP(customPassID);
Evan Chengb25f4632008-10-02 18:29:27 +0000912}
913
Lang Hamesfd1bc422010-09-23 04:28:54 +0000914FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Lang Hames8f31f442014-10-09 18:20:51 +0000915 return createPBQPRegisterAllocator();
Lang Hamescb1e1012010-09-18 09:07:10 +0000916}
Evan Chengb25f4632008-10-02 18:29:27 +0000917
918#undef DEBUG_TYPE