SpillPlacement.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. //===- SpillPlacement.cpp - Optimal Spill Code Placement ------------------===//
  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 implements the spill code placement analysis.
  10. //
  11. // Each edge bundle corresponds to a node in a Hopfield network. Constraints on
  12. // basic blocks are weighted by the block frequency and added to become the node
  13. // bias.
  14. //
  15. // Transparent basic blocks have the variable live through, but don't care if it
  16. // is spilled or in a register. These blocks become connections in the Hopfield
  17. // network, again weighted by block frequency.
  18. //
  19. // The Hopfield network minimizes (possibly locally) its energy function:
  20. //
  21. // E = -sum_n V_n * ( B_n + sum_{n, m linked by b} V_m * F_b )
  22. //
  23. // The energy function represents the expected spill code execution frequency,
  24. // or the cost of spilling. This is a Lyapunov function which never increases
  25. // when a node is updated. It is guaranteed to converge to a local minimum.
  26. //
  27. //===----------------------------------------------------------------------===//
  28. #include "SpillPlacement.h"
  29. #include "llvm/ADT/ArrayRef.h"
  30. #include "llvm/ADT/BitVector.h"
  31. #include "llvm/ADT/SmallVector.h"
  32. #include "llvm/ADT/SparseSet.h"
  33. #include "llvm/CodeGen/EdgeBundles.h"
  34. #include "llvm/CodeGen/MachineBasicBlock.h"
  35. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  36. #include "llvm/CodeGen/MachineFunction.h"
  37. #include "llvm/CodeGen/MachineLoopInfo.h"
  38. #include "llvm/CodeGen/Passes.h"
  39. #include "llvm/Pass.h"
  40. #include "llvm/Support/BlockFrequency.h"
  41. #include <algorithm>
  42. #include <cassert>
  43. #include <cstdint>
  44. #include <utility>
  45. using namespace llvm;
  46. #define DEBUG_TYPE "spill-code-placement"
  47. char SpillPlacement::ID = 0;
  48. char &llvm::SpillPlacementID = SpillPlacement::ID;
  49. INITIALIZE_PASS_BEGIN(SpillPlacement, DEBUG_TYPE,
  50. "Spill Code Placement Analysis", true, true)
  51. INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
  52. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  53. INITIALIZE_PASS_END(SpillPlacement, DEBUG_TYPE,
  54. "Spill Code Placement Analysis", true, true)
  55. void SpillPlacement::getAnalysisUsage(AnalysisUsage &AU) const {
  56. AU.setPreservesAll();
  57. AU.addRequired<MachineBlockFrequencyInfo>();
  58. AU.addRequiredTransitive<EdgeBundles>();
  59. AU.addRequiredTransitive<MachineLoopInfo>();
  60. MachineFunctionPass::getAnalysisUsage(AU);
  61. }
  62. /// Node - Each edge bundle corresponds to a Hopfield node.
  63. ///
  64. /// The node contains precomputed frequency data that only depends on the CFG,
  65. /// but Bias and Links are computed each time placeSpills is called.
  66. ///
  67. /// The node Value is positive when the variable should be in a register. The
  68. /// value can change when linked nodes change, but convergence is very fast
  69. /// because all weights are positive.
  70. struct SpillPlacement::Node {
  71. /// BiasN - Sum of blocks that prefer a spill.
  72. BlockFrequency BiasN;
  73. /// BiasP - Sum of blocks that prefer a register.
  74. BlockFrequency BiasP;
  75. /// Value - Output value of this node computed from the Bias and links.
  76. /// This is always on of the values {-1, 0, 1}. A positive number means the
  77. /// variable should go in a register through this bundle.
  78. int Value;
  79. using LinkVector = SmallVector<std::pair<BlockFrequency, unsigned>, 4>;
  80. /// Links - (Weight, BundleNo) for all transparent blocks connecting to other
  81. /// bundles. The weights are all positive block frequencies.
  82. LinkVector Links;
  83. /// SumLinkWeights - Cached sum of the weights of all links + ThresHold.
  84. BlockFrequency SumLinkWeights;
  85. /// preferReg - Return true when this node prefers to be in a register.
  86. bool preferReg() const {
  87. // Undecided nodes (Value==0) go on the stack.
  88. return Value > 0;
  89. }
  90. /// mustSpill - Return True if this node is so biased that it must spill.
  91. bool mustSpill() const {
  92. // We must spill if Bias < -sum(weights) or the MustSpill flag was set.
  93. // BiasN is saturated when MustSpill is set, make sure this still returns
  94. // true when the RHS saturates. Note that SumLinkWeights includes Threshold.
  95. return BiasN >= BiasP + SumLinkWeights;
  96. }
  97. /// clear - Reset per-query data, but preserve frequencies that only depend on
  98. /// the CFG.
  99. void clear(const BlockFrequency &Threshold) {
  100. BiasN = BiasP = Value = 0;
  101. SumLinkWeights = Threshold;
  102. Links.clear();
  103. }
  104. /// addLink - Add a link to bundle b with weight w.
  105. void addLink(unsigned b, BlockFrequency w) {
  106. // Update cached sum.
  107. SumLinkWeights += w;
  108. // There can be multiple links to the same bundle, add them up.
  109. for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)
  110. if (I->second == b) {
  111. I->first += w;
  112. return;
  113. }
  114. // This must be the first link to b.
  115. Links.push_back(std::make_pair(w, b));
  116. }
  117. /// addBias - Bias this node.
  118. void addBias(BlockFrequency freq, BorderConstraint direction) {
  119. switch (direction) {
  120. default:
  121. break;
  122. case PrefReg:
  123. BiasP += freq;
  124. break;
  125. case PrefSpill:
  126. BiasN += freq;
  127. break;
  128. case MustSpill:
  129. BiasN = BlockFrequency::getMaxFrequency();
  130. break;
  131. }
  132. }
  133. /// update - Recompute Value from Bias and Links. Return true when node
  134. /// preference changes.
  135. bool update(const Node nodes[], const BlockFrequency &Threshold) {
  136. // Compute the weighted sum of inputs.
  137. BlockFrequency SumN = BiasN;
  138. BlockFrequency SumP = BiasP;
  139. for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I) {
  140. if (nodes[I->second].Value == -1)
  141. SumN += I->first;
  142. else if (nodes[I->second].Value == 1)
  143. SumP += I->first;
  144. }
  145. // Each weighted sum is going to be less than the total frequency of the
  146. // bundle. Ideally, we should simply set Value = sign(SumP - SumN), but we
  147. // will add a dead zone around 0 for two reasons:
  148. //
  149. // 1. It avoids arbitrary bias when all links are 0 as is possible during
  150. // initial iterations.
  151. // 2. It helps tame rounding errors when the links nominally sum to 0.
  152. //
  153. bool Before = preferReg();
  154. if (SumN >= SumP + Threshold)
  155. Value = -1;
  156. else if (SumP >= SumN + Threshold)
  157. Value = 1;
  158. else
  159. Value = 0;
  160. return Before != preferReg();
  161. }
  162. void getDissentingNeighbors(SparseSet<unsigned> &List,
  163. const Node nodes[]) const {
  164. for (const auto &Elt : Links) {
  165. unsigned n = Elt.second;
  166. // Neighbors that already have the same value are not going to
  167. // change because of this node changing.
  168. if (Value != nodes[n].Value)
  169. List.insert(n);
  170. }
  171. }
  172. };
  173. bool SpillPlacement::runOnMachineFunction(MachineFunction &mf) {
  174. MF = &mf;
  175. bundles = &getAnalysis<EdgeBundles>();
  176. loops = &getAnalysis<MachineLoopInfo>();
  177. assert(!nodes && "Leaking node array");
  178. nodes = new Node[bundles->getNumBundles()];
  179. TodoList.clear();
  180. TodoList.setUniverse(bundles->getNumBundles());
  181. // Compute total ingoing and outgoing block frequencies for all bundles.
  182. BlockFrequencies.resize(mf.getNumBlockIDs());
  183. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  184. setThreshold(MBFI->getEntryFreq());
  185. for (auto &I : mf) {
  186. unsigned Num = I.getNumber();
  187. BlockFrequencies[Num] = MBFI->getBlockFreq(&I);
  188. }
  189. // We never change the function.
  190. return false;
  191. }
  192. void SpillPlacement::releaseMemory() {
  193. delete[] nodes;
  194. nodes = nullptr;
  195. TodoList.clear();
  196. }
  197. /// activate - mark node n as active if it wasn't already.
  198. void SpillPlacement::activate(unsigned n) {
  199. TodoList.insert(n);
  200. if (ActiveNodes->test(n))
  201. return;
  202. ActiveNodes->set(n);
  203. nodes[n].clear(Threshold);
  204. // Very large bundles usually come from big switches, indirect branches,
  205. // landing pads, or loops with many 'continue' statements. It is difficult to
  206. // allocate registers when so many different blocks are involved.
  207. //
  208. // Give a small negative bias to large bundles such that a substantial
  209. // fraction of the connected blocks need to be interested before we consider
  210. // expanding the region through the bundle. This helps compile time by
  211. // limiting the number of blocks visited and the number of links in the
  212. // Hopfield network.
  213. if (bundles->getBlocks(n).size() > 100) {
  214. nodes[n].BiasP = 0;
  215. nodes[n].BiasN = (MBFI->getEntryFreq() / 16);
  216. }
  217. }
  218. /// Set the threshold for a given entry frequency.
  219. ///
  220. /// Set the threshold relative to \c Entry. Since the threshold is used as a
  221. /// bound on the open interval (-Threshold;Threshold), 1 is the minimum
  222. /// threshold.
  223. void SpillPlacement::setThreshold(const BlockFrequency &Entry) {
  224. // Apparently 2 is a good threshold when Entry==2^14, but we need to scale
  225. // it. Divide by 2^13, rounding as appropriate.
  226. uint64_t Freq = Entry.getFrequency();
  227. uint64_t Scaled = (Freq >> 13) + bool(Freq & (1 << 12));
  228. Threshold = std::max(UINT64_C(1), Scaled);
  229. }
  230. /// addConstraints - Compute node biases and weights from a set of constraints.
  231. /// Set a bit in NodeMask for each active node.
  232. void SpillPlacement::addConstraints(ArrayRef<BlockConstraint> LiveBlocks) {
  233. for (ArrayRef<BlockConstraint>::iterator I = LiveBlocks.begin(),
  234. E = LiveBlocks.end(); I != E; ++I) {
  235. BlockFrequency Freq = BlockFrequencies[I->Number];
  236. // Live-in to block?
  237. if (I->Entry != DontCare) {
  238. unsigned ib = bundles->getBundle(I->Number, false);
  239. activate(ib);
  240. nodes[ib].addBias(Freq, I->Entry);
  241. }
  242. // Live-out from block?
  243. if (I->Exit != DontCare) {
  244. unsigned ob = bundles->getBundle(I->Number, true);
  245. activate(ob);
  246. nodes[ob].addBias(Freq, I->Exit);
  247. }
  248. }
  249. }
  250. /// addPrefSpill - Same as addConstraints(PrefSpill)
  251. void SpillPlacement::addPrefSpill(ArrayRef<unsigned> Blocks, bool Strong) {
  252. for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
  253. I != E; ++I) {
  254. BlockFrequency Freq = BlockFrequencies[*I];
  255. if (Strong)
  256. Freq += Freq;
  257. unsigned ib = bundles->getBundle(*I, false);
  258. unsigned ob = bundles->getBundle(*I, true);
  259. activate(ib);
  260. activate(ob);
  261. nodes[ib].addBias(Freq, PrefSpill);
  262. nodes[ob].addBias(Freq, PrefSpill);
  263. }
  264. }
  265. void SpillPlacement::addLinks(ArrayRef<unsigned> Links) {
  266. for (ArrayRef<unsigned>::iterator I = Links.begin(), E = Links.end(); I != E;
  267. ++I) {
  268. unsigned Number = *I;
  269. unsigned ib = bundles->getBundle(Number, false);
  270. unsigned ob = bundles->getBundle(Number, true);
  271. // Ignore self-loops.
  272. if (ib == ob)
  273. continue;
  274. activate(ib);
  275. activate(ob);
  276. BlockFrequency Freq = BlockFrequencies[Number];
  277. nodes[ib].addLink(ob, Freq);
  278. nodes[ob].addLink(ib, Freq);
  279. }
  280. }
  281. bool SpillPlacement::scanActiveBundles() {
  282. RecentPositive.clear();
  283. for (unsigned n : ActiveNodes->set_bits()) {
  284. update(n);
  285. // A node that must spill, or a node without any links is not going to
  286. // change its value ever again, so exclude it from iterations.
  287. if (nodes[n].mustSpill())
  288. continue;
  289. if (nodes[n].preferReg())
  290. RecentPositive.push_back(n);
  291. }
  292. return !RecentPositive.empty();
  293. }
  294. bool SpillPlacement::update(unsigned n) {
  295. if (!nodes[n].update(nodes, Threshold))
  296. return false;
  297. nodes[n].getDissentingNeighbors(TodoList, nodes);
  298. return true;
  299. }
  300. /// iterate - Repeatedly update the Hopfield nodes until stability or the
  301. /// maximum number of iterations is reached.
  302. void SpillPlacement::iterate() {
  303. // We do not need to push those node in the todolist.
  304. // They are already been proceeded as part of the previous iteration.
  305. RecentPositive.clear();
  306. // Since the last iteration, the todolist have been augmented by calls
  307. // to addConstraints, addLinks, and co.
  308. // Update the network energy starting at this new frontier.
  309. // The call to ::update will add the nodes that changed into the todolist.
  310. unsigned Limit = bundles->getNumBundles() * 10;
  311. while(Limit-- > 0 && !TodoList.empty()) {
  312. unsigned n = TodoList.pop_back_val();
  313. if (!update(n))
  314. continue;
  315. if (nodes[n].preferReg())
  316. RecentPositive.push_back(n);
  317. }
  318. }
  319. void SpillPlacement::prepare(BitVector &RegBundles) {
  320. RecentPositive.clear();
  321. TodoList.clear();
  322. // Reuse RegBundles as our ActiveNodes vector.
  323. ActiveNodes = &RegBundles;
  324. ActiveNodes->clear();
  325. ActiveNodes->resize(bundles->getNumBundles());
  326. }
  327. bool
  328. SpillPlacement::finish() {
  329. assert(ActiveNodes && "Call prepare() first");
  330. // Write preferences back to ActiveNodes.
  331. bool Perfect = true;
  332. for (unsigned n : ActiveNodes->set_bits())
  333. if (!nodes[n].preferReg()) {
  334. ActiveNodes->reset(n);
  335. Perfect = false;
  336. }
  337. ActiveNodes = nullptr;
  338. return Perfect;
  339. }