xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Scalar/SimplifyCFGPass.cpp (revision f5b7695d2d5abd735064870ad43f4b9c723940c1)
1 //===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===//
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 // This file implements dead code elimination and basic block merging, along
10 // with a collection of other peephole control flow optimizations.  For example:
11 //
12 //   * Removes basic blocks with no predecessors.
13 //   * Merges a basic block into its predecessor if there is only one and the
14 //     predecessor only has one successor.
15 //   * Eliminates PHI nodes for basic blocks with a single predecessor.
16 //   * Eliminates a basic block that only contains an unconditional branch.
17 //   * Changes invoke instructions to nounwind functions to be calls.
18 //   * Change things like "if (x) if (y)" into "if (x&y)".
19 //   * etc..
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AssumptionCache.h"
27 #include "llvm/Analysis/CFG.h"
28 #include "llvm/Analysis/GlobalsModRef.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/CFG.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include <utility>
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "simplifycfg"
47 
48 static cl::opt<unsigned> UserBonusInstThreshold(
49     "bonus-inst-threshold", cl::Hidden, cl::init(1),
50     cl::desc("Control the number of bonus instructions (default = 1)"));
51 
52 static cl::opt<bool> UserKeepLoops(
53     "keep-loops", cl::Hidden, cl::init(true),
54     cl::desc("Preserve canonical loop structure (default = true)"));
55 
56 static cl::opt<bool> UserSwitchToLookup(
57     "switch-to-lookup", cl::Hidden, cl::init(false),
58     cl::desc("Convert switches to lookup tables (default = false)"));
59 
60 static cl::opt<bool> UserForwardSwitchCond(
61     "forward-switch-cond", cl::Hidden, cl::init(false),
62     cl::desc("Forward switch condition to phi ops (default = false)"));
63 
64 static cl::opt<bool> UserSinkCommonInsts(
65     "sink-common-insts", cl::Hidden, cl::init(false),
66     cl::desc("Sink common instructions (default = false)"));
67 
68 
69 STATISTIC(NumSimpl, "Number of blocks simplified");
70 
71 /// If we have more than one empty (other than phi node) return blocks,
72 /// merge them together to promote recursive block merging.
73 static bool mergeEmptyReturnBlocks(Function &F) {
74   bool Changed = false;
75 
76   BasicBlock *RetBlock = nullptr;
77 
78   // Scan all the blocks in the function, looking for empty return blocks.
79   for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) {
80     BasicBlock &BB = *BBI++;
81 
82     // Only look at return blocks.
83     ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
84     if (!Ret) continue;
85 
86     // Only look at the block if it is empty or the only other thing in it is a
87     // single PHI node that is the operand to the return.
88     if (Ret != &BB.front()) {
89       // Check for something else in the block.
90       BasicBlock::iterator I(Ret);
91       --I;
92       // Skip over debug info.
93       while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
94         --I;
95       if (!isa<DbgInfoIntrinsic>(I) &&
96           (!isa<PHINode>(I) || I != BB.begin() || Ret->getNumOperands() == 0 ||
97            Ret->getOperand(0) != &*I))
98         continue;
99     }
100 
101     // If this is the first returning block, remember it and keep going.
102     if (!RetBlock) {
103       RetBlock = &BB;
104       continue;
105     }
106 
107     // Otherwise, we found a duplicate return block.  Merge the two.
108     Changed = true;
109 
110     // Case when there is no input to the return or when the returned values
111     // agree is trivial.  Note that they can't agree if there are phis in the
112     // blocks.
113     if (Ret->getNumOperands() == 0 ||
114         Ret->getOperand(0) ==
115           cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) {
116       BB.replaceAllUsesWith(RetBlock);
117       BB.eraseFromParent();
118       continue;
119     }
120 
121     // If the canonical return block has no PHI node, create one now.
122     PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin());
123     if (!RetBlockPHI) {
124       Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0);
125       pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock);
126       RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(),
127                                     std::distance(PB, PE), "merge",
128                                     &RetBlock->front());
129 
130       for (pred_iterator PI = PB; PI != PE; ++PI)
131         RetBlockPHI->addIncoming(InVal, *PI);
132       RetBlock->getTerminator()->setOperand(0, RetBlockPHI);
133     }
134 
135     // Turn BB into a block that just unconditionally branches to the return
136     // block.  This handles the case when the two return blocks have a common
137     // predecessor but that return different things.
138     RetBlockPHI->addIncoming(Ret->getOperand(0), &BB);
139     BB.getTerminator()->eraseFromParent();
140     BranchInst::Create(RetBlock, &BB);
141   }
142 
143   return Changed;
144 }
145 
146 /// Call SimplifyCFG on all the blocks in the function,
147 /// iterating until no more changes are made.
148 static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI,
149                                    const SimplifyCFGOptions &Options) {
150   bool Changed = false;
151   bool LocalChange = true;
152 
153   SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 32> Edges;
154   FindFunctionBackedges(F, Edges);
155   SmallPtrSet<BasicBlock *, 16> LoopHeaders;
156   for (unsigned i = 0, e = Edges.size(); i != e; ++i)
157     LoopHeaders.insert(const_cast<BasicBlock *>(Edges[i].second));
158 
159   while (LocalChange) {
160     LocalChange = false;
161 
162     // Loop over all of the basic blocks and remove them if they are unneeded.
163     for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
164       if (simplifyCFG(&*BBIt++, TTI, Options, &LoopHeaders)) {
165         LocalChange = true;
166         ++NumSimpl;
167       }
168     }
169     Changed |= LocalChange;
170   }
171   return Changed;
172 }
173 
174 static bool simplifyFunctionCFG(Function &F, const TargetTransformInfo &TTI,
175                                 const SimplifyCFGOptions &Options) {
176   bool EverChanged = removeUnreachableBlocks(F);
177   EverChanged |= mergeEmptyReturnBlocks(F);
178   EverChanged |= iterativelySimplifyCFG(F, TTI, Options);
179 
180   // If neither pass changed anything, we're done.
181   if (!EverChanged) return false;
182 
183   // iterativelySimplifyCFG can (rarely) make some loops dead.  If this happens,
184   // removeUnreachableBlocks is needed to nuke them, which means we should
185   // iterate between the two optimizations.  We structure the code like this to
186   // avoid rerunning iterativelySimplifyCFG if the second pass of
187   // removeUnreachableBlocks doesn't do anything.
188   if (!removeUnreachableBlocks(F))
189     return true;
190 
191   do {
192     EverChanged = iterativelySimplifyCFG(F, TTI, Options);
193     EverChanged |= removeUnreachableBlocks(F);
194   } while (EverChanged);
195 
196   return true;
197 }
198 
199 // Command-line settings override compile-time settings.
200 SimplifyCFGPass::SimplifyCFGPass(const SimplifyCFGOptions &Opts) {
201   Options.BonusInstThreshold = UserBonusInstThreshold.getNumOccurrences()
202                                    ? UserBonusInstThreshold
203                                    : Opts.BonusInstThreshold;
204   Options.ForwardSwitchCondToPhi = UserForwardSwitchCond.getNumOccurrences()
205                                        ? UserForwardSwitchCond
206                                        : Opts.ForwardSwitchCondToPhi;
207   Options.ConvertSwitchToLookupTable = UserSwitchToLookup.getNumOccurrences()
208                                            ? UserSwitchToLookup
209                                            : Opts.ConvertSwitchToLookupTable;
210   Options.NeedCanonicalLoop = UserKeepLoops.getNumOccurrences()
211                                   ? UserKeepLoops
212                                   : Opts.NeedCanonicalLoop;
213   Options.SinkCommonInsts = UserSinkCommonInsts.getNumOccurrences()
214                                 ? UserSinkCommonInsts
215                                 : Opts.SinkCommonInsts;
216 }
217 
218 PreservedAnalyses SimplifyCFGPass::run(Function &F,
219                                        FunctionAnalysisManager &AM) {
220   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
221   Options.AC = &AM.getResult<AssumptionAnalysis>(F);
222   if (!simplifyFunctionCFG(F, TTI, Options))
223     return PreservedAnalyses::all();
224   PreservedAnalyses PA;
225   PA.preserve<GlobalsAA>();
226   return PA;
227 }
228 
229 namespace {
230 struct CFGSimplifyPass : public FunctionPass {
231   static char ID;
232   SimplifyCFGOptions Options;
233   std::function<bool(const Function &)> PredicateFtor;
234 
235   CFGSimplifyPass(unsigned Threshold = 1, bool ForwardSwitchCond = false,
236                   bool ConvertSwitch = false, bool KeepLoops = true,
237                   bool SinkCommon = false,
238                   std::function<bool(const Function &)> Ftor = nullptr)
239       : FunctionPass(ID), PredicateFtor(std::move(Ftor)) {
240 
241     initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry());
242 
243     // Check for command-line overrides of options for debug/customization.
244     Options.BonusInstThreshold = UserBonusInstThreshold.getNumOccurrences()
245                                     ? UserBonusInstThreshold
246                                     : Threshold;
247 
248     Options.ForwardSwitchCondToPhi = UserForwardSwitchCond.getNumOccurrences()
249                                          ? UserForwardSwitchCond
250                                          : ForwardSwitchCond;
251 
252     Options.ConvertSwitchToLookupTable = UserSwitchToLookup.getNumOccurrences()
253                                              ? UserSwitchToLookup
254                                              : ConvertSwitch;
255 
256     Options.NeedCanonicalLoop =
257         UserKeepLoops.getNumOccurrences() ? UserKeepLoops : KeepLoops;
258 
259     Options.SinkCommonInsts = UserSinkCommonInsts.getNumOccurrences()
260                                   ? UserSinkCommonInsts
261                                   : SinkCommon;
262   }
263 
264   bool runOnFunction(Function &F) override {
265     if (skipFunction(F) || (PredicateFtor && !PredicateFtor(F)))
266       return false;
267 
268     Options.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
269     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
270     return simplifyFunctionCFG(F, TTI, Options);
271   }
272   void getAnalysisUsage(AnalysisUsage &AU) const override {
273     AU.addRequired<AssumptionCacheTracker>();
274     AU.addRequired<TargetTransformInfoWrapperPass>();
275     AU.addPreserved<GlobalsAAWrapperPass>();
276   }
277 };
278 }
279 
280 char CFGSimplifyPass::ID = 0;
281 INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
282                       false)
283 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
284 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
285 INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
286                     false)
287 
288 // Public interface to the CFGSimplification pass
289 FunctionPass *
290 llvm::createCFGSimplificationPass(unsigned Threshold, bool ForwardSwitchCond,
291                                   bool ConvertSwitch, bool KeepLoops,
292                                   bool SinkCommon,
293                                   std::function<bool(const Function &)> Ftor) {
294   return new CFGSimplifyPass(Threshold, ForwardSwitchCond, ConvertSwitch,
295                              KeepLoops, SinkCommon, std::move(Ftor));
296 }
297