RegAllocPBQP.cpp 34 KB

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