BlockFrequencyInfoImpl.cpp 26 KB

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