RegAllocPBQP.cpp 31 KB

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