LLVM 24.0.0git
BlockFrequencyInfo.cpp
Go to the documentation of this file.
1//===- BlockFrequencyInfo.cpp - Block Frequency Analysis ------------------===//
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
14#include "AnalysisOptions.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/iterator.h"
20#include "llvm/IR/CFG.h"
21#include "llvm/IR/Function.h"
22#include "llvm/IR/PassManager.h"
24#include "llvm/Pass.h"
28#include <cassert>
29#include <optional>
30#include <string>
31
32using namespace llvm;
33
34#define DEBUG_TYPE "block-freq"
35
37 "view-block-freq-propagation-dags", cl::Hidden,
38 cl::desc("Pop up a window to show a dag displaying how block "
39 "frequencies propagation through the CFG."),
40 cl::values(clEnumValN(GVDT_None, "none", "do not display graphs."),
41 clEnumValN(GVDT_Fraction, "fraction",
42 "display a graph using the "
43 "fractional block frequency representation."),
44 clEnumValN(GVDT_Integer, "integer",
45 "display a graph using the raw "
46 "integer fractional block frequency representation."),
47 clEnumValN(GVDT_Count, "count", "display a graph using the real "
48 "profile count if available.")));
49
51 return getAnalysisOptions(C).view_bfi_func_name;
52}
54 return getAnalysisOptions(C).view_hot_freq_percent;
55}
60 return getAnalysisOptions(C).print_bfi_func_name;
61}
62
63namespace llvm {
64
70
71template <>
73 using NodeRef = const BasicBlock *;
76
78 return &G->getFunction()->front();
79 }
80
82 return succ_begin(N);
83 }
84
85 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
86
88 return nodes_iterator(G->getFunction()->begin());
89 }
90
92 return nodes_iterator(G->getFunction()->end());
93 }
94};
95
98
99template <>
101 explicit DOTGraphTraits(bool isSimple = false)
103
104 std::string getNodeLabel(const BasicBlock *Node,
105 const BlockFrequencyInfo *Graph) {
106
108 getGVDT(Node->getContext()));
109 }
110
112 const BlockFrequencyInfo *Graph) {
114 Node, Graph, getViewHotFreqPercent(Node->getContext()));
115 }
116
118 const BlockFrequencyInfo *BFI) {
120 Node, EI, BFI, BFI->getBPI(),
121 getViewHotFreqPercent(Node->getContext()));
122 }
123};
124
125} // end namespace llvm
126
128
130 const BranchProbabilityInfo &BPI,
131 const CycleInfo &CI) {
132 calculate(F, BPI, CI);
133}
134
137
140 BFI = std::move(RHS.BFI);
141 return *this;
142}
143
144// Explicitly define the default constructor otherwise it would be implicitly
145// defined at the first ODR-use which is the BFI member in the
146// LazyBlockFrequencyInfo header. The dtor needs the BlockFrequencyInfoImpl
147// template instantiated which is not available in the header.
149
151 FunctionAnalysisManager::Invalidator &) {
152 // Check whether the analysis, all analyses on functions, or the function's
153 // CFG have been preserved.
154 auto PAC = PA.getChecker<BlockFrequencyAnalysis>();
155 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
156 PAC.preservedSet<CFGAnalyses>());
157}
158
160 const BranchProbabilityInfo &BPI,
161 const CycleInfo &CI) {
162 if (!BFI)
163 BFI.reset(new ImplType);
164 BFI->calculate(F, BPI, CI);
165 const AnalysisOptions &Opts = getAnalysisOptions(F);
167 (Opts.view_bfi_func_name.empty() ||
168 F.getName() == Opts.view_bfi_func_name)) {
169 view();
170 }
171 if (Opts.print_bfi && (Opts.print_bfi_func_name.empty() ||
172 F.getName() == Opts.print_bfi_func_name)) {
173 print(dbgs());
174 }
175}
176
178 return BFI ? BFI->getBlockFreq(BB) : BlockFrequency(0);
179}
180
181std::optional<uint64_t>
183 if (!BFI)
184 return std::nullopt;
185
186 return BFI->getBlockProfileCount(*getFunction(), BB);
187}
188
189std::optional<uint64_t>
191 if (!BFI)
192 return std::nullopt;
193 return BFI->getProfileCountFromFreq(*getFunction(), Freq);
194}
195
197 assert(BFI && "Expected analysis to be available");
198 return BFI->isIrrLoopHeader(BB);
199}
200
202 BlockFrequency Freq) {
203 assert(BFI && "Expected analysis to be available");
204 BFI->setBlockFreq(BB, Freq);
205}
206
208 const BasicBlock *ReferenceBB, BlockFrequency Freq,
209 SmallPtrSetImpl<BasicBlock *> &BlocksToScale) {
210 assert(BFI && "Expected analysis to be available");
211 // Use 128 bits APInt to avoid overflow.
212 APInt NewFreq(128, Freq.getFrequency());
213 APInt OldFreq(128, BFI->getBlockFreq(ReferenceBB).getFrequency());
214 APInt BBFreq(128, 0);
215 for (auto *BB : BlocksToScale) {
216 BBFreq = BFI->getBlockFreq(BB).getFrequency();
217 // Multiply first by NewFreq and then divide by OldFreq
218 // to minimize loss of precision.
219 BBFreq *= NewFreq;
220 // udiv is an expensive operation in the general case. If this ends up being
221 // a hot spot, one of the options proposed in
222 // https://reviews.llvm.org/D28535#650071 could be used to avoid this.
223 BBFreq = BBFreq.udiv(OldFreq);
224 BFI->setBlockFreq(BB, BlockFrequency(BBFreq.getLimitedValue()));
225 }
226 BFI->setBlockFreq(ReferenceBB, Freq);
227}
228
229/// Pop up a ghostview window with the current block frequency propagation
230/// rendered using dot.
232 ViewGraph(const_cast<BlockFrequencyInfo *>(this), title);
233}
234
236 return BFI ? BFI->getFunction() : nullptr;
237}
238
240 return BFI ? &BFI->getBPI() : nullptr;
241}
242
244 return BFI ? BFI->getEntryFreq() : BlockFrequency(0);
245}
246
248
250 if (BFI)
251 BFI->print(OS);
252}
253
255 if (BFI)
256 BFI->verifyMatch(*Other.BFI);
257}
258
260 BlockFrequency Freq) {
261 return Printable([&BFI, Freq](raw_ostream &OS) {
262 printRelativeBlockFreq(OS, BFI.getEntryFreq(), Freq);
263 });
264}
265
267 const BasicBlock &BB) {
268 return printBlockFreq(BFI, BFI.getBlockFreq(&BB));
269}
270
272 "Block Frequency Analysis", true, true)
276 "Block Frequency Analysis", true, true)
277
279
282
284
286 const Module *) const {
287 BFI.print(OS);
288}
289
295
296void BlockFrequencyInfoWrapperPass::releaseMemory() { BFI.releaseMemory(); }
297
302 BFI.calculate(F, BPI, LI);
303 return false;
304}
305
306AnalysisKey BlockFrequencyAnalysis::Key;
309 auto &BP = AM.getResult<BranchProbabilityAnalysis>(F);
310 auto &LI = AM.getResult<CycleAnalysis>(F);
312 BFI.calculate(F, BP, LI);
313 return BFI;
314}
315
318 OS << "Printing analysis results of BFI for function "
319 << "'" << F.getName() << "':"
320 << "\n";
322 return PreservedAnalyses::all();
323}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static cl::opt< GVDAGType > ViewBlockFreqPropagationDAG("view-block-freq-propagation-dags", cl::Hidden, cl::desc("Pop up a window to show a dag displaying how block " "frequencies propagation through the CFG."), cl::values(clEnumValN(GVDT_None, "none", "do not display graphs."), clEnumValN(GVDT_Fraction, "fraction", "display a graph using the " "fractional block frequency representation."), clEnumValN(GVDT_Integer, "integer", "display a graph using the raw " "integer fractional block frequency representation."), clEnumValN(GVDT_Count, "count", "display a graph using the real " "profile count if available.")))
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file declares an analysis pass that computes CycleInfo for LLVM IR, specialized from GenericCycl...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define G(x, y, z)
Definition MD5.cpp:55
static GVDAGType getGVDT()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
Class for arbitrary precision integers.
Definition APInt.h:78
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Analysis pass which computes BlockFrequencyInfo.
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM)
Run the analysis pass over a function and produce BFI.
Legacy analysis pass which computes BlockFrequencyInfo.
void print(raw_ostream &OS, const Module *M) const override
print - Print out the internal state of the pass.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI bool isIrrLoopHeader(const BasicBlock *BB)
Returns true if BB is an irreducible loop header block.
LLVM_ABI std::optional< uint64_t > getProfileCountFromFreq(BlockFrequency Freq) const
Returns the estimated profile count of Freq.
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI ~BlockFrequencyInfo()
LLVM_ABI const Function * getFunction() const
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
BlockFrequencyInfo & operator=(const BlockFrequencyInfo &)=delete
LLVM_ABI void calculate(const Function &F, const BranchProbabilityInfo &BPI, const CycleInfo &CI)
calculate - compute block frequency info for the given function.
LLVM_ABI void view(StringRef="BlockFrequencyDAGs") const
Pop up a ghostview window with the current block frequency propagation rendered using dot.
LLVM_ABI void setBlockFreqAndScale(const BasicBlock *ReferenceBB, BlockFrequency Freq, SmallPtrSetImpl< BasicBlock * > &BlocksToScale)
Set the frequency of ReferenceBB to Freq and scale the frequencies of the blocks in BlocksToScale suc...
LLVM_ABI const BranchProbabilityInfo * getBPI() const
LLVM_ABI BlockFrequency getEntryFreq() const
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
LLVM_ABI void verifyMatch(BlockFrequencyInfo &Other) const
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
Analysis pass which computes BranchProbabilityInfo.
Legacy analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Analysis pass which computes a CycleInfo.
Legacy analysis pass which computes a CycleInfo.
FunctionPass(char &pid)
Definition Pass.h:314
const Function & getFunction() const
Definition Function.h:167
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
Simple wrapper around std::function<void(raw_ostream&)>.
Definition Printable.h:38
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
BFIDOTGraphTraitsBase< BlockFrequencyInfo, BranchProbabilityInfo > BFIDOTGTraitsBase
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI PGOViewCountsType getPGOViewCounts(const LLVMContext &C)
Return -pgo-view-counts.
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
@ Other
Any other memory.
Definition ModRef.h:68
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI void printRelativeBlockFreq(raw_ostream &OS, BlockFrequency EntryFreq, BlockFrequency Freq)
Instruction::const_succ_iterator const_succ_iterator
Definition CFG.h:127
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
LLVM_ABI StringRef getPrintBFIFuncName(const LLVMContext &C)
Return -print-bfi-func-name.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI StringRef getViewBlockFreqFuncName(const LLVMContext &C)
Return -view-bfi-func-name.
LLVM_ABI unsigned getViewHotFreqPercent(const LLVMContext &C)
Return -view-hot-freq-percent.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
std::string getNodeAttributes(NodeRef Node, const BlockFrequencyInfo *Graph, unsigned HotPercentThreshold=0)
std::string getNodeLabel(NodeRef Node, const BlockFrequencyInfo *Graph, GVDAGType GType, int layout_order=-1)
std::string getEdgeAttributes(NodeRef Node, EdgeIter EI, const BlockFrequencyInfo *BFI, const BranchProbabilityInfo *BPI, unsigned HotPercentThreshold=0)
std::string getNodeAttributes(const BasicBlock *Node, const BlockFrequencyInfo *Graph)
std::string getEdgeAttributes(const BasicBlock *Node, EdgeIter EI, const BlockFrequencyInfo *BFI)
std::string getNodeLabel(const BasicBlock *Node, const BlockFrequencyInfo *Graph)
static ChildIteratorType child_begin(const NodeRef N)
static NodeRef getEntryNode(const BlockFrequencyInfo *G)
static ChildIteratorType child_end(const NodeRef N)
static nodes_iterator nodes_end(const BlockFrequencyInfo *G)
pointer_iterator< Function::const_iterator > nodes_iterator
static nodes_iterator nodes_begin(const BlockFrequencyInfo *G)