1 //===- CFGPrinter.cpp - DOT printer for the control flow graph ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines a `-dot-cfg` analysis pass, which emits the
10 // `<prefix>.<fnname>.dot` file for each function in the program, with a graph
11 // of the CFG for that function. The default value for `<prefix>` is `cfg` but
12 // can be customized as needed.
14 // The other main feature of this file is that it implements the
15 // Function::viewCFG method, which is useful for debugging passes which operate
18 //===----------------------------------------------------------------------===//
20 #include "llvm/Analysis/CFGPrinter.h"
21 #include "llvm/ADT/PostOrderIterator.h"
22 #include "llvm/InitializePasses.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/FileSystem.h"
30 static cl::opt
<std::string
>
31 CFGFuncName("cfg-func-name", cl::Hidden
,
32 cl::desc("The name of a function (or its substring)"
33 " whose CFG is viewed/printed."));
35 static cl::opt
<std::string
> CFGDotFilenamePrefix(
36 "cfg-dot-filename-prefix", cl::Hidden
,
37 cl::desc("The prefix used for the CFG dot file names."));
39 static cl::opt
<bool> HideUnreachablePaths("cfg-hide-unreachable-paths",
42 static cl::opt
<bool> HideDeoptimizePaths("cfg-hide-deoptimize-paths",
45 static cl::opt
<double> HideColdPaths(
46 "cfg-hide-cold-paths", cl::init(0.0),
47 cl::desc("Hide blocks with relative frequency below the given value"));
49 static cl::opt
<bool> ShowHeatColors("cfg-heat-colors", cl::init(true),
51 cl::desc("Show heat colors in CFG"));
53 static cl::opt
<bool> UseRawEdgeWeight("cfg-raw-weights", cl::init(false),
55 cl::desc("Use raw weights for labels. "
56 "Use percentages as default."));
59 ShowEdgeWeight("cfg-weights", cl::init(false), cl::Hidden
,
60 cl::desc("Show edges labeled with weights"));
62 static void writeCFGToDotFile(Function
&F
, BlockFrequencyInfo
*BFI
,
63 BranchProbabilityInfo
*BPI
, uint64_t MaxFreq
,
64 bool CFGOnly
= false) {
65 std::string Filename
=
66 (CFGDotFilenamePrefix
+ "." + F
.getName() + ".dot").str();
67 errs() << "Writing '" << Filename
<< "'...";
70 raw_fd_ostream
File(Filename
, EC
, sys::fs::OF_Text
);
72 DOTFuncInfo
CFGInfo(&F
, BFI
, BPI
, MaxFreq
);
73 CFGInfo
.setHeatColors(ShowHeatColors
);
74 CFGInfo
.setEdgeWeights(ShowEdgeWeight
);
75 CFGInfo
.setRawEdgeWeights(UseRawEdgeWeight
);
78 WriteGraph(File
, &CFGInfo
, CFGOnly
);
80 errs() << " error opening file for writing!";
84 static void viewCFG(Function
&F
, const BlockFrequencyInfo
*BFI
,
85 const BranchProbabilityInfo
*BPI
, uint64_t MaxFreq
,
86 bool CFGOnly
= false) {
87 DOTFuncInfo
CFGInfo(&F
, BFI
, BPI
, MaxFreq
);
88 CFGInfo
.setHeatColors(ShowHeatColors
);
89 CFGInfo
.setEdgeWeights(ShowEdgeWeight
);
90 CFGInfo
.setRawEdgeWeights(UseRawEdgeWeight
);
92 ViewGraph(&CFGInfo
, "cfg." + F
.getName(), CFGOnly
);
96 struct CFGViewerLegacyPass
: public FunctionPass
{
97 static char ID
; // Pass identifcation, replacement for typeid
98 CFGViewerLegacyPass() : FunctionPass(ID
) {
99 initializeCFGViewerLegacyPassPass(*PassRegistry::getPassRegistry());
102 bool runOnFunction(Function
&F
) override
{
103 if (!CFGFuncName
.empty() && !F
.getName().contains(CFGFuncName
))
105 auto *BPI
= &getAnalysis
<BranchProbabilityInfoWrapperPass
>().getBPI();
106 auto *BFI
= &getAnalysis
<BlockFrequencyInfoWrapperPass
>().getBFI();
107 viewCFG(F
, BFI
, BPI
, getMaxFreq(F
, BFI
));
111 void print(raw_ostream
&OS
, const Module
* = nullptr) const override
{}
113 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
114 FunctionPass::getAnalysisUsage(AU
);
115 AU
.addRequired
<BlockFrequencyInfoWrapperPass
>();
116 AU
.addRequired
<BranchProbabilityInfoWrapperPass
>();
117 AU
.setPreservesAll();
122 char CFGViewerLegacyPass::ID
= 0;
123 INITIALIZE_PASS(CFGViewerLegacyPass
, "view-cfg", "View CFG of function", false,
126 PreservedAnalyses
CFGViewerPass::run(Function
&F
, FunctionAnalysisManager
&AM
) {
127 if (!CFGFuncName
.empty() && !F
.getName().contains(CFGFuncName
))
128 return PreservedAnalyses::all();
129 auto *BFI
= &AM
.getResult
<BlockFrequencyAnalysis
>(F
);
130 auto *BPI
= &AM
.getResult
<BranchProbabilityAnalysis
>(F
);
131 viewCFG(F
, BFI
, BPI
, getMaxFreq(F
, BFI
));
132 return PreservedAnalyses::all();
136 struct CFGOnlyViewerLegacyPass
: public FunctionPass
{
137 static char ID
; // Pass identifcation, replacement for typeid
138 CFGOnlyViewerLegacyPass() : FunctionPass(ID
) {
139 initializeCFGOnlyViewerLegacyPassPass(*PassRegistry::getPassRegistry());
142 bool runOnFunction(Function
&F
) override
{
143 if (!CFGFuncName
.empty() && !F
.getName().contains(CFGFuncName
))
145 auto *BPI
= &getAnalysis
<BranchProbabilityInfoWrapperPass
>().getBPI();
146 auto *BFI
= &getAnalysis
<BlockFrequencyInfoWrapperPass
>().getBFI();
147 viewCFG(F
, BFI
, BPI
, getMaxFreq(F
, BFI
), /*CFGOnly=*/true);
151 void print(raw_ostream
&OS
, const Module
* = nullptr) const override
{}
153 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
154 FunctionPass::getAnalysisUsage(AU
);
155 AU
.addRequired
<BlockFrequencyInfoWrapperPass
>();
156 AU
.addRequired
<BranchProbabilityInfoWrapperPass
>();
157 AU
.setPreservesAll();
162 char CFGOnlyViewerLegacyPass::ID
= 0;
163 INITIALIZE_PASS(CFGOnlyViewerLegacyPass
, "view-cfg-only",
164 "View CFG of function (with no function bodies)", false, true)
166 PreservedAnalyses
CFGOnlyViewerPass::run(Function
&F
,
167 FunctionAnalysisManager
&AM
) {
168 if (!CFGFuncName
.empty() && !F
.getName().contains(CFGFuncName
))
169 return PreservedAnalyses::all();
170 auto *BFI
= &AM
.getResult
<BlockFrequencyAnalysis
>(F
);
171 auto *BPI
= &AM
.getResult
<BranchProbabilityAnalysis
>(F
);
172 viewCFG(F
, BFI
, BPI
, getMaxFreq(F
, BFI
), /*CFGOnly=*/true);
173 return PreservedAnalyses::all();
177 struct CFGPrinterLegacyPass
: public FunctionPass
{
178 static char ID
; // Pass identification, replacement for typeid
179 CFGPrinterLegacyPass() : FunctionPass(ID
) {
180 initializeCFGPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
183 bool runOnFunction(Function
&F
) override
{
184 if (!CFGFuncName
.empty() && !F
.getName().contains(CFGFuncName
))
186 auto *BPI
= &getAnalysis
<BranchProbabilityInfoWrapperPass
>().getBPI();
187 auto *BFI
= &getAnalysis
<BlockFrequencyInfoWrapperPass
>().getBFI();
188 writeCFGToDotFile(F
, BFI
, BPI
, getMaxFreq(F
, BFI
));
192 void print(raw_ostream
&OS
, const Module
* = nullptr) const override
{}
194 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
195 FunctionPass::getAnalysisUsage(AU
);
196 AU
.addRequired
<BlockFrequencyInfoWrapperPass
>();
197 AU
.addRequired
<BranchProbabilityInfoWrapperPass
>();
198 AU
.setPreservesAll();
203 char CFGPrinterLegacyPass::ID
= 0;
204 INITIALIZE_PASS(CFGPrinterLegacyPass
, "dot-cfg",
205 "Print CFG of function to 'dot' file", false, true)
207 PreservedAnalyses
CFGPrinterPass::run(Function
&F
,
208 FunctionAnalysisManager
&AM
) {
209 if (!CFGFuncName
.empty() && !F
.getName().contains(CFGFuncName
))
210 return PreservedAnalyses::all();
211 auto *BFI
= &AM
.getResult
<BlockFrequencyAnalysis
>(F
);
212 auto *BPI
= &AM
.getResult
<BranchProbabilityAnalysis
>(F
);
213 writeCFGToDotFile(F
, BFI
, BPI
, getMaxFreq(F
, BFI
));
214 return PreservedAnalyses::all();
218 struct CFGOnlyPrinterLegacyPass
: public FunctionPass
{
219 static char ID
; // Pass identification, replacement for typeid
220 CFGOnlyPrinterLegacyPass() : FunctionPass(ID
) {
221 initializeCFGOnlyPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
224 bool runOnFunction(Function
&F
) override
{
225 if (!CFGFuncName
.empty() && !F
.getName().contains(CFGFuncName
))
227 auto *BPI
= &getAnalysis
<BranchProbabilityInfoWrapperPass
>().getBPI();
228 auto *BFI
= &getAnalysis
<BlockFrequencyInfoWrapperPass
>().getBFI();
229 writeCFGToDotFile(F
, BFI
, BPI
, getMaxFreq(F
, BFI
), /*CFGOnly=*/true);
232 void print(raw_ostream
&OS
, const Module
* = nullptr) const override
{}
234 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
235 FunctionPass::getAnalysisUsage(AU
);
236 AU
.addRequired
<BlockFrequencyInfoWrapperPass
>();
237 AU
.addRequired
<BranchProbabilityInfoWrapperPass
>();
238 AU
.setPreservesAll();
243 char CFGOnlyPrinterLegacyPass::ID
= 0;
244 INITIALIZE_PASS(CFGOnlyPrinterLegacyPass
, "dot-cfg-only",
245 "Print CFG of function to 'dot' file (with no function bodies)",
248 PreservedAnalyses
CFGOnlyPrinterPass::run(Function
&F
,
249 FunctionAnalysisManager
&AM
) {
250 if (!CFGFuncName
.empty() && !F
.getName().contains(CFGFuncName
))
251 return PreservedAnalyses::all();
252 auto *BFI
= &AM
.getResult
<BlockFrequencyAnalysis
>(F
);
253 auto *BPI
= &AM
.getResult
<BranchProbabilityAnalysis
>(F
);
254 writeCFGToDotFile(F
, BFI
, BPI
, getMaxFreq(F
, BFI
), /*CFGOnly=*/true);
255 return PreservedAnalyses::all();
258 /// viewCFG - This function is meant for use from the debugger. You can just
259 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
260 /// program, displaying the CFG of the current function. This depends on there
261 /// being a 'dot' and 'gv' program in your path.
263 void Function::viewCFG() const { viewCFG(false, nullptr, nullptr); }
265 void Function::viewCFG(bool ViewCFGOnly
, const BlockFrequencyInfo
*BFI
,
266 const BranchProbabilityInfo
*BPI
) const {
267 if (!CFGFuncName
.empty() && !getName().contains(CFGFuncName
))
269 DOTFuncInfo
CFGInfo(this, BFI
, BPI
, BFI
? getMaxFreq(*this, BFI
) : 0);
270 ViewGraph(&CFGInfo
, "cfg" + getName(), ViewCFGOnly
);
273 /// viewCFGOnly - This function is meant for use from the debugger. It works
274 /// just like viewCFG, but it does not include the contents of basic blocks
275 /// into the nodes, just the label. If you are only interested in the CFG
276 /// this can make the graph smaller.
278 void Function::viewCFGOnly() const { viewCFGOnly(nullptr, nullptr); }
280 void Function::viewCFGOnly(const BlockFrequencyInfo
*BFI
,
281 const BranchProbabilityInfo
*BPI
) const {
282 viewCFG(true, BFI
, BPI
);
285 FunctionPass
*llvm::createCFGPrinterLegacyPassPass() {
286 return new CFGPrinterLegacyPass();
289 FunctionPass
*llvm::createCFGOnlyPrinterLegacyPassPass() {
290 return new CFGOnlyPrinterLegacyPass();
293 /// Find all blocks on the paths which terminate with a deoptimize or
294 /// unreachable (i.e. all blocks which are post-dominated by a deoptimize
295 /// or unreachable). These paths are hidden if the corresponding cl::opts
297 void DOTGraphTraits
<DOTFuncInfo
*>::computeDeoptOrUnreachablePaths(
299 auto evaluateBB
= [&](const BasicBlock
*Node
) {
300 if (succ_empty(Node
)) {
301 const Instruction
*TI
= Node
->getTerminator();
302 isOnDeoptOrUnreachablePath
[Node
] =
303 (HideUnreachablePaths
&& isa
<UnreachableInst
>(TI
)) ||
304 (HideDeoptimizePaths
&& Node
->getTerminatingDeoptimizeCall());
307 isOnDeoptOrUnreachablePath
[Node
] =
308 llvm::all_of(successors(Node
), [this](const BasicBlock
*BB
) {
309 return isOnDeoptOrUnreachablePath
[BB
];
312 /// The post order traversal iteration is done to know the status of
313 /// isOnDeoptOrUnreachablePath for all the successors on the current BB.
314 llvm::for_each(post_order(&F
->getEntryBlock()), evaluateBB
);
317 bool DOTGraphTraits
<DOTFuncInfo
*>::isNodeHidden(const BasicBlock
*Node
,
318 const DOTFuncInfo
*CFGInfo
) {
319 if (HideColdPaths
.getNumOccurrences() > 0)
320 if (auto *BFI
= CFGInfo
->getBFI()) {
321 uint64_t NodeFreq
= BFI
->getBlockFreq(Node
).getFrequency();
322 uint64_t EntryFreq
= BFI
->getEntryFreq();
323 // Hide blocks with relative frequency below HideColdPaths threshold.
324 if ((double)NodeFreq
/ EntryFreq
< HideColdPaths
)
327 if (HideUnreachablePaths
|| HideDeoptimizePaths
) {
328 if (isOnDeoptOrUnreachablePath
.find(Node
) ==
329 isOnDeoptOrUnreachablePath
.end())
330 computeDeoptOrUnreachablePaths(Node
->getParent());
331 return isOnDeoptOrUnreachablePath
[Node
];