RegAllocPBQP.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- RegAllocPBQP.h -------------------------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the PBQPBuilder interface, for classes which build PBQP
  15. // instances to represent register allocation problems, and the RegAllocPBQP
  16. // interface.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_CODEGEN_REGALLOCPBQP_H
  20. #define LLVM_CODEGEN_REGALLOCPBQP_H
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/Hashing.h"
  23. #include "llvm/CodeGen/PBQP/CostAllocator.h"
  24. #include "llvm/CodeGen/PBQP/Graph.h"
  25. #include "llvm/CodeGen/PBQP/Math.h"
  26. #include "llvm/CodeGen/PBQP/ReductionRules.h"
  27. #include "llvm/CodeGen/PBQP/Solution.h"
  28. #include "llvm/CodeGen/Register.h"
  29. #include "llvm/MC/MCRegister.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. #include <algorithm>
  32. #include <cassert>
  33. #include <cstddef>
  34. #include <limits>
  35. #include <memory>
  36. #include <set>
  37. #include <vector>
  38. namespace llvm {
  39. class FunctionPass;
  40. class LiveIntervals;
  41. class MachineBlockFrequencyInfo;
  42. class MachineFunction;
  43. class raw_ostream;
  44. namespace PBQP {
  45. namespace RegAlloc {
  46. /// Spill option index.
  47. inline unsigned getSpillOptionIdx() { return 0; }
  48. /// Metadata to speed allocatability test.
  49. ///
  50. /// Keeps track of the number of infinities in each row and column.
  51. class MatrixMetadata {
  52. public:
  53. MatrixMetadata(const Matrix& M)
  54. : UnsafeRows(new bool[M.getRows() - 1]()),
  55. UnsafeCols(new bool[M.getCols() - 1]()) {
  56. unsigned* ColCounts = new unsigned[M.getCols() - 1]();
  57. for (unsigned i = 1; i < M.getRows(); ++i) {
  58. unsigned RowCount = 0;
  59. for (unsigned j = 1; j < M.getCols(); ++j) {
  60. if (M[i][j] == std::numeric_limits<PBQPNum>::infinity()) {
  61. ++RowCount;
  62. ++ColCounts[j - 1];
  63. UnsafeRows[i - 1] = true;
  64. UnsafeCols[j - 1] = true;
  65. }
  66. }
  67. WorstRow = std::max(WorstRow, RowCount);
  68. }
  69. unsigned WorstColCountForCurRow =
  70. *std::max_element(ColCounts, ColCounts + M.getCols() - 1);
  71. WorstCol = std::max(WorstCol, WorstColCountForCurRow);
  72. delete[] ColCounts;
  73. }
  74. MatrixMetadata(const MatrixMetadata &) = delete;
  75. MatrixMetadata &operator=(const MatrixMetadata &) = delete;
  76. unsigned getWorstRow() const { return WorstRow; }
  77. unsigned getWorstCol() const { return WorstCol; }
  78. const bool* getUnsafeRows() const { return UnsafeRows.get(); }
  79. const bool* getUnsafeCols() const { return UnsafeCols.get(); }
  80. private:
  81. unsigned WorstRow = 0;
  82. unsigned WorstCol = 0;
  83. std::unique_ptr<bool[]> UnsafeRows;
  84. std::unique_ptr<bool[]> UnsafeCols;
  85. };
  86. /// Holds a vector of the allowed physical regs for a vreg.
  87. class AllowedRegVector {
  88. friend hash_code hash_value(const AllowedRegVector &);
  89. public:
  90. AllowedRegVector() = default;
  91. AllowedRegVector(AllowedRegVector &&) = default;
  92. AllowedRegVector(const std::vector<MCRegister> &OptVec)
  93. : NumOpts(OptVec.size()), Opts(new MCRegister[NumOpts]) {
  94. std::copy(OptVec.begin(), OptVec.end(), Opts.get());
  95. }
  96. unsigned size() const { return NumOpts; }
  97. MCRegister operator[](size_t I) const { return Opts[I]; }
  98. bool operator==(const AllowedRegVector &Other) const {
  99. if (NumOpts != Other.NumOpts)
  100. return false;
  101. return std::equal(Opts.get(), Opts.get() + NumOpts, Other.Opts.get());
  102. }
  103. bool operator!=(const AllowedRegVector &Other) const {
  104. return !(*this == Other);
  105. }
  106. private:
  107. unsigned NumOpts = 0;
  108. std::unique_ptr<MCRegister[]> Opts;
  109. };
  110. inline hash_code hash_value(const AllowedRegVector &OptRegs) {
  111. MCRegister *OStart = OptRegs.Opts.get();
  112. MCRegister *OEnd = OptRegs.Opts.get() + OptRegs.NumOpts;
  113. return hash_combine(OptRegs.NumOpts,
  114. hash_combine_range(OStart, OEnd));
  115. }
  116. /// Holds graph-level metadata relevant to PBQP RA problems.
  117. class GraphMetadata {
  118. private:
  119. using AllowedRegVecPool = ValuePool<AllowedRegVector>;
  120. public:
  121. using AllowedRegVecRef = AllowedRegVecPool::PoolRef;
  122. GraphMetadata(MachineFunction &MF,
  123. LiveIntervals &LIS,
  124. MachineBlockFrequencyInfo &MBFI)
  125. : MF(MF), LIS(LIS), MBFI(MBFI) {}
  126. MachineFunction &MF;
  127. LiveIntervals &LIS;
  128. MachineBlockFrequencyInfo &MBFI;
  129. void setNodeIdForVReg(Register VReg, GraphBase::NodeId NId) {
  130. VRegToNodeId[VReg.id()] = NId;
  131. }
  132. GraphBase::NodeId getNodeIdForVReg(Register VReg) const {
  133. auto VRegItr = VRegToNodeId.find(VReg);
  134. if (VRegItr == VRegToNodeId.end())
  135. return GraphBase::invalidNodeId();
  136. return VRegItr->second;
  137. }
  138. AllowedRegVecRef getAllowedRegs(AllowedRegVector Allowed) {
  139. return AllowedRegVecs.getValue(std::move(Allowed));
  140. }
  141. private:
  142. DenseMap<Register, GraphBase::NodeId> VRegToNodeId;
  143. AllowedRegVecPool AllowedRegVecs;
  144. };
  145. /// Holds solver state and other metadata relevant to each PBQP RA node.
  146. class NodeMetadata {
  147. public:
  148. using AllowedRegVector = RegAlloc::AllowedRegVector;
  149. // The node's reduction state. The order in this enum is important,
  150. // as it is assumed nodes can only progress up (i.e. towards being
  151. // optimally reducible) when reducing the graph.
  152. using ReductionState = enum {
  153. Unprocessed,
  154. NotProvablyAllocatable,
  155. ConservativelyAllocatable,
  156. OptimallyReducible
  157. };
  158. NodeMetadata() = default;
  159. NodeMetadata(const NodeMetadata &Other)
  160. : RS(Other.RS), NumOpts(Other.NumOpts), DeniedOpts(Other.DeniedOpts),
  161. OptUnsafeEdges(new unsigned[NumOpts]), VReg(Other.VReg),
  162. AllowedRegs(Other.AllowedRegs)
  163. #ifndef NDEBUG
  164. , everConservativelyAllocatable(Other.everConservativelyAllocatable)
  165. #endif
  166. {
  167. if (NumOpts > 0) {
  168. std::copy(&Other.OptUnsafeEdges[0], &Other.OptUnsafeEdges[NumOpts],
  169. &OptUnsafeEdges[0]);
  170. }
  171. }
  172. NodeMetadata(NodeMetadata &&) = default;
  173. NodeMetadata& operator=(NodeMetadata &&) = default;
  174. void setVReg(Register VReg) { this->VReg = VReg; }
  175. Register getVReg() const { return VReg; }
  176. void setAllowedRegs(GraphMetadata::AllowedRegVecRef AllowedRegs) {
  177. this->AllowedRegs = std::move(AllowedRegs);
  178. }
  179. const AllowedRegVector& getAllowedRegs() const { return *AllowedRegs; }
  180. void setup(const Vector& Costs) {
  181. NumOpts = Costs.getLength() - 1;
  182. OptUnsafeEdges = std::unique_ptr<unsigned[]>(new unsigned[NumOpts]());
  183. }
  184. ReductionState getReductionState() const { return RS; }
  185. void setReductionState(ReductionState RS) {
  186. assert(RS >= this->RS && "A node's reduction state can not be downgraded");
  187. this->RS = RS;
  188. #ifndef NDEBUG
  189. // Remember this state to assert later that a non-infinite register
  190. // option was available.
  191. if (RS == ConservativelyAllocatable)
  192. everConservativelyAllocatable = true;
  193. #endif
  194. }
  195. void handleAddEdge(const MatrixMetadata& MD, bool Transpose) {
  196. DeniedOpts += Transpose ? MD.getWorstRow() : MD.getWorstCol();
  197. const bool* UnsafeOpts =
  198. Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
  199. for (unsigned i = 0; i < NumOpts; ++i)
  200. OptUnsafeEdges[i] += UnsafeOpts[i];
  201. }
  202. void handleRemoveEdge(const MatrixMetadata& MD, bool Transpose) {
  203. DeniedOpts -= Transpose ? MD.getWorstRow() : MD.getWorstCol();
  204. const bool* UnsafeOpts =
  205. Transpose ? MD.getUnsafeCols() : MD.getUnsafeRows();
  206. for (unsigned i = 0; i < NumOpts; ++i)
  207. OptUnsafeEdges[i] -= UnsafeOpts[i];
  208. }
  209. bool isConservativelyAllocatable() const {
  210. return (DeniedOpts < NumOpts) ||
  211. (std::find(&OptUnsafeEdges[0], &OptUnsafeEdges[NumOpts], 0) !=
  212. &OptUnsafeEdges[NumOpts]);
  213. }
  214. #ifndef NDEBUG
  215. bool wasConservativelyAllocatable() const {
  216. return everConservativelyAllocatable;
  217. }
  218. #endif
  219. private:
  220. ReductionState RS = Unprocessed;
  221. unsigned NumOpts = 0;
  222. unsigned DeniedOpts = 0;
  223. std::unique_ptr<unsigned[]> OptUnsafeEdges;
  224. Register VReg;
  225. GraphMetadata::AllowedRegVecRef AllowedRegs;
  226. #ifndef NDEBUG
  227. bool everConservativelyAllocatable = false;
  228. #endif
  229. };
  230. class RegAllocSolverImpl {
  231. private:
  232. using RAMatrix = MDMatrix<MatrixMetadata>;
  233. public:
  234. using RawVector = PBQP::Vector;
  235. using RawMatrix = PBQP::Matrix;
  236. using Vector = PBQP::Vector;
  237. using Matrix = RAMatrix;
  238. using CostAllocator = PBQP::PoolCostAllocator<Vector, Matrix>;
  239. using NodeId = GraphBase::NodeId;
  240. using EdgeId = GraphBase::EdgeId;
  241. using NodeMetadata = RegAlloc::NodeMetadata;
  242. struct EdgeMetadata {};
  243. using GraphMetadata = RegAlloc::GraphMetadata;
  244. using Graph = PBQP::Graph<RegAllocSolverImpl>;
  245. RegAllocSolverImpl(Graph &G) : G(G) {}
  246. Solution solve() {
  247. G.setSolver(*this);
  248. Solution S;
  249. setup();
  250. S = backpropagate(G, reduce());
  251. G.unsetSolver();
  252. return S;
  253. }
  254. void handleAddNode(NodeId NId) {
  255. assert(G.getNodeCosts(NId).getLength() > 1 &&
  256. "PBQP Graph should not contain single or zero-option nodes");
  257. G.getNodeMetadata(NId).setup(G.getNodeCosts(NId));
  258. }
  259. void handleRemoveNode(NodeId NId) {}
  260. void handleSetNodeCosts(NodeId NId, const Vector& newCosts) {}
  261. void handleAddEdge(EdgeId EId) {
  262. handleReconnectEdge(EId, G.getEdgeNode1Id(EId));
  263. handleReconnectEdge(EId, G.getEdgeNode2Id(EId));
  264. }
  265. void handleDisconnectEdge(EdgeId EId, NodeId NId) {
  266. NodeMetadata& NMd = G.getNodeMetadata(NId);
  267. const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
  268. NMd.handleRemoveEdge(MMd, NId == G.getEdgeNode2Id(EId));
  269. promote(NId, NMd);
  270. }
  271. void handleReconnectEdge(EdgeId EId, NodeId NId) {
  272. NodeMetadata& NMd = G.getNodeMetadata(NId);
  273. const MatrixMetadata& MMd = G.getEdgeCosts(EId).getMetadata();
  274. NMd.handleAddEdge(MMd, NId == G.getEdgeNode2Id(EId));
  275. }
  276. void handleUpdateCosts(EdgeId EId, const Matrix& NewCosts) {
  277. NodeId N1Id = G.getEdgeNode1Id(EId);
  278. NodeId N2Id = G.getEdgeNode2Id(EId);
  279. NodeMetadata& N1Md = G.getNodeMetadata(N1Id);
  280. NodeMetadata& N2Md = G.getNodeMetadata(N2Id);
  281. bool Transpose = N1Id != G.getEdgeNode1Id(EId);
  282. // Metadata are computed incrementally. First, update them
  283. // by removing the old cost.
  284. const MatrixMetadata& OldMMd = G.getEdgeCosts(EId).getMetadata();
  285. N1Md.handleRemoveEdge(OldMMd, Transpose);
  286. N2Md.handleRemoveEdge(OldMMd, !Transpose);
  287. // And update now the metadata with the new cost.
  288. const MatrixMetadata& MMd = NewCosts.getMetadata();
  289. N1Md.handleAddEdge(MMd, Transpose);
  290. N2Md.handleAddEdge(MMd, !Transpose);
  291. // As the metadata may have changed with the update, the nodes may have
  292. // become ConservativelyAllocatable or OptimallyReducible.
  293. promote(N1Id, N1Md);
  294. promote(N2Id, N2Md);
  295. }
  296. private:
  297. void promote(NodeId NId, NodeMetadata& NMd) {
  298. if (G.getNodeDegree(NId) == 3) {
  299. // This node is becoming optimally reducible.
  300. moveToOptimallyReducibleNodes(NId);
  301. } else if (NMd.getReductionState() ==
  302. NodeMetadata::NotProvablyAllocatable &&
  303. NMd.isConservativelyAllocatable()) {
  304. // This node just became conservatively allocatable.
  305. moveToConservativelyAllocatableNodes(NId);
  306. }
  307. }
  308. void removeFromCurrentSet(NodeId NId) {
  309. switch (G.getNodeMetadata(NId).getReductionState()) {
  310. case NodeMetadata::Unprocessed: break;
  311. case NodeMetadata::OptimallyReducible:
  312. assert(OptimallyReducibleNodes.find(NId) !=
  313. OptimallyReducibleNodes.end() &&
  314. "Node not in optimally reducible set.");
  315. OptimallyReducibleNodes.erase(NId);
  316. break;
  317. case NodeMetadata::ConservativelyAllocatable:
  318. assert(ConservativelyAllocatableNodes.find(NId) !=
  319. ConservativelyAllocatableNodes.end() &&
  320. "Node not in conservatively allocatable set.");
  321. ConservativelyAllocatableNodes.erase(NId);
  322. break;
  323. case NodeMetadata::NotProvablyAllocatable:
  324. assert(NotProvablyAllocatableNodes.find(NId) !=
  325. NotProvablyAllocatableNodes.end() &&
  326. "Node not in not-provably-allocatable set.");
  327. NotProvablyAllocatableNodes.erase(NId);
  328. break;
  329. }
  330. }
  331. void moveToOptimallyReducibleNodes(NodeId NId) {
  332. removeFromCurrentSet(NId);
  333. OptimallyReducibleNodes.insert(NId);
  334. G.getNodeMetadata(NId).setReductionState(
  335. NodeMetadata::OptimallyReducible);
  336. }
  337. void moveToConservativelyAllocatableNodes(NodeId NId) {
  338. removeFromCurrentSet(NId);
  339. ConservativelyAllocatableNodes.insert(NId);
  340. G.getNodeMetadata(NId).setReductionState(
  341. NodeMetadata::ConservativelyAllocatable);
  342. }
  343. void moveToNotProvablyAllocatableNodes(NodeId NId) {
  344. removeFromCurrentSet(NId);
  345. NotProvablyAllocatableNodes.insert(NId);
  346. G.getNodeMetadata(NId).setReductionState(
  347. NodeMetadata::NotProvablyAllocatable);
  348. }
  349. void setup() {
  350. // Set up worklists.
  351. for (auto NId : G.nodeIds()) {
  352. if (G.getNodeDegree(NId) < 3)
  353. moveToOptimallyReducibleNodes(NId);
  354. else if (G.getNodeMetadata(NId).isConservativelyAllocatable())
  355. moveToConservativelyAllocatableNodes(NId);
  356. else
  357. moveToNotProvablyAllocatableNodes(NId);
  358. }
  359. }
  360. // Compute a reduction order for the graph by iteratively applying PBQP
  361. // reduction rules. Locally optimal rules are applied whenever possible (R0,
  362. // R1, R2). If no locally-optimal rules apply then any conservatively
  363. // allocatable node is reduced. Finally, if no conservatively allocatable
  364. // node exists then the node with the lowest spill-cost:degree ratio is
  365. // selected.
  366. std::vector<GraphBase::NodeId> reduce() {
  367. assert(!G.empty() && "Cannot reduce empty graph.");
  368. using NodeId = GraphBase::NodeId;
  369. std::vector<NodeId> NodeStack;
  370. // Consume worklists.
  371. while (true) {
  372. if (!OptimallyReducibleNodes.empty()) {
  373. NodeSet::iterator NItr = OptimallyReducibleNodes.begin();
  374. NodeId NId = *NItr;
  375. OptimallyReducibleNodes.erase(NItr);
  376. NodeStack.push_back(NId);
  377. switch (G.getNodeDegree(NId)) {
  378. case 0:
  379. break;
  380. case 1:
  381. applyR1(G, NId);
  382. break;
  383. case 2:
  384. applyR2(G, NId);
  385. break;
  386. default: llvm_unreachable("Not an optimally reducible node.");
  387. }
  388. } else if (!ConservativelyAllocatableNodes.empty()) {
  389. // Conservatively allocatable nodes will never spill. For now just
  390. // take the first node in the set and push it on the stack. When we
  391. // start optimizing more heavily for register preferencing, it may
  392. // would be better to push nodes with lower 'expected' or worst-case
  393. // register costs first (since early nodes are the most
  394. // constrained).
  395. NodeSet::iterator NItr = ConservativelyAllocatableNodes.begin();
  396. NodeId NId = *NItr;
  397. ConservativelyAllocatableNodes.erase(NItr);
  398. NodeStack.push_back(NId);
  399. G.disconnectAllNeighborsFromNode(NId);
  400. } else if (!NotProvablyAllocatableNodes.empty()) {
  401. NodeSet::iterator NItr =
  402. std::min_element(NotProvablyAllocatableNodes.begin(),
  403. NotProvablyAllocatableNodes.end(),
  404. SpillCostComparator(G));
  405. NodeId NId = *NItr;
  406. NotProvablyAllocatableNodes.erase(NItr);
  407. NodeStack.push_back(NId);
  408. G.disconnectAllNeighborsFromNode(NId);
  409. } else
  410. break;
  411. }
  412. return NodeStack;
  413. }
  414. class SpillCostComparator {
  415. public:
  416. SpillCostComparator(const Graph& G) : G(G) {}
  417. bool operator()(NodeId N1Id, NodeId N2Id) {
  418. PBQPNum N1SC = G.getNodeCosts(N1Id)[0];
  419. PBQPNum N2SC = G.getNodeCosts(N2Id)[0];
  420. if (N1SC == N2SC)
  421. return G.getNodeDegree(N1Id) < G.getNodeDegree(N2Id);
  422. return N1SC < N2SC;
  423. }
  424. private:
  425. const Graph& G;
  426. };
  427. Graph& G;
  428. using NodeSet = std::set<NodeId>;
  429. NodeSet OptimallyReducibleNodes;
  430. NodeSet ConservativelyAllocatableNodes;
  431. NodeSet NotProvablyAllocatableNodes;
  432. };
  433. class PBQPRAGraph : public PBQP::Graph<RegAllocSolverImpl> {
  434. private:
  435. using BaseT = PBQP::Graph<RegAllocSolverImpl>;
  436. public:
  437. PBQPRAGraph(GraphMetadata Metadata) : BaseT(std::move(Metadata)) {}
  438. /// Dump this graph to dbgs().
  439. void dump() const;
  440. /// Dump this graph to an output stream.
  441. /// @param OS Output stream to print on.
  442. void dump(raw_ostream &OS) const;
  443. /// Print a representation of this graph in DOT format.
  444. /// @param OS Output stream to print on.
  445. void printDot(raw_ostream &OS) const;
  446. };
  447. inline Solution solve(PBQPRAGraph& G) {
  448. if (G.empty())
  449. return Solution();
  450. RegAllocSolverImpl RegAllocSolver(G);
  451. return RegAllocSolver.solve();
  452. }
  453. } // end namespace RegAlloc
  454. } // end namespace PBQP
  455. /// Create a PBQP register allocator instance.
  456. FunctionPass *
  457. createPBQPRegisterAllocator(char *customPassID = nullptr);
  458. } // end namespace llvm
  459. #endif // LLVM_CODEGEN_REGALLOCPBQP_H
  460. #ifdef __GNUC__
  461. #pragma GCC diagnostic pop
  462. #endif