BlockFrequencyInfoImpl.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. //===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===//
  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. // Loops should be simplified before this analysis.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
  13. #include "llvm/ADT/APInt.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/GraphTraits.h"
  16. #include "llvm/ADT/None.h"
  17. #include "llvm/ADT/SCCIterator.h"
  18. #include "llvm/Config/llvm-config.h"
  19. #include "llvm/IR/Function.h"
  20. #include "llvm/Support/BlockFrequency.h"
  21. #include "llvm/Support/BranchProbability.h"
  22. #include "llvm/Support/Compiler.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/ScaledNumber.h"
  25. #include "llvm/Support/MathExtras.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <algorithm>
  28. #include <cassert>
  29. #include <cstddef>
  30. #include <cstdint>
  31. #include <iterator>
  32. #include <list>
  33. #include <numeric>
  34. #include <utility>
  35. #include <vector>
  36. using namespace llvm;
  37. using namespace llvm::bfi_detail;
  38. #define DEBUG_TYPE "block-freq"
  39. namespace llvm {
  40. cl::opt<bool> CheckBFIUnknownBlockQueries(
  41. "check-bfi-unknown-block-queries",
  42. cl::init(false), cl::Hidden,
  43. cl::desc("Check if block frequency is queried for an unknown block "
  44. "for debugging missed BFI updates"));
  45. cl::opt<bool> UseIterativeBFIInference(
  46. "use-iterative-bfi-inference", cl::init(false), cl::Hidden, cl::ZeroOrMore,
  47. cl::desc("Apply an iterative post-processing to infer correct BFI counts"));
  48. cl::opt<unsigned> IterativeBFIMaxIterationsPerBlock(
  49. "iterative-bfi-max-iterations-per-block", cl::init(1000), cl::Hidden,
  50. cl::desc("Iterative inference: maximum number of update iterations "
  51. "per block"));
  52. cl::opt<double> IterativeBFIPrecision(
  53. "iterative-bfi-precision", cl::init(1e-12), cl::Hidden,
  54. cl::desc("Iterative inference: delta convergence precision; smaller values "
  55. "typically lead to better results at the cost of worsen runtime"));
  56. }
  57. ScaledNumber<uint64_t> BlockMass::toScaled() const {
  58. if (isFull())
  59. return ScaledNumber<uint64_t>(1, 0);
  60. return ScaledNumber<uint64_t>(getMass() + 1, -64);
  61. }
  62. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  63. LLVM_DUMP_METHOD void BlockMass::dump() const { print(dbgs()); }
  64. #endif
  65. static char getHexDigit(int N) {
  66. assert(N < 16);
  67. if (N < 10)
  68. return '0' + N;
  69. return 'a' + N - 10;
  70. }
  71. raw_ostream &BlockMass::print(raw_ostream &OS) const {
  72. for (int Digits = 0; Digits < 16; ++Digits)
  73. OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
  74. return OS;
  75. }
  76. namespace {
  77. using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
  78. using Distribution = BlockFrequencyInfoImplBase::Distribution;
  79. using WeightList = BlockFrequencyInfoImplBase::Distribution::WeightList;
  80. using Scaled64 = BlockFrequencyInfoImplBase::Scaled64;
  81. using LoopData = BlockFrequencyInfoImplBase::LoopData;
  82. using Weight = BlockFrequencyInfoImplBase::Weight;
  83. using FrequencyData = BlockFrequencyInfoImplBase::FrequencyData;
  84. /// Dithering mass distributer.
  85. ///
  86. /// This class splits up a single mass into portions by weight, dithering to
  87. /// spread out error. No mass is lost. The dithering precision depends on the
  88. /// precision of the product of \a BlockMass and \a BranchProbability.
  89. ///
  90. /// The distribution algorithm follows.
  91. ///
  92. /// 1. Initialize by saving the sum of the weights in \a RemWeight and the
  93. /// mass to distribute in \a RemMass.
  94. ///
  95. /// 2. For each portion:
  96. ///
  97. /// 1. Construct a branch probability, P, as the portion's weight divided
  98. /// by the current value of \a RemWeight.
  99. /// 2. Calculate the portion's mass as \a RemMass times P.
  100. /// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
  101. /// the current portion's weight and mass.
  102. struct DitheringDistributer {
  103. uint32_t RemWeight;
  104. BlockMass RemMass;
  105. DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
  106. BlockMass takeMass(uint32_t Weight);
  107. };
  108. } // end anonymous namespace
  109. DitheringDistributer::DitheringDistributer(Distribution &Dist,
  110. const BlockMass &Mass) {
  111. Dist.normalize();
  112. RemWeight = Dist.Total;
  113. RemMass = Mass;
  114. }
  115. BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
  116. assert(Weight && "invalid weight");
  117. assert(Weight <= RemWeight);
  118. BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
  119. // Decrement totals (dither).
  120. RemWeight -= Weight;
  121. RemMass -= Mass;
  122. return Mass;
  123. }
  124. void Distribution::add(const BlockNode &Node, uint64_t Amount,
  125. Weight::DistType Type) {
  126. assert(Amount && "invalid weight of 0");
  127. uint64_t NewTotal = Total + Amount;
  128. // Check for overflow. It should be impossible to overflow twice.
  129. bool IsOverflow = NewTotal < Total;
  130. assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
  131. DidOverflow |= IsOverflow;
  132. // Update the total.
  133. Total = NewTotal;
  134. // Save the weight.
  135. Weights.push_back(Weight(Type, Node, Amount));
  136. }
  137. static void combineWeight(Weight &W, const Weight &OtherW) {
  138. assert(OtherW.TargetNode.isValid());
  139. if (!W.Amount) {
  140. W = OtherW;
  141. return;
  142. }
  143. assert(W.Type == OtherW.Type);
  144. assert(W.TargetNode == OtherW.TargetNode);
  145. assert(OtherW.Amount && "Expected non-zero weight");
  146. if (W.Amount > W.Amount + OtherW.Amount)
  147. // Saturate on overflow.
  148. W.Amount = UINT64_MAX;
  149. else
  150. W.Amount += OtherW.Amount;
  151. }
  152. static void combineWeightsBySorting(WeightList &Weights) {
  153. // Sort so edges to the same node are adjacent.
  154. llvm::sort(Weights, [](const Weight &L, const Weight &R) {
  155. return L.TargetNode < R.TargetNode;
  156. });
  157. // Combine adjacent edges.
  158. WeightList::iterator O = Weights.begin();
  159. for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
  160. ++O, (I = L)) {
  161. *O = *I;
  162. // Find the adjacent weights to the same node.
  163. for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
  164. combineWeight(*O, *L);
  165. }
  166. // Erase extra entries.
  167. Weights.erase(O, Weights.end());
  168. }
  169. static void combineWeightsByHashing(WeightList &Weights) {
  170. // Collect weights into a DenseMap.
  171. using HashTable = DenseMap<BlockNode::IndexType, Weight>;
  172. HashTable Combined(NextPowerOf2(2 * Weights.size()));
  173. for (const Weight &W : Weights)
  174. combineWeight(Combined[W.TargetNode.Index], W);
  175. // Check whether anything changed.
  176. if (Weights.size() == Combined.size())
  177. return;
  178. // Fill in the new weights.
  179. Weights.clear();
  180. Weights.reserve(Combined.size());
  181. for (const auto &I : Combined)
  182. Weights.push_back(I.second);
  183. }
  184. static void combineWeights(WeightList &Weights) {
  185. // Use a hash table for many successors to keep this linear.
  186. if (Weights.size() > 128) {
  187. combineWeightsByHashing(Weights);
  188. return;
  189. }
  190. combineWeightsBySorting(Weights);
  191. }
  192. static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
  193. assert(Shift >= 0);
  194. assert(Shift < 64);
  195. if (!Shift)
  196. return N;
  197. return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
  198. }
  199. void Distribution::normalize() {
  200. // Early exit for termination nodes.
  201. if (Weights.empty())
  202. return;
  203. // Only bother if there are multiple successors.
  204. if (Weights.size() > 1)
  205. combineWeights(Weights);
  206. // Early exit when combined into a single successor.
  207. if (Weights.size() == 1) {
  208. Total = 1;
  209. Weights.front().Amount = 1;
  210. return;
  211. }
  212. // Determine how much to shift right so that the total fits into 32-bits.
  213. //
  214. // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
  215. // for each weight can cause a 32-bit overflow.
  216. int Shift = 0;
  217. if (DidOverflow)
  218. Shift = 33;
  219. else if (Total > UINT32_MAX)
  220. Shift = 33 - countLeadingZeros(Total);
  221. // Early exit if nothing needs to be scaled.
  222. if (!Shift) {
  223. // If we didn't overflow then combineWeights() shouldn't have changed the
  224. // sum of the weights, but let's double-check.
  225. assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
  226. [](uint64_t Sum, const Weight &W) {
  227. return Sum + W.Amount;
  228. }) &&
  229. "Expected total to be correct");
  230. return;
  231. }
  232. // Recompute the total through accumulation (rather than shifting it) so that
  233. // it's accurate after shifting and any changes combineWeights() made above.
  234. Total = 0;
  235. // Sum the weights to each node and shift right if necessary.
  236. for (Weight &W : Weights) {
  237. // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
  238. // can round here without concern about overflow.
  239. assert(W.TargetNode.isValid());
  240. W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
  241. assert(W.Amount <= UINT32_MAX);
  242. // Update the total.
  243. Total += W.Amount;
  244. }
  245. assert(Total <= UINT32_MAX);
  246. }
  247. void BlockFrequencyInfoImplBase::clear() {
  248. // Swap with a default-constructed std::vector, since std::vector<>::clear()
  249. // does not actually clear heap storage.
  250. std::vector<FrequencyData>().swap(Freqs);
  251. IsIrrLoopHeader.clear();
  252. std::vector<WorkingData>().swap(Working);
  253. Loops.clear();
  254. }
  255. /// Clear all memory not needed downstream.
  256. ///
  257. /// Releases all memory not used downstream. In particular, saves Freqs.
  258. static void cleanup(BlockFrequencyInfoImplBase &BFI) {
  259. std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
  260. SparseBitVector<> SavedIsIrrLoopHeader(std::move(BFI.IsIrrLoopHeader));
  261. BFI.clear();
  262. BFI.Freqs = std::move(SavedFreqs);
  263. BFI.IsIrrLoopHeader = std::move(SavedIsIrrLoopHeader);
  264. }
  265. bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
  266. const LoopData *OuterLoop,
  267. const BlockNode &Pred,
  268. const BlockNode &Succ,
  269. uint64_t Weight) {
  270. if (!Weight)
  271. Weight = 1;
  272. auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
  273. return OuterLoop && OuterLoop->isHeader(Node);
  274. };
  275. BlockNode Resolved = Working[Succ.Index].getResolvedNode();
  276. #ifndef NDEBUG
  277. auto debugSuccessor = [&](const char *Type) {
  278. dbgs() << " =>"
  279. << " [" << Type << "] weight = " << Weight;
  280. if (!isLoopHeader(Resolved))
  281. dbgs() << ", succ = " << getBlockName(Succ);
  282. if (Resolved != Succ)
  283. dbgs() << ", resolved = " << getBlockName(Resolved);
  284. dbgs() << "\n";
  285. };
  286. (void)debugSuccessor;
  287. #endif
  288. if (isLoopHeader(Resolved)) {
  289. LLVM_DEBUG(debugSuccessor("backedge"));
  290. Dist.addBackedge(Resolved, Weight);
  291. return true;
  292. }
  293. if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
  294. LLVM_DEBUG(debugSuccessor(" exit "));
  295. Dist.addExit(Resolved, Weight);
  296. return true;
  297. }
  298. if (Resolved < Pred) {
  299. if (!isLoopHeader(Pred)) {
  300. // If OuterLoop is an irreducible loop, we can't actually handle this.
  301. assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
  302. "unhandled irreducible control flow");
  303. // Irreducible backedge. Abort.
  304. LLVM_DEBUG(debugSuccessor("abort!!!"));
  305. return false;
  306. }
  307. // If "Pred" is a loop header, then this isn't really a backedge; rather,
  308. // OuterLoop must be irreducible. These false backedges can come only from
  309. // secondary loop headers.
  310. assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
  311. "unhandled irreducible control flow");
  312. }
  313. LLVM_DEBUG(debugSuccessor(" local "));
  314. Dist.addLocal(Resolved, Weight);
  315. return true;
  316. }
  317. bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
  318. const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
  319. // Copy the exit map into Dist.
  320. for (const auto &I : Loop.Exits)
  321. if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
  322. I.second.getMass()))
  323. // Irreducible backedge.
  324. return false;
  325. return true;
  326. }
  327. /// Compute the loop scale for a loop.
  328. void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
  329. // Compute loop scale.
  330. LLVM_DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
  331. // Infinite loops need special handling. If we give the back edge an infinite
  332. // mass, they may saturate all the other scales in the function down to 1,
  333. // making all the other region temperatures look exactly the same. Choose an
  334. // arbitrary scale to avoid these issues.
  335. //
  336. // FIXME: An alternate way would be to select a symbolic scale which is later
  337. // replaced to be the maximum of all computed scales plus 1. This would
  338. // appropriately describe the loop as having a large scale, without skewing
  339. // the final frequency computation.
  340. const Scaled64 InfiniteLoopScale(1, 12);
  341. // LoopScale == 1 / ExitMass
  342. // ExitMass == HeadMass - BackedgeMass
  343. BlockMass TotalBackedgeMass;
  344. for (auto &Mass : Loop.BackedgeMass)
  345. TotalBackedgeMass += Mass;
  346. BlockMass ExitMass = BlockMass::getFull() - TotalBackedgeMass;
  347. // Block scale stores the inverse of the scale. If this is an infinite loop,
  348. // its exit mass will be zero. In this case, use an arbitrary scale for the
  349. // loop scale.
  350. Loop.Scale =
  351. ExitMass.isEmpty() ? InfiniteLoopScale : ExitMass.toScaled().inverse();
  352. LLVM_DEBUG(dbgs() << " - exit-mass = " << ExitMass << " ("
  353. << BlockMass::getFull() << " - " << TotalBackedgeMass
  354. << ")\n"
  355. << " - scale = " << Loop.Scale << "\n");
  356. }
  357. /// Package up a loop.
  358. void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
  359. LLVM_DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
  360. // Clear the subloop exits to prevent quadratic memory usage.
  361. for (const BlockNode &M : Loop.Nodes) {
  362. if (auto *Loop = Working[M.Index].getPackagedLoop())
  363. Loop->Exits.clear();
  364. LLVM_DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
  365. }
  366. Loop.IsPackaged = true;
  367. }
  368. #ifndef NDEBUG
  369. static void debugAssign(const BlockFrequencyInfoImplBase &BFI,
  370. const DitheringDistributer &D, const BlockNode &T,
  371. const BlockMass &M, const char *Desc) {
  372. dbgs() << " => assign " << M << " (" << D.RemMass << ")";
  373. if (Desc)
  374. dbgs() << " [" << Desc << "]";
  375. if (T.isValid())
  376. dbgs() << " to " << BFI.getBlockName(T);
  377. dbgs() << "\n";
  378. }
  379. #endif
  380. void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
  381. LoopData *OuterLoop,
  382. Distribution &Dist) {
  383. BlockMass Mass = Working[Source.Index].getMass();
  384. LLVM_DEBUG(dbgs() << " => mass: " << Mass << "\n");
  385. // Distribute mass to successors as laid out in Dist.
  386. DitheringDistributer D(Dist, Mass);
  387. for (const Weight &W : Dist.Weights) {
  388. // Check for a local edge (non-backedge and non-exit).
  389. BlockMass Taken = D.takeMass(W.Amount);
  390. if (W.Type == Weight::Local) {
  391. Working[W.TargetNode.Index].getMass() += Taken;
  392. LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
  393. continue;
  394. }
  395. // Backedges and exits only make sense if we're processing a loop.
  396. assert(OuterLoop && "backedge or exit outside of loop");
  397. // Check for a backedge.
  398. if (W.Type == Weight::Backedge) {
  399. OuterLoop->BackedgeMass[OuterLoop->getHeaderIndex(W.TargetNode)] += Taken;
  400. LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "back"));
  401. continue;
  402. }
  403. // This must be an exit.
  404. assert(W.Type == Weight::Exit);
  405. OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
  406. LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "exit"));
  407. }
  408. }
  409. static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
  410. const Scaled64 &Min, const Scaled64 &Max) {
  411. // Scale the Factor to a size that creates integers. Ideally, integers would
  412. // be scaled so that Max == UINT64_MAX so that they can be best
  413. // differentiated. However, in the presence of large frequency values, small
  414. // frequencies are scaled down to 1, making it impossible to differentiate
  415. // small, unequal numbers. When the spread between Min and Max frequencies
  416. // fits well within MaxBits, we make the scale be at least 8.
  417. const unsigned MaxBits = 64;
  418. const unsigned SpreadBits = (Max / Min).lg();
  419. Scaled64 ScalingFactor;
  420. if (SpreadBits <= MaxBits - 3) {
  421. // If the values are small enough, make the scaling factor at least 8 to
  422. // allow distinguishing small values.
  423. ScalingFactor = Min.inverse();
  424. ScalingFactor <<= 3;
  425. } else {
  426. // If the values need more than MaxBits to be represented, saturate small
  427. // frequency values down to 1 by using a scaling factor that benefits large
  428. // frequency values.
  429. ScalingFactor = Scaled64(1, MaxBits) / Max;
  430. }
  431. // Translate the floats to integers.
  432. LLVM_DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
  433. << ", factor = " << ScalingFactor << "\n");
  434. for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
  435. Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
  436. BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
  437. LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
  438. << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
  439. << ", int = " << BFI.Freqs[Index].Integer << "\n");
  440. }
  441. }
  442. /// Unwrap a loop package.
  443. ///
  444. /// Visits all the members of a loop, adjusting their BlockData according to
  445. /// the loop's pseudo-node.
  446. static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
  447. LLVM_DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
  448. << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
  449. << "\n");
  450. Loop.Scale *= Loop.Mass.toScaled();
  451. Loop.IsPackaged = false;
  452. LLVM_DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
  453. // Propagate the head scale through the loop. Since members are visited in
  454. // RPO, the head scale will be updated by the loop scale first, and then the
  455. // final head scale will be used for updated the rest of the members.
  456. for (const BlockNode &N : Loop.Nodes) {
  457. const auto &Working = BFI.Working[N.Index];
  458. Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
  459. : BFI.Freqs[N.Index].Scaled;
  460. Scaled64 New = Loop.Scale * F;
  461. LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => "
  462. << New << "\n");
  463. F = New;
  464. }
  465. }
  466. void BlockFrequencyInfoImplBase::unwrapLoops() {
  467. // Set initial frequencies from loop-local masses.
  468. for (size_t Index = 0; Index < Working.size(); ++Index)
  469. Freqs[Index].Scaled = Working[Index].Mass.toScaled();
  470. for (LoopData &Loop : Loops)
  471. unwrapLoop(*this, Loop);
  472. }
  473. void BlockFrequencyInfoImplBase::finalizeMetrics() {
  474. // Unwrap loop packages in reverse post-order, tracking min and max
  475. // frequencies.
  476. auto Min = Scaled64::getLargest();
  477. auto Max = Scaled64::getZero();
  478. for (size_t Index = 0; Index < Working.size(); ++Index) {
  479. // Update min/max scale.
  480. Min = std::min(Min, Freqs[Index].Scaled);
  481. Max = std::max(Max, Freqs[Index].Scaled);
  482. }
  483. // Convert to integers.
  484. convertFloatingToInteger(*this, Min, Max);
  485. // Clean up data structures.
  486. cleanup(*this);
  487. // Print out the final stats.
  488. LLVM_DEBUG(dump());
  489. }
  490. BlockFrequency
  491. BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
  492. if (!Node.isValid()) {
  493. #ifndef NDEBUG
  494. if (CheckBFIUnknownBlockQueries) {
  495. SmallString<256> Msg;
  496. raw_svector_ostream OS(Msg);
  497. OS << "*** Detected BFI query for unknown block " << getBlockName(Node);
  498. report_fatal_error(OS.str());
  499. }
  500. #endif
  501. return 0;
  502. }
  503. return Freqs[Node.Index].Integer;
  504. }
  505. Optional<uint64_t>
  506. BlockFrequencyInfoImplBase::getBlockProfileCount(const Function &F,
  507. const BlockNode &Node,
  508. bool AllowSynthetic) const {
  509. return getProfileCountFromFreq(F, getBlockFreq(Node).getFrequency(),
  510. AllowSynthetic);
  511. }
  512. Optional<uint64_t>
  513. BlockFrequencyInfoImplBase::getProfileCountFromFreq(const Function &F,
  514. uint64_t Freq,
  515. bool AllowSynthetic) const {
  516. auto EntryCount = F.getEntryCount(AllowSynthetic);
  517. if (!EntryCount)
  518. return None;
  519. // Use 128 bit APInt to do the arithmetic to avoid overflow.
  520. APInt BlockCount(128, EntryCount->getCount());
  521. APInt BlockFreq(128, Freq);
  522. APInt EntryFreq(128, getEntryFreq());
  523. BlockCount *= BlockFreq;
  524. // Rounded division of BlockCount by EntryFreq. Since EntryFreq is unsigned
  525. // lshr by 1 gives EntryFreq/2.
  526. BlockCount = (BlockCount + EntryFreq.lshr(1)).udiv(EntryFreq);
  527. return BlockCount.getLimitedValue();
  528. }
  529. bool
  530. BlockFrequencyInfoImplBase::isIrrLoopHeader(const BlockNode &Node) {
  531. if (!Node.isValid())
  532. return false;
  533. return IsIrrLoopHeader.test(Node.Index);
  534. }
  535. Scaled64
  536. BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
  537. if (!Node.isValid())
  538. return Scaled64::getZero();
  539. return Freqs[Node.Index].Scaled;
  540. }
  541. void BlockFrequencyInfoImplBase::setBlockFreq(const BlockNode &Node,
  542. uint64_t Freq) {
  543. assert(Node.isValid() && "Expected valid node");
  544. assert(Node.Index < Freqs.size() && "Expected legal index");
  545. Freqs[Node.Index].Integer = Freq;
  546. }
  547. std::string
  548. BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
  549. return {};
  550. }
  551. std::string
  552. BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
  553. return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
  554. }
  555. raw_ostream &
  556. BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
  557. const BlockNode &Node) const {
  558. return OS << getFloatingBlockFreq(Node);
  559. }
  560. raw_ostream &
  561. BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
  562. const BlockFrequency &Freq) const {
  563. Scaled64 Block(Freq.getFrequency(), 0);
  564. Scaled64 Entry(getEntryFreq(), 0);
  565. return OS << Block / Entry;
  566. }
  567. void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
  568. Start = OuterLoop.getHeader();
  569. Nodes.reserve(OuterLoop.Nodes.size());
  570. for (auto N : OuterLoop.Nodes)
  571. addNode(N);
  572. indexNodes();
  573. }
  574. void IrreducibleGraph::addNodesInFunction() {
  575. Start = 0;
  576. for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
  577. if (!BFI.Working[Index].isPackaged())
  578. addNode(Index);
  579. indexNodes();
  580. }
  581. void IrreducibleGraph::indexNodes() {
  582. for (auto &I : Nodes)
  583. Lookup[I.Node.Index] = &I;
  584. }
  585. void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
  586. const BFIBase::LoopData *OuterLoop) {
  587. if (OuterLoop && OuterLoop->isHeader(Succ))
  588. return;
  589. auto L = Lookup.find(Succ.Index);
  590. if (L == Lookup.end())
  591. return;
  592. IrrNode &SuccIrr = *L->second;
  593. Irr.Edges.push_back(&SuccIrr);
  594. SuccIrr.Edges.push_front(&Irr);
  595. ++SuccIrr.NumIn;
  596. }
  597. namespace llvm {
  598. template <> struct GraphTraits<IrreducibleGraph> {
  599. using GraphT = bfi_detail::IrreducibleGraph;
  600. using NodeRef = const GraphT::IrrNode *;
  601. using ChildIteratorType = GraphT::IrrNode::iterator;
  602. static NodeRef getEntryNode(const GraphT &G) { return G.StartIrr; }
  603. static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
  604. static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
  605. };
  606. } // end namespace llvm
  607. /// Find extra irreducible headers.
  608. ///
  609. /// Find entry blocks and other blocks with backedges, which exist when \c G
  610. /// contains irreducible sub-SCCs.
  611. static void findIrreducibleHeaders(
  612. const BlockFrequencyInfoImplBase &BFI,
  613. const IrreducibleGraph &G,
  614. const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
  615. LoopData::NodeList &Headers, LoopData::NodeList &Others) {
  616. // Map from nodes in the SCC to whether it's an entry block.
  617. SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
  618. // InSCC also acts the set of nodes in the graph. Seed it.
  619. for (const auto *I : SCC)
  620. InSCC[I] = false;
  621. for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
  622. auto &Irr = *I->first;
  623. for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
  624. if (InSCC.count(P))
  625. continue;
  626. // This is an entry block.
  627. I->second = true;
  628. Headers.push_back(Irr.Node);
  629. LLVM_DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node)
  630. << "\n");
  631. break;
  632. }
  633. }
  634. assert(Headers.size() >= 2 &&
  635. "Expected irreducible CFG; -loop-info is likely invalid");
  636. if (Headers.size() == InSCC.size()) {
  637. // Every block is a header.
  638. llvm::sort(Headers);
  639. return;
  640. }
  641. // Look for extra headers from irreducible sub-SCCs.
  642. for (const auto &I : InSCC) {
  643. // Entry blocks are already headers.
  644. if (I.second)
  645. continue;
  646. auto &Irr = *I.first;
  647. for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
  648. // Skip forward edges.
  649. if (P->Node < Irr.Node)
  650. continue;
  651. // Skip predecessors from entry blocks. These can have inverted
  652. // ordering.
  653. if (InSCC.lookup(P))
  654. continue;
  655. // Store the extra header.
  656. Headers.push_back(Irr.Node);
  657. LLVM_DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node)
  658. << "\n");
  659. break;
  660. }
  661. if (Headers.back() == Irr.Node)
  662. // Added this as a header.
  663. continue;
  664. // This is not a header.
  665. Others.push_back(Irr.Node);
  666. LLVM_DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
  667. }
  668. llvm::sort(Headers);
  669. llvm::sort(Others);
  670. }
  671. static void createIrreducibleLoop(
  672. BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
  673. LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
  674. const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
  675. // Translate the SCC into RPO.
  676. LLVM_DEBUG(dbgs() << " - found-scc\n");
  677. LoopData::NodeList Headers;
  678. LoopData::NodeList Others;
  679. findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
  680. auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
  681. Headers.end(), Others.begin(), Others.end());
  682. // Update loop hierarchy.
  683. for (const auto &N : Loop->Nodes)
  684. if (BFI.Working[N.Index].isLoopHeader())
  685. BFI.Working[N.Index].Loop->Parent = &*Loop;
  686. else
  687. BFI.Working[N.Index].Loop = &*Loop;
  688. }
  689. iterator_range<std::list<LoopData>::iterator>
  690. BlockFrequencyInfoImplBase::analyzeIrreducible(
  691. const IrreducibleGraph &G, LoopData *OuterLoop,
  692. std::list<LoopData>::iterator Insert) {
  693. assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
  694. auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
  695. for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
  696. if (I->size() < 2)
  697. continue;
  698. // Translate the SCC into RPO.
  699. createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
  700. }
  701. if (OuterLoop)
  702. return make_range(std::next(Prev), Insert);
  703. return make_range(Loops.begin(), Insert);
  704. }
  705. void
  706. BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
  707. OuterLoop.Exits.clear();
  708. for (auto &Mass : OuterLoop.BackedgeMass)
  709. Mass = BlockMass::getEmpty();
  710. auto O = OuterLoop.Nodes.begin() + 1;
  711. for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
  712. if (!Working[I->Index].isPackaged())
  713. *O++ = *I;
  714. OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());
  715. }
  716. void BlockFrequencyInfoImplBase::adjustLoopHeaderMass(LoopData &Loop) {
  717. assert(Loop.isIrreducible() && "this only makes sense on irreducible loops");
  718. // Since the loop has more than one header block, the mass flowing back into
  719. // each header will be different. Adjust the mass in each header loop to
  720. // reflect the masses flowing through back edges.
  721. //
  722. // To do this, we distribute the initial mass using the backedge masses
  723. // as weights for the distribution.
  724. BlockMass LoopMass = BlockMass::getFull();
  725. Distribution Dist;
  726. LLVM_DEBUG(dbgs() << "adjust-loop-header-mass:\n");
  727. for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
  728. auto &HeaderNode = Loop.Nodes[H];
  729. auto &BackedgeMass = Loop.BackedgeMass[Loop.getHeaderIndex(HeaderNode)];
  730. LLVM_DEBUG(dbgs() << " - Add back edge mass for node "
  731. << getBlockName(HeaderNode) << ": " << BackedgeMass
  732. << "\n");
  733. if (BackedgeMass.getMass() > 0)
  734. Dist.addLocal(HeaderNode, BackedgeMass.getMass());
  735. else
  736. LLVM_DEBUG(dbgs() << " Nothing added. Back edge mass is zero\n");
  737. }
  738. DitheringDistributer D(Dist, LoopMass);
  739. LLVM_DEBUG(dbgs() << " Distribute loop mass " << LoopMass
  740. << " to headers using above weights\n");
  741. for (const Weight &W : Dist.Weights) {
  742. BlockMass Taken = D.takeMass(W.Amount);
  743. assert(W.Type == Weight::Local && "all weights should be local");
  744. Working[W.TargetNode.Index].getMass() = Taken;
  745. LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
  746. }
  747. }
  748. void BlockFrequencyInfoImplBase::distributeIrrLoopHeaderMass(Distribution &Dist) {
  749. BlockMass LoopMass = BlockMass::getFull();
  750. DitheringDistributer D(Dist, LoopMass);
  751. for (const Weight &W : Dist.Weights) {
  752. BlockMass Taken = D.takeMass(W.Amount);
  753. assert(W.Type == Weight::Local && "all weights should be local");
  754. Working[W.TargetNode.Index].getMass() = Taken;
  755. LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
  756. }
  757. }