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