1 //===- RegAllocPBQP.cpp ---- PBQP Register Allocator ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a Partitioned Boolean Quadratic Programming (PBQP) based
10 // register allocator for LLVM. This allocator works by constructing a PBQP
11 // problem representing the register allocation problem under consideration,
12 // solving this using a PBQP solver, and mapping the solution back to a
13 // register assignment. If any variables are selected for spilling then spill
14 // code is inserted and the process repeated.
15 //
16 // The PBQP solver (pbqp.c) provided for this allocator uses a heuristic tuned
17 // for register allocation. For more information on PBQP for register
18 // allocation, see the following papers:
19 //
20 //   (1) Hames, L. and Scholz, B. 2006. Nearly optimal register allocation with
21 //   PBQP. In Proceedings of the 7th Joint Modular Languages Conference
22 //   (JMLC'06). LNCS, vol. 4228. Springer, New York, NY, USA. 346-361.
23 //
24 //   (2) Scholz, B., Eckstein, E. 2002. Register allocation for irregular
25 //   architectures. In Proceedings of the Joint Conference on Languages,
26 //   Compilers and Tools for Embedded Systems (LCTES'02), ACM Press, New York,
27 //   NY, USA, 139-148.
28 //
29 //===----------------------------------------------------------------------===//
30 
31 #include "llvm/CodeGen/RegAllocPBQP.h"
32 #include "RegisterCoalescer.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/BitVector.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/DenseSet.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/CodeGen/CalcSpillWeights.h"
43 #include "llvm/CodeGen/LiveInterval.h"
44 #include "llvm/CodeGen/LiveIntervals.h"
45 #include "llvm/CodeGen/LiveRangeEdit.h"
46 #include "llvm/CodeGen/LiveStacks.h"
47 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
48 #include "llvm/CodeGen/MachineDominators.h"
49 #include "llvm/CodeGen/MachineFunction.h"
50 #include "llvm/CodeGen/MachineFunctionPass.h"
51 #include "llvm/CodeGen/MachineInstr.h"
52 #include "llvm/CodeGen/MachineLoopInfo.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/PBQP/Graph.h"
55 #include "llvm/CodeGen/PBQP/Math.h"
56 #include "llvm/CodeGen/PBQP/Solution.h"
57 #include "llvm/CodeGen/PBQPRAConstraint.h"
58 #include "llvm/CodeGen/RegAllocRegistry.h"
59 #include "llvm/CodeGen/SlotIndexes.h"
60 #include "llvm/CodeGen/Spiller.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/VirtRegMap.h"
64 #include "llvm/Config/llvm-config.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/MC/MCRegisterInfo.h"
68 #include "llvm/Pass.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/FileSystem.h"
73 #include "llvm/Support/Printable.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstddef>
78 #include <limits>
79 #include <map>
80 #include <memory>
81 #include <queue>
82 #include <set>
83 #include <sstream>
84 #include <string>
85 #include <system_error>
86 #include <tuple>
87 #include <utility>
88 #include <vector>
89 
90 using namespace llvm;
91 
92 #define DEBUG_TYPE "regalloc"
93 
94 static RegisterRegAlloc
95 RegisterPBQPRepAlloc("pbqp", "PBQP register allocator",
96                        createDefaultPBQPRegisterAllocator);
97 
98 static cl::opt<bool>
99 PBQPCoalescing("pbqp-coalescing",
100                 cl::desc("Attempt coalescing during PBQP register allocation."),
101                 cl::init(false), cl::Hidden);
102 
103 #ifndef NDEBUG
104 static cl::opt<bool>
105 PBQPDumpGraphs("pbqp-dump-graphs",
106                cl::desc("Dump graphs for each function/round in the compilation unit."),
107                cl::init(false), cl::Hidden);
108 #endif
109 
110 namespace {
111 
112 ///
113 /// PBQP based allocators solve the register allocation problem by mapping
114 /// register allocation problems to Partitioned Boolean Quadratic
115 /// Programming problems.
116 class RegAllocPBQP : public MachineFunctionPass {
117 public:
118   static char ID;
119 
120   /// Construct a PBQP register allocator.
121   RegAllocPBQP(char *cPassID = nullptr)
122       : MachineFunctionPass(ID), customPassID(cPassID) {
123     initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
124     initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
125     initializeLiveStacksPass(*PassRegistry::getPassRegistry());
126     initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
127   }
128 
129   /// Return the pass name.
130   StringRef getPassName() const override { return "PBQP Register Allocator"; }
131 
132   /// PBQP analysis usage.
133   void getAnalysisUsage(AnalysisUsage &au) const override;
134 
135   /// Perform register allocation
136   bool runOnMachineFunction(MachineFunction &MF) override;
137 
138   MachineFunctionProperties getRequiredProperties() const override {
139     return MachineFunctionProperties().set(
140         MachineFunctionProperties::Property::NoPHIs);
141   }
142 
143 private:
144   using LI2NodeMap = std::map<const LiveInterval *, unsigned>;
145   using Node2LIMap = std::vector<const LiveInterval *>;
146   using AllowedSet = std::vector<unsigned>;
147   using AllowedSetMap = std::vector<AllowedSet>;
148   using RegPair = std::pair<unsigned, unsigned>;
149   using CoalesceMap = std::map<RegPair, PBQP::PBQPNum>;
150   using RegSet = std::set<unsigned>;
151 
152   char *customPassID;
153 
154   RegSet VRegsToAlloc, EmptyIntervalVRegs;
155 
156   /// Inst which is a def of an original reg and whose defs are already all
157   /// dead after remat is saved in DeadRemats. The deletion of such inst is
158   /// postponed till all the allocations are done, so its remat expr is
159   /// always available for the remat of all the siblings of the original reg.
160   SmallPtrSet<MachineInstr *, 32> DeadRemats;
161 
162   /// Finds the initial set of vreg intervals to allocate.
163   void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS);
164 
165   /// Constructs an initial graph.
166   void initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM, Spiller &VRegSpiller);
167 
168   /// Spill the given VReg.
169   void spillVReg(Register VReg, SmallVectorImpl<Register> &NewIntervals,
170                  MachineFunction &MF, LiveIntervals &LIS, VirtRegMap &VRM,
171                  Spiller &VRegSpiller);
172 
173   /// Given a solved PBQP problem maps this solution back to a register
174   /// assignment.
175   bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
176                          const PBQP::Solution &Solution,
177                          VirtRegMap &VRM,
178                          Spiller &VRegSpiller);
179 
180   /// Postprocessing before final spilling. Sets basic block "live in"
181   /// variables.
182   void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
183                      VirtRegMap &VRM) const;
184 
185   void postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS);
186 };
187 
188 char RegAllocPBQP::ID = 0;
189 
190 /// Set spill costs for each node in the PBQP reg-alloc graph.
191 class SpillCosts : public PBQPRAConstraint {
192 public:
193   void apply(PBQPRAGraph &G) override {
194     LiveIntervals &LIS = G.getMetadata().LIS;
195 
196     // A minimum spill costs, so that register constraints can can be set
197     // without normalization in the [0.0:MinSpillCost( interval.
198     const PBQP::PBQPNum MinSpillCost = 10.0;
199 
200     for (auto NId : G.nodeIds()) {
201       PBQP::PBQPNum SpillCost =
202           LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight();
203       if (SpillCost == 0.0)
204         SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
205       else
206         SpillCost += MinSpillCost;
207       PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
208       NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
209       G.setNodeCosts(NId, std::move(NodeCosts));
210     }
211   }
212 };
213 
214 /// Add interference edges between overlapping vregs.
215 class Interference : public PBQPRAConstraint {
216 private:
217   using AllowedRegVecPtr = const PBQP::RegAlloc::AllowedRegVector *;
218   using IKey = std::pair<AllowedRegVecPtr, AllowedRegVecPtr>;
219   using IMatrixCache = DenseMap<IKey, PBQPRAGraph::MatrixPtr>;
220   using DisjointAllowedRegsCache = DenseSet<IKey>;
221   using IEdgeKey = std::pair<PBQP::GraphBase::NodeId, PBQP::GraphBase::NodeId>;
222   using IEdgeCache = DenseSet<IEdgeKey>;
223 
224   bool haveDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
225                                PBQPRAGraph::NodeId MId,
226                                const DisjointAllowedRegsCache &D) const {
227     const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
228     const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
229 
230     if (NRegs == MRegs)
231       return false;
232 
233     if (NRegs < MRegs)
234       return D.count(IKey(NRegs, MRegs)) > 0;
235 
236     return D.count(IKey(MRegs, NRegs)) > 0;
237   }
238 
239   void setDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
240                               PBQPRAGraph::NodeId MId,
241                               DisjointAllowedRegsCache &D) {
242     const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
243     const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
244 
245     assert(NRegs != MRegs && "AllowedRegs can not be disjoint with itself");
246 
247     if (NRegs < MRegs)
248       D.insert(IKey(NRegs, MRegs));
249     else
250       D.insert(IKey(MRegs, NRegs));
251   }
252 
253   // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
254   // for the fast interference graph construction algorithm. The last is there
255   // to save us from looking up node ids via the VRegToNode map in the graph
256   // metadata.
257   using IntervalInfo =
258       std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>;
259 
260   static SlotIndex getStartPoint(const IntervalInfo &I) {
261     return std::get<0>(I)->segments[std::get<1>(I)].start;
262   }
263 
264   static SlotIndex getEndPoint(const IntervalInfo &I) {
265     return std::get<0>(I)->segments[std::get<1>(I)].end;
266   }
267 
268   static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
269     return std::get<2>(I);
270   }
271 
272   static bool lowestStartPoint(const IntervalInfo &I1,
273                                const IntervalInfo &I2) {
274     // Condition reversed because priority queue has the *highest* element at
275     // the front, rather than the lowest.
276     return getStartPoint(I1) > getStartPoint(I2);
277   }
278 
279   static bool lowestEndPoint(const IntervalInfo &I1,
280                              const IntervalInfo &I2) {
281     SlotIndex E1 = getEndPoint(I1);
282     SlotIndex E2 = getEndPoint(I2);
283 
284     if (E1 < E2)
285       return true;
286 
287     if (E1 > E2)
288       return false;
289 
290     // If two intervals end at the same point, we need a way to break the tie or
291     // the set will assume they're actually equal and refuse to insert a
292     // "duplicate". Just compare the vregs - fast and guaranteed unique.
293     return std::get<0>(I1)->reg() < std::get<0>(I2)->reg();
294   }
295 
296   static bool isAtLastSegment(const IntervalInfo &I) {
297     return std::get<1>(I) == std::get<0>(I)->size() - 1;
298   }
299 
300   static IntervalInfo nextSegment(const IntervalInfo &I) {
301     return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
302   }
303 
304 public:
305   void apply(PBQPRAGraph &G) override {
306     // The following is loosely based on the linear scan algorithm introduced in
307     // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
308     // isn't linear, because the size of the active set isn't bound by the
309     // number of registers, but rather the size of the largest clique in the
310     // graph. Still, we expect this to be better than N^2.
311     LiveIntervals &LIS = G.getMetadata().LIS;
312 
313     // Interferenc matrices are incredibly regular - they're only a function of
314     // the allowed sets, so we cache them to avoid the overhead of constructing
315     // and uniquing them.
316     IMatrixCache C;
317 
318     // Finding an edge is expensive in the worst case (O(max_clique(G))). So
319     // cache locally edges we have already seen.
320     IEdgeCache EC;
321 
322     // Cache known disjoint allowed registers pairs
323     DisjointAllowedRegsCache D;
324 
325     using IntervalSet = std::set<IntervalInfo, decltype(&lowestEndPoint)>;
326     using IntervalQueue =
327         std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
328                             decltype(&lowestStartPoint)>;
329     IntervalSet Active(lowestEndPoint);
330     IntervalQueue Inactive(lowestStartPoint);
331 
332     // Start by building the inactive set.
333     for (auto NId : G.nodeIds()) {
334       unsigned VReg = G.getNodeMetadata(NId).getVReg();
335       LiveInterval &LI = LIS.getInterval(VReg);
336       assert(!LI.empty() && "PBQP graph contains node for empty interval");
337       Inactive.push(std::make_tuple(&LI, 0, NId));
338     }
339 
340     while (!Inactive.empty()) {
341       // Tentatively grab the "next" interval - this choice may be overriden
342       // below.
343       IntervalInfo Cur = Inactive.top();
344 
345       // Retire any active intervals that end before Cur starts.
346       IntervalSet::iterator RetireItr = Active.begin();
347       while (RetireItr != Active.end() &&
348              (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
349         // If this interval has subsequent segments, add the next one to the
350         // inactive list.
351         if (!isAtLastSegment(*RetireItr))
352           Inactive.push(nextSegment(*RetireItr));
353 
354         ++RetireItr;
355       }
356       Active.erase(Active.begin(), RetireItr);
357 
358       // One of the newly retired segments may actually start before the
359       // Cur segment, so re-grab the front of the inactive list.
360       Cur = Inactive.top();
361       Inactive.pop();
362 
363       // At this point we know that Cur overlaps all active intervals. Add the
364       // interference edges.
365       PBQP::GraphBase::NodeId NId = getNodeId(Cur);
366       for (const auto &A : Active) {
367         PBQP::GraphBase::NodeId MId = getNodeId(A);
368 
369         // Do not add an edge when the nodes' allowed registers do not
370         // intersect: there is obviously no interference.
371         if (haveDisjointAllowedRegs(G, NId, MId, D))
372           continue;
373 
374         // Check that we haven't already added this edge
375         IEdgeKey EK(std::min(NId, MId), std::max(NId, MId));
376         if (EC.count(EK))
377           continue;
378 
379         // This is a new edge - add it to the graph.
380         if (!createInterferenceEdge(G, NId, MId, C))
381           setDisjointAllowedRegs(G, NId, MId, D);
382         else
383           EC.insert(EK);
384       }
385 
386       // Finally, add Cur to the Active set.
387       Active.insert(Cur);
388     }
389   }
390 
391 private:
392   // Create an Interference edge and add it to the graph, unless it is
393   // a null matrix, meaning the nodes' allowed registers do not have any
394   // interference. This case occurs frequently between integer and floating
395   // point registers for example.
396   // return true iff both nodes interferes.
397   bool createInterferenceEdge(PBQPRAGraph &G,
398                               PBQPRAGraph::NodeId NId, PBQPRAGraph::NodeId MId,
399                               IMatrixCache &C) {
400     const TargetRegisterInfo &TRI =
401         *G.getMetadata().MF.getSubtarget().getRegisterInfo();
402     const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
403     const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
404 
405     // Try looking the edge costs up in the IMatrixCache first.
406     IKey K(&NRegs, &MRegs);
407     IMatrixCache::iterator I = C.find(K);
408     if (I != C.end()) {
409       G.addEdgeBypassingCostAllocator(NId, MId, I->second);
410       return true;
411     }
412 
413     PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
414     bool NodesInterfere = false;
415     for (unsigned I = 0; I != NRegs.size(); ++I) {
416       unsigned PRegN = NRegs[I];
417       for (unsigned J = 0; J != MRegs.size(); ++J) {
418         unsigned PRegM = MRegs[J];
419         if (TRI.regsOverlap(PRegN, PRegM)) {
420           M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
421           NodesInterfere = true;
422         }
423       }
424     }
425 
426     if (!NodesInterfere)
427       return false;
428 
429     PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
430     C[K] = G.getEdgeCostsPtr(EId);
431 
432     return true;
433   }
434 };
435 
436 class Coalescing : public PBQPRAConstraint {
437 public:
438   void apply(PBQPRAGraph &G) override {
439     MachineFunction &MF = G.getMetadata().MF;
440     MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
441     CoalescerPair CP(*MF.getSubtarget().getRegisterInfo());
442 
443     // Scan the machine function and add a coalescing cost whenever CoalescerPair
444     // gives the Ok.
445     for (const auto &MBB : MF) {
446       for (const auto &MI : MBB) {
447         // Skip not-coalescable or already coalesced copies.
448         if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
449           continue;
450 
451         unsigned DstReg = CP.getDstReg();
452         unsigned SrcReg = CP.getSrcReg();
453 
454         PBQP::PBQPNum CBenefit = MBFI.getBlockFreqRelativeToEntryBlock(&MBB);
455 
456         if (CP.isPhys()) {
457           if (!MF.getRegInfo().isAllocatable(DstReg))
458             continue;
459 
460           PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
461 
462           const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
463             G.getNodeMetadata(NId).getAllowedRegs();
464 
465           unsigned PRegOpt = 0;
466           while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
467             ++PRegOpt;
468 
469           if (PRegOpt < Allowed.size()) {
470             PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
471             NewCosts[PRegOpt + 1] -= CBenefit;
472             G.setNodeCosts(NId, std::move(NewCosts));
473           }
474         } else {
475           PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
476           PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
477           const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
478             &G.getNodeMetadata(N1Id).getAllowedRegs();
479           const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
480             &G.getNodeMetadata(N2Id).getAllowedRegs();
481 
482           PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
483           if (EId == G.invalidEdgeId()) {
484             PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
485                                          Allowed2->size() + 1, 0);
486             addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
487             G.addEdge(N1Id, N2Id, std::move(Costs));
488           } else {
489             if (G.getEdgeNode1Id(EId) == N2Id) {
490               std::swap(N1Id, N2Id);
491               std::swap(Allowed1, Allowed2);
492             }
493             PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
494             addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
495             G.updateEdgeCosts(EId, std::move(Costs));
496           }
497         }
498       }
499     }
500   }
501 
502 private:
503   void addVirtRegCoalesce(
504                     PBQPRAGraph::RawMatrix &CostMat,
505                     const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
506                     const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
507                     PBQP::PBQPNum Benefit) {
508     assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
509     assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
510     for (unsigned I = 0; I != Allowed1.size(); ++I) {
511       unsigned PReg1 = Allowed1[I];
512       for (unsigned J = 0; J != Allowed2.size(); ++J) {
513         unsigned PReg2 = Allowed2[J];
514         if (PReg1 == PReg2)
515           CostMat[I + 1][J + 1] -= Benefit;
516       }
517     }
518   }
519 };
520 
521 /// PBQP-specific implementation of weight normalization.
522 class PBQPVirtRegAuxInfo final : public VirtRegAuxInfo {
523   float normalize(float UseDefFreq, unsigned Size, unsigned NumInstr) override {
524     // All intervals have a spill weight that is mostly proportional to the
525     // number of uses, with uses in loops having a bigger weight.
526     return NumInstr * VirtRegAuxInfo::normalize(UseDefFreq, Size, 1);
527   }
528 
529 public:
530   PBQPVirtRegAuxInfo(MachineFunction &MF, LiveIntervals &LIS, VirtRegMap &VRM,
531                      const MachineLoopInfo &Loops,
532                      const MachineBlockFrequencyInfo &MBFI)
533       : VirtRegAuxInfo(MF, LIS, VRM, Loops, MBFI) {}
534 };
535 } // end anonymous namespace
536 
537 // Out-of-line destructor/anchor for PBQPRAConstraint.
538 PBQPRAConstraint::~PBQPRAConstraint() = default;
539 
540 void PBQPRAConstraint::anchor() {}
541 
542 void PBQPRAConstraintList::anchor() {}
543 
544 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
545   au.setPreservesCFG();
546   au.addRequired<AAResultsWrapperPass>();
547   au.addPreserved<AAResultsWrapperPass>();
548   au.addRequired<SlotIndexes>();
549   au.addPreserved<SlotIndexes>();
550   au.addRequired<LiveIntervals>();
551   au.addPreserved<LiveIntervals>();
552   //au.addRequiredID(SplitCriticalEdgesID);
553   if (customPassID)
554     au.addRequiredID(*customPassID);
555   au.addRequired<LiveStacks>();
556   au.addPreserved<LiveStacks>();
557   au.addRequired<MachineBlockFrequencyInfo>();
558   au.addPreserved<MachineBlockFrequencyInfo>();
559   au.addRequired<MachineLoopInfo>();
560   au.addPreserved<MachineLoopInfo>();
561   au.addRequired<MachineDominatorTree>();
562   au.addPreserved<MachineDominatorTree>();
563   au.addRequired<VirtRegMap>();
564   au.addPreserved<VirtRegMap>();
565   MachineFunctionPass::getAnalysisUsage(au);
566 }
567 
568 void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
569                                             LiveIntervals &LIS) {
570   const MachineRegisterInfo &MRI = MF.getRegInfo();
571 
572   // Iterate over all live ranges.
573   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
574     unsigned Reg = Register::index2VirtReg(I);
575     if (MRI.reg_nodbg_empty(Reg))
576       continue;
577     VRegsToAlloc.insert(Reg);
578   }
579 }
580 
581 static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI,
582                                    const MachineFunction &MF) {
583   const MCPhysReg *CSR = MF.getRegInfo().getCalleeSavedRegs();
584   for (unsigned i = 0; CSR[i] != 0; ++i)
585     if (TRI.regsOverlap(reg, CSR[i]))
586       return true;
587   return false;
588 }
589 
590 void RegAllocPBQP::initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM,
591                                    Spiller &VRegSpiller) {
592   MachineFunction &MF = G.getMetadata().MF;
593 
594   LiveIntervals &LIS = G.getMetadata().LIS;
595   const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
596   const TargetRegisterInfo &TRI =
597       *G.getMetadata().MF.getSubtarget().getRegisterInfo();
598 
599   std::vector<unsigned> Worklist(VRegsToAlloc.begin(), VRegsToAlloc.end());
600 
601   std::map<unsigned, std::vector<unsigned>> VRegAllowedMap;
602 
603   while (!Worklist.empty()) {
604     unsigned VReg = Worklist.back();
605     Worklist.pop_back();
606 
607     LiveInterval &VRegLI = LIS.getInterval(VReg);
608 
609     // If this is an empty interval move it to the EmptyIntervalVRegs set then
610     // continue.
611     if (VRegLI.empty()) {
612       EmptyIntervalVRegs.insert(VRegLI.reg());
613       VRegsToAlloc.erase(VRegLI.reg());
614       continue;
615     }
616 
617     const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
618 
619     // Record any overlaps with regmask operands.
620     BitVector RegMaskOverlaps;
621     LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
622 
623     // Compute an initial allowed set for the current vreg.
624     std::vector<unsigned> VRegAllowed;
625     ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
626     for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
627       unsigned PReg = RawPRegOrder[I];
628       if (MRI.isReserved(PReg))
629         continue;
630 
631       // vregLI crosses a regmask operand that clobbers preg.
632       if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
633         continue;
634 
635       // vregLI overlaps fixed regunit interference.
636       bool Interference = false;
637       for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
638         if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
639           Interference = true;
640           break;
641         }
642       }
643       if (Interference)
644         continue;
645 
646       // preg is usable for this virtual register.
647       VRegAllowed.push_back(PReg);
648     }
649 
650     // Check for vregs that have no allowed registers. These should be
651     // pre-spilled and the new vregs added to the worklist.
652     if (VRegAllowed.empty()) {
653       SmallVector<Register, 8> NewVRegs;
654       spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
655       Worklist.insert(Worklist.end(), NewVRegs.begin(), NewVRegs.end());
656       continue;
657     } else
658       VRegAllowedMap[VReg] = std::move(VRegAllowed);
659   }
660 
661   for (auto &KV : VRegAllowedMap) {
662     auto VReg = KV.first;
663 
664     // Move empty intervals to the EmptyIntervalVReg set.
665     if (LIS.getInterval(VReg).empty()) {
666       EmptyIntervalVRegs.insert(VReg);
667       VRegsToAlloc.erase(VReg);
668       continue;
669     }
670 
671     auto &VRegAllowed = KV.second;
672 
673     PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
674 
675     // Tweak cost of callee saved registers, as using then force spilling and
676     // restoring them. This would only happen in the prologue / epilogue though.
677     for (unsigned i = 0; i != VRegAllowed.size(); ++i)
678       if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF))
679         NodeCosts[1 + i] += 1.0;
680 
681     PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
682     G.getNodeMetadata(NId).setVReg(VReg);
683     G.getNodeMetadata(NId).setAllowedRegs(
684       G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
685     G.getMetadata().setNodeIdForVReg(VReg, NId);
686   }
687 }
688 
689 void RegAllocPBQP::spillVReg(Register VReg,
690                              SmallVectorImpl<Register> &NewIntervals,
691                              MachineFunction &MF, LiveIntervals &LIS,
692                              VirtRegMap &VRM, Spiller &VRegSpiller) {
693   VRegsToAlloc.erase(VReg);
694   LiveRangeEdit LRE(&LIS.getInterval(VReg), NewIntervals, MF, LIS, &VRM,
695                     nullptr, &DeadRemats);
696   VRegSpiller.spill(LRE);
697 
698   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
699   (void)TRI;
700   LLVM_DEBUG(dbgs() << "VREG " << printReg(VReg, &TRI) << " -> SPILLED (Cost: "
701                     << LRE.getParent().weight() << ", New vregs: ");
702 
703   // Copy any newly inserted live intervals into the list of regs to
704   // allocate.
705   for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
706        I != E; ++I) {
707     const LiveInterval &LI = LIS.getInterval(*I);
708     assert(!LI.empty() && "Empty spill range.");
709     LLVM_DEBUG(dbgs() << printReg(LI.reg(), &TRI) << " ");
710     VRegsToAlloc.insert(LI.reg());
711   }
712 
713   LLVM_DEBUG(dbgs() << ")\n");
714 }
715 
716 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
717                                      const PBQP::Solution &Solution,
718                                      VirtRegMap &VRM,
719                                      Spiller &VRegSpiller) {
720   MachineFunction &MF = G.getMetadata().MF;
721   LiveIntervals &LIS = G.getMetadata().LIS;
722   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
723   (void)TRI;
724 
725   // Set to true if we have any spills
726   bool AnotherRoundNeeded = false;
727 
728   // Clear the existing allocation.
729   VRM.clearAllVirt();
730 
731   // Iterate over the nodes mapping the PBQP solution to a register
732   // assignment.
733   for (auto NId : G.nodeIds()) {
734     unsigned VReg = G.getNodeMetadata(NId).getVReg();
735     unsigned AllocOption = Solution.getSelection(NId);
736 
737     if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
738       unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
739       LLVM_DEBUG(dbgs() << "VREG " << printReg(VReg, &TRI) << " -> "
740                         << TRI.getName(PReg) << "\n");
741       assert(PReg != 0 && "Invalid preg selected.");
742       VRM.assignVirt2Phys(VReg, PReg);
743     } else {
744       // Spill VReg. If this introduces new intervals we'll need another round
745       // of allocation.
746       SmallVector<Register, 8> NewVRegs;
747       spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
748       AnotherRoundNeeded |= !NewVRegs.empty();
749     }
750   }
751 
752   return !AnotherRoundNeeded;
753 }
754 
755 void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
756                                  LiveIntervals &LIS,
757                                  VirtRegMap &VRM) const {
758   MachineRegisterInfo &MRI = MF.getRegInfo();
759 
760   // First allocate registers for the empty intervals.
761   for (RegSet::const_iterator
762          I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
763          I != E; ++I) {
764     LiveInterval &LI = LIS.getInterval(*I);
765 
766     unsigned PReg = MRI.getSimpleHint(LI.reg());
767 
768     if (PReg == 0) {
769       const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg());
770       const ArrayRef<MCPhysReg> RawPRegOrder = RC.getRawAllocationOrder(MF);
771       for (unsigned CandidateReg : RawPRegOrder) {
772         if (!VRM.getRegInfo().isReserved(CandidateReg)) {
773           PReg = CandidateReg;
774           break;
775         }
776       }
777       assert(PReg &&
778              "No un-reserved physical registers in this register class");
779     }
780 
781     VRM.assignVirt2Phys(LI.reg(), PReg);
782   }
783 }
784 
785 void RegAllocPBQP::postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS) {
786   VRegSpiller.postOptimization();
787   /// Remove dead defs because of rematerialization.
788   for (auto DeadInst : DeadRemats) {
789     LIS.RemoveMachineInstrFromMaps(*DeadInst);
790     DeadInst->eraseFromParent();
791   }
792   DeadRemats.clear();
793 }
794 
795 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
796   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
797   MachineBlockFrequencyInfo &MBFI =
798     getAnalysis<MachineBlockFrequencyInfo>();
799 
800   VirtRegMap &VRM = getAnalysis<VirtRegMap>();
801 
802   PBQPVirtRegAuxInfo VRAI(MF, LIS, VRM, getAnalysis<MachineLoopInfo>(), MBFI);
803   VRAI.calculateSpillWeightsAndHints();
804 
805   std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
806 
807   MF.getRegInfo().freezeReservedRegs(MF);
808 
809   LLVM_DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
810 
811   // Allocator main loop:
812   //
813   // * Map current regalloc problem to a PBQP problem
814   // * Solve the PBQP problem
815   // * Map the solution back to a register allocation
816   // * Spill if necessary
817   //
818   // This process is continued till no more spills are generated.
819 
820   // Find the vreg intervals in need of allocation.
821   findVRegIntervalsToAlloc(MF, LIS);
822 
823 #ifndef NDEBUG
824   const Function &F = MF.getFunction();
825   std::string FullyQualifiedName =
826     F.getParent()->getModuleIdentifier() + "." + F.getName().str();
827 #endif
828 
829   // If there are non-empty intervals allocate them using pbqp.
830   if (!VRegsToAlloc.empty()) {
831     const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
832     std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
833       std::make_unique<PBQPRAConstraintList>();
834     ConstraintsRoot->addConstraint(std::make_unique<SpillCosts>());
835     ConstraintsRoot->addConstraint(std::make_unique<Interference>());
836     if (PBQPCoalescing)
837       ConstraintsRoot->addConstraint(std::make_unique<Coalescing>());
838     ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
839 
840     bool PBQPAllocComplete = false;
841     unsigned Round = 0;
842 
843     while (!PBQPAllocComplete) {
844       LLVM_DEBUG(dbgs() << "  PBQP Regalloc round " << Round << ":\n");
845 
846       PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
847       initializeGraph(G, VRM, *VRegSpiller);
848       ConstraintsRoot->apply(G);
849 
850 #ifndef NDEBUG
851       if (PBQPDumpGraphs) {
852         std::ostringstream RS;
853         RS << Round;
854         std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
855                                     ".pbqpgraph";
856         std::error_code EC;
857         raw_fd_ostream OS(GraphFileName, EC, sys::fs::OF_Text);
858         LLVM_DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
859                           << GraphFileName << "\"\n");
860         G.dump(OS);
861       }
862 #endif
863 
864       PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
865       PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
866       ++Round;
867     }
868   }
869 
870   // Finalise allocation, allocate empty ranges.
871   finalizeAlloc(MF, LIS, VRM);
872   postOptimization(*VRegSpiller, LIS);
873   VRegsToAlloc.clear();
874   EmptyIntervalVRegs.clear();
875 
876   LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
877 
878   return true;
879 }
880 
881 /// Create Printable object for node and register info.
882 static Printable PrintNodeInfo(PBQP::RegAlloc::PBQPRAGraph::NodeId NId,
883                                const PBQP::RegAlloc::PBQPRAGraph &G) {
884   return Printable([NId, &G](raw_ostream &OS) {
885     const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
886     const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
887     unsigned VReg = G.getNodeMetadata(NId).getVReg();
888     const char *RegClassName = TRI->getRegClassName(MRI.getRegClass(VReg));
889     OS << NId << " (" << RegClassName << ':' << printReg(VReg, TRI) << ')';
890   });
891 }
892 
893 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
894 LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump(raw_ostream &OS) const {
895   for (auto NId : nodeIds()) {
896     const Vector &Costs = getNodeCosts(NId);
897     assert(Costs.getLength() != 0 && "Empty vector in graph.");
898     OS << PrintNodeInfo(NId, *this) << ": " << Costs << '\n';
899   }
900   OS << '\n';
901 
902   for (auto EId : edgeIds()) {
903     NodeId N1Id = getEdgeNode1Id(EId);
904     NodeId N2Id = getEdgeNode2Id(EId);
905     assert(N1Id != N2Id && "PBQP graphs should not have self-edges.");
906     const Matrix &M = getEdgeCosts(EId);
907     assert(M.getRows() != 0 && "No rows in matrix.");
908     assert(M.getCols() != 0 && "No cols in matrix.");
909     OS << PrintNodeInfo(N1Id, *this) << ' ' << M.getRows() << " rows / ";
910     OS << PrintNodeInfo(N2Id, *this) << ' ' << M.getCols() << " cols:\n";
911     OS << M << '\n';
912   }
913 }
914 
915 LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump() const {
916   dump(dbgs());
917 }
918 #endif
919 
920 void PBQP::RegAlloc::PBQPRAGraph::printDot(raw_ostream &OS) const {
921   OS << "graph {\n";
922   for (auto NId : nodeIds()) {
923     OS << "  node" << NId << " [ label=\""
924        << PrintNodeInfo(NId, *this) << "\\n"
925        << getNodeCosts(NId) << "\" ]\n";
926   }
927 
928   OS << "  edge [ len=" << nodeIds().size() << " ]\n";
929   for (auto EId : edgeIds()) {
930     OS << "  node" << getEdgeNode1Id(EId)
931        << " -- node" << getEdgeNode2Id(EId)
932        << " [ label=\"";
933     const Matrix &EdgeCosts = getEdgeCosts(EId);
934     for (unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
935       OS << EdgeCosts.getRowAsVector(i) << "\\n";
936     }
937     OS << "\" ]\n";
938   }
939   OS << "}\n";
940 }
941 
942 FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
943   return new RegAllocPBQP(customPassID);
944 }
945 
946 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
947   return createPBQPRegisterAllocator();
948 }
949