1 //===- UnifyLoopExits.cpp - Redirect exiting edges to one block -*- C++ -*-===// 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 // For each natural loop with multiple exit blocks, this pass creates a new 10 // block N such that all exiting blocks now branch to N, and then control flow 11 // is redistributed to all the original exit blocks. 12 // 13 // Limitation: This assumes that all terminators in the CFG are direct branches 14 // (the "br" instruction). The presence of any other control flow 15 // such as indirectbr, switch or callbr will cause an assert. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Transforms/Utils/UnifyLoopExits.h" 20 #include "llvm/ADT/MapVector.h" 21 #include "llvm/Analysis/LoopInfo.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/Dominators.h" 24 #include "llvm/InitializePasses.h" 25 #include "llvm/Transforms/Utils.h" 26 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 27 28 #define DEBUG_TYPE "unify-loop-exits" 29 30 using namespace llvm; 31 32 namespace { 33 struct UnifyLoopExitsLegacyPass : public FunctionPass { 34 static char ID; 35 UnifyLoopExitsLegacyPass() : FunctionPass(ID) { 36 initializeUnifyLoopExitsLegacyPassPass(*PassRegistry::getPassRegistry()); 37 } 38 39 void getAnalysisUsage(AnalysisUsage &AU) const override { 40 AU.addRequiredID(LowerSwitchID); 41 AU.addRequired<LoopInfoWrapperPass>(); 42 AU.addRequired<DominatorTreeWrapperPass>(); 43 AU.addPreservedID(LowerSwitchID); 44 AU.addPreserved<LoopInfoWrapperPass>(); 45 AU.addPreserved<DominatorTreeWrapperPass>(); 46 } 47 48 bool runOnFunction(Function &F) override; 49 }; 50 } // namespace 51 52 char UnifyLoopExitsLegacyPass::ID = 0; 53 54 FunctionPass *llvm::createUnifyLoopExitsPass() { 55 return new UnifyLoopExitsLegacyPass(); 56 } 57 58 INITIALIZE_PASS_BEGIN(UnifyLoopExitsLegacyPass, "unify-loop-exits", 59 "Fixup each natural loop to have a single exit block", 60 false /* Only looks at CFG */, false /* Analysis Pass */) 61 INITIALIZE_PASS_DEPENDENCY(LowerSwitchLegacyPass) 62 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 63 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 64 INITIALIZE_PASS_END(UnifyLoopExitsLegacyPass, "unify-loop-exits", 65 "Fixup each natural loop to have a single exit block", 66 false /* Only looks at CFG */, false /* Analysis Pass */) 67 68 // The current transform introduces new control flow paths which may break the 69 // SSA requirement that every def must dominate all its uses. For example, 70 // consider a value D defined inside the loop that is used by some instruction 71 // U outside the loop. It follows that D dominates U, since the original 72 // program has valid SSA form. After merging the exits, all paths from D to U 73 // now flow through the unified exit block. In addition, there may be other 74 // paths that do not pass through D, but now reach the unified exit 75 // block. Thus, D no longer dominates U. 76 // 77 // Restore the dominance by creating a phi for each such D at the new unified 78 // loop exit. But when doing this, ignore any uses U that are in the new unified 79 // loop exit, since those were introduced specially when the block was created. 80 // 81 // The use of SSAUpdater seems like overkill for this operation. The location 82 // for creating the new PHI is well-known, and also the set of incoming blocks 83 // to the new PHI. 84 static void restoreSSA(const DominatorTree &DT, const Loop *L, 85 const SetVector<BasicBlock *> &Incoming, 86 BasicBlock *LoopExitBlock) { 87 using InstVector = SmallVector<Instruction *, 8>; 88 using IIMap = MapVector<Instruction *, InstVector>; 89 IIMap ExternalUsers; 90 for (auto BB : L->blocks()) { 91 for (auto &I : *BB) { 92 for (auto &U : I.uses()) { 93 auto UserInst = cast<Instruction>(U.getUser()); 94 auto UserBlock = UserInst->getParent(); 95 if (UserBlock == LoopExitBlock) 96 continue; 97 if (L->contains(UserBlock)) 98 continue; 99 LLVM_DEBUG(dbgs() << "added ext use for " << I.getName() << "(" 100 << BB->getName() << ")" 101 << ": " << UserInst->getName() << "(" 102 << UserBlock->getName() << ")" 103 << "\n"); 104 ExternalUsers[&I].push_back(UserInst); 105 } 106 } 107 } 108 109 for (auto II : ExternalUsers) { 110 // For each Def used outside the loop, create NewPhi in 111 // LoopExitBlock. NewPhi receives Def only along exiting blocks that 112 // dominate it, while the remaining values are undefined since those paths 113 // didn't exist in the original CFG. 114 auto Def = II.first; 115 LLVM_DEBUG(dbgs() << "externally used: " << Def->getName() << "\n"); 116 auto NewPhi = PHINode::Create(Def->getType(), Incoming.size(), 117 Def->getName() + ".moved", 118 LoopExitBlock->getTerminator()); 119 for (auto In : Incoming) { 120 LLVM_DEBUG(dbgs() << "predecessor " << In->getName() << ": "); 121 if (Def->getParent() == In || DT.dominates(Def, In)) { 122 LLVM_DEBUG(dbgs() << "dominated\n"); 123 NewPhi->addIncoming(Def, In); 124 } else { 125 LLVM_DEBUG(dbgs() << "not dominated\n"); 126 NewPhi->addIncoming(UndefValue::get(Def->getType()), In); 127 } 128 } 129 130 LLVM_DEBUG(dbgs() << "external users:"); 131 for (auto U : II.second) { 132 LLVM_DEBUG(dbgs() << " " << U->getName()); 133 U->replaceUsesOfWith(Def, NewPhi); 134 } 135 LLVM_DEBUG(dbgs() << "\n"); 136 } 137 } 138 139 static bool unifyLoopExits(DominatorTree &DT, LoopInfo &LI, Loop *L) { 140 // To unify the loop exits, we need a list of the exiting blocks as 141 // well as exit blocks. The functions for locating these lists both 142 // traverse the entire loop body. It is more efficient to first 143 // locate the exiting blocks and then examine their successors to 144 // locate the exit blocks. 145 SetVector<BasicBlock *> ExitingBlocks; 146 SetVector<BasicBlock *> Exits; 147 148 // We need SetVectors, but the Loop API takes a vector, so we use a temporary. 149 SmallVector<BasicBlock *, 8> Temp; 150 L->getExitingBlocks(Temp); 151 for (auto BB : Temp) { 152 ExitingBlocks.insert(BB); 153 for (auto S : successors(BB)) { 154 auto SL = LI.getLoopFor(S); 155 // A successor is not an exit if it is directly or indirectly in the 156 // current loop. 157 if (SL == L || L->contains(SL)) 158 continue; 159 Exits.insert(S); 160 } 161 } 162 163 LLVM_DEBUG( 164 dbgs() << "Found exit blocks:"; 165 for (auto Exit : Exits) { 166 dbgs() << " " << Exit->getName(); 167 } 168 dbgs() << "\n"; 169 170 dbgs() << "Found exiting blocks:"; 171 for (auto EB : ExitingBlocks) { 172 dbgs() << " " << EB->getName(); 173 } 174 dbgs() << "\n";); 175 176 if (Exits.size() <= 1) { 177 LLVM_DEBUG(dbgs() << "loop does not have multiple exits; nothing to do\n"); 178 return false; 179 } 180 181 SmallVector<BasicBlock *, 8> GuardBlocks; 182 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 183 auto LoopExitBlock = CreateControlFlowHub(&DTU, GuardBlocks, ExitingBlocks, 184 Exits, "loop.exit"); 185 186 restoreSSA(DT, L, ExitingBlocks, LoopExitBlock); 187 188 #if defined(EXPENSIVE_CHECKS) 189 assert(DT.verify(DominatorTree::VerificationLevel::Full)); 190 #else 191 assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 192 #endif // EXPENSIVE_CHECKS 193 L->verifyLoop(); 194 195 // The guard blocks were created outside the loop, so they need to become 196 // members of the parent loop. 197 if (auto ParentLoop = L->getParentLoop()) { 198 for (auto G : GuardBlocks) { 199 ParentLoop->addBasicBlockToLoop(G, LI); 200 } 201 ParentLoop->verifyLoop(); 202 } 203 204 #if defined(EXPENSIVE_CHECKS) 205 LI.verify(DT); 206 #endif // EXPENSIVE_CHECKS 207 208 return true; 209 } 210 211 static bool runImpl(LoopInfo &LI, DominatorTree &DT) { 212 213 bool Changed = false; 214 auto Loops = LI.getLoopsInPreorder(); 215 for (auto L : Loops) { 216 LLVM_DEBUG(dbgs() << "Loop: " << L->getHeader()->getName() << " (depth: " 217 << LI.getLoopDepth(L->getHeader()) << ")\n"); 218 Changed |= unifyLoopExits(DT, LI, L); 219 } 220 return Changed; 221 } 222 223 bool UnifyLoopExitsLegacyPass::runOnFunction(Function &F) { 224 LLVM_DEBUG(dbgs() << "===== Unifying loop exits in function " << F.getName() 225 << "\n"); 226 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 227 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 228 229 return runImpl(LI, DT); 230 } 231 232 namespace llvm { 233 234 PreservedAnalyses UnifyLoopExitsPass::run(Function &F, 235 FunctionAnalysisManager &AM) { 236 auto &LI = AM.getResult<LoopAnalysis>(F); 237 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 238 239 if (!runImpl(LI, DT)) 240 return PreservedAnalyses::all(); 241 PreservedAnalyses PA; 242 PA.preserve<LoopAnalysis>(); 243 PA.preserve<DominatorTreeAnalysis>(); 244 return PA; 245 } 246 } // namespace llvm 247