1f4a2713aSLionel Sambuc //===------ RegAllocPBQP.cpp ---- PBQP Register Allocator -------*- C++ -*-===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This file contains a Partitioned Boolean Quadratic Programming (PBQP) based
11f4a2713aSLionel Sambuc // register allocator for LLVM. This allocator works by constructing a PBQP
12f4a2713aSLionel Sambuc // problem representing the register allocation problem under consideration,
13f4a2713aSLionel Sambuc // solving this using a PBQP solver, and mapping the solution back to a
14f4a2713aSLionel Sambuc // register assignment. If any variables are selected for spilling then spill
15f4a2713aSLionel Sambuc // code is inserted and the process repeated.
16f4a2713aSLionel Sambuc //
17f4a2713aSLionel Sambuc // The PBQP solver (pbqp.c) provided for this allocator uses a heuristic tuned
18f4a2713aSLionel Sambuc // for register allocation. For more information on PBQP for register
19f4a2713aSLionel Sambuc // allocation, see the following papers:
20f4a2713aSLionel Sambuc //
21f4a2713aSLionel Sambuc //   (1) Hames, L. and Scholz, B. 2006. Nearly optimal register allocation with
22f4a2713aSLionel Sambuc //   PBQP. In Proceedings of the 7th Joint Modular Languages Conference
23f4a2713aSLionel Sambuc //   (JMLC'06). LNCS, vol. 4228. Springer, New York, NY, USA. 346-361.
24f4a2713aSLionel Sambuc //
25f4a2713aSLionel Sambuc //   (2) Scholz, B., Eckstein, E. 2002. Register allocation for irregular
26f4a2713aSLionel Sambuc //   architectures. In Proceedings of the Joint Conference on Languages,
27f4a2713aSLionel Sambuc //   Compilers and Tools for Embedded Systems (LCTES'02), ACM Press, New York,
28f4a2713aSLionel Sambuc //   NY, USA, 139-148.
29f4a2713aSLionel Sambuc //
30f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
31f4a2713aSLionel Sambuc 
32f4a2713aSLionel Sambuc #include "llvm/CodeGen/RegAllocPBQP.h"
33f4a2713aSLionel Sambuc #include "RegisterCoalescer.h"
34f4a2713aSLionel Sambuc #include "Spiller.h"
35f4a2713aSLionel Sambuc #include "llvm/Analysis/AliasAnalysis.h"
36f4a2713aSLionel Sambuc #include "llvm/CodeGen/CalcSpillWeights.h"
37f4a2713aSLionel Sambuc #include "llvm/CodeGen/LiveIntervalAnalysis.h"
38f4a2713aSLionel Sambuc #include "llvm/CodeGen/LiveRangeEdit.h"
39f4a2713aSLionel Sambuc #include "llvm/CodeGen/LiveStackAnalysis.h"
40f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
41f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineDominators.h"
42f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineFunctionPass.h"
43f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineLoopInfo.h"
44f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineRegisterInfo.h"
45f4a2713aSLionel Sambuc #include "llvm/CodeGen/RegAllocRegistry.h"
46f4a2713aSLionel Sambuc #include "llvm/CodeGen/VirtRegMap.h"
47f4a2713aSLionel Sambuc #include "llvm/IR/Module.h"
48f4a2713aSLionel Sambuc #include "llvm/Support/Debug.h"
49*0a6a1f1dSLionel Sambuc #include "llvm/Support/FileSystem.h"
50f4a2713aSLionel Sambuc #include "llvm/Support/raw_ostream.h"
51f4a2713aSLionel Sambuc #include "llvm/Target/TargetInstrInfo.h"
52*0a6a1f1dSLionel Sambuc #include "llvm/Target/TargetSubtargetInfo.h"
53f4a2713aSLionel Sambuc #include <limits>
54f4a2713aSLionel Sambuc #include <memory>
55*0a6a1f1dSLionel Sambuc #include <queue>
56f4a2713aSLionel Sambuc #include <set>
57f4a2713aSLionel Sambuc #include <sstream>
58f4a2713aSLionel Sambuc #include <vector>
59f4a2713aSLionel Sambuc 
60f4a2713aSLionel Sambuc using namespace llvm;
61f4a2713aSLionel Sambuc 
62*0a6a1f1dSLionel Sambuc #define DEBUG_TYPE "regalloc"
63*0a6a1f1dSLionel Sambuc 
64f4a2713aSLionel Sambuc static RegisterRegAlloc
65*0a6a1f1dSLionel Sambuc RegisterPBQPRepAlloc("pbqp", "PBQP register allocator",
66f4a2713aSLionel Sambuc                        createDefaultPBQPRegisterAllocator);
67f4a2713aSLionel Sambuc 
68f4a2713aSLionel Sambuc static cl::opt<bool>
69*0a6a1f1dSLionel Sambuc PBQPCoalescing("pbqp-coalescing",
70f4a2713aSLionel Sambuc                 cl::desc("Attempt coalescing during PBQP register allocation."),
71f4a2713aSLionel Sambuc                 cl::init(false), cl::Hidden);
72f4a2713aSLionel Sambuc 
73f4a2713aSLionel Sambuc #ifndef NDEBUG
74f4a2713aSLionel Sambuc static cl::opt<bool>
75*0a6a1f1dSLionel Sambuc PBQPDumpGraphs("pbqp-dump-graphs",
76f4a2713aSLionel Sambuc                cl::desc("Dump graphs for each function/round in the compilation unit."),
77f4a2713aSLionel Sambuc                cl::init(false), cl::Hidden);
78f4a2713aSLionel Sambuc #endif
79f4a2713aSLionel Sambuc 
80f4a2713aSLionel Sambuc namespace {
81f4a2713aSLionel Sambuc 
82f4a2713aSLionel Sambuc ///
83f4a2713aSLionel Sambuc /// PBQP based allocators solve the register allocation problem by mapping
84f4a2713aSLionel Sambuc /// register allocation problems to Partitioned Boolean Quadratic
85f4a2713aSLionel Sambuc /// Programming problems.
86f4a2713aSLionel Sambuc class RegAllocPBQP : public MachineFunctionPass {
87f4a2713aSLionel Sambuc public:
88f4a2713aSLionel Sambuc 
89f4a2713aSLionel Sambuc   static char ID;
90f4a2713aSLionel Sambuc 
91f4a2713aSLionel Sambuc   /// Construct a PBQP register allocator.
RegAllocPBQP(char * cPassID=nullptr)92*0a6a1f1dSLionel Sambuc   RegAllocPBQP(char *cPassID = nullptr)
93*0a6a1f1dSLionel Sambuc       : MachineFunctionPass(ID), customPassID(cPassID) {
94f4a2713aSLionel Sambuc     initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
95f4a2713aSLionel Sambuc     initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96f4a2713aSLionel Sambuc     initializeLiveStacksPass(*PassRegistry::getPassRegistry());
97f4a2713aSLionel Sambuc     initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
98f4a2713aSLionel Sambuc   }
99f4a2713aSLionel Sambuc 
100f4a2713aSLionel Sambuc   /// Return the pass name.
getPassName() const101*0a6a1f1dSLionel Sambuc   const char* getPassName() const override {
102f4a2713aSLionel Sambuc     return "PBQP Register Allocator";
103f4a2713aSLionel Sambuc   }
104f4a2713aSLionel Sambuc 
105f4a2713aSLionel Sambuc   /// PBQP analysis usage.
106*0a6a1f1dSLionel Sambuc   void getAnalysisUsage(AnalysisUsage &au) const override;
107f4a2713aSLionel Sambuc 
108f4a2713aSLionel Sambuc   /// Perform register allocation
109*0a6a1f1dSLionel Sambuc   bool runOnMachineFunction(MachineFunction &MF) override;
110f4a2713aSLionel Sambuc 
111f4a2713aSLionel Sambuc private:
112f4a2713aSLionel Sambuc 
113f4a2713aSLionel Sambuc   typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
114f4a2713aSLionel Sambuc   typedef std::vector<const LiveInterval*> Node2LIMap;
115f4a2713aSLionel Sambuc   typedef std::vector<unsigned> AllowedSet;
116f4a2713aSLionel Sambuc   typedef std::vector<AllowedSet> AllowedSetMap;
117f4a2713aSLionel Sambuc   typedef std::pair<unsigned, unsigned> RegPair;
118f4a2713aSLionel Sambuc   typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
119f4a2713aSLionel Sambuc   typedef std::set<unsigned> RegSet;
120f4a2713aSLionel Sambuc 
121f4a2713aSLionel Sambuc   char *customPassID;
122f4a2713aSLionel Sambuc 
123*0a6a1f1dSLionel Sambuc   RegSet VRegsToAlloc, EmptyIntervalVRegs;
124f4a2713aSLionel Sambuc 
125f4a2713aSLionel Sambuc   /// \brief Finds the initial set of vreg intervals to allocate.
126*0a6a1f1dSLionel Sambuc   void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS);
127*0a6a1f1dSLionel Sambuc 
128*0a6a1f1dSLionel Sambuc   /// \brief Constructs an initial graph.
129*0a6a1f1dSLionel Sambuc   void initializeGraph(PBQPRAGraph &G);
130f4a2713aSLionel Sambuc 
131f4a2713aSLionel Sambuc   /// \brief Given a solved PBQP problem maps this solution back to a register
132f4a2713aSLionel Sambuc   /// assignment.
133*0a6a1f1dSLionel Sambuc   bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
134*0a6a1f1dSLionel Sambuc                          const PBQP::Solution &Solution,
135*0a6a1f1dSLionel Sambuc                          VirtRegMap &VRM,
136*0a6a1f1dSLionel Sambuc                          Spiller &VRegSpiller);
137f4a2713aSLionel Sambuc 
138f4a2713aSLionel Sambuc   /// \brief Postprocessing before final spilling. Sets basic block "live in"
139f4a2713aSLionel Sambuc   /// variables.
140*0a6a1f1dSLionel Sambuc   void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
141*0a6a1f1dSLionel Sambuc                      VirtRegMap &VRM) const;
142f4a2713aSLionel Sambuc 
143f4a2713aSLionel Sambuc };
144f4a2713aSLionel Sambuc 
145f4a2713aSLionel Sambuc char RegAllocPBQP::ID = 0;
146f4a2713aSLionel Sambuc 
147*0a6a1f1dSLionel Sambuc /// @brief Set spill costs for each node in the PBQP reg-alloc graph.
148*0a6a1f1dSLionel Sambuc class SpillCosts : public PBQPRAConstraint {
149*0a6a1f1dSLionel Sambuc public:
apply(PBQPRAGraph & G)150*0a6a1f1dSLionel Sambuc   void apply(PBQPRAGraph &G) override {
151*0a6a1f1dSLionel Sambuc     LiveIntervals &LIS = G.getMetadata().LIS;
152f4a2713aSLionel Sambuc 
153*0a6a1f1dSLionel Sambuc     // A minimum spill costs, so that register constraints can can be set
154*0a6a1f1dSLionel Sambuc     // without normalization in the [0.0:MinSpillCost( interval.
155*0a6a1f1dSLionel Sambuc     const PBQP::PBQPNum MinSpillCost = 10.0;
156*0a6a1f1dSLionel Sambuc 
157*0a6a1f1dSLionel Sambuc     for (auto NId : G.nodeIds()) {
158*0a6a1f1dSLionel Sambuc       PBQP::PBQPNum SpillCost =
159*0a6a1f1dSLionel Sambuc         LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight;
160*0a6a1f1dSLionel Sambuc       if (SpillCost == 0.0)
161*0a6a1f1dSLionel Sambuc         SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
162*0a6a1f1dSLionel Sambuc       else
163*0a6a1f1dSLionel Sambuc         SpillCost += MinSpillCost;
164*0a6a1f1dSLionel Sambuc       PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
165*0a6a1f1dSLionel Sambuc       NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
166*0a6a1f1dSLionel Sambuc       G.setNodeCosts(NId, std::move(NodeCosts));
167*0a6a1f1dSLionel Sambuc     }
168*0a6a1f1dSLionel Sambuc   }
169*0a6a1f1dSLionel Sambuc };
170*0a6a1f1dSLionel Sambuc 
171*0a6a1f1dSLionel Sambuc /// @brief Add interference edges between overlapping vregs.
172*0a6a1f1dSLionel Sambuc class Interference : public PBQPRAConstraint {
173*0a6a1f1dSLionel Sambuc private:
174*0a6a1f1dSLionel Sambuc 
175*0a6a1f1dSLionel Sambuc private:
176*0a6a1f1dSLionel Sambuc 
177*0a6a1f1dSLionel Sambuc   typedef const PBQP::RegAlloc::AllowedRegVector* AllowedRegVecPtr;
178*0a6a1f1dSLionel Sambuc   typedef std::pair<AllowedRegVecPtr, AllowedRegVecPtr> IMatrixKey;
179*0a6a1f1dSLionel Sambuc   typedef DenseMap<IMatrixKey, PBQPRAGraph::MatrixPtr> IMatrixCache;
180*0a6a1f1dSLionel Sambuc 
181*0a6a1f1dSLionel Sambuc   // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
182*0a6a1f1dSLionel Sambuc   // for the fast interference graph construction algorithm. The last is there
183*0a6a1f1dSLionel Sambuc   // to save us from looking up node ids via the VRegToNode map in the graph
184*0a6a1f1dSLionel Sambuc   // metadata.
185*0a6a1f1dSLionel Sambuc   typedef std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>
186*0a6a1f1dSLionel Sambuc     IntervalInfo;
187*0a6a1f1dSLionel Sambuc 
getStartPoint(const IntervalInfo & I)188*0a6a1f1dSLionel Sambuc   static SlotIndex getStartPoint(const IntervalInfo &I) {
189*0a6a1f1dSLionel Sambuc     return std::get<0>(I)->segments[std::get<1>(I)].start;
190f4a2713aSLionel Sambuc   }
191f4a2713aSLionel Sambuc 
getEndPoint(const IntervalInfo & I)192*0a6a1f1dSLionel Sambuc   static SlotIndex getEndPoint(const IntervalInfo &I) {
193*0a6a1f1dSLionel Sambuc     return std::get<0>(I)->segments[std::get<1>(I)].end;
194f4a2713aSLionel Sambuc   }
195f4a2713aSLionel Sambuc 
getNodeId(const IntervalInfo & I)196*0a6a1f1dSLionel Sambuc   static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
197*0a6a1f1dSLionel Sambuc     return std::get<2>(I);
198f4a2713aSLionel Sambuc   }
199f4a2713aSLionel Sambuc 
lowestStartPoint(const IntervalInfo & I1,const IntervalInfo & I2)200*0a6a1f1dSLionel Sambuc   static bool lowestStartPoint(const IntervalInfo &I1,
201*0a6a1f1dSLionel Sambuc                                const IntervalInfo &I2) {
202*0a6a1f1dSLionel Sambuc     // Condition reversed because priority queue has the *highest* element at
203*0a6a1f1dSLionel Sambuc     // the front, rather than the lowest.
204*0a6a1f1dSLionel Sambuc     return getStartPoint(I1) > getStartPoint(I2);
205f4a2713aSLionel Sambuc   }
206f4a2713aSLionel Sambuc 
lowestEndPoint(const IntervalInfo & I1,const IntervalInfo & I2)207*0a6a1f1dSLionel Sambuc   static bool lowestEndPoint(const IntervalInfo &I1,
208*0a6a1f1dSLionel Sambuc                              const IntervalInfo &I2) {
209*0a6a1f1dSLionel Sambuc     SlotIndex E1 = getEndPoint(I1);
210*0a6a1f1dSLionel Sambuc     SlotIndex E2 = getEndPoint(I2);
211f4a2713aSLionel Sambuc 
212*0a6a1f1dSLionel Sambuc     if (E1 < E2)
213*0a6a1f1dSLionel Sambuc       return true;
214f4a2713aSLionel Sambuc 
215*0a6a1f1dSLionel Sambuc     if (E1 > E2)
216*0a6a1f1dSLionel Sambuc       return false;
217f4a2713aSLionel Sambuc 
218*0a6a1f1dSLionel Sambuc     // If two intervals end at the same point, we need a way to break the tie or
219*0a6a1f1dSLionel Sambuc     // the set will assume they're actually equal and refuse to insert a
220*0a6a1f1dSLionel Sambuc     // "duplicate". Just compare the vregs - fast and guaranteed unique.
221*0a6a1f1dSLionel Sambuc     return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
222f4a2713aSLionel Sambuc   }
223f4a2713aSLionel Sambuc 
isAtLastSegment(const IntervalInfo & I)224*0a6a1f1dSLionel Sambuc   static bool isAtLastSegment(const IntervalInfo &I) {
225*0a6a1f1dSLionel Sambuc     return std::get<1>(I) == std::get<0>(I)->size() - 1;
226*0a6a1f1dSLionel Sambuc   }
227f4a2713aSLionel Sambuc 
nextSegment(const IntervalInfo & I)228*0a6a1f1dSLionel Sambuc   static IntervalInfo nextSegment(const IntervalInfo &I) {
229*0a6a1f1dSLionel Sambuc     return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
230*0a6a1f1dSLionel Sambuc   }
231f4a2713aSLionel Sambuc 
232*0a6a1f1dSLionel Sambuc public:
233*0a6a1f1dSLionel Sambuc 
apply(PBQPRAGraph & G)234*0a6a1f1dSLionel Sambuc   void apply(PBQPRAGraph &G) override {
235*0a6a1f1dSLionel Sambuc     // The following is loosely based on the linear scan algorithm introduced in
236*0a6a1f1dSLionel Sambuc     // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
237*0a6a1f1dSLionel Sambuc     // isn't linear, because the size of the active set isn't bound by the
238*0a6a1f1dSLionel Sambuc     // number of registers, but rather the size of the largest clique in the
239*0a6a1f1dSLionel Sambuc     // graph. Still, we expect this to be better than N^2.
240*0a6a1f1dSLionel Sambuc     LiveIntervals &LIS = G.getMetadata().LIS;
241*0a6a1f1dSLionel Sambuc 
242*0a6a1f1dSLionel Sambuc     // Interferenc matrices are incredibly regular - they're only a function of
243*0a6a1f1dSLionel Sambuc     // the allowed sets, so we cache them to avoid the overhead of constructing
244*0a6a1f1dSLionel Sambuc     // and uniquing them.
245*0a6a1f1dSLionel Sambuc     IMatrixCache C;
246*0a6a1f1dSLionel Sambuc 
247*0a6a1f1dSLionel Sambuc     typedef std::set<IntervalInfo, decltype(&lowestEndPoint)> IntervalSet;
248*0a6a1f1dSLionel Sambuc     typedef std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
249*0a6a1f1dSLionel Sambuc                                 decltype(&lowestStartPoint)> IntervalQueue;
250*0a6a1f1dSLionel Sambuc     IntervalSet Active(lowestEndPoint);
251*0a6a1f1dSLionel Sambuc     IntervalQueue Inactive(lowestStartPoint);
252*0a6a1f1dSLionel Sambuc 
253*0a6a1f1dSLionel Sambuc     // Start by building the inactive set.
254*0a6a1f1dSLionel Sambuc     for (auto NId : G.nodeIds()) {
255*0a6a1f1dSLionel Sambuc       unsigned VReg = G.getNodeMetadata(NId).getVReg();
256*0a6a1f1dSLionel Sambuc       LiveInterval &LI = LIS.getInterval(VReg);
257*0a6a1f1dSLionel Sambuc       assert(!LI.empty() && "PBQP graph contains node for empty interval");
258*0a6a1f1dSLionel Sambuc       Inactive.push(std::make_tuple(&LI, 0, NId));
259*0a6a1f1dSLionel Sambuc     }
260*0a6a1f1dSLionel Sambuc 
261*0a6a1f1dSLionel Sambuc     while (!Inactive.empty()) {
262*0a6a1f1dSLionel Sambuc       // Tentatively grab the "next" interval - this choice may be overriden
263*0a6a1f1dSLionel Sambuc       // below.
264*0a6a1f1dSLionel Sambuc       IntervalInfo Cur = Inactive.top();
265*0a6a1f1dSLionel Sambuc 
266*0a6a1f1dSLionel Sambuc       // Retire any active intervals that end before Cur starts.
267*0a6a1f1dSLionel Sambuc       IntervalSet::iterator RetireItr = Active.begin();
268*0a6a1f1dSLionel Sambuc       while (RetireItr != Active.end() &&
269*0a6a1f1dSLionel Sambuc              (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
270*0a6a1f1dSLionel Sambuc         // If this interval has subsequent segments, add the next one to the
271*0a6a1f1dSLionel Sambuc         // inactive list.
272*0a6a1f1dSLionel Sambuc         if (!isAtLastSegment(*RetireItr))
273*0a6a1f1dSLionel Sambuc           Inactive.push(nextSegment(*RetireItr));
274*0a6a1f1dSLionel Sambuc 
275*0a6a1f1dSLionel Sambuc         ++RetireItr;
276*0a6a1f1dSLionel Sambuc       }
277*0a6a1f1dSLionel Sambuc       Active.erase(Active.begin(), RetireItr);
278*0a6a1f1dSLionel Sambuc 
279*0a6a1f1dSLionel Sambuc       // One of the newly retired segments may actually start before the
280*0a6a1f1dSLionel Sambuc       // Cur segment, so re-grab the front of the inactive list.
281*0a6a1f1dSLionel Sambuc       Cur = Inactive.top();
282*0a6a1f1dSLionel Sambuc       Inactive.pop();
283*0a6a1f1dSLionel Sambuc 
284*0a6a1f1dSLionel Sambuc       // At this point we know that Cur overlaps all active intervals. Add the
285*0a6a1f1dSLionel Sambuc       // interference edges.
286*0a6a1f1dSLionel Sambuc       PBQP::GraphBase::NodeId NId = getNodeId(Cur);
287*0a6a1f1dSLionel Sambuc       for (const auto &A : Active) {
288*0a6a1f1dSLionel Sambuc         PBQP::GraphBase::NodeId MId = getNodeId(A);
289*0a6a1f1dSLionel Sambuc 
290*0a6a1f1dSLionel Sambuc         // Check that we haven't already added this edge
291*0a6a1f1dSLionel Sambuc         // FIXME: findEdge is expensive in the worst case (O(max_clique(G))).
292*0a6a1f1dSLionel Sambuc         //        It might be better to replace this with a local bit-matrix.
293*0a6a1f1dSLionel Sambuc         if (G.findEdge(NId, MId) != PBQPRAGraph::invalidEdgeId())
294f4a2713aSLionel Sambuc           continue;
295f4a2713aSLionel Sambuc 
296*0a6a1f1dSLionel Sambuc         // This is a new edge - add it to the graph.
297*0a6a1f1dSLionel Sambuc         createInterferenceEdge(G, NId, MId, C);
298f4a2713aSLionel Sambuc       }
299f4a2713aSLionel Sambuc 
300*0a6a1f1dSLionel Sambuc       // Finally, add Cur to the Active set.
301*0a6a1f1dSLionel Sambuc       Active.insert(Cur);
302f4a2713aSLionel Sambuc     }
303f4a2713aSLionel Sambuc   }
304f4a2713aSLionel Sambuc 
305*0a6a1f1dSLionel Sambuc private:
306f4a2713aSLionel Sambuc 
createInterferenceEdge(PBQPRAGraph & G,PBQPRAGraph::NodeId NId,PBQPRAGraph::NodeId MId,IMatrixCache & C)307*0a6a1f1dSLionel Sambuc   void createInterferenceEdge(PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
308*0a6a1f1dSLionel Sambuc                               PBQPRAGraph::NodeId MId, IMatrixCache &C) {
309f4a2713aSLionel Sambuc 
310*0a6a1f1dSLionel Sambuc     const TargetRegisterInfo &TRI =
311*0a6a1f1dSLionel Sambuc       *G.getMetadata().MF.getTarget().getSubtargetImpl()->getRegisterInfo();
312*0a6a1f1dSLionel Sambuc 
313*0a6a1f1dSLionel Sambuc     const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
314*0a6a1f1dSLionel Sambuc     const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
315*0a6a1f1dSLionel Sambuc 
316*0a6a1f1dSLionel Sambuc     // Try looking the edge costs up in the IMatrixCache first.
317*0a6a1f1dSLionel Sambuc     IMatrixKey K(&NRegs, &MRegs);
318*0a6a1f1dSLionel Sambuc     IMatrixCache::iterator I = C.find(K);
319*0a6a1f1dSLionel Sambuc     if (I != C.end()) {
320*0a6a1f1dSLionel Sambuc       G.addEdgeBypassingCostAllocator(NId, MId, I->second);
321*0a6a1f1dSLionel Sambuc       return;
322*0a6a1f1dSLionel Sambuc     }
323*0a6a1f1dSLionel Sambuc 
324*0a6a1f1dSLionel Sambuc     PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
325*0a6a1f1dSLionel Sambuc     for (unsigned I = 0; I != NRegs.size(); ++I) {
326*0a6a1f1dSLionel Sambuc       unsigned PRegN = NRegs[I];
327*0a6a1f1dSLionel Sambuc       for (unsigned J = 0; J != MRegs.size(); ++J) {
328*0a6a1f1dSLionel Sambuc         unsigned PRegM = MRegs[J];
329*0a6a1f1dSLionel Sambuc         if (TRI.regsOverlap(PRegN, PRegM))
330*0a6a1f1dSLionel Sambuc           M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
331*0a6a1f1dSLionel Sambuc       }
332*0a6a1f1dSLionel Sambuc     }
333*0a6a1f1dSLionel Sambuc 
334*0a6a1f1dSLionel Sambuc     PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
335*0a6a1f1dSLionel Sambuc     C[K] = G.getEdgeCostsPtr(EId);
336*0a6a1f1dSLionel Sambuc   }
337*0a6a1f1dSLionel Sambuc };
338*0a6a1f1dSLionel Sambuc 
339*0a6a1f1dSLionel Sambuc 
340*0a6a1f1dSLionel Sambuc class Coalescing : public PBQPRAConstraint {
341*0a6a1f1dSLionel Sambuc public:
apply(PBQPRAGraph & G)342*0a6a1f1dSLionel Sambuc   void apply(PBQPRAGraph &G) override {
343*0a6a1f1dSLionel Sambuc     MachineFunction &MF = G.getMetadata().MF;
344*0a6a1f1dSLionel Sambuc     MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
345*0a6a1f1dSLionel Sambuc     CoalescerPair CP(*MF.getTarget().getSubtargetImpl()->getRegisterInfo());
346f4a2713aSLionel Sambuc 
347f4a2713aSLionel Sambuc     // Scan the machine function and add a coalescing cost whenever CoalescerPair
348f4a2713aSLionel Sambuc     // gives the Ok.
349*0a6a1f1dSLionel Sambuc     for (const auto &MBB : MF) {
350*0a6a1f1dSLionel Sambuc       for (const auto &MI : MBB) {
351f4a2713aSLionel Sambuc 
352*0a6a1f1dSLionel Sambuc         // Skip not-coalescable or already coalesced copies.
353*0a6a1f1dSLionel Sambuc         if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
354f4a2713aSLionel Sambuc           continue;
355f4a2713aSLionel Sambuc 
356*0a6a1f1dSLionel Sambuc         unsigned DstReg = CP.getDstReg();
357*0a6a1f1dSLionel Sambuc         unsigned SrcReg = CP.getSrcReg();
358*0a6a1f1dSLionel Sambuc 
359*0a6a1f1dSLionel Sambuc         const float Scale = 1.0f / MBFI.getEntryFreq();
360*0a6a1f1dSLionel Sambuc         PBQP::PBQPNum CBenefit = MBFI.getBlockFreq(&MBB).getFrequency() * Scale;
361*0a6a1f1dSLionel Sambuc 
362*0a6a1f1dSLionel Sambuc         if (CP.isPhys()) {
363*0a6a1f1dSLionel Sambuc           if (!MF.getRegInfo().isAllocatable(DstReg))
364*0a6a1f1dSLionel Sambuc             continue;
365*0a6a1f1dSLionel Sambuc 
366*0a6a1f1dSLionel Sambuc           PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
367*0a6a1f1dSLionel Sambuc 
368*0a6a1f1dSLionel Sambuc           const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
369*0a6a1f1dSLionel Sambuc             G.getNodeMetadata(NId).getAllowedRegs();
370*0a6a1f1dSLionel Sambuc 
371*0a6a1f1dSLionel Sambuc           unsigned PRegOpt = 0;
372*0a6a1f1dSLionel Sambuc           while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
373*0a6a1f1dSLionel Sambuc             ++PRegOpt;
374*0a6a1f1dSLionel Sambuc 
375*0a6a1f1dSLionel Sambuc           if (PRegOpt < Allowed.size()) {
376*0a6a1f1dSLionel Sambuc             PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
377*0a6a1f1dSLionel Sambuc             NewCosts[PRegOpt + 1] -= CBenefit;
378*0a6a1f1dSLionel Sambuc             G.setNodeCosts(NId, std::move(NewCosts));
379f4a2713aSLionel Sambuc           }
380f4a2713aSLionel Sambuc         } else {
381*0a6a1f1dSLionel Sambuc           PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
382*0a6a1f1dSLionel Sambuc           PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
383*0a6a1f1dSLionel Sambuc           const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
384*0a6a1f1dSLionel Sambuc             &G.getNodeMetadata(N1Id).getAllowedRegs();
385*0a6a1f1dSLionel Sambuc           const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
386*0a6a1f1dSLionel Sambuc             &G.getNodeMetadata(N2Id).getAllowedRegs();
387*0a6a1f1dSLionel Sambuc 
388*0a6a1f1dSLionel Sambuc           PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
389*0a6a1f1dSLionel Sambuc           if (EId == G.invalidEdgeId()) {
390*0a6a1f1dSLionel Sambuc             PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
391*0a6a1f1dSLionel Sambuc                                          Allowed2->size() + 1, 0);
392*0a6a1f1dSLionel Sambuc             addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
393*0a6a1f1dSLionel Sambuc             G.addEdge(N1Id, N2Id, std::move(Costs));
394f4a2713aSLionel Sambuc           } else {
395*0a6a1f1dSLionel Sambuc             if (G.getEdgeNode1Id(EId) == N2Id) {
396*0a6a1f1dSLionel Sambuc               std::swap(N1Id, N2Id);
397*0a6a1f1dSLionel Sambuc               std::swap(Allowed1, Allowed2);
398f4a2713aSLionel Sambuc             }
399*0a6a1f1dSLionel Sambuc             PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
400*0a6a1f1dSLionel Sambuc             addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
401*0a6a1f1dSLionel Sambuc             G.setEdgeCosts(EId, std::move(Costs));
402f4a2713aSLionel Sambuc           }
403f4a2713aSLionel Sambuc         }
404f4a2713aSLionel Sambuc       }
405f4a2713aSLionel Sambuc     }
406f4a2713aSLionel Sambuc   }
407f4a2713aSLionel Sambuc 
408*0a6a1f1dSLionel Sambuc private:
409*0a6a1f1dSLionel Sambuc 
addVirtRegCoalesce(PBQPRAGraph::RawMatrix & CostMat,const PBQPRAGraph::NodeMetadata::AllowedRegVector & Allowed1,const PBQPRAGraph::NodeMetadata::AllowedRegVector & Allowed2,PBQP::PBQPNum Benefit)410*0a6a1f1dSLionel Sambuc   void addVirtRegCoalesce(
411*0a6a1f1dSLionel Sambuc                     PBQPRAGraph::RawMatrix &CostMat,
412*0a6a1f1dSLionel Sambuc                     const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
413*0a6a1f1dSLionel Sambuc                     const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
414*0a6a1f1dSLionel Sambuc                     PBQP::PBQPNum Benefit) {
415*0a6a1f1dSLionel Sambuc     assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
416*0a6a1f1dSLionel Sambuc     assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
417*0a6a1f1dSLionel Sambuc     for (unsigned I = 0; I != Allowed1.size(); ++I) {
418*0a6a1f1dSLionel Sambuc       unsigned PReg1 = Allowed1[I];
419*0a6a1f1dSLionel Sambuc       for (unsigned J = 0; J != Allowed2.size(); ++J) {
420*0a6a1f1dSLionel Sambuc         unsigned PReg2 = Allowed2[J];
421*0a6a1f1dSLionel Sambuc         if (PReg1 == PReg2)
422*0a6a1f1dSLionel Sambuc           CostMat[I + 1][J + 1] -= Benefit;
423*0a6a1f1dSLionel Sambuc       }
424*0a6a1f1dSLionel Sambuc     }
425*0a6a1f1dSLionel Sambuc   }
426*0a6a1f1dSLionel Sambuc 
427*0a6a1f1dSLionel Sambuc };
428*0a6a1f1dSLionel Sambuc 
429*0a6a1f1dSLionel Sambuc } // End anonymous namespace.
430*0a6a1f1dSLionel Sambuc 
431*0a6a1f1dSLionel Sambuc // Out-of-line destructor/anchor for PBQPRAConstraint.
~PBQPRAConstraint()432*0a6a1f1dSLionel Sambuc PBQPRAConstraint::~PBQPRAConstraint() {}
anchor()433*0a6a1f1dSLionel Sambuc void PBQPRAConstraint::anchor() {}
anchor()434*0a6a1f1dSLionel Sambuc void PBQPRAConstraintList::anchor() {}
435f4a2713aSLionel Sambuc 
getAnalysisUsage(AnalysisUsage & au) const436f4a2713aSLionel Sambuc void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
437f4a2713aSLionel Sambuc   au.setPreservesCFG();
438f4a2713aSLionel Sambuc   au.addRequired<AliasAnalysis>();
439f4a2713aSLionel Sambuc   au.addPreserved<AliasAnalysis>();
440f4a2713aSLionel Sambuc   au.addRequired<SlotIndexes>();
441f4a2713aSLionel Sambuc   au.addPreserved<SlotIndexes>();
442f4a2713aSLionel Sambuc   au.addRequired<LiveIntervals>();
443f4a2713aSLionel Sambuc   au.addPreserved<LiveIntervals>();
444f4a2713aSLionel Sambuc   //au.addRequiredID(SplitCriticalEdgesID);
445f4a2713aSLionel Sambuc   if (customPassID)
446f4a2713aSLionel Sambuc     au.addRequiredID(*customPassID);
447f4a2713aSLionel Sambuc   au.addRequired<LiveStacks>();
448f4a2713aSLionel Sambuc   au.addPreserved<LiveStacks>();
449f4a2713aSLionel Sambuc   au.addRequired<MachineBlockFrequencyInfo>();
450f4a2713aSLionel Sambuc   au.addPreserved<MachineBlockFrequencyInfo>();
451f4a2713aSLionel Sambuc   au.addRequired<MachineLoopInfo>();
452f4a2713aSLionel Sambuc   au.addPreserved<MachineLoopInfo>();
453f4a2713aSLionel Sambuc   au.addRequired<MachineDominatorTree>();
454f4a2713aSLionel Sambuc   au.addPreserved<MachineDominatorTree>();
455f4a2713aSLionel Sambuc   au.addRequired<VirtRegMap>();
456f4a2713aSLionel Sambuc   au.addPreserved<VirtRegMap>();
457f4a2713aSLionel Sambuc   MachineFunctionPass::getAnalysisUsage(au);
458f4a2713aSLionel Sambuc }
459f4a2713aSLionel Sambuc 
findVRegIntervalsToAlloc(const MachineFunction & MF,LiveIntervals & LIS)460*0a6a1f1dSLionel Sambuc void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
461*0a6a1f1dSLionel Sambuc                                             LiveIntervals &LIS) {
462*0a6a1f1dSLionel Sambuc   const MachineRegisterInfo &MRI = MF.getRegInfo();
463f4a2713aSLionel Sambuc 
464f4a2713aSLionel Sambuc   // Iterate over all live ranges.
465*0a6a1f1dSLionel Sambuc   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
466*0a6a1f1dSLionel Sambuc     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
467*0a6a1f1dSLionel Sambuc     if (MRI.reg_nodbg_empty(Reg))
468f4a2713aSLionel Sambuc       continue;
469*0a6a1f1dSLionel Sambuc     LiveInterval &LI = LIS.getInterval(Reg);
470f4a2713aSLionel Sambuc 
471f4a2713aSLionel Sambuc     // If this live interval is non-empty we will use pbqp to allocate it.
472f4a2713aSLionel Sambuc     // Empty intervals we allocate in a simple post-processing stage in
473f4a2713aSLionel Sambuc     // finalizeAlloc.
474*0a6a1f1dSLionel Sambuc     if (!LI.empty()) {
475*0a6a1f1dSLionel Sambuc       VRegsToAlloc.insert(LI.reg);
476f4a2713aSLionel Sambuc     } else {
477*0a6a1f1dSLionel Sambuc       EmptyIntervalVRegs.insert(LI.reg);
478f4a2713aSLionel Sambuc     }
479f4a2713aSLionel Sambuc   }
480f4a2713aSLionel Sambuc }
481f4a2713aSLionel Sambuc 
isACalleeSavedRegister(unsigned reg,const TargetRegisterInfo & TRI,const MachineFunction & MF)482*0a6a1f1dSLionel Sambuc static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI,
483*0a6a1f1dSLionel Sambuc                                    const MachineFunction &MF) {
484*0a6a1f1dSLionel Sambuc   const MCPhysReg *CSR = TRI.getCalleeSavedRegs(&MF);
485*0a6a1f1dSLionel Sambuc   for (unsigned i = 0; CSR[i] != 0; ++i)
486*0a6a1f1dSLionel Sambuc     if (TRI.regsOverlap(reg, CSR[i]))
487*0a6a1f1dSLionel Sambuc       return true;
488*0a6a1f1dSLionel Sambuc   return false;
489*0a6a1f1dSLionel Sambuc }
490*0a6a1f1dSLionel Sambuc 
initializeGraph(PBQPRAGraph & G)491*0a6a1f1dSLionel Sambuc void RegAllocPBQP::initializeGraph(PBQPRAGraph &G) {
492*0a6a1f1dSLionel Sambuc   MachineFunction &MF = G.getMetadata().MF;
493*0a6a1f1dSLionel Sambuc 
494*0a6a1f1dSLionel Sambuc   LiveIntervals &LIS = G.getMetadata().LIS;
495*0a6a1f1dSLionel Sambuc   const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
496*0a6a1f1dSLionel Sambuc   const TargetRegisterInfo &TRI =
497*0a6a1f1dSLionel Sambuc     *G.getMetadata().MF.getTarget().getSubtargetImpl()->getRegisterInfo();
498*0a6a1f1dSLionel Sambuc 
499*0a6a1f1dSLionel Sambuc   for (auto VReg : VRegsToAlloc) {
500*0a6a1f1dSLionel Sambuc     const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
501*0a6a1f1dSLionel Sambuc     LiveInterval &VRegLI = LIS.getInterval(VReg);
502*0a6a1f1dSLionel Sambuc 
503*0a6a1f1dSLionel Sambuc     // Record any overlaps with regmask operands.
504*0a6a1f1dSLionel Sambuc     BitVector RegMaskOverlaps;
505*0a6a1f1dSLionel Sambuc     LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
506*0a6a1f1dSLionel Sambuc 
507*0a6a1f1dSLionel Sambuc     // Compute an initial allowed set for the current vreg.
508*0a6a1f1dSLionel Sambuc     std::vector<unsigned> VRegAllowed;
509*0a6a1f1dSLionel Sambuc     ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
510*0a6a1f1dSLionel Sambuc     for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
511*0a6a1f1dSLionel Sambuc       unsigned PReg = RawPRegOrder[I];
512*0a6a1f1dSLionel Sambuc       if (MRI.isReserved(PReg))
513*0a6a1f1dSLionel Sambuc         continue;
514*0a6a1f1dSLionel Sambuc 
515*0a6a1f1dSLionel Sambuc       // vregLI crosses a regmask operand that clobbers preg.
516*0a6a1f1dSLionel Sambuc       if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
517*0a6a1f1dSLionel Sambuc         continue;
518*0a6a1f1dSLionel Sambuc 
519*0a6a1f1dSLionel Sambuc       // vregLI overlaps fixed regunit interference.
520*0a6a1f1dSLionel Sambuc       bool Interference = false;
521*0a6a1f1dSLionel Sambuc       for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
522*0a6a1f1dSLionel Sambuc         if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
523*0a6a1f1dSLionel Sambuc           Interference = true;
524*0a6a1f1dSLionel Sambuc           break;
525*0a6a1f1dSLionel Sambuc         }
526*0a6a1f1dSLionel Sambuc       }
527*0a6a1f1dSLionel Sambuc       if (Interference)
528*0a6a1f1dSLionel Sambuc         continue;
529*0a6a1f1dSLionel Sambuc 
530*0a6a1f1dSLionel Sambuc       // preg is usable for this virtual register.
531*0a6a1f1dSLionel Sambuc       VRegAllowed.push_back(PReg);
532*0a6a1f1dSLionel Sambuc     }
533*0a6a1f1dSLionel Sambuc 
534*0a6a1f1dSLionel Sambuc     PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
535*0a6a1f1dSLionel Sambuc 
536*0a6a1f1dSLionel Sambuc     // Tweak cost of callee saved registers, as using then force spilling and
537*0a6a1f1dSLionel Sambuc     // restoring them. This would only happen in the prologue / epilogue though.
538*0a6a1f1dSLionel Sambuc     for (unsigned i = 0; i != VRegAllowed.size(); ++i)
539*0a6a1f1dSLionel Sambuc       if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF))
540*0a6a1f1dSLionel Sambuc         NodeCosts[1 + i] += 1.0;
541*0a6a1f1dSLionel Sambuc 
542*0a6a1f1dSLionel Sambuc     PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
543*0a6a1f1dSLionel Sambuc     G.getNodeMetadata(NId).setVReg(VReg);
544*0a6a1f1dSLionel Sambuc     G.getNodeMetadata(NId).setAllowedRegs(
545*0a6a1f1dSLionel Sambuc       G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
546*0a6a1f1dSLionel Sambuc     G.getMetadata().setNodeIdForVReg(VReg, NId);
547*0a6a1f1dSLionel Sambuc   }
548*0a6a1f1dSLionel Sambuc }
549*0a6a1f1dSLionel Sambuc 
mapPBQPToRegAlloc(const PBQPRAGraph & G,const PBQP::Solution & Solution,VirtRegMap & VRM,Spiller & VRegSpiller)550*0a6a1f1dSLionel Sambuc bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
551*0a6a1f1dSLionel Sambuc                                      const PBQP::Solution &Solution,
552*0a6a1f1dSLionel Sambuc                                      VirtRegMap &VRM,
553*0a6a1f1dSLionel Sambuc                                      Spiller &VRegSpiller) {
554*0a6a1f1dSLionel Sambuc   MachineFunction &MF = G.getMetadata().MF;
555*0a6a1f1dSLionel Sambuc   LiveIntervals &LIS = G.getMetadata().LIS;
556*0a6a1f1dSLionel Sambuc   const TargetRegisterInfo &TRI =
557*0a6a1f1dSLionel Sambuc     *MF.getTarget().getSubtargetImpl()->getRegisterInfo();
558*0a6a1f1dSLionel Sambuc   (void)TRI;
559*0a6a1f1dSLionel Sambuc 
560f4a2713aSLionel Sambuc   // Set to true if we have any spills
561*0a6a1f1dSLionel Sambuc   bool AnotherRoundNeeded = false;
562f4a2713aSLionel Sambuc 
563f4a2713aSLionel Sambuc   // Clear the existing allocation.
564*0a6a1f1dSLionel Sambuc   VRM.clearAllVirt();
565f4a2713aSLionel Sambuc 
566f4a2713aSLionel Sambuc   // Iterate over the nodes mapping the PBQP solution to a register
567f4a2713aSLionel Sambuc   // assignment.
568*0a6a1f1dSLionel Sambuc   for (auto NId : G.nodeIds()) {
569*0a6a1f1dSLionel Sambuc     unsigned VReg = G.getNodeMetadata(NId).getVReg();
570*0a6a1f1dSLionel Sambuc     unsigned AllocOption = Solution.getSelection(NId);
571f4a2713aSLionel Sambuc 
572*0a6a1f1dSLionel Sambuc     if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
573*0a6a1f1dSLionel Sambuc       unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
574*0a6a1f1dSLionel Sambuc       DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> "
575*0a6a1f1dSLionel Sambuc             << TRI.getName(PReg) << "\n");
576*0a6a1f1dSLionel Sambuc       assert(PReg != 0 && "Invalid preg selected.");
577*0a6a1f1dSLionel Sambuc       VRM.assignVirt2Phys(VReg, PReg);
578*0a6a1f1dSLionel Sambuc     } else {
579*0a6a1f1dSLionel Sambuc       VRegsToAlloc.erase(VReg);
580*0a6a1f1dSLionel Sambuc       SmallVector<unsigned, 8> NewSpills;
581*0a6a1f1dSLionel Sambuc       LiveRangeEdit LRE(&LIS.getInterval(VReg), NewSpills, MF, LIS, &VRM);
582*0a6a1f1dSLionel Sambuc       VRegSpiller.spill(LRE);
583f4a2713aSLionel Sambuc 
584*0a6a1f1dSLionel Sambuc       DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> SPILLED (Cost: "
585f4a2713aSLionel Sambuc                    << LRE.getParent().weight << ", New vregs: ");
586f4a2713aSLionel Sambuc 
587f4a2713aSLionel Sambuc       // Copy any newly inserted live intervals into the list of regs to
588f4a2713aSLionel Sambuc       // allocate.
589*0a6a1f1dSLionel Sambuc       for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
590*0a6a1f1dSLionel Sambuc            I != E; ++I) {
591*0a6a1f1dSLionel Sambuc         LiveInterval &LI = LIS.getInterval(*I);
592*0a6a1f1dSLionel Sambuc         assert(!LI.empty() && "Empty spill range.");
593*0a6a1f1dSLionel Sambuc         DEBUG(dbgs() << PrintReg(LI.reg, &TRI) << " ");
594*0a6a1f1dSLionel Sambuc         VRegsToAlloc.insert(LI.reg);
595f4a2713aSLionel Sambuc       }
596f4a2713aSLionel Sambuc 
597f4a2713aSLionel Sambuc       DEBUG(dbgs() << ")\n");
598f4a2713aSLionel Sambuc 
599f4a2713aSLionel Sambuc       // We need another round if spill intervals were added.
600*0a6a1f1dSLionel Sambuc       AnotherRoundNeeded |= !LRE.empty();
601f4a2713aSLionel Sambuc     }
602f4a2713aSLionel Sambuc   }
603f4a2713aSLionel Sambuc 
604*0a6a1f1dSLionel Sambuc   return !AnotherRoundNeeded;
605f4a2713aSLionel Sambuc }
606f4a2713aSLionel Sambuc 
finalizeAlloc(MachineFunction & MF,LiveIntervals & LIS,VirtRegMap & VRM) const607*0a6a1f1dSLionel Sambuc void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
608*0a6a1f1dSLionel Sambuc                                  LiveIntervals &LIS,
609*0a6a1f1dSLionel Sambuc                                  VirtRegMap &VRM) const {
610*0a6a1f1dSLionel Sambuc   MachineRegisterInfo &MRI = MF.getRegInfo();
611f4a2713aSLionel Sambuc 
612f4a2713aSLionel Sambuc   // First allocate registers for the empty intervals.
613f4a2713aSLionel Sambuc   for (RegSet::const_iterator
614*0a6a1f1dSLionel Sambuc          I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
615*0a6a1f1dSLionel Sambuc          I != E; ++I) {
616*0a6a1f1dSLionel Sambuc     LiveInterval &LI = LIS.getInterval(*I);
617f4a2713aSLionel Sambuc 
618*0a6a1f1dSLionel Sambuc     unsigned PReg = MRI.getSimpleHint(LI.reg);
619f4a2713aSLionel Sambuc 
620*0a6a1f1dSLionel Sambuc     if (PReg == 0) {
621*0a6a1f1dSLionel Sambuc       const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg);
622*0a6a1f1dSLionel Sambuc       PReg = RC.getRawAllocationOrder(MF).front();
623f4a2713aSLionel Sambuc     }
624f4a2713aSLionel Sambuc 
625*0a6a1f1dSLionel Sambuc     VRM.assignVirt2Phys(LI.reg, PReg);
626f4a2713aSLionel Sambuc   }
627f4a2713aSLionel Sambuc }
628f4a2713aSLionel Sambuc 
normalizePBQPSpillWeight(float UseDefFreq,unsigned Size,unsigned NumInstr)629*0a6a1f1dSLionel Sambuc static inline float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size,
630*0a6a1f1dSLionel Sambuc                                          unsigned NumInstr) {
631*0a6a1f1dSLionel Sambuc   // All intervals have a spill weight that is mostly proportional to the number
632*0a6a1f1dSLionel Sambuc   // of uses, with uses in loops having a bigger weight.
633*0a6a1f1dSLionel Sambuc   return NumInstr * normalizeSpillWeight(UseDefFreq, Size, 1);
634*0a6a1f1dSLionel Sambuc }
635*0a6a1f1dSLionel Sambuc 
runOnMachineFunction(MachineFunction & MF)636f4a2713aSLionel Sambuc bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
637*0a6a1f1dSLionel Sambuc   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
638*0a6a1f1dSLionel Sambuc   MachineBlockFrequencyInfo &MBFI =
639*0a6a1f1dSLionel Sambuc     getAnalysis<MachineBlockFrequencyInfo>();
640f4a2713aSLionel Sambuc 
641*0a6a1f1dSLionel Sambuc   calculateSpillWeightsAndHints(LIS, MF, getAnalysis<MachineLoopInfo>(), MBFI,
642*0a6a1f1dSLionel Sambuc                                 normalizePBQPSpillWeight);
643f4a2713aSLionel Sambuc 
644*0a6a1f1dSLionel Sambuc   VirtRegMap &VRM = getAnalysis<VirtRegMap>();
645f4a2713aSLionel Sambuc 
646*0a6a1f1dSLionel Sambuc   std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
647f4a2713aSLionel Sambuc 
648*0a6a1f1dSLionel Sambuc   MF.getRegInfo().freezeReservedRegs(MF);
649f4a2713aSLionel Sambuc 
650*0a6a1f1dSLionel Sambuc   DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
651f4a2713aSLionel Sambuc 
652f4a2713aSLionel Sambuc   // Allocator main loop:
653f4a2713aSLionel Sambuc   //
654f4a2713aSLionel Sambuc   // * Map current regalloc problem to a PBQP problem
655f4a2713aSLionel Sambuc   // * Solve the PBQP problem
656f4a2713aSLionel Sambuc   // * Map the solution back to a register allocation
657f4a2713aSLionel Sambuc   // * Spill if necessary
658f4a2713aSLionel Sambuc   //
659f4a2713aSLionel Sambuc   // This process is continued till no more spills are generated.
660f4a2713aSLionel Sambuc 
661f4a2713aSLionel Sambuc   // Find the vreg intervals in need of allocation.
662*0a6a1f1dSLionel Sambuc   findVRegIntervalsToAlloc(MF, LIS);
663f4a2713aSLionel Sambuc 
664f4a2713aSLionel Sambuc #ifndef NDEBUG
665*0a6a1f1dSLionel Sambuc   const Function &F = *MF.getFunction();
666*0a6a1f1dSLionel Sambuc   std::string FullyQualifiedName =
667*0a6a1f1dSLionel Sambuc     F.getParent()->getModuleIdentifier() + "." + F.getName().str();
668f4a2713aSLionel Sambuc #endif
669f4a2713aSLionel Sambuc 
670f4a2713aSLionel Sambuc   // If there are non-empty intervals allocate them using pbqp.
671*0a6a1f1dSLionel Sambuc   if (!VRegsToAlloc.empty()) {
672f4a2713aSLionel Sambuc 
673*0a6a1f1dSLionel Sambuc     const TargetSubtargetInfo &Subtarget = *MF.getTarget().getSubtargetImpl();
674*0a6a1f1dSLionel Sambuc     std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
675*0a6a1f1dSLionel Sambuc       llvm::make_unique<PBQPRAConstraintList>();
676*0a6a1f1dSLionel Sambuc     ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
677*0a6a1f1dSLionel Sambuc     ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
678*0a6a1f1dSLionel Sambuc     if (PBQPCoalescing)
679*0a6a1f1dSLionel Sambuc       ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
680*0a6a1f1dSLionel Sambuc     ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
681f4a2713aSLionel Sambuc 
682*0a6a1f1dSLionel Sambuc     bool PBQPAllocComplete = false;
683*0a6a1f1dSLionel Sambuc     unsigned Round = 0;
684f4a2713aSLionel Sambuc 
685*0a6a1f1dSLionel Sambuc     while (!PBQPAllocComplete) {
686*0a6a1f1dSLionel Sambuc       DEBUG(dbgs() << "  PBQP Regalloc round " << Round << ":\n");
687*0a6a1f1dSLionel Sambuc 
688*0a6a1f1dSLionel Sambuc       PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
689*0a6a1f1dSLionel Sambuc       initializeGraph(G);
690*0a6a1f1dSLionel Sambuc       ConstraintsRoot->apply(G);
691f4a2713aSLionel Sambuc 
692f4a2713aSLionel Sambuc #ifndef NDEBUG
693*0a6a1f1dSLionel Sambuc       if (PBQPDumpGraphs) {
694*0a6a1f1dSLionel Sambuc         std::ostringstream RS;
695*0a6a1f1dSLionel Sambuc         RS << Round;
696*0a6a1f1dSLionel Sambuc         std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
697*0a6a1f1dSLionel Sambuc                                     ".pbqpgraph";
698*0a6a1f1dSLionel Sambuc         std::error_code EC;
699*0a6a1f1dSLionel Sambuc         raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text);
700*0a6a1f1dSLionel Sambuc         DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
701*0a6a1f1dSLionel Sambuc               << GraphFileName << "\"\n");
702*0a6a1f1dSLionel Sambuc         G.dumpToStream(OS);
703f4a2713aSLionel Sambuc       }
704f4a2713aSLionel Sambuc #endif
705f4a2713aSLionel Sambuc 
706*0a6a1f1dSLionel Sambuc       PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
707*0a6a1f1dSLionel Sambuc       PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
708*0a6a1f1dSLionel Sambuc       ++Round;
709f4a2713aSLionel Sambuc     }
710f4a2713aSLionel Sambuc   }
711f4a2713aSLionel Sambuc 
712f4a2713aSLionel Sambuc   // Finalise allocation, allocate empty ranges.
713*0a6a1f1dSLionel Sambuc   finalizeAlloc(MF, LIS, VRM);
714*0a6a1f1dSLionel Sambuc   VRegsToAlloc.clear();
715*0a6a1f1dSLionel Sambuc   EmptyIntervalVRegs.clear();
716f4a2713aSLionel Sambuc 
717*0a6a1f1dSLionel Sambuc   DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
718f4a2713aSLionel Sambuc 
719f4a2713aSLionel Sambuc   return true;
720f4a2713aSLionel Sambuc }
721f4a2713aSLionel Sambuc 
createPBQPRegisterAllocator(char * customPassID)722*0a6a1f1dSLionel Sambuc FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
723*0a6a1f1dSLionel Sambuc   return new RegAllocPBQP(customPassID);
724f4a2713aSLionel Sambuc }
725f4a2713aSLionel Sambuc 
createDefaultPBQPRegisterAllocator()726f4a2713aSLionel Sambuc FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
727*0a6a1f1dSLionel Sambuc   return createPBQPRegisterAllocator();
728f4a2713aSLionel Sambuc }
729f4a2713aSLionel Sambuc 
730f4a2713aSLionel Sambuc #undef DEBUG_TYPE
731