blob: 5a67178cef37d3c2718b33c9013890d5f866c8b9 [file] [log] [blame]
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +00001///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chandler Carruth6bda14b2017-06-06 11:49:48 +000010#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000011#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000012#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000013#include "llvm/ADT/Sequence.h"
14#include "llvm/ADT/SetVector.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000015#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000016#include "llvm/ADT/SmallVector.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000017#include "llvm/ADT/Statistic.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000018#include "llvm/ADT/Twine.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000019#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth32e62f92018-04-19 18:44:25 +000020#include "llvm/Analysis/CFG.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000021#include "llvm/Analysis/CodeMetrics.h"
Max Kazantsev619a8342018-10-26 14:20:11 +000022#include "llvm/Analysis/GuardUtils.h"
Chandler Carruth4da33312018-06-20 18:57:07 +000023#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000024#include "llvm/Analysis/LoopAnalysisManager.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000025#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth32e62f92018-04-19 18:44:25 +000026#include "llvm/Analysis/LoopIterator.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000027#include "llvm/Analysis/LoopPass.h"
Alina Sbirleaa2eebb82018-12-04 14:23:37 +000028#include "llvm/Analysis/MemorySSA.h"
29#include "llvm/Analysis/MemorySSAUpdater.h"
Chandler Carruth4da33312018-06-20 18:57:07 +000030#include "llvm/Analysis/Utils/Local.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000031#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/Constant.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000033#include "llvm/IR/Constants.h"
34#include "llvm/IR/Dominators.h"
35#include "llvm/IR/Function.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000036#include "llvm/IR/InstrTypes.h"
37#include "llvm/IR/Instruction.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000038#include "llvm/IR/Instructions.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000039#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000040#include "llvm/IR/Use.h"
41#include "llvm/IR/Value.h"
42#include "llvm/Pass.h"
43#include "llvm/Support/Casting.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000044#include "llvm/Support/Debug.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000045#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/GenericDomTree.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000047#include "llvm/Support/raw_ostream.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000048#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000049#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000050#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000051#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000052#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000053#include <algorithm>
54#include <cassert>
55#include <iterator>
Chandler Carruth693eedb2017-11-17 19:58:36 +000056#include <numeric>
Eugene Zelenkoa369a452017-05-16 23:10:25 +000057#include <utility>
Chandler Carruth1353f9a2017-04-27 18:45:20 +000058
59#define DEBUG_TYPE "simple-loop-unswitch"
60
61using namespace llvm;
62
63STATISTIC(NumBranches, "Number of branches unswitched");
64STATISTIC(NumSwitches, "Number of switches unswitched");
Max Kazantsev619a8342018-10-26 14:20:11 +000065STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
Chandler Carruth1353f9a2017-04-27 18:45:20 +000066STATISTIC(NumTrivial, "Number of unswitches that are trivial");
Fedor Sergeev2e3e2242018-11-16 21:16:43 +000067STATISTIC(
68 NumCostMultiplierSkipped,
69 "Number of unswitch candidates that had their cost multiplier skipped");
Chandler Carruth1353f9a2017-04-27 18:45:20 +000070
Chandler Carruth693eedb2017-11-17 19:58:36 +000071static cl::opt<bool> EnableNonTrivialUnswitch(
72 "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
73 cl::desc("Forcibly enables non-trivial loop unswitching rather than "
74 "following the configuration passed into the pass."));
75
76static cl::opt<int>
77 UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
78 cl::desc("The cost threshold for unswitching a loop."));
79
Fedor Sergeev2e3e2242018-11-16 21:16:43 +000080static cl::opt<bool> EnableUnswitchCostMultiplier(
81 "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
82 cl::desc("Enable unswitch cost multiplier that prohibits exponential "
83 "explosion in nontrivial unswitch."));
84static cl::opt<int> UnswitchSiblingsToplevelDiv(
85 "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
86 cl::desc("Toplevel siblings divisor for cost multiplier."));
87static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
88 "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
89 cl::desc("Number of unswitch candidates that are ignored when calculating "
90 "cost multiplier."));
Max Kazantsev619a8342018-10-26 14:20:11 +000091static cl::opt<bool> UnswitchGuards(
92 "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
93 cl::desc("If enabled, simple loop unswitching will also consider "
94 "llvm.experimental.guard intrinsics as unswitch candidates."));
95
Chandler Carruth4da33312018-06-20 18:57:07 +000096/// Collect all of the loop invariant input values transitively used by the
97/// homogeneous instruction graph from a given root.
98///
99/// This essentially walks from a root recursively through loop variant operands
100/// which have the exact same opcode and finds all inputs which are loop
101/// invariant. For some operations these can be re-associated and unswitched out
102/// of the loop entirely.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000103static TinyPtrVector<Value *>
Chandler Carruth4da33312018-06-20 18:57:07 +0000104collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
105 LoopInfo &LI) {
Chandler Carruth4da33312018-06-20 18:57:07 +0000106 assert(!L.isLoopInvariant(&Root) &&
107 "Only need to walk the graph if root itself is not invariant.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000108 TinyPtrVector<Value *> Invariants;
Chandler Carruth4da33312018-06-20 18:57:07 +0000109
110 // Build a worklist and recurse through operators collecting invariants.
111 SmallVector<Instruction *, 4> Worklist;
112 SmallPtrSet<Instruction *, 8> Visited;
113 Worklist.push_back(&Root);
114 Visited.insert(&Root);
115 do {
116 Instruction &I = *Worklist.pop_back_val();
117 for (Value *OpV : I.operand_values()) {
118 // Skip constants as unswitching isn't interesting for them.
119 if (isa<Constant>(OpV))
120 continue;
121
122 // Add it to our result if loop invariant.
123 if (L.isLoopInvariant(OpV)) {
124 Invariants.push_back(OpV);
125 continue;
126 }
127
128 // If not an instruction with the same opcode, nothing we can do.
129 Instruction *OpI = dyn_cast<Instruction>(OpV);
130 if (!OpI || OpI->getOpcode() != Root.getOpcode())
131 continue;
132
133 // Visit this operand.
134 if (Visited.insert(OpI).second)
135 Worklist.push_back(OpI);
136 }
137 } while (!Worklist.empty());
138
139 return Invariants;
140}
141
142static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
143 Constant &Replacement) {
144 assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000145
146 // Replace uses of LIC in the loop with the given constant.
Chandler Carruth4da33312018-06-20 18:57:07 +0000147 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end(); UI != UE;) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000148 // Grab the use and walk past it so we can clobber it in the use list.
149 Use *U = &*UI++;
150 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000151
152 // Replace this use within the loop body.
Chandler Carruth4da33312018-06-20 18:57:07 +0000153 if (UserI && L.contains(UserI))
154 U->set(&Replacement);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000155 }
156}
157
Chandler Carruthd869b182017-05-12 02:19:59 +0000158/// Check that all the LCSSA PHI nodes in the loop exit block have trivial
159/// incoming values along this edge.
160static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
161 BasicBlock &ExitBB) {
162 for (Instruction &I : ExitBB) {
163 auto *PN = dyn_cast<PHINode>(&I);
164 if (!PN)
165 // No more PHIs to check.
166 return true;
167
168 // If the incoming value for this edge isn't loop invariant the unswitch
169 // won't be trivial.
170 if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
171 return false;
172 }
173 llvm_unreachable("Basic blocks should never be empty!");
174}
175
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000176/// Insert code to test a set of loop invariant values, and conditionally branch
177/// on them.
178static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
179 ArrayRef<Value *> Invariants,
180 bool Direction,
181 BasicBlock &UnswitchedSucc,
182 BasicBlock &NormalSucc) {
183 IRBuilder<> IRB(&BB);
184 Value *Cond = Invariants.front();
185 for (Value *Invariant :
186 make_range(std::next(Invariants.begin()), Invariants.end()))
187 if (Direction)
188 Cond = IRB.CreateOr(Cond, Invariant);
189 else
190 Cond = IRB.CreateAnd(Cond, Invariant);
191
192 IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
193 Direction ? &NormalSucc : &UnswitchedSucc);
194}
195
Chandler Carruthd869b182017-05-12 02:19:59 +0000196/// Rewrite the PHI nodes in an unswitched loop exit basic block.
197///
198/// Requires that the loop exit and unswitched basic block are the same, and
199/// that the exiting block was a unique predecessor of that block. Rewrites the
200/// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
201/// PHI nodes from the old preheader that now contains the unswitched
202/// terminator.
203static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
204 BasicBlock &OldExitingBB,
205 BasicBlock &OldPH) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000206 for (PHINode &PN : UnswitchedBB.phis()) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000207 // When the loop exit is directly unswitched we just need to update the
208 // incoming basic block. We loop to handle weird cases with repeated
209 // incoming blocks, but expect to typically only have one operand here.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000210 for (auto i : seq<int>(0, PN.getNumOperands())) {
211 assert(PN.getIncomingBlock(i) == &OldExitingBB &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000212 "Found incoming block different from unique predecessor!");
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000213 PN.setIncomingBlock(i, &OldPH);
Chandler Carruthd869b182017-05-12 02:19:59 +0000214 }
215 }
216}
217
218/// Rewrite the PHI nodes in the loop exit basic block and the split off
219/// unswitched block.
220///
221/// Because the exit block remains an exit from the loop, this rewrites the
222/// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
223/// nodes into the unswitched basic block to select between the value in the
224/// old preheader and the loop exit.
225static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
226 BasicBlock &UnswitchedBB,
227 BasicBlock &OldExitingBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000228 BasicBlock &OldPH,
229 bool FullUnswitch) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000230 assert(&ExitBB != &UnswitchedBB &&
231 "Must have different loop exit and unswitched blocks!");
232 Instruction *InsertPt = &*UnswitchedBB.begin();
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000233 for (PHINode &PN : ExitBB.phis()) {
234 auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
235 PN.getName() + ".split", InsertPt);
Chandler Carruthd869b182017-05-12 02:19:59 +0000236
237 // Walk backwards over the old PHI node's inputs to minimize the cost of
238 // removing each one. We have to do this weird loop manually so that we
239 // create the same number of new incoming edges in the new PHI as we expect
240 // each case-based edge to be included in the unswitched switch in some
241 // cases.
242 // FIXME: This is really, really gross. It would be much cleaner if LLVM
243 // allowed us to create a single entry for a predecessor block without
244 // having separate entries for each "edge" even though these edges are
245 // required to produce identical results.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000246 for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
247 if (PN.getIncomingBlock(i) != &OldExitingBB)
Chandler Carruthd869b182017-05-12 02:19:59 +0000248 continue;
249
Chandler Carruth4da33312018-06-20 18:57:07 +0000250 Value *Incoming = PN.getIncomingValue(i);
251 if (FullUnswitch)
252 // No more edge from the old exiting block to the exit block.
253 PN.removeIncomingValue(i);
254
Chandler Carruthd869b182017-05-12 02:19:59 +0000255 NewPN->addIncoming(Incoming, &OldPH);
256 }
257
258 // Now replace the old PHI with the new one and wire the old one in as an
259 // input to the new one.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000260 PN.replaceAllUsesWith(NewPN);
261 NewPN->addIncoming(&PN, &ExitBB);
Chandler Carruthd869b182017-05-12 02:19:59 +0000262 }
263}
264
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000265/// Hoist the current loop up to the innermost loop containing a remaining exit.
266///
267/// Because we've removed an exit from the loop, we may have changed the set of
268/// loops reachable and need to move the current loop up the loop nest or even
269/// to an entirely separate nest.
270static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
271 DominatorTree &DT, LoopInfo &LI) {
272 // If the loop is already at the top level, we can't hoist it anywhere.
273 Loop *OldParentL = L.getParentLoop();
274 if (!OldParentL)
275 return;
276
277 SmallVector<BasicBlock *, 4> Exits;
278 L.getExitBlocks(Exits);
279 Loop *NewParentL = nullptr;
280 for (auto *ExitBB : Exits)
281 if (Loop *ExitL = LI.getLoopFor(ExitBB))
282 if (!NewParentL || NewParentL->contains(ExitL))
283 NewParentL = ExitL;
284
285 if (NewParentL == OldParentL)
286 return;
287
288 // The new parent loop (if different) should always contain the old one.
289 if (NewParentL)
290 assert(NewParentL->contains(OldParentL) &&
291 "Can only hoist this loop up the nest!");
292
293 // The preheader will need to move with the body of this loop. However,
294 // because it isn't in this loop we also need to update the primary loop map.
295 assert(OldParentL == LI.getLoopFor(&Preheader) &&
296 "Parent loop of this loop should contain this loop's preheader!");
297 LI.changeLoopFor(&Preheader, NewParentL);
298
299 // Remove this loop from its old parent.
300 OldParentL->removeChildLoop(&L);
301
302 // Add the loop either to the new parent or as a top-level loop.
303 if (NewParentL)
304 NewParentL->addChildLoop(&L);
305 else
306 LI.addTopLevelLoop(&L);
307
308 // Remove this loops blocks from the old parent and every other loop up the
309 // nest until reaching the new parent. Also update all of these
310 // no-longer-containing loops to reflect the nesting change.
311 for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
312 OldContainingL = OldContainingL->getParentLoop()) {
313 llvm::erase_if(OldContainingL->getBlocksVector(),
314 [&](const BasicBlock *BB) {
315 return BB == &Preheader || L.contains(BB);
316 });
317
318 OldContainingL->getBlocksSet().erase(&Preheader);
319 for (BasicBlock *BB : L.blocks())
320 OldContainingL->getBlocksSet().erase(BB);
321
322 // Because we just hoisted a loop out of this one, we have essentially
323 // created new exit paths from it. That means we need to form LCSSA PHI
324 // nodes for values used in the no-longer-nested loop.
325 formLCSSA(*OldContainingL, DT, &LI, nullptr);
326
327 // We shouldn't need to form dedicated exits because the exit introduced
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000328 // here is the (just split by unswitching) preheader. However, after trivial
329 // unswitching it is possible to get new non-dedicated exits out of parent
330 // loop so let's conservatively form dedicated exit blocks and figure out
331 // if we can optimize later.
332 formDedicatedExitBlocks(OldContainingL, &DT, &LI, /*PreserveLCSSA*/ true);
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000333 }
334}
335
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000336/// Unswitch a trivial branch if the condition is loop invariant.
337///
338/// This routine should only be called when loop code leading to the branch has
339/// been validated as trivial (no side effects). This routine checks if the
340/// condition is invariant and one of the successors is a loop exit. This
341/// allows us to unswitch without duplicating the loop, making it trivial.
342///
343/// If this routine fails to unswitch the branch it returns false.
344///
345/// If the branch can be unswitched, this routine splits the preheader and
346/// hoists the branch above that split. Preserves loop simplified form
347/// (splitting the exit block as necessary). It simplifies the branch within
348/// the loop to an unconditional branch but doesn't remove it entirely. Further
349/// cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000350///
351/// If `SE` is not null, it will be updated based on the potential loop SCEVs
352/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000353static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000354 LoopInfo &LI, ScalarEvolution *SE,
355 MemorySSAUpdater *MSSAU) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000356 assert(BI.isConditional() && "Can only unswitch a conditional branch!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000357 LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000358
Chandler Carruth4da33312018-06-20 18:57:07 +0000359 // The loop invariant values that we want to unswitch.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000360 TinyPtrVector<Value *> Invariants;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000361
Chandler Carruth4da33312018-06-20 18:57:07 +0000362 // When true, we're fully unswitching the branch rather than just unswitching
363 // some input conditions to the branch.
364 bool FullUnswitch = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000365
Chandler Carruth4da33312018-06-20 18:57:07 +0000366 if (L.isLoopInvariant(BI.getCondition())) {
367 Invariants.push_back(BI.getCondition());
368 FullUnswitch = true;
369 } else {
370 if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
371 Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
372 if (Invariants.empty())
373 // Couldn't find invariant inputs!
374 return false;
375 }
376
377 // Check that one of the branch's successors exits, and which one.
378 bool ExitDirection = true;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000379 int LoopExitSuccIdx = 0;
380 auto *LoopExitBB = BI.getSuccessor(0);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000381 if (L.contains(LoopExitBB)) {
Chandler Carruth4da33312018-06-20 18:57:07 +0000382 ExitDirection = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000383 LoopExitSuccIdx = 1;
384 LoopExitBB = BI.getSuccessor(1);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000385 if (L.contains(LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000386 return false;
387 }
388 auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
Chandler Carruthd869b182017-05-12 02:19:59 +0000389 auto *ParentBB = BI.getParent();
390 if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000391 return false;
392
Chandler Carruth4da33312018-06-20 18:57:07 +0000393 // When unswitching only part of the branch's condition, we need the exit
394 // block to be reached directly from the partially unswitched input. This can
395 // be done when the exit block is along the true edge and the branch condition
396 // is a graph of `or` operations, or the exit block is along the false edge
397 // and the condition is a graph of `and` operations.
398 if (!FullUnswitch) {
399 if (ExitDirection) {
400 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or)
401 return false;
402 } else {
403 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And)
404 return false;
405 }
406 }
407
408 LLVM_DEBUG({
409 dbgs() << " unswitching trivial invariant conditions for: " << BI
410 << "\n";
411 for (Value *Invariant : Invariants) {
412 dbgs() << " " << *Invariant << " == true";
413 if (Invariant != Invariants.back())
414 dbgs() << " ||";
415 dbgs() << "\n";
416 }
417 });
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000418
Chandler Carruth3897ded2018-07-03 09:13:27 +0000419 // If we have scalar evolutions, we need to invalidate them including this
420 // loop and the loop containing the exit block.
421 if (SE) {
422 if (Loop *ExitL = LI.getLoopFor(LoopExitBB))
423 SE->forgetLoop(ExitL);
424 else
425 // Forget the entire nest as this exits the entire nest.
426 SE->forgetTopmostLoop(&L);
427 }
428
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000429 if (MSSAU && VerifyMemorySSA)
430 MSSAU->getMemorySSA()->verifyMemorySSA();
431
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000432 // Split the preheader, so that we know that there is a safe place to insert
433 // the conditional branch. We will change the preheader to have a conditional
434 // branch on LoopCond.
435 BasicBlock *OldPH = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000436 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000437
438 // Now that we have a place to insert the conditional branch, create a place
439 // to branch to: this is the exit block out of the loop that we are
440 // unswitching. We need to split this if there are other loop predecessors.
441 // Because the loop is in simplified form, *any* other predecessor is enough.
442 BasicBlock *UnswitchedBB;
Chandler Carruth4da33312018-06-20 18:57:07 +0000443 if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
444 assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000445 "A branch's parent isn't a predecessor!");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000446 UnswitchedBB = LoopExitBB;
447 } else {
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000448 UnswitchedBB =
449 SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000450 }
451
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000452 if (MSSAU && VerifyMemorySSA)
453 MSSAU->getMemorySSA()->verifyMemorySSA();
454
Chandler Carruth4da33312018-06-20 18:57:07 +0000455 // Actually move the invariant uses into the unswitched position. If possible,
456 // we do this by moving the instructions, but when doing partial unswitching
457 // we do it by building a new merge of the values in the unswitched position.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000458 OldPH->getTerminator()->eraseFromParent();
Chandler Carruth4da33312018-06-20 18:57:07 +0000459 if (FullUnswitch) {
460 // If fully unswitching, we can use the existing branch instruction.
461 // Splice it into the old PH to gate reaching the new preheader and re-point
462 // its successors.
463 OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
464 BI);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000465 if (MSSAU) {
466 // Temporarily clone the terminator, to make MSSA update cheaper by
467 // separating "insert edge" updates from "remove edge" ones.
468 ParentBB->getInstList().push_back(BI.clone());
469 } else {
470 // Create a new unconditional branch that will continue the loop as a new
471 // terminator.
472 BranchInst::Create(ContinueBB, ParentBB);
473 }
Chandler Carruth4da33312018-06-20 18:57:07 +0000474 BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
475 BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
Chandler Carruth4da33312018-06-20 18:57:07 +0000476 } else {
477 // Only unswitching a subset of inputs to the condition, so we will need to
478 // build a new branch that merges the invariant inputs.
Chandler Carruth4da33312018-06-20 18:57:07 +0000479 if (ExitDirection)
480 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
481 Instruction::Or &&
482 "Must have an `or` of `i1`s for the condition!");
483 else
484 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
485 Instruction::And &&
486 "Must have an `and` of `i1`s for the condition!");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000487 buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
488 *UnswitchedBB, *NewPH);
Chandler Carruth4da33312018-06-20 18:57:07 +0000489 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000490
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000491 // Update the dominator tree with the added edge.
492 DT.insertEdge(OldPH, UnswitchedBB);
493
494 // After the dominator tree was updated with the added edge, update MemorySSA
495 // if available.
496 if (MSSAU) {
497 SmallVector<CFGUpdate, 1> Updates;
498 Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
499 MSSAU->applyInsertUpdates(Updates, DT);
500 }
501
502 // Finish updating dominator tree and memory ssa for full unswitch.
503 if (FullUnswitch) {
504 if (MSSAU) {
505 // Remove the cloned branch instruction.
506 ParentBB->getTerminator()->eraseFromParent();
507 // Create unconditional branch now.
508 BranchInst::Create(ContinueBB, ParentBB);
509 MSSAU->removeEdge(ParentBB, LoopExitBB);
510 }
511 DT.deleteEdge(ParentBB, LoopExitBB);
512 }
513
514 if (MSSAU && VerifyMemorySSA)
515 MSSAU->getMemorySSA()->verifyMemorySSA();
516
Chandler Carruthd869b182017-05-12 02:19:59 +0000517 // Rewrite the relevant PHI nodes.
518 if (UnswitchedBB == LoopExitBB)
519 rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
520 else
521 rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000522 *ParentBB, *OldPH, FullUnswitch);
Chandler Carruthd869b182017-05-12 02:19:59 +0000523
Chandler Carruth4da33312018-06-20 18:57:07 +0000524 // The constant we can replace all of our invariants with inside the loop
525 // body. If any of the invariants have a value other than this the loop won't
526 // be entered.
527 ConstantInt *Replacement = ExitDirection
528 ? ConstantInt::getFalse(BI.getContext())
529 : ConstantInt::getTrue(BI.getContext());
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000530
531 // Since this is an i1 condition we can also trivially replace uses of it
532 // within the loop with a constant.
Chandler Carruth4da33312018-06-20 18:57:07 +0000533 for (Value *Invariant : Invariants)
534 replaceLoopInvariantUses(L, Invariant, *Replacement);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000535
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000536 // If this was full unswitching, we may have changed the nesting relationship
537 // for this loop so hoist it to its correct parent if needed.
538 if (FullUnswitch)
539 hoistLoopToNewParent(L, *NewPH, DT, LI);
540
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000541 LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000542 ++NumTrivial;
543 ++NumBranches;
544 return true;
545}
546
547/// Unswitch a trivial switch if the condition is loop invariant.
548///
549/// This routine should only be called when loop code leading to the switch has
550/// been validated as trivial (no side effects). This routine checks if the
551/// condition is invariant and that at least one of the successors is a loop
552/// exit. This allows us to unswitch without duplicating the loop, making it
553/// trivial.
554///
555/// If this routine fails to unswitch the switch it returns false.
556///
557/// If the switch can be unswitched, this routine splits the preheader and
558/// copies the switch above that split. If the default case is one of the
559/// exiting cases, it copies the non-exiting cases and points them at the new
560/// preheader. If the default case is not exiting, it copies the exiting cases
561/// and points the default at the preheader. It preserves loop simplified form
562/// (splitting the exit blocks as necessary). It simplifies the switch within
563/// the loop by removing now-dead cases. If the default case is one of those
564/// unswitched, it replaces its destination with a new basic block containing
565/// only unreachable. Such basic blocks, while technically loop exits, are not
566/// considered for unswitching so this is a stable transform and the same
567/// switch will not be revisited. If after unswitching there is only a single
568/// in-loop successor, the switch is further simplified to an unconditional
569/// branch. Still more cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000570///
571/// If `SE` is not null, it will be updated based on the potential loop SCEVs
572/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000573static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000574 LoopInfo &LI, ScalarEvolution *SE,
575 MemorySSAUpdater *MSSAU) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000576 LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000577 Value *LoopCond = SI.getCondition();
578
579 // If this isn't switching on an invariant condition, we can't unswitch it.
580 if (!L.isLoopInvariant(LoopCond))
581 return false;
582
Chandler Carruthd869b182017-05-12 02:19:59 +0000583 auto *ParentBB = SI.getParent();
584
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000585 SmallVector<int, 4> ExitCaseIndices;
586 for (auto Case : SI.cases()) {
587 auto *SuccBB = Case.getCaseSuccessor();
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000588 if (!L.contains(SuccBB) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000589 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000590 ExitCaseIndices.push_back(Case.getCaseIndex());
591 }
592 BasicBlock *DefaultExitBB = nullptr;
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000593 if (!L.contains(SI.getDefaultDest()) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000594 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) &&
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000595 !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator()))
596 DefaultExitBB = SI.getDefaultDest();
597 else if (ExitCaseIndices.empty())
598 return false;
599
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000600 LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000601
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000602 if (MSSAU && VerifyMemorySSA)
603 MSSAU->getMemorySSA()->verifyMemorySSA();
604
Chandler Carruth3897ded2018-07-03 09:13:27 +0000605 // We may need to invalidate SCEVs for the outermost loop reached by any of
606 // the exits.
607 Loop *OuterL = &L;
608
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000609 if (DefaultExitBB) {
610 // Clear out the default destination temporarily to allow accurate
611 // predecessor lists to be examined below.
612 SI.setDefaultDest(nullptr);
613 // Check the loop containing this exit.
614 Loop *ExitL = LI.getLoopFor(DefaultExitBB);
615 if (!ExitL || ExitL->contains(OuterL))
616 OuterL = ExitL;
617 }
618
619 // Store the exit cases into a separate data structure and remove them from
620 // the switch.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000621 SmallVector<std::pair<ConstantInt *, BasicBlock *>, 4> ExitCases;
622 ExitCases.reserve(ExitCaseIndices.size());
623 // We walk the case indices backwards so that we remove the last case first
624 // and don't disrupt the earlier indices.
625 for (unsigned Index : reverse(ExitCaseIndices)) {
626 auto CaseI = SI.case_begin() + Index;
Chandler Carruth3897ded2018-07-03 09:13:27 +0000627 // Compute the outer loop from this exit.
628 Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
629 if (!ExitL || ExitL->contains(OuterL))
630 OuterL = ExitL;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000631 // Save the value of this case.
632 ExitCases.push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()});
633 // Delete the unswitched cases.
634 SI.removeCase(CaseI);
635 }
636
Chandler Carruth3897ded2018-07-03 09:13:27 +0000637 if (SE) {
638 if (OuterL)
639 SE->forgetLoop(OuterL);
640 else
641 SE->forgetTopmostLoop(&L);
642 }
643
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000644 // Check if after this all of the remaining cases point at the same
645 // successor.
646 BasicBlock *CommonSuccBB = nullptr;
647 if (SI.getNumCases() > 0 &&
648 std::all_of(std::next(SI.case_begin()), SI.case_end(),
649 [&SI](const SwitchInst::CaseHandle &Case) {
650 return Case.getCaseSuccessor() ==
651 SI.case_begin()->getCaseSuccessor();
652 }))
653 CommonSuccBB = SI.case_begin()->getCaseSuccessor();
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000654 if (!DefaultExitBB) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000655 // If we're not unswitching the default, we need it to match any cases to
656 // have a common successor or if we have no cases it is the common
657 // successor.
658 if (SI.getNumCases() == 0)
659 CommonSuccBB = SI.getDefaultDest();
660 else if (SI.getDefaultDest() != CommonSuccBB)
661 CommonSuccBB = nullptr;
662 }
663
664 // Split the preheader, so that we know that there is a safe place to insert
665 // the switch.
666 BasicBlock *OldPH = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000667 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000668 OldPH->getTerminator()->eraseFromParent();
669
670 // Now add the unswitched switch.
671 auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
672
Chandler Carruthd869b182017-05-12 02:19:59 +0000673 // Rewrite the IR for the unswitched basic blocks. This requires two steps.
674 // First, we split any exit blocks with remaining in-loop predecessors. Then
675 // we update the PHIs in one of two ways depending on if there was a split.
676 // We walk in reverse so that we split in the same order as the cases
677 // appeared. This is purely for convenience of reading the resulting IR, but
678 // it doesn't cost anything really.
679 SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000680 SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
681 // Handle the default exit if necessary.
682 // FIXME: It'd be great if we could merge this with the loop below but LLVM's
683 // ranges aren't quite powerful enough yet.
Chandler Carruthd869b182017-05-12 02:19:59 +0000684 if (DefaultExitBB) {
685 if (pred_empty(DefaultExitBB)) {
686 UnswitchedExitBBs.insert(DefaultExitBB);
687 rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
688 } else {
689 auto *SplitBB =
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000690 SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
691 rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
692 *ParentBB, *OldPH,
693 /*FullUnswitch*/ true);
Chandler Carruthd869b182017-05-12 02:19:59 +0000694 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
695 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000696 }
697 // Note that we must use a reference in the for loop so that we update the
698 // container.
699 for (auto &CasePair : reverse(ExitCases)) {
700 // Grab a reference to the exit block in the pair so that we can update it.
Chandler Carruthd869b182017-05-12 02:19:59 +0000701 BasicBlock *ExitBB = CasePair.second;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000702
703 // If this case is the last edge into the exit block, we can simply reuse it
704 // as it will no longer be a loop exit. No mapping necessary.
Chandler Carruthd869b182017-05-12 02:19:59 +0000705 if (pred_empty(ExitBB)) {
706 // Only rewrite once.
707 if (UnswitchedExitBBs.insert(ExitBB).second)
708 rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000709 continue;
Chandler Carruthd869b182017-05-12 02:19:59 +0000710 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000711
712 // Otherwise we need to split the exit block so that we retain an exit
713 // block from the loop and a target for the unswitched condition.
714 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
715 if (!SplitExitBB) {
716 // If this is the first time we see this, do the split and remember it.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000717 SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
718 rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
719 *ParentBB, *OldPH,
720 /*FullUnswitch*/ true);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000721 }
Chandler Carruthd869b182017-05-12 02:19:59 +0000722 // Update the case pair to point to the split block.
723 CasePair.second = SplitExitBB;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000724 }
725
726 // Now add the unswitched cases. We do this in reverse order as we built them
727 // in reverse order.
728 for (auto CasePair : reverse(ExitCases)) {
729 ConstantInt *CaseVal = CasePair.first;
730 BasicBlock *UnswitchedBB = CasePair.second;
731
732 NewSI->addCase(CaseVal, UnswitchedBB);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000733 }
734
735 // If the default was unswitched, re-point it and add explicit cases for
736 // entering the loop.
737 if (DefaultExitBB) {
738 NewSI->setDefaultDest(DefaultExitBB);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000739
740 // We removed all the exit cases, so we just copy the cases to the
741 // unswitched switch.
742 for (auto Case : SI.cases())
743 NewSI->addCase(Case.getCaseValue(), NewPH);
744 }
745
746 // If we ended up with a common successor for every path through the switch
747 // after unswitching, rewrite it to an unconditional branch to make it easy
748 // to recognize. Otherwise we potentially have to recognize the default case
749 // pointing at unreachable and other complexity.
750 if (CommonSuccBB) {
751 BasicBlock *BB = SI.getParent();
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000752 // We may have had multiple edges to this common successor block, so remove
753 // them as predecessors. We skip the first one, either the default or the
754 // actual first case.
755 bool SkippedFirst = DefaultExitBB == nullptr;
756 for (auto Case : SI.cases()) {
757 assert(Case.getCaseSuccessor() == CommonSuccBB &&
758 "Non-common successor!");
Chandler Carruth148861f2018-07-10 08:57:04 +0000759 (void)Case;
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000760 if (!SkippedFirst) {
761 SkippedFirst = true;
762 continue;
763 }
764 CommonSuccBB->removePredecessor(BB,
765 /*DontDeleteUselessPHIs*/ true);
766 }
767 // Now nuke the switch and replace it with a direct branch.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000768 SI.eraseFromParent();
769 BranchInst::Create(CommonSuccBB, BB);
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000770 } else if (DefaultExitBB) {
771 assert(SI.getNumCases() > 0 &&
772 "If we had no cases we'd have a common successor!");
773 // Move the last case to the default successor. This is valid as if the
774 // default got unswitched it cannot be reached. This has the advantage of
775 // being simple and keeping the number of edges from this switch to
776 // successors the same, and avoiding any PHI update complexity.
777 auto LastCaseI = std::prev(SI.case_end());
778 SI.setDefaultDest(LastCaseI->getCaseSuccessor());
779 SI.removeCase(LastCaseI);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000780 }
781
Chandler Carruth2c85a232018-05-01 09:54:39 +0000782 // Walk the unswitched exit blocks and the unswitched split blocks and update
783 // the dominator tree based on the CFG edits. While we are walking unordered
784 // containers here, the API for applyUpdates takes an unordered list of
785 // updates and requires them to not contain duplicates.
786 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
787 for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
788 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
789 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
790 }
791 for (auto SplitUnswitchedPair : SplitExitBBMap) {
792 auto *UnswitchedBB = SplitUnswitchedPair.second;
793 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedBB});
794 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedBB});
795 }
796 DT.applyUpdates(DTUpdates);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000797
798 if (MSSAU) {
799 MSSAU->applyUpdates(DTUpdates, DT);
800 if (VerifyMemorySSA)
801 MSSAU->getMemorySSA()->verifyMemorySSA();
802 }
803
David Green7c35de12018-02-28 11:00:08 +0000804 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000805
806 // We may have changed the nesting relationship for this loop so hoist it to
807 // its correct parent if needed.
808 hoistLoopToNewParent(L, *NewPH, DT, LI);
809
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000810 ++NumTrivial;
811 ++NumSwitches;
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000812 LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000813 return true;
814}
815
816/// This routine scans the loop to find a branch or switch which occurs before
817/// any side effects occur. These can potentially be unswitched without
818/// duplicating the loop. If a branch or switch is successfully unswitched the
819/// scanning continues to see if subsequent branches or switches have become
820/// trivial. Once all trivial candidates have been unswitched, this routine
821/// returns.
822///
823/// The return value indicates whether anything was unswitched (and therefore
824/// changed).
Chandler Carruth3897ded2018-07-03 09:13:27 +0000825///
826/// If `SE` is not null, it will be updated based on the potential loop SCEVs
827/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000828static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000829 LoopInfo &LI, ScalarEvolution *SE,
830 MemorySSAUpdater *MSSAU) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000831 bool Changed = false;
832
833 // If loop header has only one reachable successor we should keep looking for
834 // trivial condition candidates in the successor as well. An alternative is
835 // to constant fold conditions and merge successors into loop header (then we
836 // only need to check header's terminator). The reason for not doing this in
837 // LoopUnswitch pass is that it could potentially break LoopPassManager's
838 // invariants. Folding dead branches could either eliminate the current loop
839 // or make other loops unreachable. LCSSA form might also not be preserved
840 // after deleting branches. The following code keeps traversing loop header's
841 // successors until it finds the trivial condition candidate (condition that
842 // is not a constant). Since unswitching generates branches with constant
843 // conditions, this scenario could be very common in practice.
844 BasicBlock *CurrentBB = L.getHeader();
845 SmallPtrSet<BasicBlock *, 8> Visited;
846 Visited.insert(CurrentBB);
847 do {
848 // Check if there are any side-effecting instructions (e.g. stores, calls,
849 // volatile loads) in the part of the loop that the code *would* execute
850 // without unswitching.
851 if (llvm::any_of(*CurrentBB,
852 [](Instruction &I) { return I.mayHaveSideEffects(); }))
853 return Changed;
854
Chandler Carruthedb12a82018-10-15 10:04:59 +0000855 Instruction *CurrentTerm = CurrentBB->getTerminator();
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000856
857 if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
858 // Don't bother trying to unswitch past a switch with a constant
859 // condition. This should be removed prior to running this pass by
860 // simplify-cfg.
861 if (isa<Constant>(SI->getCondition()))
862 return Changed;
863
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000864 if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
Hiroshi Inouef2096492018-06-14 05:41:49 +0000865 // Couldn't unswitch this one so we're done.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000866 return Changed;
867
868 // Mark that we managed to unswitch something.
869 Changed = true;
870
871 // If unswitching turned the terminator into an unconditional branch then
872 // we can continue. The unswitching logic specifically works to fold any
873 // cases it can into an unconditional branch to make it easier to
874 // recognize here.
875 auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
876 if (!BI || BI->isConditional())
877 return Changed;
878
879 CurrentBB = BI->getSuccessor(0);
880 continue;
881 }
882
883 auto *BI = dyn_cast<BranchInst>(CurrentTerm);
884 if (!BI)
885 // We do not understand other terminator instructions.
886 return Changed;
887
888 // Don't bother trying to unswitch past an unconditional branch or a branch
889 // with a constant value. These should be removed by simplify-cfg prior to
890 // running this pass.
891 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
892 return Changed;
893
894 // Found a trivial condition candidate: non-foldable conditional branch. If
895 // we fail to unswitch this, we can't do anything else that is trivial.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000896 if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000897 return Changed;
898
899 // Mark that we managed to unswitch something.
900 Changed = true;
901
Chandler Carruth4da33312018-06-20 18:57:07 +0000902 // If we only unswitched some of the conditions feeding the branch, we won't
903 // have collapsed it to a single successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000904 BI = cast<BranchInst>(CurrentBB->getTerminator());
Chandler Carruth4da33312018-06-20 18:57:07 +0000905 if (BI->isConditional())
906 return Changed;
907
908 // Follow the newly unconditional branch into its successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000909 CurrentBB = BI->getSuccessor(0);
910
911 // When continuing, if we exit the loop or reach a previous visited block,
912 // then we can not reach any trivial condition candidates (unfoldable
913 // branch instructions or switch instructions) and no unswitch can happen.
914 } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
915
916 return Changed;
917}
918
Chandler Carruth693eedb2017-11-17 19:58:36 +0000919/// Build the cloned blocks for an unswitched copy of the given loop.
920///
921/// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
922/// after the split block (`SplitBB`) that will be used to select between the
923/// cloned and original loop.
924///
925/// This routine handles cloning all of the necessary loop blocks and exit
926/// blocks including rewriting their instructions and the relevant PHI nodes.
Chandler Carruth16529962018-06-25 23:32:54 +0000927/// Any loop blocks or exit blocks which are dominated by a different successor
928/// than the one for this clone of the loop blocks can be trivially skipped. We
929/// use the `DominatingSucc` map to determine whether a block satisfies that
930/// property with a simple map lookup.
931///
932/// It also correctly creates the unconditional branch in the cloned
Chandler Carruth693eedb2017-11-17 19:58:36 +0000933/// unswitched parent block to only point at the unswitched successor.
934///
935/// This does not handle most of the necessary updates to `LoopInfo`. Only exit
936/// block splitting is correctly reflected in `LoopInfo`, essentially all of
937/// the cloned blocks (and their loops) are left without full `LoopInfo`
938/// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
939/// blocks to them but doesn't create the cloned `DominatorTree` structure and
940/// instead the caller must recompute an accurate DT. It *does* correctly
941/// update the `AssumptionCache` provided in `AC`.
942static BasicBlock *buildClonedLoopBlocks(
943 Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
944 ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
945 BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
Chandler Carruth16529962018-06-25 23:32:54 +0000946 const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
Chandler Carruth69e68f82018-04-25 00:18:07 +0000947 ValueToValueMapTy &VMap,
948 SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000949 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Chandler Carruth693eedb2017-11-17 19:58:36 +0000950 SmallVector<BasicBlock *, 4> NewBlocks;
951 NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
952
953 // We will need to clone a bunch of blocks, wrap up the clone operation in
954 // a helper.
955 auto CloneBlock = [&](BasicBlock *OldBB) {
956 // Clone the basic block and insert it before the new preheader.
957 BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
958 NewBB->moveBefore(LoopPH);
959
960 // Record this block and the mapping.
961 NewBlocks.push_back(NewBB);
962 VMap[OldBB] = NewBB;
963
Chandler Carruth693eedb2017-11-17 19:58:36 +0000964 return NewBB;
965 };
966
Chandler Carruth16529962018-06-25 23:32:54 +0000967 // We skip cloning blocks when they have a dominating succ that is not the
968 // succ we are cloning for.
969 auto SkipBlock = [&](BasicBlock *BB) {
970 auto It = DominatingSucc.find(BB);
971 return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
972 };
973
Chandler Carruth693eedb2017-11-17 19:58:36 +0000974 // First, clone the preheader.
975 auto *ClonedPH = CloneBlock(LoopPH);
976
977 // Then clone all the loop blocks, skipping the ones that aren't necessary.
978 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +0000979 if (!SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +0000980 CloneBlock(LoopBB);
981
982 // Split all the loop exit edges so that when we clone the exit blocks, if
983 // any of the exit blocks are *also* a preheader for some other loop, we
984 // don't create multiple predecessors entering the loop header.
985 for (auto *ExitBB : ExitBlocks) {
Chandler Carruth16529962018-06-25 23:32:54 +0000986 if (SkipBlock(ExitBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +0000987 continue;
988
989 // When we are going to clone an exit, we don't need to clone all the
990 // instructions in the exit block and we want to ensure we have an easy
991 // place to merge the CFG, so split the exit first. This is always safe to
992 // do because there cannot be any non-loop predecessors of a loop exit in
993 // loop simplified form.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000994 auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
Chandler Carruth693eedb2017-11-17 19:58:36 +0000995
996 // Rearrange the names to make it easier to write test cases by having the
997 // exit block carry the suffix rather than the merge block carrying the
998 // suffix.
999 MergeBB->takeName(ExitBB);
1000 ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1001
1002 // Now clone the original exit block.
1003 auto *ClonedExitBB = CloneBlock(ExitBB);
1004 assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1005 "Exit block should have been split to have one successor!");
1006 assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1007 "Cloned exit block has the wrong successor!");
1008
Chandler Carruth693eedb2017-11-17 19:58:36 +00001009 // Remap any cloned instructions and create a merge phi node for them.
1010 for (auto ZippedInsts : llvm::zip_first(
1011 llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1012 llvm::make_range(ClonedExitBB->begin(),
1013 std::prev(ClonedExitBB->end())))) {
1014 Instruction &I = std::get<0>(ZippedInsts);
1015 Instruction &ClonedI = std::get<1>(ZippedInsts);
1016
1017 // The only instructions in the exit block should be PHI nodes and
1018 // potentially a landing pad.
1019 assert(
1020 (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1021 "Bad instruction in exit block!");
1022 // We should have a value map between the instruction and its clone.
1023 assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1024
1025 auto *MergePN =
1026 PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1027 &*MergeBB->getFirstInsertionPt());
1028 I.replaceAllUsesWith(MergePN);
1029 MergePN->addIncoming(&I, ExitBB);
1030 MergePN->addIncoming(&ClonedI, ClonedExitBB);
1031 }
1032 }
1033
1034 // Rewrite the instructions in the cloned blocks to refer to the instructions
1035 // in the cloned blocks. We have to do this as a second pass so that we have
1036 // everything available. Also, we have inserted new instructions which may
1037 // include assume intrinsics, so we update the assumption cache while
1038 // processing this.
1039 for (auto *ClonedBB : NewBlocks)
1040 for (Instruction &I : *ClonedBB) {
1041 RemapInstruction(&I, VMap,
1042 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1043 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1044 if (II->getIntrinsicID() == Intrinsic::assume)
1045 AC.registerAssumption(II);
1046 }
1047
Chandler Carruth693eedb2017-11-17 19:58:36 +00001048 // Update any PHI nodes in the cloned successors of the skipped blocks to not
1049 // have spurious incoming values.
1050 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +00001051 if (SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001052 for (auto *SuccBB : successors(LoopBB))
1053 if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1054 for (PHINode &PN : ClonedSuccBB->phis())
1055 PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1056
Chandler Carruthed296542018-07-09 10:30:48 +00001057 // Remove the cloned parent as a predecessor of any successor we ended up
1058 // cloning other than the unswitched one.
1059 auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1060 for (auto *SuccBB : successors(ParentBB)) {
1061 if (SuccBB == UnswitchedSuccBB)
1062 continue;
1063
1064 auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1065 if (!ClonedSuccBB)
1066 continue;
1067
1068 ClonedSuccBB->removePredecessor(ClonedParentBB,
1069 /*DontDeleteUselessPHIs*/ true);
1070 }
1071
1072 // Replace the cloned branch with an unconditional branch to the cloned
1073 // unswitched successor.
1074 auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1075 ClonedParentBB->getTerminator()->eraseFromParent();
1076 BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1077
1078 // If there are duplicate entries in the PHI nodes because of multiple edges
1079 // to the unswitched successor, we need to nuke all but one as we replaced it
1080 // with a direct branch.
1081 for (PHINode &PN : ClonedSuccBB->phis()) {
1082 bool Found = false;
1083 // Loop over the incoming operands backwards so we can easily delete as we
1084 // go without invalidating the index.
1085 for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1086 if (PN.getIncomingBlock(i) != ClonedParentBB)
1087 continue;
1088 if (!Found) {
1089 Found = true;
1090 continue;
1091 }
1092 PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1093 }
1094 }
1095
Chandler Carruth69e68f82018-04-25 00:18:07 +00001096 // Record the domtree updates for the new blocks.
Chandler Carruth44aab922018-05-01 09:42:09 +00001097 SmallPtrSet<BasicBlock *, 4> SuccSet;
1098 for (auto *ClonedBB : NewBlocks) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001099 for (auto *SuccBB : successors(ClonedBB))
Chandler Carruth44aab922018-05-01 09:42:09 +00001100 if (SuccSet.insert(SuccBB).second)
1101 DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1102 SuccSet.clear();
1103 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001104
Chandler Carruth693eedb2017-11-17 19:58:36 +00001105 return ClonedPH;
1106}
1107
1108/// Recursively clone the specified loop and all of its children.
1109///
1110/// The target parent loop for the clone should be provided, or can be null if
1111/// the clone is a top-level loop. While cloning, all the blocks are mapped
1112/// with the provided value map. The entire original loop must be present in
1113/// the value map. The cloned loop is returned.
1114static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1115 const ValueToValueMapTy &VMap, LoopInfo &LI) {
1116 auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1117 assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1118 ClonedL.reserveBlocks(OrigL.getNumBlocks());
1119 for (auto *BB : OrigL.blocks()) {
1120 auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1121 ClonedL.addBlockEntry(ClonedBB);
Chandler Carruth0ace1482018-04-24 03:27:00 +00001122 if (LI.getLoopFor(BB) == &OrigL)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001123 LI.changeLoopFor(ClonedBB, &ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001124 }
1125 };
1126
1127 // We specially handle the first loop because it may get cloned into
1128 // a different parent and because we most commonly are cloning leaf loops.
1129 Loop *ClonedRootL = LI.AllocateLoop();
1130 if (RootParentL)
1131 RootParentL->addChildLoop(ClonedRootL);
1132 else
1133 LI.addTopLevelLoop(ClonedRootL);
1134 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1135
1136 if (OrigRootL.empty())
1137 return ClonedRootL;
1138
1139 // If we have a nest, we can quickly clone the entire loop nest using an
1140 // iterative approach because it is a tree. We keep the cloned parent in the
1141 // data structure to avoid repeatedly querying through a map to find it.
1142 SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1143 // Build up the loops to clone in reverse order as we'll clone them from the
1144 // back.
1145 for (Loop *ChildL : llvm::reverse(OrigRootL))
1146 LoopsToClone.push_back({ClonedRootL, ChildL});
1147 do {
1148 Loop *ClonedParentL, *L;
1149 std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1150 Loop *ClonedL = LI.AllocateLoop();
1151 ClonedParentL->addChildLoop(ClonedL);
1152 AddClonedBlocksToLoop(*L, *ClonedL);
1153 for (Loop *ChildL : llvm::reverse(*L))
1154 LoopsToClone.push_back({ClonedL, ChildL});
1155 } while (!LoopsToClone.empty());
1156
1157 return ClonedRootL;
1158}
1159
1160/// Build the cloned loops of an original loop from unswitching.
1161///
1162/// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1163/// operation. We need to re-verify that there even is a loop (as the backedge
1164/// may not have been cloned), and even if there are remaining backedges the
1165/// backedge set may be different. However, we know that each child loop is
1166/// undisturbed, we only need to find where to place each child loop within
1167/// either any parent loop or within a cloned version of the original loop.
1168///
1169/// Because child loops may end up cloned outside of any cloned version of the
1170/// original loop, multiple cloned sibling loops may be created. All of them
1171/// are returned so that the newly introduced loop nest roots can be
1172/// identified.
Chandler Carruth92815032018-06-02 01:29:01 +00001173static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1174 const ValueToValueMapTy &VMap, LoopInfo &LI,
1175 SmallVectorImpl<Loop *> &NonChildClonedLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00001176 Loop *ClonedL = nullptr;
1177
1178 auto *OrigPH = OrigL.getLoopPreheader();
1179 auto *OrigHeader = OrigL.getHeader();
1180
1181 auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1182 auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1183
1184 // We need to know the loops of the cloned exit blocks to even compute the
1185 // accurate parent loop. If we only clone exits to some parent of the
1186 // original parent, we want to clone into that outer loop. We also keep track
1187 // of the loops that our cloned exit blocks participate in.
1188 Loop *ParentL = nullptr;
1189 SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1190 SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1191 ClonedExitsInLoops.reserve(ExitBlocks.size());
1192 for (auto *ExitBB : ExitBlocks)
1193 if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1194 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1195 ExitLoopMap[ClonedExitBB] = ExitL;
1196 ClonedExitsInLoops.push_back(ClonedExitBB);
1197 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1198 ParentL = ExitL;
1199 }
1200 assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1201 ParentL->contains(OrigL.getParentLoop())) &&
1202 "The computed parent loop should always contain (or be) the parent of "
1203 "the original loop.");
1204
1205 // We build the set of blocks dominated by the cloned header from the set of
1206 // cloned blocks out of the original loop. While not all of these will
1207 // necessarily be in the cloned loop, it is enough to establish that they
1208 // aren't in unreachable cycles, etc.
1209 SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1210 for (auto *BB : OrigL.blocks())
1211 if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1212 ClonedLoopBlocks.insert(ClonedBB);
1213
1214 // Rebuild the set of blocks that will end up in the cloned loop. We may have
1215 // skipped cloning some region of this loop which can in turn skip some of
1216 // the backedges so we have to rebuild the blocks in the loop based on the
1217 // backedges that remain after cloning.
1218 SmallVector<BasicBlock *, 16> Worklist;
1219 SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1220 for (auto *Pred : predecessors(ClonedHeader)) {
1221 // The only possible non-loop header predecessor is the preheader because
1222 // we know we cloned the loop in simplified form.
1223 if (Pred == ClonedPH)
1224 continue;
1225
1226 // Because the loop was in simplified form, the only non-loop predecessor
1227 // should be the preheader.
1228 assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1229 "header other than the preheader "
1230 "that is not part of the loop!");
1231
1232 // Insert this block into the loop set and on the first visit (and if it
1233 // isn't the header we're currently walking) put it into the worklist to
1234 // recurse through.
1235 if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1236 Worklist.push_back(Pred);
1237 }
1238
1239 // If we had any backedges then there *is* a cloned loop. Put the header into
1240 // the loop set and then walk the worklist backwards to find all the blocks
1241 // that remain within the loop after cloning.
1242 if (!BlocksInClonedLoop.empty()) {
1243 BlocksInClonedLoop.insert(ClonedHeader);
1244
1245 while (!Worklist.empty()) {
1246 BasicBlock *BB = Worklist.pop_back_val();
1247 assert(BlocksInClonedLoop.count(BB) &&
1248 "Didn't put block into the loop set!");
1249
1250 // Insert any predecessors that are in the possible set into the cloned
1251 // set, and if the insert is successful, add them to the worklist. Note
1252 // that we filter on the blocks that are definitely reachable via the
1253 // backedge to the loop header so we may prune out dead code within the
1254 // cloned loop.
1255 for (auto *Pred : predecessors(BB))
1256 if (ClonedLoopBlocks.count(Pred) &&
1257 BlocksInClonedLoop.insert(Pred).second)
1258 Worklist.push_back(Pred);
1259 }
1260
1261 ClonedL = LI.AllocateLoop();
1262 if (ParentL) {
1263 ParentL->addBasicBlockToLoop(ClonedPH, LI);
1264 ParentL->addChildLoop(ClonedL);
1265 } else {
1266 LI.addTopLevelLoop(ClonedL);
1267 }
Chandler Carruth92815032018-06-02 01:29:01 +00001268 NonChildClonedLoops.push_back(ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001269
1270 ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1271 // We don't want to just add the cloned loop blocks based on how we
1272 // discovered them. The original order of blocks was carefully built in
1273 // a way that doesn't rely on predecessor ordering. Rather than re-invent
1274 // that logic, we just re-walk the original blocks (and those of the child
1275 // loops) and filter them as we add them into the cloned loop.
1276 for (auto *BB : OrigL.blocks()) {
1277 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1278 if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1279 continue;
1280
1281 // Directly add the blocks that are only in this loop.
1282 if (LI.getLoopFor(BB) == &OrigL) {
1283 ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1284 continue;
1285 }
1286
1287 // We want to manually add it to this loop and parents.
1288 // Registering it with LoopInfo will happen when we clone the top
1289 // loop for this block.
1290 for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1291 PL->addBlockEntry(ClonedBB);
1292 }
1293
1294 // Now add each child loop whose header remains within the cloned loop. All
1295 // of the blocks within the loop must satisfy the same constraints as the
1296 // header so once we pass the header checks we can just clone the entire
1297 // child loop nest.
1298 for (Loop *ChildL : OrigL) {
1299 auto *ClonedChildHeader =
1300 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1301 if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1302 continue;
1303
1304#ifndef NDEBUG
1305 // We should never have a cloned child loop header but fail to have
1306 // all of the blocks for that child loop.
1307 for (auto *ChildLoopBB : ChildL->blocks())
1308 assert(BlocksInClonedLoop.count(
1309 cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1310 "Child cloned loop has a header within the cloned outer "
1311 "loop but not all of its blocks!");
1312#endif
1313
1314 cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1315 }
1316 }
1317
1318 // Now that we've handled all the components of the original loop that were
1319 // cloned into a new loop, we still need to handle anything from the original
1320 // loop that wasn't in a cloned loop.
1321
1322 // Figure out what blocks are left to place within any loop nest containing
1323 // the unswitched loop. If we never formed a loop, the cloned PH is one of
1324 // them.
1325 SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1326 if (BlocksInClonedLoop.empty())
1327 UnloopedBlockSet.insert(ClonedPH);
1328 for (auto *ClonedBB : ClonedLoopBlocks)
1329 if (!BlocksInClonedLoop.count(ClonedBB))
1330 UnloopedBlockSet.insert(ClonedBB);
1331
1332 // Copy the cloned exits and sort them in ascending loop depth, we'll work
1333 // backwards across these to process them inside out. The order shouldn't
1334 // matter as we're just trying to build up the map from inside-out; we use
1335 // the map in a more stably ordered way below.
1336 auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
Fangrui Song0cac7262018-09-27 02:13:45 +00001337 llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1338 return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1339 ExitLoopMap.lookup(RHS)->getLoopDepth();
1340 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001341
1342 // Populate the existing ExitLoopMap with everything reachable from each
1343 // exit, starting from the inner most exit.
1344 while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1345 assert(Worklist.empty() && "Didn't clear worklist!");
1346
1347 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1348 Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1349
1350 // Walk the CFG back until we hit the cloned PH adding everything reachable
1351 // and in the unlooped set to this exit block's loop.
1352 Worklist.push_back(ExitBB);
1353 do {
1354 BasicBlock *BB = Worklist.pop_back_val();
1355 // We can stop recursing at the cloned preheader (if we get there).
1356 if (BB == ClonedPH)
1357 continue;
1358
1359 for (BasicBlock *PredBB : predecessors(BB)) {
1360 // If this pred has already been moved to our set or is part of some
1361 // (inner) loop, no update needed.
1362 if (!UnloopedBlockSet.erase(PredBB)) {
1363 assert(
1364 (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1365 "Predecessor not mapped to a loop!");
1366 continue;
1367 }
1368
1369 // We just insert into the loop set here. We'll add these blocks to the
1370 // exit loop after we build up the set in an order that doesn't rely on
1371 // predecessor order (which in turn relies on use list order).
1372 bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1373 (void)Inserted;
1374 assert(Inserted && "Should only visit an unlooped block once!");
1375
1376 // And recurse through to its predecessors.
1377 Worklist.push_back(PredBB);
1378 }
1379 } while (!Worklist.empty());
1380 }
1381
1382 // Now that the ExitLoopMap gives as mapping for all the non-looping cloned
1383 // blocks to their outer loops, walk the cloned blocks and the cloned exits
1384 // in their original order adding them to the correct loop.
1385
1386 // We need a stable insertion order. We use the order of the original loop
1387 // order and map into the correct parent loop.
1388 for (auto *BB : llvm::concat<BasicBlock *const>(
1389 makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1390 if (Loop *OuterL = ExitLoopMap.lookup(BB))
1391 OuterL->addBasicBlockToLoop(BB, LI);
1392
1393#ifndef NDEBUG
1394 for (auto &BBAndL : ExitLoopMap) {
1395 auto *BB = BBAndL.first;
1396 auto *OuterL = BBAndL.second;
1397 assert(LI.getLoopFor(BB) == OuterL &&
1398 "Failed to put all blocks into outer loops!");
1399 }
1400#endif
1401
1402 // Now that all the blocks are placed into the correct containing loop in the
1403 // absence of child loops, find all the potentially cloned child loops and
1404 // clone them into whatever outer loop we placed their header into.
1405 for (Loop *ChildL : OrigL) {
1406 auto *ClonedChildHeader =
1407 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1408 if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1409 continue;
1410
1411#ifndef NDEBUG
1412 for (auto *ChildLoopBB : ChildL->blocks())
1413 assert(VMap.count(ChildLoopBB) &&
1414 "Cloned a child loop header but not all of that loops blocks!");
1415#endif
1416
1417 NonChildClonedLoops.push_back(cloneLoopNest(
1418 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1419 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001420}
1421
Chandler Carruth69e68f82018-04-25 00:18:07 +00001422static void
Chandler Carruth16529962018-06-25 23:32:54 +00001423deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1424 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001425 DominatorTree &DT, MemorySSAUpdater *MSSAU) {
Chandler Carruth16529962018-06-25 23:32:54 +00001426 // Find all the dead clones, and remove them from their successors.
1427 SmallVector<BasicBlock *, 16> DeadBlocks;
1428 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1429 for (auto &VMap : VMaps)
1430 if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1431 if (!DT.isReachableFromEntry(ClonedBB)) {
1432 for (BasicBlock *SuccBB : successors(ClonedBB))
1433 SuccBB->removePredecessor(ClonedBB);
1434 DeadBlocks.push_back(ClonedBB);
1435 }
1436
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001437 // Remove all MemorySSA in the dead blocks
1438 if (MSSAU) {
1439 SmallPtrSet<BasicBlock *, 16> DeadBlockSet(DeadBlocks.begin(),
1440 DeadBlocks.end());
1441 MSSAU->removeBlocks(DeadBlockSet);
1442 }
1443
Chandler Carruth16529962018-06-25 23:32:54 +00001444 // Drop any remaining references to break cycles.
1445 for (BasicBlock *BB : DeadBlocks)
1446 BB->dropAllReferences();
1447 // Erase them from the IR.
1448 for (BasicBlock *BB : DeadBlocks)
1449 BB->eraseFromParent();
1450}
1451
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001452static void deleteDeadBlocksFromLoop(Loop &L,
1453 SmallVectorImpl<BasicBlock *> &ExitBlocks,
1454 DominatorTree &DT, LoopInfo &LI,
1455 MemorySSAUpdater *MSSAU) {
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001456 // Find all the dead blocks tied to this loop, and remove them from their
1457 // successors.
1458 SmallPtrSet<BasicBlock *, 16> DeadBlockSet;
1459
1460 // Start with loop/exit blocks and get a transitive closure of reachable dead
1461 // blocks.
1462 SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
1463 ExitBlocks.end());
1464 DeathCandidates.append(L.blocks().begin(), L.blocks().end());
1465 while (!DeathCandidates.empty()) {
1466 auto *BB = DeathCandidates.pop_back_val();
1467 if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
1468 for (BasicBlock *SuccBB : successors(BB)) {
Chandler Carruth16529962018-06-25 23:32:54 +00001469 SuccBB->removePredecessor(BB);
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001470 DeathCandidates.push_back(SuccBB);
Fedor Sergeev7b49aa02018-08-29 19:10:44 +00001471 }
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001472 DeadBlockSet.insert(BB);
1473 }
1474 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001475
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001476 // Remove all MemorySSA in the dead blocks
1477 if (MSSAU)
1478 MSSAU->removeBlocks(DeadBlockSet);
1479
Chandler Carruth693eedb2017-11-17 19:58:36 +00001480 // Filter out the dead blocks from the exit blocks list so that it can be
1481 // used in the caller.
1482 llvm::erase_if(ExitBlocks,
Chandler Carruth69e68f82018-04-25 00:18:07 +00001483 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001484
Chandler Carruth693eedb2017-11-17 19:58:36 +00001485 // Walk from this loop up through its parents removing all of the dead blocks.
1486 for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001487 for (auto *BB : DeadBlockSet)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001488 ParentL->getBlocksSet().erase(BB);
1489 llvm::erase_if(ParentL->getBlocksVector(),
Chandler Carruth69e68f82018-04-25 00:18:07 +00001490 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001491 }
1492
1493 // Now delete the dead child loops. This raw delete will clear them
1494 // recursively.
1495 llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001496 if (!DeadBlockSet.count(ChildL->getHeader()))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001497 return false;
1498
1499 assert(llvm::all_of(ChildL->blocks(),
1500 [&](BasicBlock *ChildBB) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001501 return DeadBlockSet.count(ChildBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001502 }) &&
1503 "If the child loop header is dead all blocks in the child loop must "
1504 "be dead as well!");
1505 LI.destroy(ChildL);
1506 return true;
1507 });
1508
Chandler Carruth69e68f82018-04-25 00:18:07 +00001509 // Remove the loop mappings for the dead blocks and drop all the references
1510 // from these blocks to others to handle cyclic references as we start
1511 // deleting the blocks themselves.
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001512 for (auto *BB : DeadBlockSet) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001513 // Check that the dominator tree has already been updated.
1514 assert(!DT.getNode(BB) && "Should already have cleared domtree!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001515 LI.changeLoopFor(BB, nullptr);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001516 BB->dropAllReferences();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001517 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001518
1519 // Actually delete the blocks now that they've been fully unhooked from the
1520 // IR.
Fedor Sergeev7b49aa02018-08-29 19:10:44 +00001521 for (auto *BB : DeadBlockSet)
Chandler Carruth69e68f82018-04-25 00:18:07 +00001522 BB->eraseFromParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001523}
1524
1525/// Recompute the set of blocks in a loop after unswitching.
1526///
1527/// This walks from the original headers predecessors to rebuild the loop. We
1528/// take advantage of the fact that new blocks can't have been added, and so we
1529/// filter by the original loop's blocks. This also handles potentially
1530/// unreachable code that we don't want to explore but might be found examining
1531/// the predecessors of the header.
1532///
1533/// If the original loop is no longer a loop, this will return an empty set. If
1534/// it remains a loop, all the blocks within it will be added to the set
1535/// (including those blocks in inner loops).
1536static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1537 LoopInfo &LI) {
1538 SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1539
1540 auto *PH = L.getLoopPreheader();
1541 auto *Header = L.getHeader();
1542
1543 // A worklist to use while walking backwards from the header.
1544 SmallVector<BasicBlock *, 16> Worklist;
1545
1546 // First walk the predecessors of the header to find the backedges. This will
1547 // form the basis of our walk.
1548 for (auto *Pred : predecessors(Header)) {
1549 // Skip the preheader.
1550 if (Pred == PH)
1551 continue;
1552
1553 // Because the loop was in simplified form, the only non-loop predecessor
1554 // is the preheader.
1555 assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1556 "than the preheader that is not part of the "
1557 "loop!");
1558
1559 // Insert this block into the loop set and on the first visit and, if it
1560 // isn't the header we're currently walking, put it into the worklist to
1561 // recurse through.
1562 if (LoopBlockSet.insert(Pred).second && Pred != Header)
1563 Worklist.push_back(Pred);
1564 }
1565
1566 // If no backedges were found, we're done.
1567 if (LoopBlockSet.empty())
1568 return LoopBlockSet;
1569
Chandler Carruth693eedb2017-11-17 19:58:36 +00001570 // We found backedges, recurse through them to identify the loop blocks.
1571 while (!Worklist.empty()) {
1572 BasicBlock *BB = Worklist.pop_back_val();
1573 assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1574
Chandler Carruth43acdb32018-04-24 10:33:08 +00001575 // No need to walk past the header.
1576 if (BB == Header)
1577 continue;
1578
Chandler Carruth693eedb2017-11-17 19:58:36 +00001579 // Because we know the inner loop structure remains valid we can use the
1580 // loop structure to jump immediately across the entire nested loop.
1581 // Further, because it is in loop simplified form, we can directly jump
1582 // to its preheader afterward.
1583 if (Loop *InnerL = LI.getLoopFor(BB))
1584 if (InnerL != &L) {
1585 assert(L.contains(InnerL) &&
1586 "Should not reach a loop *outside* this loop!");
1587 // The preheader is the only possible predecessor of the loop so
1588 // insert it into the set and check whether it was already handled.
1589 auto *InnerPH = InnerL->getLoopPreheader();
1590 assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1591 "but not contain the inner loop "
1592 "preheader!");
1593 if (!LoopBlockSet.insert(InnerPH).second)
1594 // The only way to reach the preheader is through the loop body
1595 // itself so if it has been visited the loop is already handled.
1596 continue;
1597
1598 // Insert all of the blocks (other than those already present) into
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001599 // the loop set. We expect at least the block that led us to find the
1600 // inner loop to be in the block set, but we may also have other loop
1601 // blocks if they were already enqueued as predecessors of some other
1602 // outer loop block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00001603 for (auto *InnerBB : InnerL->blocks()) {
1604 if (InnerBB == BB) {
1605 assert(LoopBlockSet.count(InnerBB) &&
1606 "Block should already be in the set!");
1607 continue;
1608 }
1609
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001610 LoopBlockSet.insert(InnerBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001611 }
1612
1613 // Add the preheader to the worklist so we will continue past the
1614 // loop body.
1615 Worklist.push_back(InnerPH);
1616 continue;
1617 }
1618
1619 // Insert any predecessors that were in the original loop into the new
1620 // set, and if the insert is successful, add them to the worklist.
1621 for (auto *Pred : predecessors(BB))
1622 if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1623 Worklist.push_back(Pred);
1624 }
1625
Chandler Carruth43acdb32018-04-24 10:33:08 +00001626 assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1627
Chandler Carruth693eedb2017-11-17 19:58:36 +00001628 // We've found all the blocks participating in the loop, return our completed
1629 // set.
1630 return LoopBlockSet;
1631}
1632
1633/// Rebuild a loop after unswitching removes some subset of blocks and edges.
1634///
1635/// The removal may have removed some child loops entirely but cannot have
1636/// disturbed any remaining child loops. However, they may need to be hoisted
1637/// to the parent loop (or to be top-level loops). The original loop may be
1638/// completely removed.
1639///
1640/// The sibling loops resulting from this update are returned. If the original
1641/// loop remains a valid loop, it will be the first entry in this list with all
1642/// of the newly sibling loops following it.
1643///
1644/// Returns true if the loop remains a loop after unswitching, and false if it
1645/// is no longer a loop after unswitching (and should not continue to be
1646/// referenced).
1647static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1648 LoopInfo &LI,
1649 SmallVectorImpl<Loop *> &HoistedLoops) {
1650 auto *PH = L.getLoopPreheader();
1651
1652 // Compute the actual parent loop from the exit blocks. Because we may have
1653 // pruned some exits the loop may be different from the original parent.
1654 Loop *ParentL = nullptr;
1655 SmallVector<Loop *, 4> ExitLoops;
1656 SmallVector<BasicBlock *, 4> ExitsInLoops;
1657 ExitsInLoops.reserve(ExitBlocks.size());
1658 for (auto *ExitBB : ExitBlocks)
1659 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1660 ExitLoops.push_back(ExitL);
1661 ExitsInLoops.push_back(ExitBB);
1662 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1663 ParentL = ExitL;
1664 }
1665
1666 // Recompute the blocks participating in this loop. This may be empty if it
1667 // is no longer a loop.
1668 auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1669
1670 // If we still have a loop, we need to re-set the loop's parent as the exit
1671 // block set changing may have moved it within the loop nest. Note that this
1672 // can only happen when this loop has a parent as it can only hoist the loop
1673 // *up* the nest.
1674 if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1675 // Remove this loop's (original) blocks from all of the intervening loops.
1676 for (Loop *IL = L.getParentLoop(); IL != ParentL;
1677 IL = IL->getParentLoop()) {
1678 IL->getBlocksSet().erase(PH);
1679 for (auto *BB : L.blocks())
1680 IL->getBlocksSet().erase(BB);
1681 llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1682 return BB == PH || L.contains(BB);
1683 });
1684 }
1685
1686 LI.changeLoopFor(PH, ParentL);
1687 L.getParentLoop()->removeChildLoop(&L);
1688 if (ParentL)
1689 ParentL->addChildLoop(&L);
1690 else
1691 LI.addTopLevelLoop(&L);
1692 }
1693
1694 // Now we update all the blocks which are no longer within the loop.
1695 auto &Blocks = L.getBlocksVector();
1696 auto BlocksSplitI =
1697 LoopBlockSet.empty()
1698 ? Blocks.begin()
1699 : std::stable_partition(
1700 Blocks.begin(), Blocks.end(),
1701 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1702
1703 // Before we erase the list of unlooped blocks, build a set of them.
1704 SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1705 if (LoopBlockSet.empty())
1706 UnloopedBlocks.insert(PH);
1707
1708 // Now erase these blocks from the loop.
1709 for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1710 L.getBlocksSet().erase(BB);
1711 Blocks.erase(BlocksSplitI, Blocks.end());
1712
1713 // Sort the exits in ascending loop depth, we'll work backwards across these
1714 // to process them inside out.
1715 std::stable_sort(ExitsInLoops.begin(), ExitsInLoops.end(),
1716 [&](BasicBlock *LHS, BasicBlock *RHS) {
1717 return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1718 });
1719
1720 // We'll build up a set for each exit loop.
1721 SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1722 Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1723
1724 auto RemoveUnloopedBlocksFromLoop =
1725 [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1726 for (auto *BB : UnloopedBlocks)
1727 L.getBlocksSet().erase(BB);
1728 llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1729 return UnloopedBlocks.count(BB);
1730 });
1731 };
1732
1733 SmallVector<BasicBlock *, 16> Worklist;
1734 while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1735 assert(Worklist.empty() && "Didn't clear worklist!");
1736 assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1737
1738 // Grab the next exit block, in decreasing loop depth order.
1739 BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1740 Loop &ExitL = *LI.getLoopFor(ExitBB);
1741 assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1742
1743 // Erase all of the unlooped blocks from the loops between the previous
1744 // exit loop and this exit loop. This works because the ExitInLoops list is
1745 // sorted in increasing order of loop depth and thus we visit loops in
1746 // decreasing order of loop depth.
1747 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1748 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1749
1750 // Walk the CFG back until we hit the cloned PH adding everything reachable
1751 // and in the unlooped set to this exit block's loop.
1752 Worklist.push_back(ExitBB);
1753 do {
1754 BasicBlock *BB = Worklist.pop_back_val();
1755 // We can stop recursing at the cloned preheader (if we get there).
1756 if (BB == PH)
1757 continue;
1758
1759 for (BasicBlock *PredBB : predecessors(BB)) {
1760 // If this pred has already been moved to our set or is part of some
1761 // (inner) loop, no update needed.
1762 if (!UnloopedBlocks.erase(PredBB)) {
1763 assert((NewExitLoopBlocks.count(PredBB) ||
1764 ExitL.contains(LI.getLoopFor(PredBB))) &&
1765 "Predecessor not in a nested loop (or already visited)!");
1766 continue;
1767 }
1768
1769 // We just insert into the loop set here. We'll add these blocks to the
1770 // exit loop after we build up the set in a deterministic order rather
1771 // than the predecessor-influenced visit order.
1772 bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1773 (void)Inserted;
1774 assert(Inserted && "Should only visit an unlooped block once!");
1775
1776 // And recurse through to its predecessors.
1777 Worklist.push_back(PredBB);
1778 }
1779 } while (!Worklist.empty());
1780
1781 // If blocks in this exit loop were directly part of the original loop (as
1782 // opposed to a child loop) update the map to point to this exit loop. This
1783 // just updates a map and so the fact that the order is unstable is fine.
1784 for (auto *BB : NewExitLoopBlocks)
1785 if (Loop *BBL = LI.getLoopFor(BB))
1786 if (BBL == &L || !L.contains(BBL))
1787 LI.changeLoopFor(BB, &ExitL);
1788
1789 // We will remove the remaining unlooped blocks from this loop in the next
1790 // iteration or below.
1791 NewExitLoopBlocks.clear();
1792 }
1793
1794 // Any remaining unlooped blocks are no longer part of any loop unless they
1795 // are part of some child loop.
1796 for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1797 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1798 for (auto *BB : UnloopedBlocks)
1799 if (Loop *BBL = LI.getLoopFor(BB))
1800 if (BBL == &L || !L.contains(BBL))
1801 LI.changeLoopFor(BB, nullptr);
1802
1803 // Sink all the child loops whose headers are no longer in the loop set to
1804 // the parent (or to be top level loops). We reach into the loop and directly
1805 // update its subloop vector to make this batch update efficient.
1806 auto &SubLoops = L.getSubLoopsVector();
1807 auto SubLoopsSplitI =
1808 LoopBlockSet.empty()
1809 ? SubLoops.begin()
1810 : std::stable_partition(
1811 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1812 return LoopBlockSet.count(SubL->getHeader());
1813 });
1814 for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1815 HoistedLoops.push_back(HoistedL);
1816 HoistedL->setParentLoop(nullptr);
1817
1818 // To compute the new parent of this hoisted loop we look at where we
1819 // placed the preheader above. We can't lookup the header itself because we
1820 // retained the mapping from the header to the hoisted loop. But the
1821 // preheader and header should have the exact same new parent computed
1822 // based on the set of exit blocks from the original loop as the preheader
1823 // is a predecessor of the header and so reached in the reverse walk. And
1824 // because the loops were all in simplified form the preheader of the
1825 // hoisted loop can't be part of some *other* loop.
1826 if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1827 NewParentL->addChildLoop(HoistedL);
1828 else
1829 LI.addTopLevelLoop(HoistedL);
1830 }
1831 SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1832
1833 // Actually delete the loop if nothing remained within it.
1834 if (Blocks.empty()) {
1835 assert(SubLoops.empty() &&
1836 "Failed to remove all subloops from the original loop!");
1837 if (Loop *ParentL = L.getParentLoop())
1838 ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1839 else
1840 LI.removeLoop(llvm::find(LI, &L));
1841 LI.destroy(&L);
1842 return false;
1843 }
1844
1845 return true;
1846}
1847
1848/// Helper to visit a dominator subtree, invoking a callable on each node.
1849///
1850/// Returning false at any point will stop walking past that node of the tree.
1851template <typename CallableT>
1852void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1853 SmallVector<DomTreeNode *, 4> DomWorklist;
1854 DomWorklist.push_back(DT[BB]);
1855#ifndef NDEBUG
1856 SmallPtrSet<DomTreeNode *, 4> Visited;
1857 Visited.insert(DT[BB]);
1858#endif
1859 do {
1860 DomTreeNode *N = DomWorklist.pop_back_val();
1861
1862 // Visit this node.
1863 if (!Callable(N->getBlock()))
1864 continue;
1865
1866 // Accumulate the child nodes.
1867 for (DomTreeNode *ChildN : *N) {
1868 assert(Visited.insert(ChildN).second &&
1869 "Cannot visit a node twice when walking a tree!");
1870 DomWorklist.push_back(ChildN);
1871 }
1872 } while (!DomWorklist.empty());
1873}
1874
Max Kazantsevbde31002018-10-26 09:52:58 +00001875static void unswitchNontrivialInvariants(
Chandler Carruth60b2e052018-10-18 00:40:26 +00001876 Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
Max Kazantsevbde31002018-10-26 09:52:58 +00001877 SmallVectorImpl<BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI,
1878 AssumptionCache &AC, function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001879 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruth16529962018-06-25 23:32:54 +00001880 auto *ParentBB = TI.getParent();
1881 BranchInst *BI = dyn_cast<BranchInst>(&TI);
1882 SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001883
Chandler Carruth16529962018-06-25 23:32:54 +00001884 // We can only unswitch switches, conditional branches with an invariant
1885 // condition, or combining invariant conditions with an instruction.
1886 assert((SI || BI->isConditional()) &&
1887 "Can only unswitch switches and conditional branch!");
1888 bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001889 if (FullUnswitch)
1890 assert(Invariants.size() == 1 &&
1891 "Cannot have other invariants with full unswitching!");
1892 else
Chandler Carruth16529962018-06-25 23:32:54 +00001893 assert(isa<Instruction>(BI->getCondition()) &&
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001894 "Partial unswitching requires an instruction as the condition!");
1895
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001896 if (MSSAU && VerifyMemorySSA)
1897 MSSAU->getMemorySSA()->verifyMemorySSA();
1898
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001899 // Constant and BBs tracking the cloned and continuing successor. When we are
1900 // unswitching the entire condition, this can just be trivially chosen to
1901 // unswitch towards `true`. However, when we are unswitching a set of
1902 // invariants combined with `and` or `or`, the combining operation determines
1903 // the best direction to unswitch: we want to unswitch the direction that will
1904 // collapse the branch.
1905 bool Direction = true;
1906 int ClonedSucc = 0;
1907 if (!FullUnswitch) {
Chandler Carruth16529962018-06-25 23:32:54 +00001908 if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1909 assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1910 Instruction::And &&
1911 "Only `or` and `and` instructions can combine invariants being "
1912 "unswitched.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001913 Direction = false;
1914 ClonedSucc = 1;
1915 }
1916 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001917
Chandler Carruth16529962018-06-25 23:32:54 +00001918 BasicBlock *RetainedSuccBB =
1919 BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1920 SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1921 if (BI)
1922 UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1923 else
1924 for (auto Case : SI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00001925 if (Case.getCaseSuccessor() != RetainedSuccBB)
1926 UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
Chandler Carruth16529962018-06-25 23:32:54 +00001927
1928 assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1929 "Should not unswitch the same successor we are retaining!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001930
1931 // The branch should be in this exact loop. Any inner loop's invariant branch
1932 // should be handled by unswitching that inner loop. The caller of this
1933 // routine should filter out any candidates that remain (but were skipped for
1934 // whatever reason).
1935 assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1936
Chandler Carruth693eedb2017-11-17 19:58:36 +00001937 // Compute the parent loop now before we start hacking on things.
1938 Loop *ParentL = L.getParentLoop();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001939 // Get blocks in RPO order for MSSA update, before changing the CFG.
1940 LoopBlocksRPO LBRPO(&L);
1941 if (MSSAU)
1942 LBRPO.perform(&LI);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001943
1944 // Compute the outer-most loop containing one of our exit blocks. This is the
1945 // furthest up our loopnest which can be mutated, which we will use below to
1946 // update things.
1947 Loop *OuterExitL = &L;
1948 for (auto *ExitBB : ExitBlocks) {
1949 Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1950 if (!NewOuterExitL) {
1951 // We exited the entire nest with this block, so we're done.
1952 OuterExitL = nullptr;
1953 break;
1954 }
1955 if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1956 OuterExitL = NewOuterExitL;
1957 }
1958
Chandler Carruth3897ded2018-07-03 09:13:27 +00001959 // At this point, we're definitely going to unswitch something so invalidate
1960 // any cached information in ScalarEvolution for the outer most loop
1961 // containing an exit block and all nested loops.
1962 if (SE) {
1963 if (OuterExitL)
1964 SE->forgetLoop(OuterExitL);
1965 else
1966 SE->forgetTopmostLoop(&L);
1967 }
1968
Chandler Carruth16529962018-06-25 23:32:54 +00001969 // If the edge from this terminator to a successor dominates that successor,
1970 // store a map from each block in its dominator subtree to it. This lets us
1971 // tell when cloning for a particular successor if a block is dominated by
1972 // some *other* successor with a single data structure. We use this to
1973 // significantly reduce cloning.
1974 SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
1975 for (auto *SuccBB : llvm::concat<BasicBlock *const>(
1976 makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
1977 if (SuccBB->getUniquePredecessor() ||
1978 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
1979 return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
1980 }))
1981 visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
1982 DominatingSucc[BB] = SuccBB;
1983 return true;
1984 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001985
1986 // Split the preheader, so that we know that there is a safe place to insert
1987 // the conditional branch. We will change the preheader to have a conditional
1988 // branch on LoopCond. The original preheader will become the split point
1989 // between the unswitched versions, and we will have a new preheader for the
1990 // original loop.
1991 BasicBlock *SplitBB = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001992 BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001993
Chandler Carruth69e68f82018-04-25 00:18:07 +00001994 // Keep track of the dominator tree updates needed.
1995 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
1996
Chandler Carruth16529962018-06-25 23:32:54 +00001997 // Clone the loop for each unswitched successor.
1998 SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
1999 VMaps.reserve(UnswitchedSuccBBs.size());
2000 SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
2001 for (auto *SuccBB : UnswitchedSuccBBs) {
2002 VMaps.emplace_back(new ValueToValueMapTy());
2003 ClonedPHs[SuccBB] = buildClonedLoopBlocks(
2004 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002005 DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
Chandler Carruth16529962018-06-25 23:32:54 +00002006 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002007
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002008 // The stitching of the branched code back together depends on whether we're
2009 // doing full unswitching or not with the exception that we always want to
2010 // nuke the initial terminator placed in the split block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002011 SplitBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002012 if (FullUnswitch) {
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002013 // Splice the terminator from the original loop and rewrite its
2014 // successors.
2015 SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2016
2017 // Keep a clone of the terminator for MSSA updates.
2018 Instruction *NewTI = TI.clone();
2019 ParentBB->getInstList().push_back(NewTI);
2020
2021 // First wire up the moved terminator to the preheaders.
2022 if (BI) {
2023 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2024 BI->setSuccessor(ClonedSucc, ClonedPH);
2025 BI->setSuccessor(1 - ClonedSucc, LoopPH);
2026 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2027 } else {
2028 assert(SI && "Must either be a branch or switch!");
2029
2030 // Walk the cases and directly update their successors.
2031 assert(SI->getDefaultDest() == RetainedSuccBB &&
2032 "Not retaining default successor!");
2033 SI->setDefaultDest(LoopPH);
2034 for (auto &Case : SI->cases())
2035 if (Case.getCaseSuccessor() == RetainedSuccBB)
2036 Case.setSuccessor(LoopPH);
2037 else
2038 Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2039
2040 // We need to use the set to populate domtree updates as even when there
2041 // are multiple cases pointing at the same successor we only want to
2042 // remove and insert one edge in the domtree.
2043 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2044 DTUpdates.push_back(
2045 {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2046 }
2047
2048 if (MSSAU) {
2049 DT.applyUpdates(DTUpdates);
2050 DTUpdates.clear();
2051
2052 // Remove all but one edge to the retained block and all unswitched
2053 // blocks. This is to avoid having duplicate entries in the cloned Phis,
2054 // when we know we only keep a single edge for each case.
2055 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2056 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2057 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2058
2059 for (auto &VMap : VMaps)
2060 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2061 /*IgnoreIncomingWithNoClones=*/true);
2062 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2063
2064 // Remove all edges to unswitched blocks.
2065 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2066 MSSAU->removeEdge(ParentBB, SuccBB);
2067 }
2068
2069 // Now unhook the successor relationship as we'll be replacing
Chandler Carruthed296542018-07-09 10:30:48 +00002070 // the terminator with a direct branch. This is much simpler for branches
2071 // than switches so we handle those first.
Chandler Carruth16529962018-06-25 23:32:54 +00002072 if (BI) {
Chandler Carruthed296542018-07-09 10:30:48 +00002073 // Remove the parent as a predecessor of the unswitched successor.
Chandler Carruth16529962018-06-25 23:32:54 +00002074 assert(UnswitchedSuccBBs.size() == 1 &&
2075 "Only one possible unswitched block for a branch!");
Chandler Carruthed296542018-07-09 10:30:48 +00002076 BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2077 UnswitchedSuccBB->removePredecessor(ParentBB,
2078 /*DontDeleteUselessPHIs*/ true);
2079 DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2080 } else {
2081 // Note that we actually want to remove the parent block as a predecessor
2082 // of *every* case successor. The case successor is either unswitched,
2083 // completely eliminating an edge from the parent to that successor, or it
2084 // is a duplicate edge to the retained successor as the retained successor
2085 // is always the default successor and as we'll replace this with a direct
2086 // branch we no longer need the duplicate entries in the PHI nodes.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002087 SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2088 assert(NewSI->getDefaultDest() == RetainedSuccBB &&
Chandler Carruthed296542018-07-09 10:30:48 +00002089 "Not retaining default successor!");
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002090 for (auto &Case : NewSI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00002091 Case.getCaseSuccessor()->removePredecessor(
2092 ParentBB,
2093 /*DontDeleteUselessPHIs*/ true);
2094
2095 // We need to use the set to populate domtree updates as even when there
2096 // are multiple cases pointing at the same successor we only want to
2097 // remove and insert one edge in the domtree.
2098 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2099 DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
2100 }
2101
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002102 // After MSSAU update, remove the cloned terminator instruction NewTI.
2103 ParentBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002104
2105 // Create a new unconditional branch to the continuing block (as opposed to
2106 // the one cloned).
Chandler Carruth16529962018-06-25 23:32:54 +00002107 BranchInst::Create(RetainedSuccBB, ParentBB);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002108 } else {
Chandler Carruth16529962018-06-25 23:32:54 +00002109 assert(BI && "Only branches have partial unswitching.");
2110 assert(UnswitchedSuccBBs.size() == 1 &&
2111 "Only one possible unswitched block for a branch!");
2112 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002113 // When doing a partial unswitch, we have to do a bit more work to build up
2114 // the branch in the split block.
2115 buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
2116 *ClonedPH, *LoopPH);
Chandler Carruth16529962018-06-25 23:32:54 +00002117 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002118 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002119
Chandler Carruth16529962018-06-25 23:32:54 +00002120 // Apply the updates accumulated above to get an up-to-date dominator tree.
Chandler Carruth69e68f82018-04-25 00:18:07 +00002121 DT.applyUpdates(DTUpdates);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002122 if (!FullUnswitch && MSSAU) {
2123 // Update MSSA for partial unswitch, after DT update.
2124 SmallVector<CFGUpdate, 1> Updates;
2125 Updates.push_back(
2126 {cfg::UpdateKind::Insert, SplitBB, ClonedPHs.begin()->second});
2127 MSSAU->applyInsertUpdates(Updates, DT);
2128 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00002129
Chandler Carruth16529962018-06-25 23:32:54 +00002130 // Now that we have an accurate dominator tree, first delete the dead cloned
2131 // blocks so that we can accurately build any cloned loops. It is important to
2132 // not delete the blocks from the original loop yet because we still want to
2133 // reference the original loop to understand the cloned loop's structure.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002134 deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
Chandler Carruth16529962018-06-25 23:32:54 +00002135
Chandler Carruth69e68f82018-04-25 00:18:07 +00002136 // Build the cloned loop structure itself. This may be substantially
2137 // different from the original structure due to the simplified CFG. This also
2138 // handles inserting all the cloned blocks into the correct loops.
2139 SmallVector<Loop *, 4> NonChildClonedLoops;
Chandler Carruth16529962018-06-25 23:32:54 +00002140 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2141 buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
Chandler Carruth69e68f82018-04-25 00:18:07 +00002142
Chandler Carruth16529962018-06-25 23:32:54 +00002143 // Now that our cloned loops have been built, we can update the original loop.
2144 // First we delete the dead blocks from it and then we rebuild the loop
2145 // structure taking these deletions into account.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002146 deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU);
2147
2148 if (MSSAU && VerifyMemorySSA)
2149 MSSAU->getMemorySSA()->verifyMemorySSA();
2150
Chandler Carruth693eedb2017-11-17 19:58:36 +00002151 SmallVector<Loop *, 4> HoistedLoops;
2152 bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2153
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002154 if (MSSAU && VerifyMemorySSA)
2155 MSSAU->getMemorySSA()->verifyMemorySSA();
2156
Chandler Carruth69e68f82018-04-25 00:18:07 +00002157 // This transformation has a high risk of corrupting the dominator tree, and
2158 // the below steps to rebuild loop structures will result in hard to debug
2159 // errors in that case so verify that the dominator tree is sane first.
2160 // FIXME: Remove this when the bugs stop showing up and rely on existing
2161 // verification steps.
2162 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth693eedb2017-11-17 19:58:36 +00002163
Chandler Carruth16529962018-06-25 23:32:54 +00002164 if (BI) {
2165 // If we unswitched a branch which collapses the condition to a known
2166 // constant we want to replace all the uses of the invariants within both
2167 // the original and cloned blocks. We do this here so that we can use the
2168 // now updated dominator tree to identify which side the users are on.
2169 assert(UnswitchedSuccBBs.size() == 1 &&
2170 "Only one possible unswitched block for a branch!");
2171 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Fedor Sergeevf9a02a72018-11-07 20:05:11 +00002172
2173 // When considering multiple partially-unswitched invariants
2174 // we cant just go replace them with constants in both branches.
2175 //
2176 // For 'AND' we infer that true branch ("continue") means true
2177 // for each invariant operand.
2178 // For 'OR' we can infer that false branch ("continue") means false
2179 // for each invariant operand.
2180 // So it happens that for multiple-partial case we dont replace
2181 // in the unswitched branch.
2182 bool ReplaceUnswitched = FullUnswitch || (Invariants.size() == 1);
2183
Chandler Carruth16529962018-06-25 23:32:54 +00002184 ConstantInt *UnswitchedReplacement =
2185 Direction ? ConstantInt::getTrue(BI->getContext())
2186 : ConstantInt::getFalse(BI->getContext());
2187 ConstantInt *ContinueReplacement =
2188 Direction ? ConstantInt::getFalse(BI->getContext())
2189 : ConstantInt::getTrue(BI->getContext());
2190 for (Value *Invariant : Invariants)
2191 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2192 UI != UE;) {
2193 // Grab the use and walk past it so we can clobber it in the use list.
2194 Use *U = &*UI++;
2195 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2196 if (!UserI)
2197 continue;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002198
Chandler Carruth16529962018-06-25 23:32:54 +00002199 // Replace it with the 'continue' side if in the main loop body, and the
2200 // unswitched if in the cloned blocks.
2201 if (DT.dominates(LoopPH, UserI->getParent()))
2202 U->set(ContinueReplacement);
Fedor Sergeevf9a02a72018-11-07 20:05:11 +00002203 else if (ReplaceUnswitched &&
2204 DT.dominates(ClonedPH, UserI->getParent()))
Chandler Carruth16529962018-06-25 23:32:54 +00002205 U->set(UnswitchedReplacement);
2206 }
2207 }
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002208
Chandler Carruth693eedb2017-11-17 19:58:36 +00002209 // We can change which blocks are exit blocks of all the cloned sibling
2210 // loops, the current loop, and any parent loops which shared exit blocks
2211 // with the current loop. As a consequence, we need to re-form LCSSA for
2212 // them. But we shouldn't need to re-form LCSSA for any child loops.
2213 // FIXME: This could be made more efficient by tracking which exit blocks are
2214 // new, and focusing on them, but that isn't likely to be necessary.
2215 //
2216 // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2217 // loop nest and update every loop that could have had its exits changed. We
2218 // also need to cover any intervening loops. We add all of these loops to
2219 // a list and sort them by loop depth to achieve this without updating
2220 // unnecessary loops.
Chandler Carruth92815032018-06-02 01:29:01 +00002221 auto UpdateLoop = [&](Loop &UpdateL) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002222#ifndef NDEBUG
Chandler Carruth43acdb32018-04-24 10:33:08 +00002223 UpdateL.verifyLoop();
2224 for (Loop *ChildL : UpdateL) {
2225 ChildL->verifyLoop();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002226 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2227 "Perturbed a child loop's LCSSA form!");
Chandler Carruth43acdb32018-04-24 10:33:08 +00002228 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002229#endif
Chandler Carruth92815032018-06-02 01:29:01 +00002230 // First build LCSSA for this loop so that we can preserve it when
2231 // forming dedicated exits. We don't want to perturb some other loop's
2232 // LCSSA while doing that CFG edit.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002233 formLCSSA(UpdateL, DT, &LI, nullptr);
Chandler Carruth92815032018-06-02 01:29:01 +00002234
2235 // For loops reached by this loop's original exit blocks we may
2236 // introduced new, non-dedicated exits. At least try to re-form dedicated
2237 // exits for these loops. This may fail if they couldn't have dedicated
2238 // exits to start with.
2239 formDedicatedExitBlocks(&UpdateL, &DT, &LI, /*PreserveLCSSA*/ true);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002240 };
2241
2242 // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2243 // and we can do it in any order as they don't nest relative to each other.
Chandler Carruth92815032018-06-02 01:29:01 +00002244 //
2245 // Also check if any of the loops we have updated have become top-level loops
2246 // as that will necessitate widening the outer loop scope.
2247 for (Loop *UpdatedL :
2248 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2249 UpdateLoop(*UpdatedL);
2250 if (!UpdatedL->getParentLoop())
2251 OuterExitL = nullptr;
2252 }
2253 if (IsStillLoop) {
2254 UpdateLoop(L);
2255 if (!L.getParentLoop())
2256 OuterExitL = nullptr;
2257 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002258
2259 // If the original loop had exit blocks, walk up through the outer most loop
2260 // of those exit blocks to update LCSSA and form updated dedicated exits.
Chandler Carruth92815032018-06-02 01:29:01 +00002261 if (OuterExitL != &L)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002262 for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2263 OuterL = OuterL->getParentLoop())
Chandler Carruth92815032018-06-02 01:29:01 +00002264 UpdateLoop(*OuterL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002265
2266#ifndef NDEBUG
2267 // Verify the entire loop structure to catch any incorrect updates before we
2268 // progress in the pass pipeline.
2269 LI.verify(DT);
2270#endif
2271
2272 // Now that we've unswitched something, make callbacks to report the changes.
2273 // For that we need to merge together the updated loops and the cloned loops
2274 // and check whether the original loop survived.
2275 SmallVector<Loop *, 4> SibLoops;
2276 for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2277 if (UpdatedL->getParentLoop() == ParentL)
2278 SibLoops.push_back(UpdatedL);
Chandler Carruth71fd2702018-05-30 02:46:45 +00002279 UnswitchCB(IsStillLoop, SibLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002280
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002281 if (MSSAU && VerifyMemorySSA)
2282 MSSAU->getMemorySSA()->verifyMemorySSA();
2283
Zaara Syedab7dff9c2019-01-15 15:08:01 +00002284 if (BI)
2285 ++NumBranches;
2286 else
2287 ++NumSwitches;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002288}
2289
2290/// Recursively compute the cost of a dominator subtree based on the per-block
2291/// cost map provided.
2292///
2293/// The recursive computation is memozied into the provided DT-indexed cost map
2294/// to allow querying it for most nodes in the domtree without it becoming
2295/// quadratic.
2296static int
2297computeDomSubtreeCost(DomTreeNode &N,
2298 const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2299 SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2300 // Don't accumulate cost (or recurse through) blocks not in our block cost
2301 // map and thus not part of the duplication cost being considered.
2302 auto BBCostIt = BBCostMap.find(N.getBlock());
2303 if (BBCostIt == BBCostMap.end())
2304 return 0;
2305
2306 // Lookup this node to see if we already computed its cost.
2307 auto DTCostIt = DTCostMap.find(&N);
2308 if (DTCostIt != DTCostMap.end())
2309 return DTCostIt->second;
2310
2311 // If not, we have to compute it. We can't use insert above and update
2312 // because computing the cost may insert more things into the map.
2313 int Cost = std::accumulate(
2314 N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2315 return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2316 });
2317 bool Inserted = DTCostMap.insert({&N, Cost}).second;
2318 (void)Inserted;
2319 assert(Inserted && "Should not insert a node while visiting children!");
2320 return Cost;
2321}
2322
Max Kazantsev619a8342018-10-26 14:20:11 +00002323/// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2324/// making the following replacement:
2325///
Simon Pilgrima1320162018-10-27 15:14:42 +00002326/// --code before guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002327/// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
Simon Pilgrima1320162018-10-27 15:14:42 +00002328/// --code after guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002329///
2330/// into
2331///
Simon Pilgrima1320162018-10-27 15:14:42 +00002332/// --code before guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002333/// br i1 %cond, label %guarded, label %deopt
2334///
2335/// guarded:
Simon Pilgrima1320162018-10-27 15:14:42 +00002336/// --code after guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002337///
2338/// deopt:
2339/// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2340/// unreachable
2341///
2342/// It also makes all relevant DT and LI updates, so that all structures are in
2343/// valid state after this transform.
2344static BranchInst *
2345turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2346 SmallVectorImpl<BasicBlock *> &ExitBlocks,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002347 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Max Kazantsev619a8342018-10-26 14:20:11 +00002348 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2349 LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2350 BasicBlock *CheckBB = GI->getParent();
2351
Alina Sbirlea797935f2018-12-04 14:43:24 +00002352 if (MSSAU && VerifyMemorySSA)
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002353 MSSAU->getMemorySSA()->verifyMemorySSA();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002354
Max Kazantsev619a8342018-10-26 14:20:11 +00002355 // Remove all CheckBB's successors from DomTree. A block can be seen among
2356 // successors more than once, but for DomTree it should be added only once.
2357 SmallPtrSet<BasicBlock *, 4> Successors;
2358 for (auto *Succ : successors(CheckBB))
2359 if (Successors.insert(Succ).second)
2360 DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2361
2362 Instruction *DeoptBlockTerm =
2363 SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2364 BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2365 // SplitBlockAndInsertIfThen inserts control flow that branches to
2366 // DeoptBlockTerm if the condition is true. We want the opposite.
2367 CheckBI->swapSuccessors();
2368
2369 BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2370 GuardedBlock->setName("guarded");
2371 CheckBI->getSuccessor(1)->setName("deopt");
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002372 BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
Max Kazantsev619a8342018-10-26 14:20:11 +00002373
2374 // We now have a new exit block.
2375 ExitBlocks.push_back(CheckBI->getSuccessor(1));
2376
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002377 if (MSSAU)
2378 MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2379
Max Kazantsev619a8342018-10-26 14:20:11 +00002380 GI->moveBefore(DeoptBlockTerm);
2381 GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2382
2383 // Add new successors of CheckBB into DomTree.
2384 for (auto *Succ : successors(CheckBB))
2385 DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2386
2387 // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2388 // successors.
2389 for (auto *Succ : Successors)
2390 DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2391
2392 // Make proper changes to DT.
2393 DT.applyUpdates(DTUpdates);
2394 // Inform LI of a new loop block.
2395 L.addBasicBlockToLoop(GuardedBlock, LI);
2396
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002397 if (MSSAU) {
2398 MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2399 MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::End);
2400 if (VerifyMemorySSA)
2401 MSSAU->getMemorySSA()->verifyMemorySSA();
2402 }
2403
Max Kazantsev619a8342018-10-26 14:20:11 +00002404 ++NumGuards;
2405 return CheckBI;
2406}
2407
Fedor Sergeev2e3e2242018-11-16 21:16:43 +00002408/// Cost multiplier is a way to limit potentially exponential behavior
2409/// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2410/// candidates available. Also accounting for the number of "sibling" loops with
2411/// the idea to account for previous unswitches that already happened on this
2412/// cluster of loops. There was an attempt to keep this formula simple,
2413/// just enough to limit the worst case behavior. Even if it is not that simple
2414/// now it is still not an attempt to provide a detailed heuristic size
2415/// prediction.
2416///
2417/// TODO: Make a proper accounting of "explosion" effect for all kinds of
2418/// unswitch candidates, making adequate predictions instead of wild guesses.
2419/// That requires knowing not just the number of "remaining" candidates but
2420/// also costs of unswitching for each of these candidates.
2421static int calculateUnswitchCostMultiplier(
2422 Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
2423 ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
2424 UnswitchCandidates) {
2425
2426 // Guards and other exiting conditions do not contribute to exponential
2427 // explosion as soon as they dominate the latch (otherwise there might be
2428 // another path to the latch remaining that does not allow to eliminate the
2429 // loop copy on unswitch).
2430 BasicBlock *Latch = L.getLoopLatch();
2431 BasicBlock *CondBlock = TI.getParent();
2432 if (DT.dominates(CondBlock, Latch) &&
2433 (isGuard(&TI) ||
2434 llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
2435 return L.contains(SuccBB);
2436 }) <= 1)) {
2437 NumCostMultiplierSkipped++;
2438 return 1;
2439 }
2440
2441 auto *ParentL = L.getParentLoop();
2442 int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2443 : std::distance(LI.begin(), LI.end()));
2444 // Count amount of clones that all the candidates might cause during
2445 // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2446 int UnswitchedClones = 0;
2447 for (auto Candidate : UnswitchCandidates) {
2448 Instruction *CI = Candidate.first;
2449 BasicBlock *CondBlock = CI->getParent();
2450 bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2451 if (isGuard(CI)) {
2452 if (!SkipExitingSuccessors)
2453 UnswitchedClones++;
2454 continue;
2455 }
2456 int NonExitingSuccessors = llvm::count_if(
2457 successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
2458 return !SkipExitingSuccessors || L.contains(SuccBB);
2459 });
2460 UnswitchedClones += Log2_32(NonExitingSuccessors);
2461 }
2462
2463 // Ignore up to the "unscaled candidates" number of unswitch candidates
2464 // when calculating the power-of-two scaling of the cost. The main idea
2465 // with this control is to allow a small number of unswitches to happen
2466 // and rely more on siblings multiplier (see below) when the number
2467 // of candidates is small.
2468 unsigned ClonesPower =
2469 std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
2470
2471 // Allowing top-level loops to spread a bit more than nested ones.
2472 int SiblingsMultiplier =
2473 std::max((ParentL ? SiblingsCount
2474 : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
2475 1);
2476 // Compute the cost multiplier in a way that won't overflow by saturating
2477 // at an upper bound.
2478 int CostMultiplier;
2479 if (ClonesPower > Log2_32(UnswitchThreshold) ||
2480 SiblingsMultiplier > UnswitchThreshold)
2481 CostMultiplier = UnswitchThreshold;
2482 else
2483 CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2484 (int)UnswitchThreshold);
2485
2486 LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier
2487 << " (siblings " << SiblingsMultiplier << " * clones "
2488 << (1 << ClonesPower) << ")"
2489 << " for unswitch candidate: " << TI << "\n");
2490 return CostMultiplier;
2491}
2492
Chandler Carruth3897ded2018-07-03 09:13:27 +00002493static bool
2494unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2495 AssumptionCache &AC, TargetTransformInfo &TTI,
2496 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002497 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002498 // Collect all invariant conditions within this loop (as opposed to an inner
2499 // loop which would be handled when visiting that inner loop).
Chandler Carruth60b2e052018-10-18 00:40:26 +00002500 SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002501 UnswitchCandidates;
Max Kazantsev619a8342018-10-26 14:20:11 +00002502
2503 // Whether or not we should also collect guards in the loop.
2504 bool CollectGuards = false;
2505 if (UnswitchGuards) {
2506 auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2507 Intrinsic::getName(Intrinsic::experimental_guard));
2508 if (GuardDecl && !GuardDecl->use_empty())
2509 CollectGuards = true;
2510 }
2511
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002512 for (auto *BB : L.blocks()) {
2513 if (LI.getLoopFor(BB) != &L)
2514 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002515
Max Kazantsev619a8342018-10-26 14:20:11 +00002516 if (CollectGuards)
2517 for (auto &I : *BB)
2518 if (isGuard(&I)) {
2519 auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2520 // TODO: Support AND, OR conditions and partial unswitching.
2521 if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2522 UnswitchCandidates.push_back({&I, {Cond}});
2523 }
2524
Chandler Carruth16529962018-06-25 23:32:54 +00002525 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2526 // We can only consider fully loop-invariant switch conditions as we need
2527 // to completely eliminate the switch after unswitching.
2528 if (!isa<Constant>(SI->getCondition()) &&
2529 L.isLoopInvariant(SI->getCondition()))
2530 UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2531 continue;
2532 }
2533
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002534 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002535 if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2536 BI->getSuccessor(0) == BI->getSuccessor(1))
2537 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002538
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002539 if (L.isLoopInvariant(BI->getCondition())) {
2540 UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2541 continue;
2542 }
2543
2544 Instruction &CondI = *cast<Instruction>(BI->getCondition());
2545 if (CondI.getOpcode() != Instruction::And &&
2546 CondI.getOpcode() != Instruction::Or)
2547 continue;
2548
2549 TinyPtrVector<Value *> Invariants =
2550 collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2551 if (Invariants.empty())
2552 continue;
2553
2554 UnswitchCandidates.push_back({BI, std::move(Invariants)});
Chandler Carruth71fd2702018-05-30 02:46:45 +00002555 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002556
Chandler Carruth693eedb2017-11-17 19:58:36 +00002557 // If we didn't find any candidates, we're done.
2558 if (UnswitchCandidates.empty())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002559 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002560
Chandler Carruth32e62f92018-04-19 18:44:25 +00002561 // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2562 // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2563 // irreducible control flow into reducible control flow and introduce new
2564 // loops "out of thin air". If we ever discover important use cases for doing
2565 // this, we can add support to loop unswitch, but it is a lot of complexity
Hiroshi Inouef2096492018-06-14 05:41:49 +00002566 // for what seems little or no real world benefit.
Chandler Carruth32e62f92018-04-19 18:44:25 +00002567 LoopBlocksRPO RPOT(&L);
2568 RPOT.perform(&LI);
2569 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002570 return false;
Chandler Carruth32e62f92018-04-19 18:44:25 +00002571
Max Kazantsevbde31002018-10-26 09:52:58 +00002572 SmallVector<BasicBlock *, 4> ExitBlocks;
2573 L.getUniqueExitBlocks(ExitBlocks);
2574
2575 // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
2576 // don't know how to split those exit blocks.
2577 // FIXME: We should teach SplitBlock to handle this and remove this
2578 // restriction.
2579 for (auto *ExitBB : ExitBlocks)
2580 if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) {
2581 dbgs() << "Cannot unswitch because of cleanuppad in exit block\n";
2582 return false;
2583 }
2584
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002585 LLVM_DEBUG(
2586 dbgs() << "Considering " << UnswitchCandidates.size()
2587 << " non-trivial loop invariant conditions for unswitching.\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002588
2589 // Given that unswitching these terminators will require duplicating parts of
2590 // the loop, so we need to be able to model that cost. Compute the ephemeral
2591 // values and set up a data structure to hold per-BB costs. We cache each
2592 // block's cost so that we don't recompute this when considering different
2593 // subsets of the loop for duplication during unswitching.
2594 SmallPtrSet<const Value *, 4> EphValues;
2595 CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2596 SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2597
2598 // Compute the cost of each block, as well as the total loop cost. Also, bail
2599 // out if we see instructions which are incompatible with loop unswitching
2600 // (convergent, noduplicate, or cross-basic-block tokens).
2601 // FIXME: We might be able to safely handle some of these in non-duplicated
2602 // regions.
2603 int LoopCost = 0;
2604 for (auto *BB : L.blocks()) {
2605 int Cost = 0;
2606 for (auto &I : *BB) {
2607 if (EphValues.count(&I))
2608 continue;
2609
2610 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002611 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002612 if (auto CS = CallSite(&I))
2613 if (CS.isConvergent() || CS.cannotDuplicate())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002614 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002615
2616 Cost += TTI.getUserCost(&I);
2617 }
2618 assert(Cost >= 0 && "Must not have negative costs!");
2619 LoopCost += Cost;
2620 assert(LoopCost >= 0 && "Must not have negative loop costs!");
2621 BBCostMap[BB] = Cost;
2622 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002623 LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002624
2625 // Now we find the best candidate by searching for the one with the following
2626 // properties in order:
2627 //
2628 // 1) An unswitching cost below the threshold
2629 // 2) The smallest number of duplicated unswitch candidates (to avoid
2630 // creating redundant subsequent unswitching)
2631 // 3) The smallest cost after unswitching.
2632 //
2633 // We prioritize reducing fanout of unswitch candidates provided the cost
2634 // remains below the threshold because this has a multiplicative effect.
2635 //
2636 // This requires memoizing each dominator subtree to avoid redundant work.
2637 //
2638 // FIXME: Need to actually do the number of candidates part above.
2639 SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2640 // Given a terminator which might be unswitched, computes the non-duplicated
2641 // cost for that terminator.
Chandler Carruth60b2e052018-10-18 00:40:26 +00002642 auto ComputeUnswitchedCost = [&](Instruction &TI, bool FullUnswitch) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002643 BasicBlock &BB = *TI.getParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002644 SmallPtrSet<BasicBlock *, 4> Visited;
2645
2646 int Cost = LoopCost;
2647 for (BasicBlock *SuccBB : successors(&BB)) {
2648 // Don't count successors more than once.
2649 if (!Visited.insert(SuccBB).second)
2650 continue;
2651
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002652 // If this is a partial unswitch candidate, then it must be a conditional
2653 // branch with a condition of either `or` or `and`. In that case, one of
2654 // the successors is necessarily duplicated, so don't even try to remove
2655 // its cost.
2656 if (!FullUnswitch) {
2657 auto &BI = cast<BranchInst>(TI);
2658 if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2659 Instruction::And) {
2660 if (SuccBB == BI.getSuccessor(1))
2661 continue;
2662 } else {
2663 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2664 Instruction::Or &&
2665 "Only `and` and `or` conditions can result in a partial "
2666 "unswitch!");
2667 if (SuccBB == BI.getSuccessor(0))
2668 continue;
2669 }
2670 }
2671
Chandler Carruth693eedb2017-11-17 19:58:36 +00002672 // This successor's domtree will not need to be duplicated after
2673 // unswitching if the edge to the successor dominates it (and thus the
2674 // entire tree). This essentially means there is no other path into this
2675 // subtree and so it will end up live in only one clone of the loop.
2676 if (SuccBB->getUniquePredecessor() ||
2677 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2678 return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2679 })) {
2680 Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2681 assert(Cost >= 0 &&
2682 "Non-duplicated cost should never exceed total loop cost!");
2683 }
2684 }
2685
2686 // Now scale the cost by the number of unique successors minus one. We
2687 // subtract one because there is already at least one copy of the entire
2688 // loop. This is computing the new cost of unswitching a condition.
Max Kazantsev619a8342018-10-26 14:20:11 +00002689 // Note that guards always have 2 unique successors that are implicit and
2690 // will be materialized if we decide to unswitch it.
2691 int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2692 assert(SuccessorsCount > 1 &&
Chandler Carruth693eedb2017-11-17 19:58:36 +00002693 "Cannot unswitch a condition without multiple distinct successors!");
Max Kazantsev619a8342018-10-26 14:20:11 +00002694 return Cost * (SuccessorsCount - 1);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002695 };
Chandler Carruth60b2e052018-10-18 00:40:26 +00002696 Instruction *BestUnswitchTI = nullptr;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002697 int BestUnswitchCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002698 ArrayRef<Value *> BestUnswitchInvariants;
2699 for (auto &TerminatorAndInvariants : UnswitchCandidates) {
Chandler Carruth60b2e052018-10-18 00:40:26 +00002700 Instruction &TI = *TerminatorAndInvariants.first;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002701 ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2702 BranchInst *BI = dyn_cast<BranchInst>(&TI);
Chandler Carruth16529962018-06-25 23:32:54 +00002703 int CandidateCost = ComputeUnswitchedCost(
2704 TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2705 Invariants[0] == BI->getCondition()));
Fedor Sergeev2e3e2242018-11-16 21:16:43 +00002706 // Calculate cost multiplier which is a tool to limit potentially
2707 // exponential behavior of loop-unswitch.
2708 if (EnableUnswitchCostMultiplier) {
2709 int CostMultiplier =
2710 calculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
2711 assert(
2712 (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
2713 "cost multiplier needs to be in the range of 1..UnswitchThreshold");
2714 CandidateCost *= CostMultiplier;
2715 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2716 << " (multiplier: " << CostMultiplier << ")"
2717 << " for unswitch candidate: " << TI << "\n");
2718 } else {
2719 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2720 << " for unswitch candidate: " << TI << "\n");
2721 }
2722
Chandler Carruth693eedb2017-11-17 19:58:36 +00002723 if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002724 BestUnswitchTI = &TI;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002725 BestUnswitchCost = CandidateCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002726 BestUnswitchInvariants = Invariants;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002727 }
2728 }
2729
Chandler Carruth71fd2702018-05-30 02:46:45 +00002730 if (BestUnswitchCost >= UnswitchThreshold) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002731 LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2732 << BestUnswitchCost << "\n");
Chandler Carruth71fd2702018-05-30 02:46:45 +00002733 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002734 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002735
Max Kazantsev619a8342018-10-26 14:20:11 +00002736 // If the best candidate is a guard, turn it into a branch.
2737 if (isGuard(BestUnswitchTI))
2738 BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002739 ExitBlocks, DT, LI, MSSAU);
Max Kazantsev619a8342018-10-26 14:20:11 +00002740
Max Kazantsevbde31002018-10-26 09:52:58 +00002741 LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = "
Chandler Carruth16529962018-06-25 23:32:54 +00002742 << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2743 << "\n");
Max Kazantsevbde31002018-10-26 09:52:58 +00002744 unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002745 ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU);
Max Kazantsevbde31002018-10-26 09:52:58 +00002746 return true;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002747}
2748
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002749/// Unswitch control flow predicated on loop invariant conditions.
2750///
2751/// This first hoists all branches or switches which are trivial (IE, do not
2752/// require duplicating any part of the loop) out of the loop body. It then
2753/// looks at other loop invariant control flows and tries to unswitch those as
2754/// well by cloning the loop if the result is small enough.
Chandler Carruth3897ded2018-07-03 09:13:27 +00002755///
2756/// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2757/// updated based on the unswitch.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002758/// The `MSSA` analysis is also updated if valid (i.e. its use is enabled).
Chandler Carruth3897ded2018-07-03 09:13:27 +00002759///
2760/// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2761/// true, we will attempt to do non-trivial unswitching as well as trivial
2762/// unswitching.
2763///
2764/// The `UnswitchCB` callback provided will be run after unswitching is
2765/// complete, with the first parameter set to `true` if the provided loop
2766/// remains a loop, and a list of new sibling loops created.
2767///
2768/// If `SE` is non-null, we will update that analysis based on the unswitching
2769/// done.
2770static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2771 AssumptionCache &AC, TargetTransformInfo &TTI,
2772 bool NonTrivial,
2773 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002774 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002775 assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2776 "Loops must be in LCSSA form before unswitching.");
2777 bool Changed = false;
2778
2779 // Must be in loop simplified form: we need a preheader and dedicated exits.
2780 if (!L.isLoopSimplifyForm())
2781 return false;
2782
2783 // Try trivial unswitch first before loop over other basic blocks in the loop.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002784 if (unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002785 // If we unswitched successfully we will want to clean up the loop before
2786 // processing it further so just mark it as unswitched and return.
2787 UnswitchCB(/*CurrentLoopValid*/ true, {});
2788 return true;
2789 }
2790
2791 // If we're not doing non-trivial unswitching, we're done. We both accept
2792 // a parameter but also check a local flag that can be used for testing
2793 // a debugging.
2794 if (!NonTrivial && !EnableNonTrivialUnswitch)
2795 return false;
2796
2797 // For non-trivial unswitching, because it often creates new loops, we rely on
2798 // the pass manager to iterate on the loops rather than trying to immediately
2799 // reach a fixed point. There is no substantial advantage to iterating
2800 // internally, and if any of the new loops are simplified enough to contain
2801 // trivial unswitching we want to prefer those.
2802
2803 // Try to unswitch the best invariant condition. We prefer this full unswitch to
2804 // a partial unswitch when possible below the threshold.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002805 if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE, MSSAU))
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002806 return true;
2807
2808 // No other opportunities to unswitch.
2809 return Changed;
2810}
2811
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002812PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2813 LoopStandardAnalysisResults &AR,
2814 LPMUpdater &U) {
2815 Function &F = *L.getHeader()->getParent();
2816 (void)F;
2817
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002818 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2819 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002820
Chandler Carruth693eedb2017-11-17 19:58:36 +00002821 // Save the current loop name in a variable so that we can report it even
2822 // after it has been deleted.
2823 std::string LoopName = L.getName();
2824
Chandler Carruth71fd2702018-05-30 02:46:45 +00002825 auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2826 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002827 // If we did a non-trivial unswitch, we have added new (cloned) loops.
Chandler Carruth71fd2702018-05-30 02:46:45 +00002828 if (!NewLoops.empty())
2829 U.addSiblingLoops(NewLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002830
2831 // If the current loop remains valid, we should revisit it to catch any
2832 // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2833 if (CurrentLoopValid)
2834 U.revisitCurrentLoop();
2835 else
2836 U.markLoopAsDeleted(L, LoopName);
2837 };
2838
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002839 Optional<MemorySSAUpdater> MSSAU;
2840 if (AR.MSSA) {
2841 MSSAU = MemorySSAUpdater(AR.MSSA);
2842 if (VerifyMemorySSA)
2843 AR.MSSA->verifyMemorySSA();
2844 }
Chandler Carruth3897ded2018-07-03 09:13:27 +00002845 if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002846 &AR.SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002847 return PreservedAnalyses::all();
2848
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002849 if (AR.MSSA && VerifyMemorySSA)
2850 AR.MSSA->verifyMemorySSA();
2851
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002852 // Historically this pass has had issues with the dominator tree so verify it
2853 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002854 assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002855 return getLoopPassPreservedAnalyses();
2856}
2857
2858namespace {
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002859
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002860class SimpleLoopUnswitchLegacyPass : public LoopPass {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002861 bool NonTrivial;
2862
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002863public:
2864 static char ID; // Pass ID, replacement for typeid
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002865
Chandler Carruth693eedb2017-11-17 19:58:36 +00002866 explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2867 : LoopPass(ID), NonTrivial(NonTrivial) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002868 initializeSimpleLoopUnswitchLegacyPassPass(
2869 *PassRegistry::getPassRegistry());
2870 }
2871
2872 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2873
2874 void getAnalysisUsage(AnalysisUsage &AU) const override {
2875 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002876 AU.addRequired<TargetTransformInfoWrapperPass>();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002877 if (EnableMSSALoopDependency) {
2878 AU.addRequired<MemorySSAWrapperPass>();
2879 AU.addPreserved<MemorySSAWrapperPass>();
2880 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002881 getLoopAnalysisUsage(AU);
2882 }
2883};
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002884
2885} // end anonymous namespace
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002886
2887bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2888 if (skipLoop(L))
2889 return false;
2890
2891 Function &F = *L->getHeader()->getParent();
2892
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002893 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2894 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002895
2896 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2897 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2898 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002899 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002900 MemorySSA *MSSA = nullptr;
2901 Optional<MemorySSAUpdater> MSSAU;
2902 if (EnableMSSALoopDependency) {
2903 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
2904 MSSAU = MemorySSAUpdater(MSSA);
2905 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002906
Chandler Carruth3897ded2018-07-03 09:13:27 +00002907 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2908 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2909
Chandler Carruth71fd2702018-05-30 02:46:45 +00002910 auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2911 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002912 // If we did a non-trivial unswitch, we have added new (cloned) loops.
2913 for (auto *NewL : NewLoops)
2914 LPM.addLoop(*NewL);
2915
2916 // If the current loop remains valid, re-add it to the queue. This is
2917 // a little wasteful as we'll finish processing the current loop as well,
2918 // but it is the best we can do in the old PM.
2919 if (CurrentLoopValid)
2920 LPM.addLoop(*L);
2921 else
2922 LPM.markLoopAsDeleted(*L);
2923 };
2924
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002925 if (MSSA && VerifyMemorySSA)
2926 MSSA->verifyMemorySSA();
2927
2928 bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE,
2929 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
2930
2931 if (MSSA && VerifyMemorySSA)
2932 MSSA->verifyMemorySSA();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002933
2934 // If anything was unswitched, also clear any cached information about this
2935 // loop.
2936 LPM.deleteSimpleAnalysisLoop(L);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002937
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002938 // Historically this pass has had issues with the dominator tree so verify it
2939 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002940 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2941
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002942 return Changed;
2943}
2944
2945char SimpleLoopUnswitchLegacyPass::ID = 0;
2946INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2947 "Simple unswitch loops", false, false)
2948INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002949INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2950INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002951INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002952INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002953INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2954INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2955 "Simple unswitch loops", false, false)
2956
Chandler Carruth693eedb2017-11-17 19:58:36 +00002957Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2958 return new SimpleLoopUnswitchLegacyPass(NonTrivial);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002959}