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/MapVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AssumptionCache.h"
28 #include "llvm/Analysis/CFG.h"
29 #include "llvm/Analysis/DomTreeUpdater.h"
30 #include "llvm/Analysis/GlobalsModRef.h"
31 #include "llvm/Analysis/TargetTransformInfo.h"
32 #include "llvm/IR/Attributes.h"
33 #include "llvm/IR/CFG.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/ValueHandle.h"
41 #include "llvm/InitializePasses.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Transforms/Utils/SimplifyCFGOptions.h"
49 #include <utility>
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "simplifycfg"
53 
54 static cl::opt<unsigned> UserBonusInstThreshold(
55     "bonus-inst-threshold", cl::Hidden, cl::init(1),
56     cl::desc("Control the number of bonus instructions (default = 1)"));
57 
58 static cl::opt<bool> UserKeepLoops(
59     "keep-loops", cl::Hidden, cl::init(true),
60     cl::desc("Preserve canonical loop structure (default = true)"));
61 
62 static cl::opt<bool> UserSwitchToLookup(
63     "switch-to-lookup", cl::Hidden, cl::init(false),
64     cl::desc("Convert switches to lookup tables (default = false)"));
65 
66 static cl::opt<bool> UserForwardSwitchCond(
67     "forward-switch-cond", cl::Hidden, cl::init(false),
68     cl::desc("Forward switch condition to phi ops (default = false)"));
69 
70 static cl::opt<bool> UserHoistCommonInsts(
71     "hoist-common-insts", cl::Hidden, cl::init(false),
72     cl::desc("hoist common instructions (default = false)"));
73 
74 static cl::opt<bool> UserSinkCommonInsts(
75     "sink-common-insts", cl::Hidden, cl::init(false),
76     cl::desc("Sink common instructions (default = false)"));
77 
78 
79 STATISTIC(NumSimpl, "Number of blocks simplified");
80 
81 static bool tailMergeBlocksWithSimilarFunctionTerminators(Function &F,
82                                                           DomTreeUpdater *DTU) {
83   SmallMapVector<unsigned /*TerminatorOpcode*/, SmallVector<BasicBlock *, 2>, 4>
84       Structure;
85 
86   // Scan all the blocks in the function, record the interesting-ones.
87   for (BasicBlock &BB : F) {
88     if (DTU && DTU->isBBPendingDeletion(&BB))
89       continue;
90 
91     // We are only interested in function-terminating blocks.
92     if (!succ_empty(&BB))
93       continue;
94 
95     auto *Term = BB.getTerminator();
96 
97     // Fow now only support `ret` function terminators.
98     // FIXME: lift this restriction.
99     if (Term->getOpcode() != Instruction::Ret)
100       continue;
101 
102     // We can't tail-merge block that contains a musttail call.
103     if (BB.getTerminatingMustTailCall())
104       continue;
105 
106     // Calls to experimental_deoptimize must be followed by a return
107     // of the value computed by experimental_deoptimize.
108     // I.e., we can not change `ret` to `br` for this block.
109     if (auto *CI =
110             dyn_cast_or_null<CallInst>(Term->getPrevNonDebugInstruction())) {
111       if (Function *F = CI->getCalledFunction())
112         if (Intrinsic::ID ID = F->getIntrinsicID())
113           if (ID == Intrinsic::experimental_deoptimize)
114             continue;
115     }
116 
117     // PHI nodes cannot have token type, so if the terminator has an operand
118     // with token type, we can not tail-merge this kind of function terminators.
119     if (any_of(Term->operands(),
120                [](Value *Op) { return Op->getType()->isTokenTy(); }))
121       continue;
122 
123     // Canonical blocks are uniqued based on the terminator type (opcode).
124     Structure[Term->getOpcode()].emplace_back(&BB);
125   }
126 
127   bool Changed = false;
128 
129   std::vector<DominatorTree::UpdateType> Updates;
130 
131   for (ArrayRef<BasicBlock *> BBs : make_second_range(Structure)) {
132     SmallVector<PHINode *, 1> NewOps;
133 
134     // We don't want to change IR just because we can.
135     // Only do that if there are at least two blocks we'll tail-merge.
136     if (BBs.size() < 2)
137       continue;
138 
139     Changed = true;
140 
141     if (DTU)
142       Updates.reserve(Updates.size() + BBs.size());
143 
144     BasicBlock *CanonicalBB;
145     Instruction *CanonicalTerm;
146     {
147       auto *Term = BBs[0]->getTerminator();
148 
149       // Create a canonical block for this function terminator type now,
150       // placing it *before* the first block that will branch to it.
151       CanonicalBB = BasicBlock::Create(
152           F.getContext(), Twine("common.") + Term->getOpcodeName(), &F, BBs[0]);
153       // We'll also need a PHI node per each operand of the terminator.
154       NewOps.resize(Term->getNumOperands());
155       for (auto I : zip(Term->operands(), NewOps)) {
156         std::get<1>(I) = PHINode::Create(std::get<0>(I)->getType(),
157                                          /*NumReservedValues=*/BBs.size(),
158                                          CanonicalBB->getName() + ".op");
159         CanonicalBB->getInstList().push_back(std::get<1>(I));
160       }
161       // Make it so that this canonical block actually has the right
162       // terminator.
163       CanonicalTerm = Term->clone();
164       CanonicalBB->getInstList().push_back(CanonicalTerm);
165       // If the canonical terminator has operands, rewrite it to take PHI's.
166       for (auto I : zip(NewOps, CanonicalTerm->operands()))
167         std::get<1>(I) = std::get<0>(I);
168     }
169 
170     // Now, go through each block (with the current terminator type)
171     // we've recorded, and rewrite it to branch to the new common block.
172     const DILocation *CommonDebugLoc = nullptr;
173     for (BasicBlock *BB : BBs) {
174       auto *Term = BB->getTerminator();
175 
176       // Aha, found a new non-canonical function terminator. If it has operands,
177       // forward them to the PHI nodes in the canonical block.
178       for (auto I : zip(Term->operands(), NewOps))
179         std::get<1>(I)->addIncoming(std::get<0>(I), BB);
180 
181       // Compute the debug location common to all the original terminators.
182       if (!CommonDebugLoc)
183         CommonDebugLoc = Term->getDebugLoc();
184       else
185         CommonDebugLoc =
186             DILocation::getMergedLocation(CommonDebugLoc, Term->getDebugLoc());
187 
188       // And turn BB into a block that just unconditionally branches
189       // to the canonical block.
190       Term->eraseFromParent();
191       BranchInst::Create(CanonicalBB, BB);
192       if (DTU)
193         Updates.push_back({DominatorTree::Insert, BB, CanonicalBB});
194     }
195 
196     CanonicalTerm->setDebugLoc(CommonDebugLoc);
197   }
198 
199   if (DTU)
200     DTU->applyUpdates(Updates);
201 
202   return Changed;
203 }
204 
205 /// Call SimplifyCFG on all the blocks in the function,
206 /// iterating until no more changes are made.
207 static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI,
208                                    DomTreeUpdater *DTU,
209                                    const SimplifyCFGOptions &Options) {
210   bool Changed = false;
211   bool LocalChange = true;
212 
213   SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 32> Edges;
214   FindFunctionBackedges(F, Edges);
215   SmallPtrSet<BasicBlock *, 16> UniqueLoopHeaders;
216   for (unsigned i = 0, e = Edges.size(); i != e; ++i)
217     UniqueLoopHeaders.insert(const_cast<BasicBlock *>(Edges[i].second));
218 
219   SmallVector<WeakVH, 16> LoopHeaders(UniqueLoopHeaders.begin(),
220                                       UniqueLoopHeaders.end());
221 
222   while (LocalChange) {
223     LocalChange = false;
224 
225     // Loop over all of the basic blocks and remove them if they are unneeded.
226     for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
227       BasicBlock &BB = *BBIt++;
228       if (DTU) {
229         assert(
230             !DTU->isBBPendingDeletion(&BB) &&
231             "Should not end up trying to simplify blocks marked for removal.");
232         // Make sure that the advanced iterator does not point at the blocks
233         // that are marked for removal, skip over all such blocks.
234         while (BBIt != F.end() && DTU->isBBPendingDeletion(&*BBIt))
235           ++BBIt;
236       }
237       if (simplifyCFG(&BB, TTI, DTU, Options, LoopHeaders)) {
238         LocalChange = true;
239         ++NumSimpl;
240       }
241     }
242     Changed |= LocalChange;
243   }
244   return Changed;
245 }
246 
247 static bool simplifyFunctionCFGImpl(Function &F, const TargetTransformInfo &TTI,
248                                     DominatorTree *DT,
249                                     const SimplifyCFGOptions &Options) {
250   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
251 
252   bool EverChanged = removeUnreachableBlocks(F, DT ? &DTU : nullptr);
253   EverChanged |=
254       tailMergeBlocksWithSimilarFunctionTerminators(F, DT ? &DTU : nullptr);
255   EverChanged |= iterativelySimplifyCFG(F, TTI, DT ? &DTU : nullptr, Options);
256 
257   // If neither pass changed anything, we're done.
258   if (!EverChanged) return false;
259 
260   // iterativelySimplifyCFG can (rarely) make some loops dead.  If this happens,
261   // removeUnreachableBlocks is needed to nuke them, which means we should
262   // iterate between the two optimizations.  We structure the code like this to
263   // avoid rerunning iterativelySimplifyCFG if the second pass of
264   // removeUnreachableBlocks doesn't do anything.
265   if (!removeUnreachableBlocks(F, DT ? &DTU : nullptr))
266     return true;
267 
268   do {
269     EverChanged = iterativelySimplifyCFG(F, TTI, DT ? &DTU : nullptr, Options);
270     EverChanged |= removeUnreachableBlocks(F, DT ? &DTU : nullptr);
271   } while (EverChanged);
272 
273   return true;
274 }
275 
276 static bool simplifyFunctionCFG(Function &F, const TargetTransformInfo &TTI,
277                                 DominatorTree *DT,
278                                 const SimplifyCFGOptions &Options) {
279   assert((!RequireAndPreserveDomTree ||
280           (DT && DT->verify(DominatorTree::VerificationLevel::Full))) &&
281          "Original domtree is invalid?");
282 
283   bool Changed = simplifyFunctionCFGImpl(F, TTI, DT, Options);
284 
285   assert((!RequireAndPreserveDomTree ||
286           (DT && DT->verify(DominatorTree::VerificationLevel::Full))) &&
287          "Failed to maintain validity of domtree!");
288 
289   return Changed;
290 }
291 
292 // Command-line settings override compile-time settings.
293 static void applyCommandLineOverridesToOptions(SimplifyCFGOptions &Options) {
294   if (UserBonusInstThreshold.getNumOccurrences())
295     Options.BonusInstThreshold = UserBonusInstThreshold;
296   if (UserForwardSwitchCond.getNumOccurrences())
297     Options.ForwardSwitchCondToPhi = UserForwardSwitchCond;
298   if (UserSwitchToLookup.getNumOccurrences())
299     Options.ConvertSwitchToLookupTable = UserSwitchToLookup;
300   if (UserKeepLoops.getNumOccurrences())
301     Options.NeedCanonicalLoop = UserKeepLoops;
302   if (UserHoistCommonInsts.getNumOccurrences())
303     Options.HoistCommonInsts = UserHoistCommonInsts;
304   if (UserSinkCommonInsts.getNumOccurrences())
305     Options.SinkCommonInsts = UserSinkCommonInsts;
306 }
307 
308 SimplifyCFGPass::SimplifyCFGPass() : Options() {
309   applyCommandLineOverridesToOptions(Options);
310 }
311 
312 SimplifyCFGPass::SimplifyCFGPass(const SimplifyCFGOptions &Opts)
313     : Options(Opts) {
314   applyCommandLineOverridesToOptions(Options);
315 }
316 
317 PreservedAnalyses SimplifyCFGPass::run(Function &F,
318                                        FunctionAnalysisManager &AM) {
319   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
320   Options.AC = &AM.getResult<AssumptionAnalysis>(F);
321   DominatorTree *DT = nullptr;
322   if (RequireAndPreserveDomTree)
323     DT = &AM.getResult<DominatorTreeAnalysis>(F);
324   if (F.hasFnAttribute(Attribute::OptForFuzzing)) {
325     Options.setSimplifyCondBranch(false).setFoldTwoEntryPHINode(false);
326   } else {
327     Options.setSimplifyCondBranch(true).setFoldTwoEntryPHINode(true);
328   }
329   if (!simplifyFunctionCFG(F, TTI, DT, Options))
330     return PreservedAnalyses::all();
331   PreservedAnalyses PA;
332   if (RequireAndPreserveDomTree)
333     PA.preserve<DominatorTreeAnalysis>();
334   return PA;
335 }
336 
337 namespace {
338 struct CFGSimplifyPass : public FunctionPass {
339   static char ID;
340   SimplifyCFGOptions Options;
341   std::function<bool(const Function &)> PredicateFtor;
342 
343   CFGSimplifyPass(SimplifyCFGOptions Options_ = SimplifyCFGOptions(),
344                   std::function<bool(const Function &)> Ftor = nullptr)
345       : FunctionPass(ID), Options(Options_), PredicateFtor(std::move(Ftor)) {
346 
347     initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry());
348 
349     // Check for command-line overrides of options for debug/customization.
350     applyCommandLineOverridesToOptions(Options);
351   }
352 
353   bool runOnFunction(Function &F) override {
354     if (skipFunction(F) || (PredicateFtor && !PredicateFtor(F)))
355       return false;
356 
357     Options.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
358     DominatorTree *DT = nullptr;
359     if (RequireAndPreserveDomTree)
360       DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
361     if (F.hasFnAttribute(Attribute::OptForFuzzing)) {
362       Options.setSimplifyCondBranch(false)
363              .setFoldTwoEntryPHINode(false);
364     } else {
365       Options.setSimplifyCondBranch(true)
366              .setFoldTwoEntryPHINode(true);
367     }
368 
369     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
370     return simplifyFunctionCFG(F, TTI, DT, Options);
371   }
372   void getAnalysisUsage(AnalysisUsage &AU) const override {
373     AU.addRequired<AssumptionCacheTracker>();
374     if (RequireAndPreserveDomTree)
375       AU.addRequired<DominatorTreeWrapperPass>();
376     AU.addRequired<TargetTransformInfoWrapperPass>();
377     if (RequireAndPreserveDomTree)
378       AU.addPreserved<DominatorTreeWrapperPass>();
379     AU.addPreserved<GlobalsAAWrapperPass>();
380   }
381 };
382 }
383 
384 char CFGSimplifyPass::ID = 0;
385 INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
386                       false)
387 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
388 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
389 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
390 INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
391                     false)
392 
393 // Public interface to the CFGSimplification pass
394 FunctionPass *
395 llvm::createCFGSimplificationPass(SimplifyCFGOptions Options,
396                                   std::function<bool(const Function &)> Ftor) {
397   return new CFGSimplifyPass(Options, std::move(Ftor));
398 }
399