blob: de183bbde173d053b65e99bbc210f92e3c6ffc6d [file] [log] [blame]
Duncan P. N. Exon Smith689a5072014-04-11 23:20:58 +00001//===- BlockFrequencyInfo.cpp - Block Frequency Analysis ------------------===//
Jakub Staszak668c6fa2011-06-23 21:56:59 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Jakub Staszak668c6fa2011-06-23 21:56:59 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Loops should be simplified before this analysis.
10//
11//===----------------------------------------------------------------------===//
12
Jakub Staszak875ebd52011-07-25 19:25:40 +000013#include "llvm/Analysis/BlockFrequencyInfo.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000014#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/None.h"
16#include "llvm/ADT/iterator.h"
Duncan P. N. Exon Smith689a5072014-04-11 23:20:58 +000017#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/Analysis/BranchProbabilityInfo.h"
Jakub Staszak668c6fa2011-06-23 21:56:59 +000019#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000020#include "llvm/IR/CFG.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000021#include "llvm/IR/Function.h"
22#include "llvm/IR/PassManager.h"
23#include "llvm/Pass.h"
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000024#include "llvm/Support/CommandLine.h"
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000025#include "llvm/Support/GraphWriter.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000026#include "llvm/Support/raw_ostream.h"
27#include <algorithm>
28#include <cassert>
29#include <string>
Jakub Staszak668c6fa2011-06-23 21:56:59 +000030
31using namespace llvm;
32
Chandler Carruthf1221bd2014-04-22 02:48:03 +000033#define DEBUG_TYPE "block-freq"
34
Xinliang David Li8dd5ce92016-06-28 04:07:03 +000035static cl::opt<GVDAGType> ViewBlockFreqPropagationDAG(
36 "view-block-freq-propagation-dags", cl::Hidden,
37 cl::desc("Pop up a window to show a dag displaying how block "
38 "frequencies propagation through the CFG."),
39 cl::values(clEnumValN(GVDT_None, "none", "do not display graphs."),
40 clEnumValN(GVDT_Fraction, "fraction",
41 "display a graph using the "
42 "fractional block frequency representation."),
43 clEnumValN(GVDT_Integer, "integer",
44 "display a graph using the raw "
45 "integer fractional block frequency representation."),
46 clEnumValN(GVDT_Count, "count", "display a graph using the real "
Mehdi Amini732afdd2016-10-08 19:41:06 +000047 "profile count if available.")));
Xinliang David Li8dd5ce92016-06-28 04:07:03 +000048
Xinliang David Li3e176c72016-06-28 06:58:21 +000049cl::opt<std::string>
50 ViewBlockFreqFuncName("view-bfi-func-name", cl::Hidden,
51 cl::desc("The option to specify "
52 "the name of the function "
53 "whose CFG will be displayed."));
54
55cl::opt<unsigned>
56 ViewHotFreqPercent("view-hot-freq-percent", cl::init(10), cl::Hidden,
57 cl::desc("An integer in percent used to specify "
58 "the hot blocks/edges to be displayed "
59 "in red: a block or edge whose frequency "
60 "is no less than the max frequency of the "
61 "function multiplied by this percent."));
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000062
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +000063// Command line option to turn on CFG dot or text dump after profile annotation.
64cl::opt<PGOViewCountsType> PGOViewCounts(
65 "pgo-view-counts", cl::Hidden,
66 cl::desc("A boolean option to show CFG dag or text with "
67 "block profile counts and branch probabilities "
68 "right after PGO profile annotation step. The "
69 "profile counts are computed using branch "
70 "probabilities from the runtime profile data and "
71 "block frequency propagation algorithm. To view "
72 "the raw counts from the profile, use option "
73 "-pgo-view-raw-counts instead. To limit graph "
74 "display to only one function, use filtering option "
75 "-view-bfi-func-name."),
76 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
77 clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
78 clEnumValN(PGOVCT_Text, "text", "show in text.")));
Xinliang David Licb253ce2017-01-23 18:58:24 +000079
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +000080static cl::opt<bool> PrintBlockFreq(
81 "print-bfi", cl::init(false), cl::Hidden,
82 cl::desc("Print the block frequency info."));
83
84cl::opt<std::string> PrintBlockFreqFuncName(
85 "print-bfi-func-name", cl::Hidden,
86 cl::desc("The option to specify the name of the function "
87 "whose block frequency info is printed."));
88
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000089namespace llvm {
90
Xinliang David Licb253ce2017-01-23 18:58:24 +000091static GVDAGType getGVDT() {
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +000092 if (PGOViewCounts == PGOVCT_Graph)
Xinliang David Licb253ce2017-01-23 18:58:24 +000093 return GVDT_Count;
94 return ViewBlockFreqPropagationDAG;
95}
96
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000097template <>
98struct GraphTraits<BlockFrequencyInfo *> {
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000099 using NodeRef = const BasicBlock *;
100 using ChildIteratorType = succ_const_iterator;
101 using nodes_iterator = pointer_iterator<Function::const_iterator>;
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000102
Tim Shen48f814e2016-08-31 16:48:13 +0000103 static NodeRef getEntryNode(const BlockFrequencyInfo *G) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000104 return &G->getFunction()->front();
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000105 }
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000106
Tim Shenf2187ed2016-08-22 21:09:30 +0000107 static ChildIteratorType child_begin(const NodeRef N) {
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000108 return succ_begin(N);
109 }
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000110
Tim Shenf2187ed2016-08-22 21:09:30 +0000111 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000112
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000113 static nodes_iterator nodes_begin(const BlockFrequencyInfo *G) {
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000114 return nodes_iterator(G->getFunction()->begin());
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000115 }
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000116
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000117 static nodes_iterator nodes_end(const BlockFrequencyInfo *G) {
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000118 return nodes_iterator(G->getFunction()->end());
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000119 }
120};
121
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000122using BFIDOTGTraitsBase =
123 BFIDOTGraphTraitsBase<BlockFrequencyInfo, BranchProbabilityInfo>;
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000124
Xinliang David Li55415f22016-06-28 03:41:29 +0000125template <>
126struct DOTGraphTraits<BlockFrequencyInfo *> : public BFIDOTGTraitsBase {
127 explicit DOTGraphTraits(bool isSimple = false)
128 : BFIDOTGTraitsBase(isSimple) {}
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000129
130 std::string getNodeLabel(const BasicBlock *Node,
131 const BlockFrequencyInfo *Graph) {
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000132
Xinliang David Licb253ce2017-01-23 18:58:24 +0000133 return BFIDOTGTraitsBase::getNodeLabel(Node, Graph, getGVDT());
Xinliang David Li55415f22016-06-28 03:41:29 +0000134 }
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000135
Xinliang David Li3e176c72016-06-28 06:58:21 +0000136 std::string getNodeAttributes(const BasicBlock *Node,
137 const BlockFrequencyInfo *Graph) {
138 return BFIDOTGTraitsBase::getNodeAttributes(Node, Graph,
139 ViewHotFreqPercent);
140 }
141
Xinliang David Li55415f22016-06-28 03:41:29 +0000142 std::string getEdgeAttributes(const BasicBlock *Node, EdgeIter EI,
143 const BlockFrequencyInfo *BFI) {
Xinliang David Li3e176c72016-06-28 06:58:21 +0000144 return BFIDOTGTraitsBase::getEdgeAttributes(Node, EI, BFI, BFI->getBPI(),
145 ViewHotFreqPercent);
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000146 }
147};
148
149} // end namespace llvm
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000150
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000151BlockFrequencyInfo::BlockFrequencyInfo() = default;
Cong Hou9b4f6b22015-07-16 23:23:35 +0000152
153BlockFrequencyInfo::BlockFrequencyInfo(const Function &F,
154 const BranchProbabilityInfo &BPI,
155 const LoopInfo &LI) {
156 calculate(F, BPI, LI);
157}
158
Xinliang David Li28a93272016-05-05 21:13:27 +0000159BlockFrequencyInfo::BlockFrequencyInfo(BlockFrequencyInfo &&Arg)
160 : BFI(std::move(Arg.BFI)) {}
161
162BlockFrequencyInfo &BlockFrequencyInfo::operator=(BlockFrequencyInfo &&RHS) {
163 releaseMemory();
164 BFI = std::move(RHS.BFI);
165 return *this;
166}
167
Adam Nemetc2f791d2016-07-13 05:01:48 +0000168// Explicitly define the default constructor otherwise it would be implicitly
169// defined at the first ODR-use which is the BFI member in the
170// LazyBlockFrequencyInfo header. The dtor needs the BlockFrequencyInfoImpl
171// template instantiated which is not available in the header.
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000172BlockFrequencyInfo::~BlockFrequencyInfo() = default;
Adam Nemetc2f791d2016-07-13 05:01:48 +0000173
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000174bool BlockFrequencyInfo::invalidate(Function &F, const PreservedAnalyses &PA,
175 FunctionAnalysisManager::Invalidator &) {
176 // Check whether the analysis, all analyses on functions, or the function's
177 // CFG have been preserved.
178 auto PAC = PA.getChecker<BlockFrequencyAnalysis>();
179 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
180 PAC.preservedSet<CFGAnalyses>());
181}
182
Wei Mideee61e2015-07-14 23:40:50 +0000183void BlockFrequencyInfo::calculate(const Function &F,
184 const BranchProbabilityInfo &BPI,
185 const LoopInfo &LI) {
Duncan P. N. Exon Smith3dbe1052014-03-25 18:01:38 +0000186 if (!BFI)
187 BFI.reset(new ImplType);
Cong Hou5e67b662015-07-15 19:58:26 +0000188 BFI->calculate(F, BPI, LI);
Xinliang David Li8dd5ce92016-06-28 04:07:03 +0000189 if (ViewBlockFreqPropagationDAG != GVDT_None &&
190 (ViewBlockFreqFuncName.empty() ||
191 F.getName().equals(ViewBlockFreqFuncName))) {
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000192 view();
Xinliang David Li8dd5ce92016-06-28 04:07:03 +0000193 }
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +0000194 if (PrintBlockFreq &&
195 (PrintBlockFreqFuncName.empty() ||
196 F.getName().equals(PrintBlockFreqFuncName))) {
197 print(dbgs());
198 }
Chandler Carruth343fad42011-10-19 10:12:41 +0000199}
200
Jakub Staszak96f8c552011-12-20 20:03:10 +0000201BlockFrequency BlockFrequencyInfo::getBlockFreq(const BasicBlock *BB) const {
Duncan P. N. Exon Smith3dbe1052014-03-25 18:01:38 +0000202 return BFI ? BFI->getBlockFreq(BB) : 0;
Jakub Staszak668c6fa2011-06-23 21:56:59 +0000203}
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000204
Easwaran Raman12b79aa2016-03-23 18:18:26 +0000205Optional<uint64_t>
Xinliang David Li499c80b2019-04-24 19:51:16 +0000206BlockFrequencyInfo::getBlockProfileCount(const BasicBlock *BB,
207 bool AllowSynthetic) const {
Xinliang David Lib12b3532016-06-22 17:12:12 +0000208 if (!BFI)
Easwaran Raman12b79aa2016-03-23 18:18:26 +0000209 return None;
Xinliang David Lib12b3532016-06-22 17:12:12 +0000210
Xinliang David Li499c80b2019-04-24 19:51:16 +0000211 return BFI->getBlockProfileCount(*getFunction(), BB, AllowSynthetic);
Easwaran Raman12b79aa2016-03-23 18:18:26 +0000212}
213
Sean Silvaf8015752016-08-02 02:15:45 +0000214Optional<uint64_t>
215BlockFrequencyInfo::getProfileCountFromFreq(uint64_t Freq) const {
216 if (!BFI)
217 return None;
218 return BFI->getProfileCountFromFreq(*getFunction(), Freq);
219}
220
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000221bool BlockFrequencyInfo::isIrrLoopHeader(const BasicBlock *BB) {
222 assert(BFI && "Expected analysis to be available");
223 return BFI->isIrrLoopHeader(BB);
224}
225
Xinliang David Lib12b3532016-06-22 17:12:12 +0000226void BlockFrequencyInfo::setBlockFreq(const BasicBlock *BB, uint64_t Freq) {
Manman Ren72d44b12015-10-15 14:59:40 +0000227 assert(BFI && "Expected analysis to be available");
228 BFI->setBlockFreq(BB, Freq);
229}
230
Easwaran Raman6c8f5112017-01-19 18:53:16 +0000231void BlockFrequencyInfo::setBlockFreqAndScale(
232 const BasicBlock *ReferenceBB, uint64_t Freq,
233 SmallPtrSetImpl<BasicBlock *> &BlocksToScale) {
234 assert(BFI && "Expected analysis to be available");
235 // Use 128 bits APInt to avoid overflow.
236 APInt NewFreq(128, Freq);
237 APInt OldFreq(128, BFI->getBlockFreq(ReferenceBB).getFrequency());
238 APInt BBFreq(128, 0);
239 for (auto *BB : BlocksToScale) {
240 BBFreq = BFI->getBlockFreq(BB).getFrequency();
241 // Multiply first by NewFreq and then divide by OldFreq
242 // to minimize loss of precision.
243 BBFreq *= NewFreq;
244 // udiv is an expensive operation in the general case. If this ends up being
245 // a hot spot, one of the options proposed in
246 // https://reviews.llvm.org/D28535#650071 could be used to avoid this.
247 BBFreq = BBFreq.udiv(OldFreq);
248 BFI->setBlockFreq(BB, BBFreq.getLimitedValue());
249 }
250 BFI->setBlockFreq(ReferenceBB, Freq);
251}
252
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000253/// Pop up a ghostview window with the current block frequency propagation
254/// rendered using dot.
David Callahan3ef0f442019-01-09 19:12:38 +0000255void BlockFrequencyInfo::view(StringRef title) const {
256 ViewGraph(const_cast<BlockFrequencyInfo *>(this), title);
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000257}
258
259const Function *BlockFrequencyInfo::getFunction() const {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000260 return BFI ? BFI->getFunction() : nullptr;
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000261}
Michael Gottesmanfd5c4b22013-12-14 00:06:03 +0000262
Xinliang David Li55415f22016-06-28 03:41:29 +0000263const BranchProbabilityInfo *BlockFrequencyInfo::getBPI() const {
264 return BFI ? &BFI->getBPI() : nullptr;
265}
266
Michael Gottesmanfd5c4b22013-12-14 00:06:03 +0000267raw_ostream &BlockFrequencyInfo::
268printBlockFreq(raw_ostream &OS, const BlockFrequency Freq) const {
Duncan P. N. Exon Smith3dbe1052014-03-25 18:01:38 +0000269 return BFI ? BFI->printBlockFreq(OS, Freq) : OS;
Michael Gottesmanfd5c4b22013-12-14 00:06:03 +0000270}
271
272raw_ostream &
273BlockFrequencyInfo::printBlockFreq(raw_ostream &OS,
274 const BasicBlock *BB) const {
Duncan P. N. Exon Smith3dbe1052014-03-25 18:01:38 +0000275 return BFI ? BFI->printBlockFreq(OS, BB) : OS;
Michael Gottesmanfd5c4b22013-12-14 00:06:03 +0000276}
Yuchen Wu5947c8f2013-12-20 22:11:11 +0000277
278uint64_t BlockFrequencyInfo::getEntryFreq() const {
Duncan P. N. Exon Smith3dbe1052014-03-25 18:01:38 +0000279 return BFI ? BFI->getEntryFreq() : 0;
Yuchen Wu5947c8f2013-12-20 22:11:11 +0000280}
Wei Mideee61e2015-07-14 23:40:50 +0000281
282void BlockFrequencyInfo::releaseMemory() { BFI.reset(); }
283
284void BlockFrequencyInfo::print(raw_ostream &OS) const {
285 if (BFI)
286 BFI->print(OS);
287}
288
Wei Mideee61e2015-07-14 23:40:50 +0000289INITIALIZE_PASS_BEGIN(BlockFrequencyInfoWrapperPass, "block-freq",
290 "Block Frequency Analysis", true, true)
Cong Houab23bfb2015-07-15 22:48:29 +0000291INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Wei Mideee61e2015-07-14 23:40:50 +0000292INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
293INITIALIZE_PASS_END(BlockFrequencyInfoWrapperPass, "block-freq",
294 "Block Frequency Analysis", true, true)
295
296char BlockFrequencyInfoWrapperPass::ID = 0;
297
Wei Mideee61e2015-07-14 23:40:50 +0000298BlockFrequencyInfoWrapperPass::BlockFrequencyInfoWrapperPass()
299 : FunctionPass(ID) {
300 initializeBlockFrequencyInfoWrapperPassPass(*PassRegistry::getPassRegistry());
301}
302
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000303BlockFrequencyInfoWrapperPass::~BlockFrequencyInfoWrapperPass() = default;
Wei Mideee61e2015-07-14 23:40:50 +0000304
305void BlockFrequencyInfoWrapperPass::print(raw_ostream &OS,
306 const Module *) const {
307 BFI.print(OS);
308}
309
310void BlockFrequencyInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Cong Houab23bfb2015-07-15 22:48:29 +0000311 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Wei Mideee61e2015-07-14 23:40:50 +0000312 AU.addRequired<LoopInfoWrapperPass>();
313 AU.setPreservesAll();
314}
315
316void BlockFrequencyInfoWrapperPass::releaseMemory() { BFI.releaseMemory(); }
317
318bool BlockFrequencyInfoWrapperPass::runOnFunction(Function &F) {
Cong Houab23bfb2015-07-15 22:48:29 +0000319 BranchProbabilityInfo &BPI =
320 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Wei Mideee61e2015-07-14 23:40:50 +0000321 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
322 BFI.calculate(F, BPI, LI);
323 return false;
324}
Xinliang David Li28a93272016-05-05 21:13:27 +0000325
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000326AnalysisKey BlockFrequencyAnalysis::Key;
Xinliang David Li28a93272016-05-05 21:13:27 +0000327BlockFrequencyInfo BlockFrequencyAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000328 FunctionAnalysisManager &AM) {
Xinliang David Li28a93272016-05-05 21:13:27 +0000329 BlockFrequencyInfo BFI;
330 BFI.calculate(F, AM.getResult<BranchProbabilityAnalysis>(F),
331 AM.getResult<LoopAnalysis>(F));
332 return BFI;
333}
334
335PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +0000336BlockFrequencyPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li28a93272016-05-05 21:13:27 +0000337 OS << "Printing analysis results of BFI for function "
338 << "'" << F.getName() << "':"
339 << "\n";
340 AM.getResult<BlockFrequencyAnalysis>(F).print(OS);
341 return PreservedAnalyses::all();
342}