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/DomTreeUpdater.h" 29 #include "llvm/Analysis/GlobalsModRef.h" 30 #include "llvm/Analysis/TargetTransformInfo.h" 31 #include "llvm/IR/Attributes.h" 32 #include "llvm/IR/CFG.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/Dominators.h" 36 #include "llvm/IR/Instructions.h" 37 #include "llvm/IR/IntrinsicInst.h" 38 #include "llvm/IR/Module.h" 39 #include "llvm/InitializePasses.h" 40 #include "llvm/Pass.h" 41 #include "llvm/Support/CommandLine.h" 42 #include "llvm/Transforms/Scalar.h" 43 #include "llvm/Transforms/Scalar/SimplifyCFG.h" 44 #include "llvm/Transforms/Utils/Local.h" 45 #include "llvm/Transforms/Utils/SimplifyCFGOptions.h" 46 #include <utility> 47 using namespace llvm; 48 49 #define DEBUG_TYPE "simplifycfg" 50 51 static cl::opt<unsigned> UserBonusInstThreshold( 52 "bonus-inst-threshold", cl::Hidden, cl::init(1), 53 cl::desc("Control the number of bonus instructions (default = 1)")); 54 55 static cl::opt<bool> UserKeepLoops( 56 "keep-loops", cl::Hidden, cl::init(true), 57 cl::desc("Preserve canonical loop structure (default = true)")); 58 59 static cl::opt<bool> UserSwitchToLookup( 60 "switch-to-lookup", cl::Hidden, cl::init(false), 61 cl::desc("Convert switches to lookup tables (default = false)")); 62 63 static cl::opt<bool> UserForwardSwitchCond( 64 "forward-switch-cond", cl::Hidden, cl::init(false), 65 cl::desc("Forward switch condition to phi ops (default = false)")); 66 67 static cl::opt<bool> UserHoistCommonInsts( 68 "hoist-common-insts", cl::Hidden, cl::init(false), 69 cl::desc("hoist common instructions (default = false)")); 70 71 static cl::opt<bool> UserSinkCommonInsts( 72 "sink-common-insts", cl::Hidden, cl::init(false), 73 cl::desc("Sink common instructions (default = false)")); 74 75 76 STATISTIC(NumSimpl, "Number of blocks simplified"); 77 78 /// If we have more than one empty (other than phi node) return blocks, 79 /// merge them together to promote recursive block merging. 80 static bool mergeEmptyReturnBlocks(Function &F) { 81 bool Changed = false; 82 83 BasicBlock *RetBlock = nullptr; 84 85 // Scan all the blocks in the function, looking for empty return blocks. 86 for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) { 87 BasicBlock &BB = *BBI++; 88 89 // Only look at return blocks. 90 ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()); 91 if (!Ret) continue; 92 93 // Only look at the block if it is empty or the only other thing in it is a 94 // single PHI node that is the operand to the return. 95 if (Ret != &BB.front()) { 96 // Check for something else in the block. 97 BasicBlock::iterator I(Ret); 98 --I; 99 // Skip over debug info. 100 while (isa<DbgInfoIntrinsic>(I) && I != BB.begin()) 101 --I; 102 if (!isa<DbgInfoIntrinsic>(I) && 103 (!isa<PHINode>(I) || I != BB.begin() || Ret->getNumOperands() == 0 || 104 Ret->getOperand(0) != &*I)) 105 continue; 106 } 107 108 // If this is the first returning block, remember it and keep going. 109 if (!RetBlock) { 110 RetBlock = &BB; 111 continue; 112 } 113 114 // Skip merging if this would result in a CallBr instruction with a 115 // duplicate destination. FIXME: See note in CodeGenPrepare.cpp. 116 bool SkipCallBr = false; 117 for (pred_iterator PI = pred_begin(&BB), E = pred_end(&BB); 118 PI != E && !SkipCallBr; ++PI) { 119 if (auto *CBI = dyn_cast<CallBrInst>((*PI)->getTerminator())) 120 for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i) 121 if (RetBlock == CBI->getSuccessor(i)) { 122 SkipCallBr = true; 123 break; 124 } 125 } 126 if (SkipCallBr) 127 continue; 128 129 // Otherwise, we found a duplicate return block. Merge the two. 130 Changed = true; 131 132 // Case when there is no input to the return or when the returned values 133 // agree is trivial. Note that they can't agree if there are phis in the 134 // blocks. 135 if (Ret->getNumOperands() == 0 || 136 Ret->getOperand(0) == 137 cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) { 138 BB.replaceAllUsesWith(RetBlock); 139 BB.eraseFromParent(); 140 continue; 141 } 142 143 // If the canonical return block has no PHI node, create one now. 144 PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin()); 145 if (!RetBlockPHI) { 146 Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0); 147 pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock); 148 RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(), 149 std::distance(PB, PE), "merge", 150 &RetBlock->front()); 151 152 for (pred_iterator PI = PB; PI != PE; ++PI) 153 RetBlockPHI->addIncoming(InVal, *PI); 154 RetBlock->getTerminator()->setOperand(0, RetBlockPHI); 155 } 156 157 // Turn BB into a block that just unconditionally branches to the return 158 // block. This handles the case when the two return blocks have a common 159 // predecessor but that return different things. 160 RetBlockPHI->addIncoming(Ret->getOperand(0), &BB); 161 BB.getTerminator()->eraseFromParent(); 162 BranchInst::Create(RetBlock, &BB); 163 } 164 165 return Changed; 166 } 167 168 /// Call SimplifyCFG on all the blocks in the function, 169 /// iterating until no more changes are made. 170 static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI, 171 DomTreeUpdater *DTU, 172 const SimplifyCFGOptions &Options) { 173 bool Changed = false; 174 bool LocalChange = true; 175 176 SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 32> Edges; 177 FindFunctionBackedges(F, Edges); 178 SmallPtrSet<BasicBlock *, 16> LoopHeaders; 179 for (unsigned i = 0, e = Edges.size(); i != e; ++i) 180 LoopHeaders.insert(const_cast<BasicBlock *>(Edges[i].second)); 181 182 while (LocalChange) { 183 LocalChange = false; 184 185 // Loop over all of the basic blocks and remove them if they are unneeded. 186 for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) { 187 if (simplifyCFG(&*BBIt++, TTI, DTU, Options, &LoopHeaders)) { 188 LocalChange = true; 189 ++NumSimpl; 190 } 191 } 192 Changed |= LocalChange; 193 } 194 return Changed; 195 } 196 197 static bool simplifyFunctionCFGImpl(Function &F, const TargetTransformInfo &TTI, 198 DominatorTree *DT, 199 const SimplifyCFGOptions &Options) { 200 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 201 202 bool EverChanged = removeUnreachableBlocks(F, DT ? &DTU : nullptr); 203 EverChanged |= mergeEmptyReturnBlocks(F); 204 EverChanged |= iterativelySimplifyCFG(F, TTI, DT ? &DTU : nullptr, Options); 205 206 // If neither pass changed anything, we're done. 207 if (!EverChanged) return false; 208 209 // iterativelySimplifyCFG can (rarely) make some loops dead. If this happens, 210 // removeUnreachableBlocks is needed to nuke them, which means we should 211 // iterate between the two optimizations. We structure the code like this to 212 // avoid rerunning iterativelySimplifyCFG if the second pass of 213 // removeUnreachableBlocks doesn't do anything. 214 if (!removeUnreachableBlocks(F, DT ? &DTU : nullptr)) 215 return true; 216 217 do { 218 EverChanged = iterativelySimplifyCFG(F, TTI, DT ? &DTU : nullptr, Options); 219 EverChanged |= removeUnreachableBlocks(F, DT ? &DTU : nullptr); 220 } while (EverChanged); 221 222 return true; 223 } 224 225 static bool simplifyFunctionCFG(Function &F, const TargetTransformInfo &TTI, 226 DominatorTree *DT, 227 const SimplifyCFGOptions &Options) { 228 assert((!RequireAndPreserveDomTree || 229 (DT && DT->verify(DominatorTree::VerificationLevel::Full))) && 230 "Original domtree is invalid?"); 231 232 bool Changed = simplifyFunctionCFGImpl(F, TTI, DT, Options); 233 234 assert((!RequireAndPreserveDomTree || 235 (DT && DT->verify(DominatorTree::VerificationLevel::Full))) && 236 "Failed to maintain validity of domtree!"); 237 238 return Changed; 239 } 240 241 // Command-line settings override compile-time settings. 242 static void applyCommandLineOverridesToOptions(SimplifyCFGOptions &Options) { 243 if (UserBonusInstThreshold.getNumOccurrences()) 244 Options.BonusInstThreshold = UserBonusInstThreshold; 245 if (UserForwardSwitchCond.getNumOccurrences()) 246 Options.ForwardSwitchCondToPhi = UserForwardSwitchCond; 247 if (UserSwitchToLookup.getNumOccurrences()) 248 Options.ConvertSwitchToLookupTable = UserSwitchToLookup; 249 if (UserKeepLoops.getNumOccurrences()) 250 Options.NeedCanonicalLoop = UserKeepLoops; 251 if (UserHoistCommonInsts.getNumOccurrences()) 252 Options.HoistCommonInsts = UserHoistCommonInsts; 253 if (UserSinkCommonInsts.getNumOccurrences()) 254 Options.SinkCommonInsts = UserSinkCommonInsts; 255 } 256 257 SimplifyCFGPass::SimplifyCFGPass() : Options() { 258 applyCommandLineOverridesToOptions(Options); 259 } 260 261 SimplifyCFGPass::SimplifyCFGPass(const SimplifyCFGOptions &Opts) 262 : Options(Opts) { 263 applyCommandLineOverridesToOptions(Options); 264 } 265 266 PreservedAnalyses SimplifyCFGPass::run(Function &F, 267 FunctionAnalysisManager &AM) { 268 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 269 Options.AC = &AM.getResult<AssumptionAnalysis>(F); 270 DominatorTree *DT = nullptr; 271 if (RequireAndPreserveDomTree) 272 DT = &AM.getResult<DominatorTreeAnalysis>(F); 273 if (F.hasFnAttribute(Attribute::OptForFuzzing)) { 274 Options.setSimplifyCondBranch(false).setFoldTwoEntryPHINode(false); 275 } else { 276 Options.setSimplifyCondBranch(true).setFoldTwoEntryPHINode(true); 277 } 278 if (!simplifyFunctionCFG(F, TTI, DT, Options)) 279 return PreservedAnalyses::all(); 280 PreservedAnalyses PA; 281 if (RequireAndPreserveDomTree) 282 PA.preserve<DominatorTreeAnalysis>(); 283 PA.preserve<GlobalsAA>(); 284 return PA; 285 } 286 287 namespace { 288 struct CFGSimplifyPass : public FunctionPass { 289 static char ID; 290 SimplifyCFGOptions Options; 291 std::function<bool(const Function &)> PredicateFtor; 292 293 CFGSimplifyPass(SimplifyCFGOptions Options_ = SimplifyCFGOptions(), 294 std::function<bool(const Function &)> Ftor = nullptr) 295 : FunctionPass(ID), Options(Options_), PredicateFtor(std::move(Ftor)) { 296 297 initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry()); 298 299 // Check for command-line overrides of options for debug/customization. 300 applyCommandLineOverridesToOptions(Options); 301 } 302 303 bool runOnFunction(Function &F) override { 304 if (skipFunction(F) || (PredicateFtor && !PredicateFtor(F))) 305 return false; 306 307 Options.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 308 DominatorTree *DT = nullptr; 309 if (RequireAndPreserveDomTree) 310 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 311 if (F.hasFnAttribute(Attribute::OptForFuzzing)) { 312 Options.setSimplifyCondBranch(false) 313 .setFoldTwoEntryPHINode(false); 314 } else { 315 Options.setSimplifyCondBranch(true) 316 .setFoldTwoEntryPHINode(true); 317 } 318 319 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 320 return simplifyFunctionCFG(F, TTI, DT, Options); 321 } 322 void getAnalysisUsage(AnalysisUsage &AU) const override { 323 AU.addRequired<AssumptionCacheTracker>(); 324 if (RequireAndPreserveDomTree) 325 AU.addRequired<DominatorTreeWrapperPass>(); 326 AU.addRequired<TargetTransformInfoWrapperPass>(); 327 if (RequireAndPreserveDomTree) 328 AU.addPreserved<DominatorTreeWrapperPass>(); 329 AU.addPreserved<GlobalsAAWrapperPass>(); 330 } 331 }; 332 } 333 334 char CFGSimplifyPass::ID = 0; 335 INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false, 336 false) 337 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 338 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 339 INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false, 340 false) 341 342 // Public interface to the CFGSimplification pass 343 FunctionPass * 344 llvm::createCFGSimplificationPass(SimplifyCFGOptions Options, 345 std::function<bool(const Function &)> Ftor) { 346 return new CFGSimplifyPass(Options, std::move(Ftor)); 347 } 348