blob: 8113427cab71916190dc518785ccbb89b37d0014 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth1353f9a2017-04-27 18:45:20 +00006//
7//===----------------------------------------------------------------------===//
8
Chandler Carruth6bda14b2017-06-06 11:49:48 +00009#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000010#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000011#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000012#include "llvm/ADT/Sequence.h"
13#include "llvm/ADT/SetVector.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000014#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000015#include "llvm/ADT/SmallVector.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000016#include "llvm/ADT/Statistic.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000017#include "llvm/ADT/Twine.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000018#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth32e62f92018-04-19 18:44:25 +000019#include "llvm/Analysis/CFG.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000020#include "llvm/Analysis/CodeMetrics.h"
Max Kazantsev619a8342018-10-26 14:20:11 +000021#include "llvm/Analysis/GuardUtils.h"
Chandler Carruth4da33312018-06-20 18:57:07 +000022#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000023#include "llvm/Analysis/LoopAnalysisManager.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000024#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth32e62f92018-04-19 18:44:25 +000025#include "llvm/Analysis/LoopIterator.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000026#include "llvm/Analysis/LoopPass.h"
Alina Sbirleaa2eebb82018-12-04 14:23:37 +000027#include "llvm/Analysis/MemorySSA.h"
28#include "llvm/Analysis/MemorySSAUpdater.h"
Chandler Carruth4da33312018-06-20 18:57:07 +000029#include "llvm/Analysis/Utils/Local.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000030#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/Constant.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/Dominators.h"
34#include "llvm/IR/Function.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000035#include "llvm/IR/InstrTypes.h"
36#include "llvm/IR/Instruction.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000037#include "llvm/IR/Instructions.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000038#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000039#include "llvm/IR/Use.h"
40#include "llvm/IR/Value.h"
41#include "llvm/Pass.h"
42#include "llvm/Support/Casting.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000043#include "llvm/Support/Debug.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000044#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/GenericDomTree.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000046#include "llvm/Support/raw_ostream.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000047#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000048#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000049#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000050#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000051#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000052#include <algorithm>
53#include <cassert>
54#include <iterator>
Chandler Carruth693eedb2017-11-17 19:58:36 +000055#include <numeric>
Eugene Zelenkoa369a452017-05-16 23:10:25 +000056#include <utility>
Chandler Carruth1353f9a2017-04-27 18:45:20 +000057
58#define DEBUG_TYPE "simple-loop-unswitch"
59
60using namespace llvm;
61
62STATISTIC(NumBranches, "Number of branches unswitched");
63STATISTIC(NumSwitches, "Number of switches unswitched");
Max Kazantsev619a8342018-10-26 14:20:11 +000064STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
Chandler Carruth1353f9a2017-04-27 18:45:20 +000065STATISTIC(NumTrivial, "Number of unswitches that are trivial");
Fedor Sergeev2e3e2242018-11-16 21:16:43 +000066STATISTIC(
67 NumCostMultiplierSkipped,
68 "Number of unswitch candidates that had their cost multiplier skipped");
Chandler Carruth1353f9a2017-04-27 18:45:20 +000069
Chandler Carruth693eedb2017-11-17 19:58:36 +000070static cl::opt<bool> EnableNonTrivialUnswitch(
71 "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
72 cl::desc("Forcibly enables non-trivial loop unswitching rather than "
73 "following the configuration passed into the pass."));
74
75static cl::opt<int>
76 UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
77 cl::desc("The cost threshold for unswitching a loop."));
78
Fedor Sergeev2e3e2242018-11-16 21:16:43 +000079static cl::opt<bool> EnableUnswitchCostMultiplier(
80 "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
81 cl::desc("Enable unswitch cost multiplier that prohibits exponential "
82 "explosion in nontrivial unswitch."));
83static cl::opt<int> UnswitchSiblingsToplevelDiv(
84 "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
85 cl::desc("Toplevel siblings divisor for cost multiplier."));
86static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
87 "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
88 cl::desc("Number of unswitch candidates that are ignored when calculating "
89 "cost multiplier."));
Max Kazantsev619a8342018-10-26 14:20:11 +000090static cl::opt<bool> UnswitchGuards(
91 "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
92 cl::desc("If enabled, simple loop unswitching will also consider "
93 "llvm.experimental.guard intrinsics as unswitch candidates."));
94
Chandler Carruth4da33312018-06-20 18:57:07 +000095/// Collect all of the loop invariant input values transitively used by the
96/// homogeneous instruction graph from a given root.
97///
98/// This essentially walks from a root recursively through loop variant operands
99/// which have the exact same opcode and finds all inputs which are loop
100/// invariant. For some operations these can be re-associated and unswitched out
101/// of the loop entirely.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000102static TinyPtrVector<Value *>
Chandler Carruth4da33312018-06-20 18:57:07 +0000103collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
104 LoopInfo &LI) {
Chandler Carruth4da33312018-06-20 18:57:07 +0000105 assert(!L.isLoopInvariant(&Root) &&
106 "Only need to walk the graph if root itself is not invariant.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000107 TinyPtrVector<Value *> Invariants;
Chandler Carruth4da33312018-06-20 18:57:07 +0000108
109 // Build a worklist and recurse through operators collecting invariants.
110 SmallVector<Instruction *, 4> Worklist;
111 SmallPtrSet<Instruction *, 8> Visited;
112 Worklist.push_back(&Root);
113 Visited.insert(&Root);
114 do {
115 Instruction &I = *Worklist.pop_back_val();
116 for (Value *OpV : I.operand_values()) {
117 // Skip constants as unswitching isn't interesting for them.
118 if (isa<Constant>(OpV))
119 continue;
120
121 // Add it to our result if loop invariant.
122 if (L.isLoopInvariant(OpV)) {
123 Invariants.push_back(OpV);
124 continue;
125 }
126
127 // If not an instruction with the same opcode, nothing we can do.
128 Instruction *OpI = dyn_cast<Instruction>(OpV);
129 if (!OpI || OpI->getOpcode() != Root.getOpcode())
130 continue;
131
132 // Visit this operand.
133 if (Visited.insert(OpI).second)
134 Worklist.push_back(OpI);
135 }
136 } while (!Worklist.empty());
137
138 return Invariants;
139}
140
141static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
142 Constant &Replacement) {
143 assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000144
145 // Replace uses of LIC in the loop with the given constant.
Chandler Carruth4da33312018-06-20 18:57:07 +0000146 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end(); UI != UE;) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000147 // Grab the use and walk past it so we can clobber it in the use list.
148 Use *U = &*UI++;
149 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000150
151 // Replace this use within the loop body.
Chandler Carruth4da33312018-06-20 18:57:07 +0000152 if (UserI && L.contains(UserI))
153 U->set(&Replacement);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000154 }
155}
156
Chandler Carruthd869b182017-05-12 02:19:59 +0000157/// Check that all the LCSSA PHI nodes in the loop exit block have trivial
158/// incoming values along this edge.
159static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
160 BasicBlock &ExitBB) {
161 for (Instruction &I : ExitBB) {
162 auto *PN = dyn_cast<PHINode>(&I);
163 if (!PN)
164 // No more PHIs to check.
165 return true;
166
167 // If the incoming value for this edge isn't loop invariant the unswitch
168 // won't be trivial.
169 if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
170 return false;
171 }
172 llvm_unreachable("Basic blocks should never be empty!");
173}
174
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000175/// Insert code to test a set of loop invariant values, and conditionally branch
176/// on them.
177static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
178 ArrayRef<Value *> Invariants,
179 bool Direction,
180 BasicBlock &UnswitchedSucc,
181 BasicBlock &NormalSucc) {
182 IRBuilder<> IRB(&BB);
183 Value *Cond = Invariants.front();
184 for (Value *Invariant :
185 make_range(std::next(Invariants.begin()), Invariants.end()))
186 if (Direction)
187 Cond = IRB.CreateOr(Cond, Invariant);
188 else
189 Cond = IRB.CreateAnd(Cond, Invariant);
190
191 IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
192 Direction ? &NormalSucc : &UnswitchedSucc);
193}
194
Chandler Carruthd869b182017-05-12 02:19:59 +0000195/// Rewrite the PHI nodes in an unswitched loop exit basic block.
196///
197/// Requires that the loop exit and unswitched basic block are the same, and
198/// that the exiting block was a unique predecessor of that block. Rewrites the
199/// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
200/// PHI nodes from the old preheader that now contains the unswitched
201/// terminator.
202static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
203 BasicBlock &OldExitingBB,
204 BasicBlock &OldPH) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000205 for (PHINode &PN : UnswitchedBB.phis()) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000206 // When the loop exit is directly unswitched we just need to update the
207 // incoming basic block. We loop to handle weird cases with repeated
208 // incoming blocks, but expect to typically only have one operand here.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000209 for (auto i : seq<int>(0, PN.getNumOperands())) {
210 assert(PN.getIncomingBlock(i) == &OldExitingBB &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000211 "Found incoming block different from unique predecessor!");
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000212 PN.setIncomingBlock(i, &OldPH);
Chandler Carruthd869b182017-05-12 02:19:59 +0000213 }
214 }
215}
216
217/// Rewrite the PHI nodes in the loop exit basic block and the split off
218/// unswitched block.
219///
220/// Because the exit block remains an exit from the loop, this rewrites the
221/// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
222/// nodes into the unswitched basic block to select between the value in the
223/// old preheader and the loop exit.
224static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
225 BasicBlock &UnswitchedBB,
226 BasicBlock &OldExitingBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000227 BasicBlock &OldPH,
228 bool FullUnswitch) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000229 assert(&ExitBB != &UnswitchedBB &&
230 "Must have different loop exit and unswitched blocks!");
231 Instruction *InsertPt = &*UnswitchedBB.begin();
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000232 for (PHINode &PN : ExitBB.phis()) {
233 auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
234 PN.getName() + ".split", InsertPt);
Chandler Carruthd869b182017-05-12 02:19:59 +0000235
236 // Walk backwards over the old PHI node's inputs to minimize the cost of
237 // removing each one. We have to do this weird loop manually so that we
238 // create the same number of new incoming edges in the new PHI as we expect
239 // each case-based edge to be included in the unswitched switch in some
240 // cases.
241 // FIXME: This is really, really gross. It would be much cleaner if LLVM
242 // allowed us to create a single entry for a predecessor block without
243 // having separate entries for each "edge" even though these edges are
244 // required to produce identical results.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000245 for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
246 if (PN.getIncomingBlock(i) != &OldExitingBB)
Chandler Carruthd869b182017-05-12 02:19:59 +0000247 continue;
248
Chandler Carruth4da33312018-06-20 18:57:07 +0000249 Value *Incoming = PN.getIncomingValue(i);
250 if (FullUnswitch)
251 // No more edge from the old exiting block to the exit block.
252 PN.removeIncomingValue(i);
253
Chandler Carruthd869b182017-05-12 02:19:59 +0000254 NewPN->addIncoming(Incoming, &OldPH);
255 }
256
257 // Now replace the old PHI with the new one and wire the old one in as an
258 // input to the new one.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000259 PN.replaceAllUsesWith(NewPN);
260 NewPN->addIncoming(&PN, &ExitBB);
Chandler Carruthd869b182017-05-12 02:19:59 +0000261 }
262}
263
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000264/// Hoist the current loop up to the innermost loop containing a remaining exit.
265///
266/// Because we've removed an exit from the loop, we may have changed the set of
267/// loops reachable and need to move the current loop up the loop nest or even
268/// to an entirely separate nest.
269static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
270 DominatorTree &DT, LoopInfo &LI) {
271 // If the loop is already at the top level, we can't hoist it anywhere.
272 Loop *OldParentL = L.getParentLoop();
273 if (!OldParentL)
274 return;
275
276 SmallVector<BasicBlock *, 4> Exits;
277 L.getExitBlocks(Exits);
278 Loop *NewParentL = nullptr;
279 for (auto *ExitBB : Exits)
280 if (Loop *ExitL = LI.getLoopFor(ExitBB))
281 if (!NewParentL || NewParentL->contains(ExitL))
282 NewParentL = ExitL;
283
284 if (NewParentL == OldParentL)
285 return;
286
287 // The new parent loop (if different) should always contain the old one.
288 if (NewParentL)
289 assert(NewParentL->contains(OldParentL) &&
290 "Can only hoist this loop up the nest!");
291
292 // The preheader will need to move with the body of this loop. However,
293 // because it isn't in this loop we also need to update the primary loop map.
294 assert(OldParentL == LI.getLoopFor(&Preheader) &&
295 "Parent loop of this loop should contain this loop's preheader!");
296 LI.changeLoopFor(&Preheader, NewParentL);
297
298 // Remove this loop from its old parent.
299 OldParentL->removeChildLoop(&L);
300
301 // Add the loop either to the new parent or as a top-level loop.
302 if (NewParentL)
303 NewParentL->addChildLoop(&L);
304 else
305 LI.addTopLevelLoop(&L);
306
307 // Remove this loops blocks from the old parent and every other loop up the
308 // nest until reaching the new parent. Also update all of these
309 // no-longer-containing loops to reflect the nesting change.
310 for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
311 OldContainingL = OldContainingL->getParentLoop()) {
312 llvm::erase_if(OldContainingL->getBlocksVector(),
313 [&](const BasicBlock *BB) {
314 return BB == &Preheader || L.contains(BB);
315 });
316
317 OldContainingL->getBlocksSet().erase(&Preheader);
318 for (BasicBlock *BB : L.blocks())
319 OldContainingL->getBlocksSet().erase(BB);
320
321 // Because we just hoisted a loop out of this one, we have essentially
322 // created new exit paths from it. That means we need to form LCSSA PHI
323 // nodes for values used in the no-longer-nested loop.
324 formLCSSA(*OldContainingL, DT, &LI, nullptr);
325
326 // We shouldn't need to form dedicated exits because the exit introduced
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000327 // here is the (just split by unswitching) preheader. However, after trivial
328 // unswitching it is possible to get new non-dedicated exits out of parent
329 // loop so let's conservatively form dedicated exit blocks and figure out
330 // if we can optimize later.
331 formDedicatedExitBlocks(OldContainingL, &DT, &LI, /*PreserveLCSSA*/ true);
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000332 }
333}
334
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000335/// Unswitch a trivial branch if the condition is loop invariant.
336///
337/// This routine should only be called when loop code leading to the branch has
338/// been validated as trivial (no side effects). This routine checks if the
339/// condition is invariant and one of the successors is a loop exit. This
340/// allows us to unswitch without duplicating the loop, making it trivial.
341///
342/// If this routine fails to unswitch the branch it returns false.
343///
344/// If the branch can be unswitched, this routine splits the preheader and
345/// hoists the branch above that split. Preserves loop simplified form
346/// (splitting the exit block as necessary). It simplifies the branch within
347/// the loop to an unconditional branch but doesn't remove it entirely. Further
348/// cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000349///
350/// If `SE` is not null, it will be updated based on the potential loop SCEVs
351/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000352static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000353 LoopInfo &LI, ScalarEvolution *SE,
354 MemorySSAUpdater *MSSAU) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000355 assert(BI.isConditional() && "Can only unswitch a conditional branch!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000356 LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000357
Chandler Carruth4da33312018-06-20 18:57:07 +0000358 // The loop invariant values that we want to unswitch.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000359 TinyPtrVector<Value *> Invariants;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000360
Chandler Carruth4da33312018-06-20 18:57:07 +0000361 // When true, we're fully unswitching the branch rather than just unswitching
362 // some input conditions to the branch.
363 bool FullUnswitch = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000364
Chandler Carruth4da33312018-06-20 18:57:07 +0000365 if (L.isLoopInvariant(BI.getCondition())) {
366 Invariants.push_back(BI.getCondition());
367 FullUnswitch = true;
368 } else {
369 if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
370 Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
371 if (Invariants.empty())
372 // Couldn't find invariant inputs!
373 return false;
374 }
375
376 // Check that one of the branch's successors exits, and which one.
377 bool ExitDirection = true;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000378 int LoopExitSuccIdx = 0;
379 auto *LoopExitBB = BI.getSuccessor(0);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000380 if (L.contains(LoopExitBB)) {
Chandler Carruth4da33312018-06-20 18:57:07 +0000381 ExitDirection = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000382 LoopExitSuccIdx = 1;
383 LoopExitBB = BI.getSuccessor(1);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000384 if (L.contains(LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000385 return false;
386 }
387 auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
Chandler Carruthd869b182017-05-12 02:19:59 +0000388 auto *ParentBB = BI.getParent();
389 if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000390 return false;
391
Chandler Carruth4da33312018-06-20 18:57:07 +0000392 // When unswitching only part of the branch's condition, we need the exit
393 // block to be reached directly from the partially unswitched input. This can
394 // be done when the exit block is along the true edge and the branch condition
395 // is a graph of `or` operations, or the exit block is along the false edge
396 // and the condition is a graph of `and` operations.
397 if (!FullUnswitch) {
398 if (ExitDirection) {
399 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or)
400 return false;
401 } else {
402 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And)
403 return false;
404 }
405 }
406
407 LLVM_DEBUG({
408 dbgs() << " unswitching trivial invariant conditions for: " << BI
409 << "\n";
410 for (Value *Invariant : Invariants) {
411 dbgs() << " " << *Invariant << " == true";
412 if (Invariant != Invariants.back())
413 dbgs() << " ||";
414 dbgs() << "\n";
415 }
416 });
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000417
Chandler Carruth3897ded2018-07-03 09:13:27 +0000418 // If we have scalar evolutions, we need to invalidate them including this
419 // loop and the loop containing the exit block.
420 if (SE) {
421 if (Loop *ExitL = LI.getLoopFor(LoopExitBB))
422 SE->forgetLoop(ExitL);
423 else
424 // Forget the entire nest as this exits the entire nest.
425 SE->forgetTopmostLoop(&L);
426 }
427
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000428 if (MSSAU && VerifyMemorySSA)
429 MSSAU->getMemorySSA()->verifyMemorySSA();
430
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000431 // Split the preheader, so that we know that there is a safe place to insert
432 // the conditional branch. We will change the preheader to have a conditional
433 // branch on LoopCond.
434 BasicBlock *OldPH = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000435 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000436
437 // Now that we have a place to insert the conditional branch, create a place
438 // to branch to: this is the exit block out of the loop that we are
439 // unswitching. We need to split this if there are other loop predecessors.
440 // Because the loop is in simplified form, *any* other predecessor is enough.
441 BasicBlock *UnswitchedBB;
Chandler Carruth4da33312018-06-20 18:57:07 +0000442 if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
443 assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000444 "A branch's parent isn't a predecessor!");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000445 UnswitchedBB = LoopExitBB;
446 } else {
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000447 UnswitchedBB =
448 SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000449 }
450
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000451 if (MSSAU && VerifyMemorySSA)
452 MSSAU->getMemorySSA()->verifyMemorySSA();
453
Chandler Carruth4da33312018-06-20 18:57:07 +0000454 // Actually move the invariant uses into the unswitched position. If possible,
455 // we do this by moving the instructions, but when doing partial unswitching
456 // we do it by building a new merge of the values in the unswitched position.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000457 OldPH->getTerminator()->eraseFromParent();
Chandler Carruth4da33312018-06-20 18:57:07 +0000458 if (FullUnswitch) {
459 // If fully unswitching, we can use the existing branch instruction.
460 // Splice it into the old PH to gate reaching the new preheader and re-point
461 // its successors.
462 OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
463 BI);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000464 if (MSSAU) {
465 // Temporarily clone the terminator, to make MSSA update cheaper by
466 // separating "insert edge" updates from "remove edge" ones.
467 ParentBB->getInstList().push_back(BI.clone());
468 } else {
469 // Create a new unconditional branch that will continue the loop as a new
470 // terminator.
471 BranchInst::Create(ContinueBB, ParentBB);
472 }
Chandler Carruth4da33312018-06-20 18:57:07 +0000473 BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
474 BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
Chandler Carruth4da33312018-06-20 18:57:07 +0000475 } else {
476 // Only unswitching a subset of inputs to the condition, so we will need to
477 // build a new branch that merges the invariant inputs.
Chandler Carruth4da33312018-06-20 18:57:07 +0000478 if (ExitDirection)
479 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
480 Instruction::Or &&
481 "Must have an `or` of `i1`s for the condition!");
482 else
483 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
484 Instruction::And &&
485 "Must have an `and` of `i1`s for the condition!");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000486 buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
487 *UnswitchedBB, *NewPH);
Chandler Carruth4da33312018-06-20 18:57:07 +0000488 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000489
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000490 // Update the dominator tree with the added edge.
491 DT.insertEdge(OldPH, UnswitchedBB);
492
493 // After the dominator tree was updated with the added edge, update MemorySSA
494 // if available.
495 if (MSSAU) {
496 SmallVector<CFGUpdate, 1> Updates;
497 Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
498 MSSAU->applyInsertUpdates(Updates, DT);
499 }
500
501 // Finish updating dominator tree and memory ssa for full unswitch.
502 if (FullUnswitch) {
503 if (MSSAU) {
504 // Remove the cloned branch instruction.
505 ParentBB->getTerminator()->eraseFromParent();
506 // Create unconditional branch now.
507 BranchInst::Create(ContinueBB, ParentBB);
508 MSSAU->removeEdge(ParentBB, LoopExitBB);
509 }
510 DT.deleteEdge(ParentBB, LoopExitBB);
511 }
512
513 if (MSSAU && VerifyMemorySSA)
514 MSSAU->getMemorySSA()->verifyMemorySSA();
515
Chandler Carruthd869b182017-05-12 02:19:59 +0000516 // Rewrite the relevant PHI nodes.
517 if (UnswitchedBB == LoopExitBB)
518 rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
519 else
520 rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000521 *ParentBB, *OldPH, FullUnswitch);
Chandler Carruthd869b182017-05-12 02:19:59 +0000522
Chandler Carruth4da33312018-06-20 18:57:07 +0000523 // The constant we can replace all of our invariants with inside the loop
524 // body. If any of the invariants have a value other than this the loop won't
525 // be entered.
526 ConstantInt *Replacement = ExitDirection
527 ? ConstantInt::getFalse(BI.getContext())
528 : ConstantInt::getTrue(BI.getContext());
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000529
530 // Since this is an i1 condition we can also trivially replace uses of it
531 // within the loop with a constant.
Chandler Carruth4da33312018-06-20 18:57:07 +0000532 for (Value *Invariant : Invariants)
533 replaceLoopInvariantUses(L, Invariant, *Replacement);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000534
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000535 // If this was full unswitching, we may have changed the nesting relationship
536 // for this loop so hoist it to its correct parent if needed.
537 if (FullUnswitch)
538 hoistLoopToNewParent(L, *NewPH, DT, LI);
539
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000540 LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000541 ++NumTrivial;
542 ++NumBranches;
543 return true;
544}
545
546/// Unswitch a trivial switch if the condition is loop invariant.
547///
548/// This routine should only be called when loop code leading to the switch has
549/// been validated as trivial (no side effects). This routine checks if the
550/// condition is invariant and that at least one of the successors is a loop
551/// exit. This allows us to unswitch without duplicating the loop, making it
552/// trivial.
553///
554/// If this routine fails to unswitch the switch it returns false.
555///
556/// If the switch can be unswitched, this routine splits the preheader and
557/// copies the switch above that split. If the default case is one of the
558/// exiting cases, it copies the non-exiting cases and points them at the new
559/// preheader. If the default case is not exiting, it copies the exiting cases
560/// and points the default at the preheader. It preserves loop simplified form
561/// (splitting the exit blocks as necessary). It simplifies the switch within
562/// the loop by removing now-dead cases. If the default case is one of those
563/// unswitched, it replaces its destination with a new basic block containing
564/// only unreachable. Such basic blocks, while technically loop exits, are not
565/// considered for unswitching so this is a stable transform and the same
566/// switch will not be revisited. If after unswitching there is only a single
567/// in-loop successor, the switch is further simplified to an unconditional
568/// branch. Still more cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000569///
570/// If `SE` is not null, it will be updated based on the potential loop SCEVs
571/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000572static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000573 LoopInfo &LI, ScalarEvolution *SE,
574 MemorySSAUpdater *MSSAU) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000575 LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000576 Value *LoopCond = SI.getCondition();
577
578 // If this isn't switching on an invariant condition, we can't unswitch it.
579 if (!L.isLoopInvariant(LoopCond))
580 return false;
581
Chandler Carruthd869b182017-05-12 02:19:59 +0000582 auto *ParentBB = SI.getParent();
583
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000584 SmallVector<int, 4> ExitCaseIndices;
585 for (auto Case : SI.cases()) {
586 auto *SuccBB = Case.getCaseSuccessor();
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000587 if (!L.contains(SuccBB) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000588 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000589 ExitCaseIndices.push_back(Case.getCaseIndex());
590 }
591 BasicBlock *DefaultExitBB = nullptr;
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000592 if (!L.contains(SI.getDefaultDest()) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000593 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) &&
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000594 !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator()))
595 DefaultExitBB = SI.getDefaultDest();
596 else if (ExitCaseIndices.empty())
597 return false;
598
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000599 LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000600
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000601 if (MSSAU && VerifyMemorySSA)
602 MSSAU->getMemorySSA()->verifyMemorySSA();
603
Chandler Carruth3897ded2018-07-03 09:13:27 +0000604 // We may need to invalidate SCEVs for the outermost loop reached by any of
605 // the exits.
606 Loop *OuterL = &L;
607
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000608 if (DefaultExitBB) {
609 // Clear out the default destination temporarily to allow accurate
610 // predecessor lists to be examined below.
611 SI.setDefaultDest(nullptr);
612 // Check the loop containing this exit.
613 Loop *ExitL = LI.getLoopFor(DefaultExitBB);
614 if (!ExitL || ExitL->contains(OuterL))
615 OuterL = ExitL;
616 }
617
618 // Store the exit cases into a separate data structure and remove them from
619 // the switch.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000620 SmallVector<std::pair<ConstantInt *, BasicBlock *>, 4> ExitCases;
621 ExitCases.reserve(ExitCaseIndices.size());
622 // We walk the case indices backwards so that we remove the last case first
623 // and don't disrupt the earlier indices.
624 for (unsigned Index : reverse(ExitCaseIndices)) {
625 auto CaseI = SI.case_begin() + Index;
Chandler Carruth3897ded2018-07-03 09:13:27 +0000626 // Compute the outer loop from this exit.
627 Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
628 if (!ExitL || ExitL->contains(OuterL))
629 OuterL = ExitL;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000630 // Save the value of this case.
631 ExitCases.push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()});
632 // Delete the unswitched cases.
633 SI.removeCase(CaseI);
634 }
635
Chandler Carruth3897ded2018-07-03 09:13:27 +0000636 if (SE) {
637 if (OuterL)
638 SE->forgetLoop(OuterL);
639 else
640 SE->forgetTopmostLoop(&L);
641 }
642
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000643 // Check if after this all of the remaining cases point at the same
644 // successor.
645 BasicBlock *CommonSuccBB = nullptr;
646 if (SI.getNumCases() > 0 &&
647 std::all_of(std::next(SI.case_begin()), SI.case_end(),
648 [&SI](const SwitchInst::CaseHandle &Case) {
649 return Case.getCaseSuccessor() ==
650 SI.case_begin()->getCaseSuccessor();
651 }))
652 CommonSuccBB = SI.case_begin()->getCaseSuccessor();
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000653 if (!DefaultExitBB) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000654 // If we're not unswitching the default, we need it to match any cases to
655 // have a common successor or if we have no cases it is the common
656 // successor.
657 if (SI.getNumCases() == 0)
658 CommonSuccBB = SI.getDefaultDest();
659 else if (SI.getDefaultDest() != CommonSuccBB)
660 CommonSuccBB = nullptr;
661 }
662
663 // Split the preheader, so that we know that there is a safe place to insert
664 // the switch.
665 BasicBlock *OldPH = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000666 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000667 OldPH->getTerminator()->eraseFromParent();
668
669 // Now add the unswitched switch.
670 auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
671
Chandler Carruthd869b182017-05-12 02:19:59 +0000672 // Rewrite the IR for the unswitched basic blocks. This requires two steps.
673 // First, we split any exit blocks with remaining in-loop predecessors. Then
674 // we update the PHIs in one of two ways depending on if there was a split.
675 // We walk in reverse so that we split in the same order as the cases
676 // appeared. This is purely for convenience of reading the resulting IR, but
677 // it doesn't cost anything really.
678 SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000679 SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
680 // Handle the default exit if necessary.
681 // FIXME: It'd be great if we could merge this with the loop below but LLVM's
682 // ranges aren't quite powerful enough yet.
Chandler Carruthd869b182017-05-12 02:19:59 +0000683 if (DefaultExitBB) {
684 if (pred_empty(DefaultExitBB)) {
685 UnswitchedExitBBs.insert(DefaultExitBB);
686 rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
687 } else {
688 auto *SplitBB =
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000689 SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
690 rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
691 *ParentBB, *OldPH,
692 /*FullUnswitch*/ true);
Chandler Carruthd869b182017-05-12 02:19:59 +0000693 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
694 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000695 }
696 // Note that we must use a reference in the for loop so that we update the
697 // container.
698 for (auto &CasePair : reverse(ExitCases)) {
699 // Grab a reference to the exit block in the pair so that we can update it.
Chandler Carruthd869b182017-05-12 02:19:59 +0000700 BasicBlock *ExitBB = CasePair.second;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000701
702 // If this case is the last edge into the exit block, we can simply reuse it
703 // as it will no longer be a loop exit. No mapping necessary.
Chandler Carruthd869b182017-05-12 02:19:59 +0000704 if (pred_empty(ExitBB)) {
705 // Only rewrite once.
706 if (UnswitchedExitBBs.insert(ExitBB).second)
707 rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000708 continue;
Chandler Carruthd869b182017-05-12 02:19:59 +0000709 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000710
711 // Otherwise we need to split the exit block so that we retain an exit
712 // block from the loop and a target for the unswitched condition.
713 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
714 if (!SplitExitBB) {
715 // If this is the first time we see this, do the split and remember it.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000716 SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
717 rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
718 *ParentBB, *OldPH,
719 /*FullUnswitch*/ true);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000720 }
Chandler Carruthd869b182017-05-12 02:19:59 +0000721 // Update the case pair to point to the split block.
722 CasePair.second = SplitExitBB;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000723 }
724
725 // Now add the unswitched cases. We do this in reverse order as we built them
726 // in reverse order.
727 for (auto CasePair : reverse(ExitCases)) {
728 ConstantInt *CaseVal = CasePair.first;
729 BasicBlock *UnswitchedBB = CasePair.second;
730
731 NewSI->addCase(CaseVal, UnswitchedBB);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000732 }
733
734 // If the default was unswitched, re-point it and add explicit cases for
735 // entering the loop.
736 if (DefaultExitBB) {
737 NewSI->setDefaultDest(DefaultExitBB);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000738
739 // We removed all the exit cases, so we just copy the cases to the
740 // unswitched switch.
741 for (auto Case : SI.cases())
742 NewSI->addCase(Case.getCaseValue(), NewPH);
743 }
744
745 // If we ended up with a common successor for every path through the switch
746 // after unswitching, rewrite it to an unconditional branch to make it easy
747 // to recognize. Otherwise we potentially have to recognize the default case
748 // pointing at unreachable and other complexity.
749 if (CommonSuccBB) {
750 BasicBlock *BB = SI.getParent();
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000751 // We may have had multiple edges to this common successor block, so remove
752 // them as predecessors. We skip the first one, either the default or the
753 // actual first case.
754 bool SkippedFirst = DefaultExitBB == nullptr;
755 for (auto Case : SI.cases()) {
756 assert(Case.getCaseSuccessor() == CommonSuccBB &&
757 "Non-common successor!");
Chandler Carruth148861f2018-07-10 08:57:04 +0000758 (void)Case;
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000759 if (!SkippedFirst) {
760 SkippedFirst = true;
761 continue;
762 }
763 CommonSuccBB->removePredecessor(BB,
764 /*DontDeleteUselessPHIs*/ true);
765 }
766 // Now nuke the switch and replace it with a direct branch.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000767 SI.eraseFromParent();
768 BranchInst::Create(CommonSuccBB, BB);
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000769 } else if (DefaultExitBB) {
770 assert(SI.getNumCases() > 0 &&
771 "If we had no cases we'd have a common successor!");
772 // Move the last case to the default successor. This is valid as if the
773 // default got unswitched it cannot be reached. This has the advantage of
774 // being simple and keeping the number of edges from this switch to
775 // successors the same, and avoiding any PHI update complexity.
776 auto LastCaseI = std::prev(SI.case_end());
777 SI.setDefaultDest(LastCaseI->getCaseSuccessor());
778 SI.removeCase(LastCaseI);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000779 }
780
Chandler Carruth2c85a232018-05-01 09:54:39 +0000781 // Walk the unswitched exit blocks and the unswitched split blocks and update
782 // the dominator tree based on the CFG edits. While we are walking unordered
783 // containers here, the API for applyUpdates takes an unordered list of
784 // updates and requires them to not contain duplicates.
785 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
786 for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
787 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
788 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
789 }
790 for (auto SplitUnswitchedPair : SplitExitBBMap) {
791 auto *UnswitchedBB = SplitUnswitchedPair.second;
792 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedBB});
793 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedBB});
794 }
795 DT.applyUpdates(DTUpdates);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000796
797 if (MSSAU) {
798 MSSAU->applyUpdates(DTUpdates, DT);
799 if (VerifyMemorySSA)
800 MSSAU->getMemorySSA()->verifyMemorySSA();
801 }
802
David Green7c35de12018-02-28 11:00:08 +0000803 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000804
805 // We may have changed the nesting relationship for this loop so hoist it to
806 // its correct parent if needed.
807 hoistLoopToNewParent(L, *NewPH, DT, LI);
808
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000809 ++NumTrivial;
810 ++NumSwitches;
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000811 LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000812 return true;
813}
814
815/// This routine scans the loop to find a branch or switch which occurs before
816/// any side effects occur. These can potentially be unswitched without
817/// duplicating the loop. If a branch or switch is successfully unswitched the
818/// scanning continues to see if subsequent branches or switches have become
819/// trivial. Once all trivial candidates have been unswitched, this routine
820/// returns.
821///
822/// The return value indicates whether anything was unswitched (and therefore
823/// changed).
Chandler Carruth3897ded2018-07-03 09:13:27 +0000824///
825/// If `SE` is not null, it will be updated based on the potential loop SCEVs
826/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000827static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000828 LoopInfo &LI, ScalarEvolution *SE,
829 MemorySSAUpdater *MSSAU) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000830 bool Changed = false;
831
832 // If loop header has only one reachable successor we should keep looking for
833 // trivial condition candidates in the successor as well. An alternative is
834 // to constant fold conditions and merge successors into loop header (then we
835 // only need to check header's terminator). The reason for not doing this in
836 // LoopUnswitch pass is that it could potentially break LoopPassManager's
837 // invariants. Folding dead branches could either eliminate the current loop
838 // or make other loops unreachable. LCSSA form might also not be preserved
839 // after deleting branches. The following code keeps traversing loop header's
840 // successors until it finds the trivial condition candidate (condition that
841 // is not a constant). Since unswitching generates branches with constant
842 // conditions, this scenario could be very common in practice.
843 BasicBlock *CurrentBB = L.getHeader();
844 SmallPtrSet<BasicBlock *, 8> Visited;
845 Visited.insert(CurrentBB);
846 do {
847 // Check if there are any side-effecting instructions (e.g. stores, calls,
848 // volatile loads) in the part of the loop that the code *would* execute
849 // without unswitching.
Alina Sbirlea93210872019-01-28 17:48:45 +0000850 if (MSSAU) // Possible early exit with MSSA
851 if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
852 if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
853 return Changed;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000854 if (llvm::any_of(*CurrentBB,
855 [](Instruction &I) { return I.mayHaveSideEffects(); }))
856 return Changed;
857
Chandler Carruthedb12a82018-10-15 10:04:59 +0000858 Instruction *CurrentTerm = CurrentBB->getTerminator();
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000859
860 if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
861 // Don't bother trying to unswitch past a switch with a constant
862 // condition. This should be removed prior to running this pass by
863 // simplify-cfg.
864 if (isa<Constant>(SI->getCondition()))
865 return Changed;
866
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000867 if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
Hiroshi Inouef2096492018-06-14 05:41:49 +0000868 // Couldn't unswitch this one so we're done.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000869 return Changed;
870
871 // Mark that we managed to unswitch something.
872 Changed = true;
873
874 // If unswitching turned the terminator into an unconditional branch then
875 // we can continue. The unswitching logic specifically works to fold any
876 // cases it can into an unconditional branch to make it easier to
877 // recognize here.
878 auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
879 if (!BI || BI->isConditional())
880 return Changed;
881
882 CurrentBB = BI->getSuccessor(0);
883 continue;
884 }
885
886 auto *BI = dyn_cast<BranchInst>(CurrentTerm);
887 if (!BI)
888 // We do not understand other terminator instructions.
889 return Changed;
890
891 // Don't bother trying to unswitch past an unconditional branch or a branch
892 // with a constant value. These should be removed by simplify-cfg prior to
893 // running this pass.
894 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
895 return Changed;
896
897 // Found a trivial condition candidate: non-foldable conditional branch. If
898 // we fail to unswitch this, we can't do anything else that is trivial.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000899 if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000900 return Changed;
901
902 // Mark that we managed to unswitch something.
903 Changed = true;
904
Chandler Carruth4da33312018-06-20 18:57:07 +0000905 // If we only unswitched some of the conditions feeding the branch, we won't
906 // have collapsed it to a single successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000907 BI = cast<BranchInst>(CurrentBB->getTerminator());
Chandler Carruth4da33312018-06-20 18:57:07 +0000908 if (BI->isConditional())
909 return Changed;
910
911 // Follow the newly unconditional branch into its successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000912 CurrentBB = BI->getSuccessor(0);
913
914 // When continuing, if we exit the loop or reach a previous visited block,
915 // then we can not reach any trivial condition candidates (unfoldable
916 // branch instructions or switch instructions) and no unswitch can happen.
917 } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
918
919 return Changed;
920}
921
Chandler Carruth693eedb2017-11-17 19:58:36 +0000922/// Build the cloned blocks for an unswitched copy of the given loop.
923///
924/// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
925/// after the split block (`SplitBB`) that will be used to select between the
926/// cloned and original loop.
927///
928/// This routine handles cloning all of the necessary loop blocks and exit
929/// blocks including rewriting their instructions and the relevant PHI nodes.
Chandler Carruth16529962018-06-25 23:32:54 +0000930/// Any loop blocks or exit blocks which are dominated by a different successor
931/// than the one for this clone of the loop blocks can be trivially skipped. We
932/// use the `DominatingSucc` map to determine whether a block satisfies that
933/// property with a simple map lookup.
934///
935/// It also correctly creates the unconditional branch in the cloned
Chandler Carruth693eedb2017-11-17 19:58:36 +0000936/// unswitched parent block to only point at the unswitched successor.
937///
938/// This does not handle most of the necessary updates to `LoopInfo`. Only exit
939/// block splitting is correctly reflected in `LoopInfo`, essentially all of
940/// the cloned blocks (and their loops) are left without full `LoopInfo`
941/// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
942/// blocks to them but doesn't create the cloned `DominatorTree` structure and
943/// instead the caller must recompute an accurate DT. It *does* correctly
944/// update the `AssumptionCache` provided in `AC`.
945static BasicBlock *buildClonedLoopBlocks(
946 Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
947 ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
948 BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
Chandler Carruth16529962018-06-25 23:32:54 +0000949 const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
Chandler Carruth69e68f82018-04-25 00:18:07 +0000950 ValueToValueMapTy &VMap,
951 SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000952 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Chandler Carruth693eedb2017-11-17 19:58:36 +0000953 SmallVector<BasicBlock *, 4> NewBlocks;
954 NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
955
956 // We will need to clone a bunch of blocks, wrap up the clone operation in
957 // a helper.
958 auto CloneBlock = [&](BasicBlock *OldBB) {
959 // Clone the basic block and insert it before the new preheader.
960 BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
961 NewBB->moveBefore(LoopPH);
962
963 // Record this block and the mapping.
964 NewBlocks.push_back(NewBB);
965 VMap[OldBB] = NewBB;
966
Chandler Carruth693eedb2017-11-17 19:58:36 +0000967 return NewBB;
968 };
969
Chandler Carruth16529962018-06-25 23:32:54 +0000970 // We skip cloning blocks when they have a dominating succ that is not the
971 // succ we are cloning for.
972 auto SkipBlock = [&](BasicBlock *BB) {
973 auto It = DominatingSucc.find(BB);
974 return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
975 };
976
Chandler Carruth693eedb2017-11-17 19:58:36 +0000977 // First, clone the preheader.
978 auto *ClonedPH = CloneBlock(LoopPH);
979
980 // Then clone all the loop blocks, skipping the ones that aren't necessary.
981 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +0000982 if (!SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +0000983 CloneBlock(LoopBB);
984
985 // Split all the loop exit edges so that when we clone the exit blocks, if
986 // any of the exit blocks are *also* a preheader for some other loop, we
987 // don't create multiple predecessors entering the loop header.
988 for (auto *ExitBB : ExitBlocks) {
Chandler Carruth16529962018-06-25 23:32:54 +0000989 if (SkipBlock(ExitBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +0000990 continue;
991
992 // When we are going to clone an exit, we don't need to clone all the
993 // instructions in the exit block and we want to ensure we have an easy
994 // place to merge the CFG, so split the exit first. This is always safe to
995 // do because there cannot be any non-loop predecessors of a loop exit in
996 // loop simplified form.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000997 auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
Chandler Carruth693eedb2017-11-17 19:58:36 +0000998
999 // Rearrange the names to make it easier to write test cases by having the
1000 // exit block carry the suffix rather than the merge block carrying the
1001 // suffix.
1002 MergeBB->takeName(ExitBB);
1003 ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1004
1005 // Now clone the original exit block.
1006 auto *ClonedExitBB = CloneBlock(ExitBB);
1007 assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1008 "Exit block should have been split to have one successor!");
1009 assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1010 "Cloned exit block has the wrong successor!");
1011
Chandler Carruth693eedb2017-11-17 19:58:36 +00001012 // Remap any cloned instructions and create a merge phi node for them.
1013 for (auto ZippedInsts : llvm::zip_first(
1014 llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1015 llvm::make_range(ClonedExitBB->begin(),
1016 std::prev(ClonedExitBB->end())))) {
1017 Instruction &I = std::get<0>(ZippedInsts);
1018 Instruction &ClonedI = std::get<1>(ZippedInsts);
1019
1020 // The only instructions in the exit block should be PHI nodes and
1021 // potentially a landing pad.
1022 assert(
1023 (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1024 "Bad instruction in exit block!");
1025 // We should have a value map between the instruction and its clone.
1026 assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1027
1028 auto *MergePN =
1029 PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1030 &*MergeBB->getFirstInsertionPt());
1031 I.replaceAllUsesWith(MergePN);
1032 MergePN->addIncoming(&I, ExitBB);
1033 MergePN->addIncoming(&ClonedI, ClonedExitBB);
1034 }
1035 }
1036
1037 // Rewrite the instructions in the cloned blocks to refer to the instructions
1038 // in the cloned blocks. We have to do this as a second pass so that we have
1039 // everything available. Also, we have inserted new instructions which may
1040 // include assume intrinsics, so we update the assumption cache while
1041 // processing this.
1042 for (auto *ClonedBB : NewBlocks)
1043 for (Instruction &I : *ClonedBB) {
1044 RemapInstruction(&I, VMap,
1045 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1046 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1047 if (II->getIntrinsicID() == Intrinsic::assume)
1048 AC.registerAssumption(II);
1049 }
1050
Chandler Carruth693eedb2017-11-17 19:58:36 +00001051 // Update any PHI nodes in the cloned successors of the skipped blocks to not
1052 // have spurious incoming values.
1053 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +00001054 if (SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001055 for (auto *SuccBB : successors(LoopBB))
1056 if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1057 for (PHINode &PN : ClonedSuccBB->phis())
1058 PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1059
Chandler Carruthed296542018-07-09 10:30:48 +00001060 // Remove the cloned parent as a predecessor of any successor we ended up
1061 // cloning other than the unswitched one.
1062 auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1063 for (auto *SuccBB : successors(ParentBB)) {
1064 if (SuccBB == UnswitchedSuccBB)
1065 continue;
1066
1067 auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1068 if (!ClonedSuccBB)
1069 continue;
1070
1071 ClonedSuccBB->removePredecessor(ClonedParentBB,
1072 /*DontDeleteUselessPHIs*/ true);
1073 }
1074
1075 // Replace the cloned branch with an unconditional branch to the cloned
1076 // unswitched successor.
1077 auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1078 ClonedParentBB->getTerminator()->eraseFromParent();
1079 BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1080
1081 // If there are duplicate entries in the PHI nodes because of multiple edges
1082 // to the unswitched successor, we need to nuke all but one as we replaced it
1083 // with a direct branch.
1084 for (PHINode &PN : ClonedSuccBB->phis()) {
1085 bool Found = false;
1086 // Loop over the incoming operands backwards so we can easily delete as we
1087 // go without invalidating the index.
1088 for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1089 if (PN.getIncomingBlock(i) != ClonedParentBB)
1090 continue;
1091 if (!Found) {
1092 Found = true;
1093 continue;
1094 }
1095 PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1096 }
1097 }
1098
Chandler Carruth69e68f82018-04-25 00:18:07 +00001099 // Record the domtree updates for the new blocks.
Chandler Carruth44aab922018-05-01 09:42:09 +00001100 SmallPtrSet<BasicBlock *, 4> SuccSet;
1101 for (auto *ClonedBB : NewBlocks) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001102 for (auto *SuccBB : successors(ClonedBB))
Chandler Carruth44aab922018-05-01 09:42:09 +00001103 if (SuccSet.insert(SuccBB).second)
1104 DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1105 SuccSet.clear();
1106 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001107
Chandler Carruth693eedb2017-11-17 19:58:36 +00001108 return ClonedPH;
1109}
1110
1111/// Recursively clone the specified loop and all of its children.
1112///
1113/// The target parent loop for the clone should be provided, or can be null if
1114/// the clone is a top-level loop. While cloning, all the blocks are mapped
1115/// with the provided value map. The entire original loop must be present in
1116/// the value map. The cloned loop is returned.
1117static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1118 const ValueToValueMapTy &VMap, LoopInfo &LI) {
1119 auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1120 assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1121 ClonedL.reserveBlocks(OrigL.getNumBlocks());
1122 for (auto *BB : OrigL.blocks()) {
1123 auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1124 ClonedL.addBlockEntry(ClonedBB);
Chandler Carruth0ace1482018-04-24 03:27:00 +00001125 if (LI.getLoopFor(BB) == &OrigL)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001126 LI.changeLoopFor(ClonedBB, &ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001127 }
1128 };
1129
1130 // We specially handle the first loop because it may get cloned into
1131 // a different parent and because we most commonly are cloning leaf loops.
1132 Loop *ClonedRootL = LI.AllocateLoop();
1133 if (RootParentL)
1134 RootParentL->addChildLoop(ClonedRootL);
1135 else
1136 LI.addTopLevelLoop(ClonedRootL);
1137 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1138
1139 if (OrigRootL.empty())
1140 return ClonedRootL;
1141
1142 // If we have a nest, we can quickly clone the entire loop nest using an
1143 // iterative approach because it is a tree. We keep the cloned parent in the
1144 // data structure to avoid repeatedly querying through a map to find it.
1145 SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1146 // Build up the loops to clone in reverse order as we'll clone them from the
1147 // back.
1148 for (Loop *ChildL : llvm::reverse(OrigRootL))
1149 LoopsToClone.push_back({ClonedRootL, ChildL});
1150 do {
1151 Loop *ClonedParentL, *L;
1152 std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1153 Loop *ClonedL = LI.AllocateLoop();
1154 ClonedParentL->addChildLoop(ClonedL);
1155 AddClonedBlocksToLoop(*L, *ClonedL);
1156 for (Loop *ChildL : llvm::reverse(*L))
1157 LoopsToClone.push_back({ClonedL, ChildL});
1158 } while (!LoopsToClone.empty());
1159
1160 return ClonedRootL;
1161}
1162
1163/// Build the cloned loops of an original loop from unswitching.
1164///
1165/// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1166/// operation. We need to re-verify that there even is a loop (as the backedge
1167/// may not have been cloned), and even if there are remaining backedges the
1168/// backedge set may be different. However, we know that each child loop is
1169/// undisturbed, we only need to find where to place each child loop within
1170/// either any parent loop or within a cloned version of the original loop.
1171///
1172/// Because child loops may end up cloned outside of any cloned version of the
1173/// original loop, multiple cloned sibling loops may be created. All of them
1174/// are returned so that the newly introduced loop nest roots can be
1175/// identified.
Chandler Carruth92815032018-06-02 01:29:01 +00001176static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1177 const ValueToValueMapTy &VMap, LoopInfo &LI,
1178 SmallVectorImpl<Loop *> &NonChildClonedLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00001179 Loop *ClonedL = nullptr;
1180
1181 auto *OrigPH = OrigL.getLoopPreheader();
1182 auto *OrigHeader = OrigL.getHeader();
1183
1184 auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1185 auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1186
1187 // We need to know the loops of the cloned exit blocks to even compute the
1188 // accurate parent loop. If we only clone exits to some parent of the
1189 // original parent, we want to clone into that outer loop. We also keep track
1190 // of the loops that our cloned exit blocks participate in.
1191 Loop *ParentL = nullptr;
1192 SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1193 SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1194 ClonedExitsInLoops.reserve(ExitBlocks.size());
1195 for (auto *ExitBB : ExitBlocks)
1196 if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1197 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1198 ExitLoopMap[ClonedExitBB] = ExitL;
1199 ClonedExitsInLoops.push_back(ClonedExitBB);
1200 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1201 ParentL = ExitL;
1202 }
1203 assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1204 ParentL->contains(OrigL.getParentLoop())) &&
1205 "The computed parent loop should always contain (or be) the parent of "
1206 "the original loop.");
1207
1208 // We build the set of blocks dominated by the cloned header from the set of
1209 // cloned blocks out of the original loop. While not all of these will
1210 // necessarily be in the cloned loop, it is enough to establish that they
1211 // aren't in unreachable cycles, etc.
1212 SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1213 for (auto *BB : OrigL.blocks())
1214 if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1215 ClonedLoopBlocks.insert(ClonedBB);
1216
1217 // Rebuild the set of blocks that will end up in the cloned loop. We may have
1218 // skipped cloning some region of this loop which can in turn skip some of
1219 // the backedges so we have to rebuild the blocks in the loop based on the
1220 // backedges that remain after cloning.
1221 SmallVector<BasicBlock *, 16> Worklist;
1222 SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1223 for (auto *Pred : predecessors(ClonedHeader)) {
1224 // The only possible non-loop header predecessor is the preheader because
1225 // we know we cloned the loop in simplified form.
1226 if (Pred == ClonedPH)
1227 continue;
1228
1229 // Because the loop was in simplified form, the only non-loop predecessor
1230 // should be the preheader.
1231 assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1232 "header other than the preheader "
1233 "that is not part of the loop!");
1234
1235 // Insert this block into the loop set and on the first visit (and if it
1236 // isn't the header we're currently walking) put it into the worklist to
1237 // recurse through.
1238 if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1239 Worklist.push_back(Pred);
1240 }
1241
1242 // If we had any backedges then there *is* a cloned loop. Put the header into
1243 // the loop set and then walk the worklist backwards to find all the blocks
1244 // that remain within the loop after cloning.
1245 if (!BlocksInClonedLoop.empty()) {
1246 BlocksInClonedLoop.insert(ClonedHeader);
1247
1248 while (!Worklist.empty()) {
1249 BasicBlock *BB = Worklist.pop_back_val();
1250 assert(BlocksInClonedLoop.count(BB) &&
1251 "Didn't put block into the loop set!");
1252
1253 // Insert any predecessors that are in the possible set into the cloned
1254 // set, and if the insert is successful, add them to the worklist. Note
1255 // that we filter on the blocks that are definitely reachable via the
1256 // backedge to the loop header so we may prune out dead code within the
1257 // cloned loop.
1258 for (auto *Pred : predecessors(BB))
1259 if (ClonedLoopBlocks.count(Pred) &&
1260 BlocksInClonedLoop.insert(Pred).second)
1261 Worklist.push_back(Pred);
1262 }
1263
1264 ClonedL = LI.AllocateLoop();
1265 if (ParentL) {
1266 ParentL->addBasicBlockToLoop(ClonedPH, LI);
1267 ParentL->addChildLoop(ClonedL);
1268 } else {
1269 LI.addTopLevelLoop(ClonedL);
1270 }
Chandler Carruth92815032018-06-02 01:29:01 +00001271 NonChildClonedLoops.push_back(ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001272
1273 ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1274 // We don't want to just add the cloned loop blocks based on how we
1275 // discovered them. The original order of blocks was carefully built in
1276 // a way that doesn't rely on predecessor ordering. Rather than re-invent
1277 // that logic, we just re-walk the original blocks (and those of the child
1278 // loops) and filter them as we add them into the cloned loop.
1279 for (auto *BB : OrigL.blocks()) {
1280 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1281 if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1282 continue;
1283
1284 // Directly add the blocks that are only in this loop.
1285 if (LI.getLoopFor(BB) == &OrigL) {
1286 ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1287 continue;
1288 }
1289
1290 // We want to manually add it to this loop and parents.
1291 // Registering it with LoopInfo will happen when we clone the top
1292 // loop for this block.
1293 for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1294 PL->addBlockEntry(ClonedBB);
1295 }
1296
1297 // Now add each child loop whose header remains within the cloned loop. All
1298 // of the blocks within the loop must satisfy the same constraints as the
1299 // header so once we pass the header checks we can just clone the entire
1300 // child loop nest.
1301 for (Loop *ChildL : OrigL) {
1302 auto *ClonedChildHeader =
1303 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1304 if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1305 continue;
1306
1307#ifndef NDEBUG
1308 // We should never have a cloned child loop header but fail to have
1309 // all of the blocks for that child loop.
1310 for (auto *ChildLoopBB : ChildL->blocks())
1311 assert(BlocksInClonedLoop.count(
1312 cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1313 "Child cloned loop has a header within the cloned outer "
1314 "loop but not all of its blocks!");
1315#endif
1316
1317 cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1318 }
1319 }
1320
1321 // Now that we've handled all the components of the original loop that were
1322 // cloned into a new loop, we still need to handle anything from the original
1323 // loop that wasn't in a cloned loop.
1324
1325 // Figure out what blocks are left to place within any loop nest containing
1326 // the unswitched loop. If we never formed a loop, the cloned PH is one of
1327 // them.
1328 SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1329 if (BlocksInClonedLoop.empty())
1330 UnloopedBlockSet.insert(ClonedPH);
1331 for (auto *ClonedBB : ClonedLoopBlocks)
1332 if (!BlocksInClonedLoop.count(ClonedBB))
1333 UnloopedBlockSet.insert(ClonedBB);
1334
1335 // Copy the cloned exits and sort them in ascending loop depth, we'll work
1336 // backwards across these to process them inside out. The order shouldn't
1337 // matter as we're just trying to build up the map from inside-out; we use
1338 // the map in a more stably ordered way below.
1339 auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
Fangrui Song0cac7262018-09-27 02:13:45 +00001340 llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1341 return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1342 ExitLoopMap.lookup(RHS)->getLoopDepth();
1343 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001344
1345 // Populate the existing ExitLoopMap with everything reachable from each
1346 // exit, starting from the inner most exit.
1347 while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1348 assert(Worklist.empty() && "Didn't clear worklist!");
1349
1350 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1351 Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1352
1353 // Walk the CFG back until we hit the cloned PH adding everything reachable
1354 // and in the unlooped set to this exit block's loop.
1355 Worklist.push_back(ExitBB);
1356 do {
1357 BasicBlock *BB = Worklist.pop_back_val();
1358 // We can stop recursing at the cloned preheader (if we get there).
1359 if (BB == ClonedPH)
1360 continue;
1361
1362 for (BasicBlock *PredBB : predecessors(BB)) {
1363 // If this pred has already been moved to our set or is part of some
1364 // (inner) loop, no update needed.
1365 if (!UnloopedBlockSet.erase(PredBB)) {
1366 assert(
1367 (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1368 "Predecessor not mapped to a loop!");
1369 continue;
1370 }
1371
1372 // We just insert into the loop set here. We'll add these blocks to the
1373 // exit loop after we build up the set in an order that doesn't rely on
1374 // predecessor order (which in turn relies on use list order).
1375 bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1376 (void)Inserted;
1377 assert(Inserted && "Should only visit an unlooped block once!");
1378
1379 // And recurse through to its predecessors.
1380 Worklist.push_back(PredBB);
1381 }
1382 } while (!Worklist.empty());
1383 }
1384
1385 // Now that the ExitLoopMap gives as mapping for all the non-looping cloned
1386 // blocks to their outer loops, walk the cloned blocks and the cloned exits
1387 // in their original order adding them to the correct loop.
1388
1389 // We need a stable insertion order. We use the order of the original loop
1390 // order and map into the correct parent loop.
1391 for (auto *BB : llvm::concat<BasicBlock *const>(
1392 makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1393 if (Loop *OuterL = ExitLoopMap.lookup(BB))
1394 OuterL->addBasicBlockToLoop(BB, LI);
1395
1396#ifndef NDEBUG
1397 for (auto &BBAndL : ExitLoopMap) {
1398 auto *BB = BBAndL.first;
1399 auto *OuterL = BBAndL.second;
1400 assert(LI.getLoopFor(BB) == OuterL &&
1401 "Failed to put all blocks into outer loops!");
1402 }
1403#endif
1404
1405 // Now that all the blocks are placed into the correct containing loop in the
1406 // absence of child loops, find all the potentially cloned child loops and
1407 // clone them into whatever outer loop we placed their header into.
1408 for (Loop *ChildL : OrigL) {
1409 auto *ClonedChildHeader =
1410 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1411 if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1412 continue;
1413
1414#ifndef NDEBUG
1415 for (auto *ChildLoopBB : ChildL->blocks())
1416 assert(VMap.count(ChildLoopBB) &&
1417 "Cloned a child loop header but not all of that loops blocks!");
1418#endif
1419
1420 NonChildClonedLoops.push_back(cloneLoopNest(
1421 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1422 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001423}
1424
Chandler Carruth69e68f82018-04-25 00:18:07 +00001425static void
Chandler Carruth16529962018-06-25 23:32:54 +00001426deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1427 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001428 DominatorTree &DT, MemorySSAUpdater *MSSAU) {
Chandler Carruth16529962018-06-25 23:32:54 +00001429 // Find all the dead clones, and remove them from their successors.
1430 SmallVector<BasicBlock *, 16> DeadBlocks;
1431 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1432 for (auto &VMap : VMaps)
1433 if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1434 if (!DT.isReachableFromEntry(ClonedBB)) {
1435 for (BasicBlock *SuccBB : successors(ClonedBB))
1436 SuccBB->removePredecessor(ClonedBB);
1437 DeadBlocks.push_back(ClonedBB);
1438 }
1439
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001440 // Remove all MemorySSA in the dead blocks
1441 if (MSSAU) {
1442 SmallPtrSet<BasicBlock *, 16> DeadBlockSet(DeadBlocks.begin(),
1443 DeadBlocks.end());
1444 MSSAU->removeBlocks(DeadBlockSet);
1445 }
1446
Chandler Carruth16529962018-06-25 23:32:54 +00001447 // Drop any remaining references to break cycles.
1448 for (BasicBlock *BB : DeadBlocks)
1449 BB->dropAllReferences();
1450 // Erase them from the IR.
1451 for (BasicBlock *BB : DeadBlocks)
1452 BB->eraseFromParent();
1453}
1454
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001455static void deleteDeadBlocksFromLoop(Loop &L,
1456 SmallVectorImpl<BasicBlock *> &ExitBlocks,
1457 DominatorTree &DT, LoopInfo &LI,
1458 MemorySSAUpdater *MSSAU) {
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001459 // Find all the dead blocks tied to this loop, and remove them from their
1460 // successors.
1461 SmallPtrSet<BasicBlock *, 16> DeadBlockSet;
1462
1463 // Start with loop/exit blocks and get a transitive closure of reachable dead
1464 // blocks.
1465 SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
1466 ExitBlocks.end());
1467 DeathCandidates.append(L.blocks().begin(), L.blocks().end());
1468 while (!DeathCandidates.empty()) {
1469 auto *BB = DeathCandidates.pop_back_val();
1470 if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
1471 for (BasicBlock *SuccBB : successors(BB)) {
Chandler Carruth16529962018-06-25 23:32:54 +00001472 SuccBB->removePredecessor(BB);
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001473 DeathCandidates.push_back(SuccBB);
Fedor Sergeev7b49aa02018-08-29 19:10:44 +00001474 }
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001475 DeadBlockSet.insert(BB);
1476 }
1477 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001478
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001479 // Remove all MemorySSA in the dead blocks
1480 if (MSSAU)
1481 MSSAU->removeBlocks(DeadBlockSet);
1482
Chandler Carruth693eedb2017-11-17 19:58:36 +00001483 // Filter out the dead blocks from the exit blocks list so that it can be
1484 // used in the caller.
1485 llvm::erase_if(ExitBlocks,
Chandler Carruth69e68f82018-04-25 00:18:07 +00001486 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001487
Chandler Carruth693eedb2017-11-17 19:58:36 +00001488 // Walk from this loop up through its parents removing all of the dead blocks.
1489 for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001490 for (auto *BB : DeadBlockSet)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001491 ParentL->getBlocksSet().erase(BB);
1492 llvm::erase_if(ParentL->getBlocksVector(),
Chandler Carruth69e68f82018-04-25 00:18:07 +00001493 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001494 }
1495
1496 // Now delete the dead child loops. This raw delete will clear them
1497 // recursively.
1498 llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001499 if (!DeadBlockSet.count(ChildL->getHeader()))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001500 return false;
1501
1502 assert(llvm::all_of(ChildL->blocks(),
1503 [&](BasicBlock *ChildBB) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001504 return DeadBlockSet.count(ChildBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001505 }) &&
1506 "If the child loop header is dead all blocks in the child loop must "
1507 "be dead as well!");
1508 LI.destroy(ChildL);
1509 return true;
1510 });
1511
Chandler Carruth69e68f82018-04-25 00:18:07 +00001512 // Remove the loop mappings for the dead blocks and drop all the references
1513 // from these blocks to others to handle cyclic references as we start
1514 // deleting the blocks themselves.
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001515 for (auto *BB : DeadBlockSet) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001516 // Check that the dominator tree has already been updated.
1517 assert(!DT.getNode(BB) && "Should already have cleared domtree!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001518 LI.changeLoopFor(BB, nullptr);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001519 BB->dropAllReferences();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001520 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001521
1522 // Actually delete the blocks now that they've been fully unhooked from the
1523 // IR.
Fedor Sergeev7b49aa02018-08-29 19:10:44 +00001524 for (auto *BB : DeadBlockSet)
Chandler Carruth69e68f82018-04-25 00:18:07 +00001525 BB->eraseFromParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001526}
1527
1528/// Recompute the set of blocks in a loop after unswitching.
1529///
1530/// This walks from the original headers predecessors to rebuild the loop. We
1531/// take advantage of the fact that new blocks can't have been added, and so we
1532/// filter by the original loop's blocks. This also handles potentially
1533/// unreachable code that we don't want to explore but might be found examining
1534/// the predecessors of the header.
1535///
1536/// If the original loop is no longer a loop, this will return an empty set. If
1537/// it remains a loop, all the blocks within it will be added to the set
1538/// (including those blocks in inner loops).
1539static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1540 LoopInfo &LI) {
1541 SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1542
1543 auto *PH = L.getLoopPreheader();
1544 auto *Header = L.getHeader();
1545
1546 // A worklist to use while walking backwards from the header.
1547 SmallVector<BasicBlock *, 16> Worklist;
1548
1549 // First walk the predecessors of the header to find the backedges. This will
1550 // form the basis of our walk.
1551 for (auto *Pred : predecessors(Header)) {
1552 // Skip the preheader.
1553 if (Pred == PH)
1554 continue;
1555
1556 // Because the loop was in simplified form, the only non-loop predecessor
1557 // is the preheader.
1558 assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1559 "than the preheader that is not part of the "
1560 "loop!");
1561
1562 // Insert this block into the loop set and on the first visit and, if it
1563 // isn't the header we're currently walking, put it into the worklist to
1564 // recurse through.
1565 if (LoopBlockSet.insert(Pred).second && Pred != Header)
1566 Worklist.push_back(Pred);
1567 }
1568
1569 // If no backedges were found, we're done.
1570 if (LoopBlockSet.empty())
1571 return LoopBlockSet;
1572
Chandler Carruth693eedb2017-11-17 19:58:36 +00001573 // We found backedges, recurse through them to identify the loop blocks.
1574 while (!Worklist.empty()) {
1575 BasicBlock *BB = Worklist.pop_back_val();
1576 assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1577
Chandler Carruth43acdb32018-04-24 10:33:08 +00001578 // No need to walk past the header.
1579 if (BB == Header)
1580 continue;
1581
Chandler Carruth693eedb2017-11-17 19:58:36 +00001582 // Because we know the inner loop structure remains valid we can use the
1583 // loop structure to jump immediately across the entire nested loop.
1584 // Further, because it is in loop simplified form, we can directly jump
1585 // to its preheader afterward.
1586 if (Loop *InnerL = LI.getLoopFor(BB))
1587 if (InnerL != &L) {
1588 assert(L.contains(InnerL) &&
1589 "Should not reach a loop *outside* this loop!");
1590 // The preheader is the only possible predecessor of the loop so
1591 // insert it into the set and check whether it was already handled.
1592 auto *InnerPH = InnerL->getLoopPreheader();
1593 assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1594 "but not contain the inner loop "
1595 "preheader!");
1596 if (!LoopBlockSet.insert(InnerPH).second)
1597 // The only way to reach the preheader is through the loop body
1598 // itself so if it has been visited the loop is already handled.
1599 continue;
1600
1601 // Insert all of the blocks (other than those already present) into
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001602 // the loop set. We expect at least the block that led us to find the
1603 // inner loop to be in the block set, but we may also have other loop
1604 // blocks if they were already enqueued as predecessors of some other
1605 // outer loop block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00001606 for (auto *InnerBB : InnerL->blocks()) {
1607 if (InnerBB == BB) {
1608 assert(LoopBlockSet.count(InnerBB) &&
1609 "Block should already be in the set!");
1610 continue;
1611 }
1612
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001613 LoopBlockSet.insert(InnerBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001614 }
1615
1616 // Add the preheader to the worklist so we will continue past the
1617 // loop body.
1618 Worklist.push_back(InnerPH);
1619 continue;
1620 }
1621
1622 // Insert any predecessors that were in the original loop into the new
1623 // set, and if the insert is successful, add them to the worklist.
1624 for (auto *Pred : predecessors(BB))
1625 if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1626 Worklist.push_back(Pred);
1627 }
1628
Chandler Carruth43acdb32018-04-24 10:33:08 +00001629 assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1630
Chandler Carruth693eedb2017-11-17 19:58:36 +00001631 // We've found all the blocks participating in the loop, return our completed
1632 // set.
1633 return LoopBlockSet;
1634}
1635
1636/// Rebuild a loop after unswitching removes some subset of blocks and edges.
1637///
1638/// The removal may have removed some child loops entirely but cannot have
1639/// disturbed any remaining child loops. However, they may need to be hoisted
1640/// to the parent loop (or to be top-level loops). The original loop may be
1641/// completely removed.
1642///
1643/// The sibling loops resulting from this update are returned. If the original
1644/// loop remains a valid loop, it will be the first entry in this list with all
1645/// of the newly sibling loops following it.
1646///
1647/// Returns true if the loop remains a loop after unswitching, and false if it
1648/// is no longer a loop after unswitching (and should not continue to be
1649/// referenced).
1650static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1651 LoopInfo &LI,
1652 SmallVectorImpl<Loop *> &HoistedLoops) {
1653 auto *PH = L.getLoopPreheader();
1654
1655 // Compute the actual parent loop from the exit blocks. Because we may have
1656 // pruned some exits the loop may be different from the original parent.
1657 Loop *ParentL = nullptr;
1658 SmallVector<Loop *, 4> ExitLoops;
1659 SmallVector<BasicBlock *, 4> ExitsInLoops;
1660 ExitsInLoops.reserve(ExitBlocks.size());
1661 for (auto *ExitBB : ExitBlocks)
1662 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1663 ExitLoops.push_back(ExitL);
1664 ExitsInLoops.push_back(ExitBB);
1665 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1666 ParentL = ExitL;
1667 }
1668
1669 // Recompute the blocks participating in this loop. This may be empty if it
1670 // is no longer a loop.
1671 auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1672
1673 // If we still have a loop, we need to re-set the loop's parent as the exit
1674 // block set changing may have moved it within the loop nest. Note that this
1675 // can only happen when this loop has a parent as it can only hoist the loop
1676 // *up* the nest.
1677 if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1678 // Remove this loop's (original) blocks from all of the intervening loops.
1679 for (Loop *IL = L.getParentLoop(); IL != ParentL;
1680 IL = IL->getParentLoop()) {
1681 IL->getBlocksSet().erase(PH);
1682 for (auto *BB : L.blocks())
1683 IL->getBlocksSet().erase(BB);
1684 llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1685 return BB == PH || L.contains(BB);
1686 });
1687 }
1688
1689 LI.changeLoopFor(PH, ParentL);
1690 L.getParentLoop()->removeChildLoop(&L);
1691 if (ParentL)
1692 ParentL->addChildLoop(&L);
1693 else
1694 LI.addTopLevelLoop(&L);
1695 }
1696
1697 // Now we update all the blocks which are no longer within the loop.
1698 auto &Blocks = L.getBlocksVector();
1699 auto BlocksSplitI =
1700 LoopBlockSet.empty()
1701 ? Blocks.begin()
1702 : std::stable_partition(
1703 Blocks.begin(), Blocks.end(),
1704 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1705
1706 // Before we erase the list of unlooped blocks, build a set of them.
1707 SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1708 if (LoopBlockSet.empty())
1709 UnloopedBlocks.insert(PH);
1710
1711 // Now erase these blocks from the loop.
1712 for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1713 L.getBlocksSet().erase(BB);
1714 Blocks.erase(BlocksSplitI, Blocks.end());
1715
1716 // Sort the exits in ascending loop depth, we'll work backwards across these
1717 // to process them inside out.
1718 std::stable_sort(ExitsInLoops.begin(), ExitsInLoops.end(),
1719 [&](BasicBlock *LHS, BasicBlock *RHS) {
1720 return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1721 });
1722
1723 // We'll build up a set for each exit loop.
1724 SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1725 Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1726
1727 auto RemoveUnloopedBlocksFromLoop =
1728 [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1729 for (auto *BB : UnloopedBlocks)
1730 L.getBlocksSet().erase(BB);
1731 llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1732 return UnloopedBlocks.count(BB);
1733 });
1734 };
1735
1736 SmallVector<BasicBlock *, 16> Worklist;
1737 while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1738 assert(Worklist.empty() && "Didn't clear worklist!");
1739 assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1740
1741 // Grab the next exit block, in decreasing loop depth order.
1742 BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1743 Loop &ExitL = *LI.getLoopFor(ExitBB);
1744 assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1745
1746 // Erase all of the unlooped blocks from the loops between the previous
1747 // exit loop and this exit loop. This works because the ExitInLoops list is
1748 // sorted in increasing order of loop depth and thus we visit loops in
1749 // decreasing order of loop depth.
1750 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1751 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1752
1753 // Walk the CFG back until we hit the cloned PH adding everything reachable
1754 // and in the unlooped set to this exit block's loop.
1755 Worklist.push_back(ExitBB);
1756 do {
1757 BasicBlock *BB = Worklist.pop_back_val();
1758 // We can stop recursing at the cloned preheader (if we get there).
1759 if (BB == PH)
1760 continue;
1761
1762 for (BasicBlock *PredBB : predecessors(BB)) {
1763 // If this pred has already been moved to our set or is part of some
1764 // (inner) loop, no update needed.
1765 if (!UnloopedBlocks.erase(PredBB)) {
1766 assert((NewExitLoopBlocks.count(PredBB) ||
1767 ExitL.contains(LI.getLoopFor(PredBB))) &&
1768 "Predecessor not in a nested loop (or already visited)!");
1769 continue;
1770 }
1771
1772 // We just insert into the loop set here. We'll add these blocks to the
1773 // exit loop after we build up the set in a deterministic order rather
1774 // than the predecessor-influenced visit order.
1775 bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1776 (void)Inserted;
1777 assert(Inserted && "Should only visit an unlooped block once!");
1778
1779 // And recurse through to its predecessors.
1780 Worklist.push_back(PredBB);
1781 }
1782 } while (!Worklist.empty());
1783
1784 // If blocks in this exit loop were directly part of the original loop (as
1785 // opposed to a child loop) update the map to point to this exit loop. This
1786 // just updates a map and so the fact that the order is unstable is fine.
1787 for (auto *BB : NewExitLoopBlocks)
1788 if (Loop *BBL = LI.getLoopFor(BB))
1789 if (BBL == &L || !L.contains(BBL))
1790 LI.changeLoopFor(BB, &ExitL);
1791
1792 // We will remove the remaining unlooped blocks from this loop in the next
1793 // iteration or below.
1794 NewExitLoopBlocks.clear();
1795 }
1796
1797 // Any remaining unlooped blocks are no longer part of any loop unless they
1798 // are part of some child loop.
1799 for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1800 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1801 for (auto *BB : UnloopedBlocks)
1802 if (Loop *BBL = LI.getLoopFor(BB))
1803 if (BBL == &L || !L.contains(BBL))
1804 LI.changeLoopFor(BB, nullptr);
1805
1806 // Sink all the child loops whose headers are no longer in the loop set to
1807 // the parent (or to be top level loops). We reach into the loop and directly
1808 // update its subloop vector to make this batch update efficient.
1809 auto &SubLoops = L.getSubLoopsVector();
1810 auto SubLoopsSplitI =
1811 LoopBlockSet.empty()
1812 ? SubLoops.begin()
1813 : std::stable_partition(
1814 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1815 return LoopBlockSet.count(SubL->getHeader());
1816 });
1817 for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1818 HoistedLoops.push_back(HoistedL);
1819 HoistedL->setParentLoop(nullptr);
1820
1821 // To compute the new parent of this hoisted loop we look at where we
1822 // placed the preheader above. We can't lookup the header itself because we
1823 // retained the mapping from the header to the hoisted loop. But the
1824 // preheader and header should have the exact same new parent computed
1825 // based on the set of exit blocks from the original loop as the preheader
1826 // is a predecessor of the header and so reached in the reverse walk. And
1827 // because the loops were all in simplified form the preheader of the
1828 // hoisted loop can't be part of some *other* loop.
1829 if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1830 NewParentL->addChildLoop(HoistedL);
1831 else
1832 LI.addTopLevelLoop(HoistedL);
1833 }
1834 SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1835
1836 // Actually delete the loop if nothing remained within it.
1837 if (Blocks.empty()) {
1838 assert(SubLoops.empty() &&
1839 "Failed to remove all subloops from the original loop!");
1840 if (Loop *ParentL = L.getParentLoop())
1841 ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1842 else
1843 LI.removeLoop(llvm::find(LI, &L));
1844 LI.destroy(&L);
1845 return false;
1846 }
1847
1848 return true;
1849}
1850
1851/// Helper to visit a dominator subtree, invoking a callable on each node.
1852///
1853/// Returning false at any point will stop walking past that node of the tree.
1854template <typename CallableT>
1855void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1856 SmallVector<DomTreeNode *, 4> DomWorklist;
1857 DomWorklist.push_back(DT[BB]);
1858#ifndef NDEBUG
1859 SmallPtrSet<DomTreeNode *, 4> Visited;
1860 Visited.insert(DT[BB]);
1861#endif
1862 do {
1863 DomTreeNode *N = DomWorklist.pop_back_val();
1864
1865 // Visit this node.
1866 if (!Callable(N->getBlock()))
1867 continue;
1868
1869 // Accumulate the child nodes.
1870 for (DomTreeNode *ChildN : *N) {
1871 assert(Visited.insert(ChildN).second &&
1872 "Cannot visit a node twice when walking a tree!");
1873 DomWorklist.push_back(ChildN);
1874 }
1875 } while (!DomWorklist.empty());
1876}
1877
Max Kazantsevbde31002018-10-26 09:52:58 +00001878static void unswitchNontrivialInvariants(
Chandler Carruth60b2e052018-10-18 00:40:26 +00001879 Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
Max Kazantsevbde31002018-10-26 09:52:58 +00001880 SmallVectorImpl<BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI,
1881 AssumptionCache &AC, function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001882 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruth16529962018-06-25 23:32:54 +00001883 auto *ParentBB = TI.getParent();
1884 BranchInst *BI = dyn_cast<BranchInst>(&TI);
1885 SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001886
Chandler Carruth16529962018-06-25 23:32:54 +00001887 // We can only unswitch switches, conditional branches with an invariant
1888 // condition, or combining invariant conditions with an instruction.
1889 assert((SI || BI->isConditional()) &&
1890 "Can only unswitch switches and conditional branch!");
1891 bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001892 if (FullUnswitch)
1893 assert(Invariants.size() == 1 &&
1894 "Cannot have other invariants with full unswitching!");
1895 else
Chandler Carruth16529962018-06-25 23:32:54 +00001896 assert(isa<Instruction>(BI->getCondition()) &&
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001897 "Partial unswitching requires an instruction as the condition!");
1898
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001899 if (MSSAU && VerifyMemorySSA)
1900 MSSAU->getMemorySSA()->verifyMemorySSA();
1901
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001902 // Constant and BBs tracking the cloned and continuing successor. When we are
1903 // unswitching the entire condition, this can just be trivially chosen to
1904 // unswitch towards `true`. However, when we are unswitching a set of
1905 // invariants combined with `and` or `or`, the combining operation determines
1906 // the best direction to unswitch: we want to unswitch the direction that will
1907 // collapse the branch.
1908 bool Direction = true;
1909 int ClonedSucc = 0;
1910 if (!FullUnswitch) {
Chandler Carruth16529962018-06-25 23:32:54 +00001911 if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1912 assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1913 Instruction::And &&
1914 "Only `or` and `and` instructions can combine invariants being "
1915 "unswitched.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001916 Direction = false;
1917 ClonedSucc = 1;
1918 }
1919 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001920
Chandler Carruth16529962018-06-25 23:32:54 +00001921 BasicBlock *RetainedSuccBB =
1922 BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1923 SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1924 if (BI)
1925 UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1926 else
1927 for (auto Case : SI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00001928 if (Case.getCaseSuccessor() != RetainedSuccBB)
1929 UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
Chandler Carruth16529962018-06-25 23:32:54 +00001930
1931 assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1932 "Should not unswitch the same successor we are retaining!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001933
1934 // The branch should be in this exact loop. Any inner loop's invariant branch
1935 // should be handled by unswitching that inner loop. The caller of this
1936 // routine should filter out any candidates that remain (but were skipped for
1937 // whatever reason).
1938 assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1939
Chandler Carruth693eedb2017-11-17 19:58:36 +00001940 // Compute the parent loop now before we start hacking on things.
1941 Loop *ParentL = L.getParentLoop();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001942 // Get blocks in RPO order for MSSA update, before changing the CFG.
1943 LoopBlocksRPO LBRPO(&L);
1944 if (MSSAU)
1945 LBRPO.perform(&LI);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001946
1947 // Compute the outer-most loop containing one of our exit blocks. This is the
1948 // furthest up our loopnest which can be mutated, which we will use below to
1949 // update things.
1950 Loop *OuterExitL = &L;
1951 for (auto *ExitBB : ExitBlocks) {
1952 Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1953 if (!NewOuterExitL) {
1954 // We exited the entire nest with this block, so we're done.
1955 OuterExitL = nullptr;
1956 break;
1957 }
1958 if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1959 OuterExitL = NewOuterExitL;
1960 }
1961
Chandler Carruth3897ded2018-07-03 09:13:27 +00001962 // At this point, we're definitely going to unswitch something so invalidate
1963 // any cached information in ScalarEvolution for the outer most loop
1964 // containing an exit block and all nested loops.
1965 if (SE) {
1966 if (OuterExitL)
1967 SE->forgetLoop(OuterExitL);
1968 else
1969 SE->forgetTopmostLoop(&L);
1970 }
1971
Chandler Carruth16529962018-06-25 23:32:54 +00001972 // If the edge from this terminator to a successor dominates that successor,
1973 // store a map from each block in its dominator subtree to it. This lets us
1974 // tell when cloning for a particular successor if a block is dominated by
1975 // some *other* successor with a single data structure. We use this to
1976 // significantly reduce cloning.
1977 SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
1978 for (auto *SuccBB : llvm::concat<BasicBlock *const>(
1979 makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
1980 if (SuccBB->getUniquePredecessor() ||
1981 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
1982 return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
1983 }))
1984 visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
1985 DominatingSucc[BB] = SuccBB;
1986 return true;
1987 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001988
1989 // Split the preheader, so that we know that there is a safe place to insert
1990 // the conditional branch. We will change the preheader to have a conditional
1991 // branch on LoopCond. The original preheader will become the split point
1992 // between the unswitched versions, and we will have a new preheader for the
1993 // original loop.
1994 BasicBlock *SplitBB = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001995 BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001996
Chandler Carruth69e68f82018-04-25 00:18:07 +00001997 // Keep track of the dominator tree updates needed.
1998 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
1999
Chandler Carruth16529962018-06-25 23:32:54 +00002000 // Clone the loop for each unswitched successor.
2001 SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
2002 VMaps.reserve(UnswitchedSuccBBs.size());
2003 SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
2004 for (auto *SuccBB : UnswitchedSuccBBs) {
2005 VMaps.emplace_back(new ValueToValueMapTy());
2006 ClonedPHs[SuccBB] = buildClonedLoopBlocks(
2007 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002008 DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
Chandler Carruth16529962018-06-25 23:32:54 +00002009 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002010
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002011 // The stitching of the branched code back together depends on whether we're
2012 // doing full unswitching or not with the exception that we always want to
2013 // nuke the initial terminator placed in the split block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002014 SplitBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002015 if (FullUnswitch) {
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002016 // Splice the terminator from the original loop and rewrite its
2017 // successors.
2018 SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2019
2020 // Keep a clone of the terminator for MSSA updates.
2021 Instruction *NewTI = TI.clone();
2022 ParentBB->getInstList().push_back(NewTI);
2023
2024 // First wire up the moved terminator to the preheaders.
2025 if (BI) {
2026 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2027 BI->setSuccessor(ClonedSucc, ClonedPH);
2028 BI->setSuccessor(1 - ClonedSucc, LoopPH);
2029 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2030 } else {
2031 assert(SI && "Must either be a branch or switch!");
2032
2033 // Walk the cases and directly update their successors.
2034 assert(SI->getDefaultDest() == RetainedSuccBB &&
2035 "Not retaining default successor!");
2036 SI->setDefaultDest(LoopPH);
2037 for (auto &Case : SI->cases())
2038 if (Case.getCaseSuccessor() == RetainedSuccBB)
2039 Case.setSuccessor(LoopPH);
2040 else
2041 Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2042
2043 // We need to use the set to populate domtree updates as even when there
2044 // are multiple cases pointing at the same successor we only want to
2045 // remove and insert one edge in the domtree.
2046 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2047 DTUpdates.push_back(
2048 {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2049 }
2050
2051 if (MSSAU) {
2052 DT.applyUpdates(DTUpdates);
2053 DTUpdates.clear();
2054
2055 // Remove all but one edge to the retained block and all unswitched
2056 // blocks. This is to avoid having duplicate entries in the cloned Phis,
2057 // when we know we only keep a single edge for each case.
2058 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2059 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2060 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2061
2062 for (auto &VMap : VMaps)
2063 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2064 /*IgnoreIncomingWithNoClones=*/true);
2065 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2066
2067 // Remove all edges to unswitched blocks.
2068 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2069 MSSAU->removeEdge(ParentBB, SuccBB);
2070 }
2071
2072 // Now unhook the successor relationship as we'll be replacing
Chandler Carruthed296542018-07-09 10:30:48 +00002073 // the terminator with a direct branch. This is much simpler for branches
2074 // than switches so we handle those first.
Chandler Carruth16529962018-06-25 23:32:54 +00002075 if (BI) {
Chandler Carruthed296542018-07-09 10:30:48 +00002076 // Remove the parent as a predecessor of the unswitched successor.
Chandler Carruth16529962018-06-25 23:32:54 +00002077 assert(UnswitchedSuccBBs.size() == 1 &&
2078 "Only one possible unswitched block for a branch!");
Chandler Carruthed296542018-07-09 10:30:48 +00002079 BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2080 UnswitchedSuccBB->removePredecessor(ParentBB,
2081 /*DontDeleteUselessPHIs*/ true);
2082 DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2083 } else {
2084 // Note that we actually want to remove the parent block as a predecessor
2085 // of *every* case successor. The case successor is either unswitched,
2086 // completely eliminating an edge from the parent to that successor, or it
2087 // is a duplicate edge to the retained successor as the retained successor
2088 // is always the default successor and as we'll replace this with a direct
2089 // branch we no longer need the duplicate entries in the PHI nodes.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002090 SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2091 assert(NewSI->getDefaultDest() == RetainedSuccBB &&
Chandler Carruthed296542018-07-09 10:30:48 +00002092 "Not retaining default successor!");
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002093 for (auto &Case : NewSI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00002094 Case.getCaseSuccessor()->removePredecessor(
2095 ParentBB,
2096 /*DontDeleteUselessPHIs*/ true);
2097
2098 // We need to use the set to populate domtree updates as even when there
2099 // are multiple cases pointing at the same successor we only want to
2100 // remove and insert one edge in the domtree.
2101 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2102 DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
2103 }
2104
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002105 // After MSSAU update, remove the cloned terminator instruction NewTI.
2106 ParentBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002107
2108 // Create a new unconditional branch to the continuing block (as opposed to
2109 // the one cloned).
Chandler Carruth16529962018-06-25 23:32:54 +00002110 BranchInst::Create(RetainedSuccBB, ParentBB);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002111 } else {
Chandler Carruth16529962018-06-25 23:32:54 +00002112 assert(BI && "Only branches have partial unswitching.");
2113 assert(UnswitchedSuccBBs.size() == 1 &&
2114 "Only one possible unswitched block for a branch!");
2115 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002116 // When doing a partial unswitch, we have to do a bit more work to build up
2117 // the branch in the split block.
2118 buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
2119 *ClonedPH, *LoopPH);
Chandler Carruth16529962018-06-25 23:32:54 +00002120 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002121 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002122
Chandler Carruth16529962018-06-25 23:32:54 +00002123 // Apply the updates accumulated above to get an up-to-date dominator tree.
Chandler Carruth69e68f82018-04-25 00:18:07 +00002124 DT.applyUpdates(DTUpdates);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002125 if (!FullUnswitch && MSSAU) {
2126 // Update MSSA for partial unswitch, after DT update.
2127 SmallVector<CFGUpdate, 1> Updates;
2128 Updates.push_back(
2129 {cfg::UpdateKind::Insert, SplitBB, ClonedPHs.begin()->second});
2130 MSSAU->applyInsertUpdates(Updates, DT);
2131 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00002132
Chandler Carruth16529962018-06-25 23:32:54 +00002133 // Now that we have an accurate dominator tree, first delete the dead cloned
2134 // blocks so that we can accurately build any cloned loops. It is important to
2135 // not delete the blocks from the original loop yet because we still want to
2136 // reference the original loop to understand the cloned loop's structure.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002137 deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
Chandler Carruth16529962018-06-25 23:32:54 +00002138
Chandler Carruth69e68f82018-04-25 00:18:07 +00002139 // Build the cloned loop structure itself. This may be substantially
2140 // different from the original structure due to the simplified CFG. This also
2141 // handles inserting all the cloned blocks into the correct loops.
2142 SmallVector<Loop *, 4> NonChildClonedLoops;
Chandler Carruth16529962018-06-25 23:32:54 +00002143 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2144 buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
Chandler Carruth69e68f82018-04-25 00:18:07 +00002145
Chandler Carruth16529962018-06-25 23:32:54 +00002146 // Now that our cloned loops have been built, we can update the original loop.
2147 // First we delete the dead blocks from it and then we rebuild the loop
2148 // structure taking these deletions into account.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002149 deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU);
2150
2151 if (MSSAU && VerifyMemorySSA)
2152 MSSAU->getMemorySSA()->verifyMemorySSA();
2153
Chandler Carruth693eedb2017-11-17 19:58:36 +00002154 SmallVector<Loop *, 4> HoistedLoops;
2155 bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2156
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002157 if (MSSAU && VerifyMemorySSA)
2158 MSSAU->getMemorySSA()->verifyMemorySSA();
2159
Chandler Carruth69e68f82018-04-25 00:18:07 +00002160 // This transformation has a high risk of corrupting the dominator tree, and
2161 // the below steps to rebuild loop structures will result in hard to debug
2162 // errors in that case so verify that the dominator tree is sane first.
2163 // FIXME: Remove this when the bugs stop showing up and rely on existing
2164 // verification steps.
2165 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth693eedb2017-11-17 19:58:36 +00002166
Chandler Carruth16529962018-06-25 23:32:54 +00002167 if (BI) {
2168 // If we unswitched a branch which collapses the condition to a known
2169 // constant we want to replace all the uses of the invariants within both
2170 // the original and cloned blocks. We do this here so that we can use the
2171 // now updated dominator tree to identify which side the users are on.
2172 assert(UnswitchedSuccBBs.size() == 1 &&
2173 "Only one possible unswitched block for a branch!");
2174 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Fedor Sergeevf9a02a72018-11-07 20:05:11 +00002175
2176 // When considering multiple partially-unswitched invariants
2177 // we cant just go replace them with constants in both branches.
2178 //
2179 // For 'AND' we infer that true branch ("continue") means true
2180 // for each invariant operand.
2181 // For 'OR' we can infer that false branch ("continue") means false
2182 // for each invariant operand.
2183 // So it happens that for multiple-partial case we dont replace
2184 // in the unswitched branch.
2185 bool ReplaceUnswitched = FullUnswitch || (Invariants.size() == 1);
2186
Chandler Carruth16529962018-06-25 23:32:54 +00002187 ConstantInt *UnswitchedReplacement =
2188 Direction ? ConstantInt::getTrue(BI->getContext())
2189 : ConstantInt::getFalse(BI->getContext());
2190 ConstantInt *ContinueReplacement =
2191 Direction ? ConstantInt::getFalse(BI->getContext())
2192 : ConstantInt::getTrue(BI->getContext());
2193 for (Value *Invariant : Invariants)
2194 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2195 UI != UE;) {
2196 // Grab the use and walk past it so we can clobber it in the use list.
2197 Use *U = &*UI++;
2198 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2199 if (!UserI)
2200 continue;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002201
Chandler Carruth16529962018-06-25 23:32:54 +00002202 // Replace it with the 'continue' side if in the main loop body, and the
2203 // unswitched if in the cloned blocks.
2204 if (DT.dominates(LoopPH, UserI->getParent()))
2205 U->set(ContinueReplacement);
Fedor Sergeevf9a02a72018-11-07 20:05:11 +00002206 else if (ReplaceUnswitched &&
2207 DT.dominates(ClonedPH, UserI->getParent()))
Chandler Carruth16529962018-06-25 23:32:54 +00002208 U->set(UnswitchedReplacement);
2209 }
2210 }
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002211
Chandler Carruth693eedb2017-11-17 19:58:36 +00002212 // We can change which blocks are exit blocks of all the cloned sibling
2213 // loops, the current loop, and any parent loops which shared exit blocks
2214 // with the current loop. As a consequence, we need to re-form LCSSA for
2215 // them. But we shouldn't need to re-form LCSSA for any child loops.
2216 // FIXME: This could be made more efficient by tracking which exit blocks are
2217 // new, and focusing on them, but that isn't likely to be necessary.
2218 //
2219 // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2220 // loop nest and update every loop that could have had its exits changed. We
2221 // also need to cover any intervening loops. We add all of these loops to
2222 // a list and sort them by loop depth to achieve this without updating
2223 // unnecessary loops.
Chandler Carruth92815032018-06-02 01:29:01 +00002224 auto UpdateLoop = [&](Loop &UpdateL) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002225#ifndef NDEBUG
Chandler Carruth43acdb32018-04-24 10:33:08 +00002226 UpdateL.verifyLoop();
2227 for (Loop *ChildL : UpdateL) {
2228 ChildL->verifyLoop();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002229 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2230 "Perturbed a child loop's LCSSA form!");
Chandler Carruth43acdb32018-04-24 10:33:08 +00002231 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002232#endif
Chandler Carruth92815032018-06-02 01:29:01 +00002233 // First build LCSSA for this loop so that we can preserve it when
2234 // forming dedicated exits. We don't want to perturb some other loop's
2235 // LCSSA while doing that CFG edit.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002236 formLCSSA(UpdateL, DT, &LI, nullptr);
Chandler Carruth92815032018-06-02 01:29:01 +00002237
2238 // For loops reached by this loop's original exit blocks we may
2239 // introduced new, non-dedicated exits. At least try to re-form dedicated
2240 // exits for these loops. This may fail if they couldn't have dedicated
2241 // exits to start with.
2242 formDedicatedExitBlocks(&UpdateL, &DT, &LI, /*PreserveLCSSA*/ true);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002243 };
2244
2245 // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2246 // and we can do it in any order as they don't nest relative to each other.
Chandler Carruth92815032018-06-02 01:29:01 +00002247 //
2248 // Also check if any of the loops we have updated have become top-level loops
2249 // as that will necessitate widening the outer loop scope.
2250 for (Loop *UpdatedL :
2251 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2252 UpdateLoop(*UpdatedL);
2253 if (!UpdatedL->getParentLoop())
2254 OuterExitL = nullptr;
2255 }
2256 if (IsStillLoop) {
2257 UpdateLoop(L);
2258 if (!L.getParentLoop())
2259 OuterExitL = nullptr;
2260 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002261
2262 // If the original loop had exit blocks, walk up through the outer most loop
2263 // of those exit blocks to update LCSSA and form updated dedicated exits.
Chandler Carruth92815032018-06-02 01:29:01 +00002264 if (OuterExitL != &L)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002265 for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2266 OuterL = OuterL->getParentLoop())
Chandler Carruth92815032018-06-02 01:29:01 +00002267 UpdateLoop(*OuterL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002268
2269#ifndef NDEBUG
2270 // Verify the entire loop structure to catch any incorrect updates before we
2271 // progress in the pass pipeline.
2272 LI.verify(DT);
2273#endif
2274
2275 // Now that we've unswitched something, make callbacks to report the changes.
2276 // For that we need to merge together the updated loops and the cloned loops
2277 // and check whether the original loop survived.
2278 SmallVector<Loop *, 4> SibLoops;
2279 for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2280 if (UpdatedL->getParentLoop() == ParentL)
2281 SibLoops.push_back(UpdatedL);
Chandler Carruth71fd2702018-05-30 02:46:45 +00002282 UnswitchCB(IsStillLoop, SibLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002283
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002284 if (MSSAU && VerifyMemorySSA)
2285 MSSAU->getMemorySSA()->verifyMemorySSA();
2286
Zaara Syedab7dff9c2019-01-15 15:08:01 +00002287 if (BI)
2288 ++NumBranches;
2289 else
2290 ++NumSwitches;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002291}
2292
2293/// Recursively compute the cost of a dominator subtree based on the per-block
2294/// cost map provided.
2295///
2296/// The recursive computation is memozied into the provided DT-indexed cost map
2297/// to allow querying it for most nodes in the domtree without it becoming
2298/// quadratic.
2299static int
2300computeDomSubtreeCost(DomTreeNode &N,
2301 const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2302 SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2303 // Don't accumulate cost (or recurse through) blocks not in our block cost
2304 // map and thus not part of the duplication cost being considered.
2305 auto BBCostIt = BBCostMap.find(N.getBlock());
2306 if (BBCostIt == BBCostMap.end())
2307 return 0;
2308
2309 // Lookup this node to see if we already computed its cost.
2310 auto DTCostIt = DTCostMap.find(&N);
2311 if (DTCostIt != DTCostMap.end())
2312 return DTCostIt->second;
2313
2314 // If not, we have to compute it. We can't use insert above and update
2315 // because computing the cost may insert more things into the map.
2316 int Cost = std::accumulate(
2317 N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2318 return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2319 });
2320 bool Inserted = DTCostMap.insert({&N, Cost}).second;
2321 (void)Inserted;
2322 assert(Inserted && "Should not insert a node while visiting children!");
2323 return Cost;
2324}
2325
Max Kazantsev619a8342018-10-26 14:20:11 +00002326/// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2327/// making the following replacement:
2328///
Simon Pilgrima1320162018-10-27 15:14:42 +00002329/// --code before guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002330/// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
Simon Pilgrima1320162018-10-27 15:14:42 +00002331/// --code after guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002332///
2333/// into
2334///
Simon Pilgrima1320162018-10-27 15:14:42 +00002335/// --code before guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002336/// br i1 %cond, label %guarded, label %deopt
2337///
2338/// guarded:
Simon Pilgrima1320162018-10-27 15:14:42 +00002339/// --code after guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002340///
2341/// deopt:
2342/// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2343/// unreachable
2344///
2345/// It also makes all relevant DT and LI updates, so that all structures are in
2346/// valid state after this transform.
2347static BranchInst *
2348turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2349 SmallVectorImpl<BasicBlock *> &ExitBlocks,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002350 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Max Kazantsev619a8342018-10-26 14:20:11 +00002351 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2352 LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2353 BasicBlock *CheckBB = GI->getParent();
2354
Alina Sbirlea797935f2018-12-04 14:43:24 +00002355 if (MSSAU && VerifyMemorySSA)
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002356 MSSAU->getMemorySSA()->verifyMemorySSA();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002357
Max Kazantsev619a8342018-10-26 14:20:11 +00002358 // Remove all CheckBB's successors from DomTree. A block can be seen among
2359 // successors more than once, but for DomTree it should be added only once.
2360 SmallPtrSet<BasicBlock *, 4> Successors;
2361 for (auto *Succ : successors(CheckBB))
2362 if (Successors.insert(Succ).second)
2363 DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2364
2365 Instruction *DeoptBlockTerm =
2366 SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2367 BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2368 // SplitBlockAndInsertIfThen inserts control flow that branches to
2369 // DeoptBlockTerm if the condition is true. We want the opposite.
2370 CheckBI->swapSuccessors();
2371
2372 BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2373 GuardedBlock->setName("guarded");
2374 CheckBI->getSuccessor(1)->setName("deopt");
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002375 BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
Max Kazantsev619a8342018-10-26 14:20:11 +00002376
2377 // We now have a new exit block.
2378 ExitBlocks.push_back(CheckBI->getSuccessor(1));
2379
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002380 if (MSSAU)
2381 MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2382
Max Kazantsev619a8342018-10-26 14:20:11 +00002383 GI->moveBefore(DeoptBlockTerm);
2384 GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2385
2386 // Add new successors of CheckBB into DomTree.
2387 for (auto *Succ : successors(CheckBB))
2388 DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2389
2390 // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2391 // successors.
2392 for (auto *Succ : Successors)
2393 DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2394
2395 // Make proper changes to DT.
2396 DT.applyUpdates(DTUpdates);
2397 // Inform LI of a new loop block.
2398 L.addBasicBlockToLoop(GuardedBlock, LI);
2399
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002400 if (MSSAU) {
2401 MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2402 MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::End);
2403 if (VerifyMemorySSA)
2404 MSSAU->getMemorySSA()->verifyMemorySSA();
2405 }
2406
Max Kazantsev619a8342018-10-26 14:20:11 +00002407 ++NumGuards;
2408 return CheckBI;
2409}
2410
Fedor Sergeev2e3e2242018-11-16 21:16:43 +00002411/// Cost multiplier is a way to limit potentially exponential behavior
2412/// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2413/// candidates available. Also accounting for the number of "sibling" loops with
2414/// the idea to account for previous unswitches that already happened on this
2415/// cluster of loops. There was an attempt to keep this formula simple,
2416/// just enough to limit the worst case behavior. Even if it is not that simple
2417/// now it is still not an attempt to provide a detailed heuristic size
2418/// prediction.
2419///
2420/// TODO: Make a proper accounting of "explosion" effect for all kinds of
2421/// unswitch candidates, making adequate predictions instead of wild guesses.
2422/// That requires knowing not just the number of "remaining" candidates but
2423/// also costs of unswitching for each of these candidates.
2424static int calculateUnswitchCostMultiplier(
2425 Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
2426 ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
2427 UnswitchCandidates) {
2428
2429 // Guards and other exiting conditions do not contribute to exponential
2430 // explosion as soon as they dominate the latch (otherwise there might be
2431 // another path to the latch remaining that does not allow to eliminate the
2432 // loop copy on unswitch).
2433 BasicBlock *Latch = L.getLoopLatch();
2434 BasicBlock *CondBlock = TI.getParent();
2435 if (DT.dominates(CondBlock, Latch) &&
2436 (isGuard(&TI) ||
2437 llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
2438 return L.contains(SuccBB);
2439 }) <= 1)) {
2440 NumCostMultiplierSkipped++;
2441 return 1;
2442 }
2443
2444 auto *ParentL = L.getParentLoop();
2445 int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2446 : std::distance(LI.begin(), LI.end()));
2447 // Count amount of clones that all the candidates might cause during
2448 // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2449 int UnswitchedClones = 0;
2450 for (auto Candidate : UnswitchCandidates) {
2451 Instruction *CI = Candidate.first;
2452 BasicBlock *CondBlock = CI->getParent();
2453 bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2454 if (isGuard(CI)) {
2455 if (!SkipExitingSuccessors)
2456 UnswitchedClones++;
2457 continue;
2458 }
2459 int NonExitingSuccessors = llvm::count_if(
2460 successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
2461 return !SkipExitingSuccessors || L.contains(SuccBB);
2462 });
2463 UnswitchedClones += Log2_32(NonExitingSuccessors);
2464 }
2465
2466 // Ignore up to the "unscaled candidates" number of unswitch candidates
2467 // when calculating the power-of-two scaling of the cost. The main idea
2468 // with this control is to allow a small number of unswitches to happen
2469 // and rely more on siblings multiplier (see below) when the number
2470 // of candidates is small.
2471 unsigned ClonesPower =
2472 std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
2473
2474 // Allowing top-level loops to spread a bit more than nested ones.
2475 int SiblingsMultiplier =
2476 std::max((ParentL ? SiblingsCount
2477 : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
2478 1);
2479 // Compute the cost multiplier in a way that won't overflow by saturating
2480 // at an upper bound.
2481 int CostMultiplier;
2482 if (ClonesPower > Log2_32(UnswitchThreshold) ||
2483 SiblingsMultiplier > UnswitchThreshold)
2484 CostMultiplier = UnswitchThreshold;
2485 else
2486 CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2487 (int)UnswitchThreshold);
2488
2489 LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier
2490 << " (siblings " << SiblingsMultiplier << " * clones "
2491 << (1 << ClonesPower) << ")"
2492 << " for unswitch candidate: " << TI << "\n");
2493 return CostMultiplier;
2494}
2495
Chandler Carruth3897ded2018-07-03 09:13:27 +00002496static bool
2497unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2498 AssumptionCache &AC, TargetTransformInfo &TTI,
2499 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002500 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002501 // Collect all invariant conditions within this loop (as opposed to an inner
2502 // loop which would be handled when visiting that inner loop).
Chandler Carruth60b2e052018-10-18 00:40:26 +00002503 SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002504 UnswitchCandidates;
Max Kazantsev619a8342018-10-26 14:20:11 +00002505
2506 // Whether or not we should also collect guards in the loop.
2507 bool CollectGuards = false;
2508 if (UnswitchGuards) {
2509 auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2510 Intrinsic::getName(Intrinsic::experimental_guard));
2511 if (GuardDecl && !GuardDecl->use_empty())
2512 CollectGuards = true;
2513 }
2514
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002515 for (auto *BB : L.blocks()) {
2516 if (LI.getLoopFor(BB) != &L)
2517 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002518
Max Kazantsev619a8342018-10-26 14:20:11 +00002519 if (CollectGuards)
2520 for (auto &I : *BB)
2521 if (isGuard(&I)) {
2522 auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2523 // TODO: Support AND, OR conditions and partial unswitching.
2524 if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2525 UnswitchCandidates.push_back({&I, {Cond}});
2526 }
2527
Chandler Carruth16529962018-06-25 23:32:54 +00002528 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2529 // We can only consider fully loop-invariant switch conditions as we need
2530 // to completely eliminate the switch after unswitching.
2531 if (!isa<Constant>(SI->getCondition()) &&
2532 L.isLoopInvariant(SI->getCondition()))
2533 UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2534 continue;
2535 }
2536
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002537 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002538 if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2539 BI->getSuccessor(0) == BI->getSuccessor(1))
2540 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002541
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002542 if (L.isLoopInvariant(BI->getCondition())) {
2543 UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2544 continue;
2545 }
2546
2547 Instruction &CondI = *cast<Instruction>(BI->getCondition());
2548 if (CondI.getOpcode() != Instruction::And &&
2549 CondI.getOpcode() != Instruction::Or)
2550 continue;
2551
2552 TinyPtrVector<Value *> Invariants =
2553 collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2554 if (Invariants.empty())
2555 continue;
2556
2557 UnswitchCandidates.push_back({BI, std::move(Invariants)});
Chandler Carruth71fd2702018-05-30 02:46:45 +00002558 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002559
Chandler Carruth693eedb2017-11-17 19:58:36 +00002560 // If we didn't find any candidates, we're done.
2561 if (UnswitchCandidates.empty())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002562 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002563
Chandler Carruth32e62f92018-04-19 18:44:25 +00002564 // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2565 // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2566 // irreducible control flow into reducible control flow and introduce new
2567 // loops "out of thin air". If we ever discover important use cases for doing
2568 // this, we can add support to loop unswitch, but it is a lot of complexity
Hiroshi Inouef2096492018-06-14 05:41:49 +00002569 // for what seems little or no real world benefit.
Chandler Carruth32e62f92018-04-19 18:44:25 +00002570 LoopBlocksRPO RPOT(&L);
2571 RPOT.perform(&LI);
2572 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002573 return false;
Chandler Carruth32e62f92018-04-19 18:44:25 +00002574
Max Kazantsevbde31002018-10-26 09:52:58 +00002575 SmallVector<BasicBlock *, 4> ExitBlocks;
2576 L.getUniqueExitBlocks(ExitBlocks);
2577
2578 // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
2579 // don't know how to split those exit blocks.
2580 // FIXME: We should teach SplitBlock to handle this and remove this
2581 // restriction.
2582 for (auto *ExitBB : ExitBlocks)
2583 if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) {
2584 dbgs() << "Cannot unswitch because of cleanuppad in exit block\n";
2585 return false;
2586 }
2587
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002588 LLVM_DEBUG(
2589 dbgs() << "Considering " << UnswitchCandidates.size()
2590 << " non-trivial loop invariant conditions for unswitching.\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002591
2592 // Given that unswitching these terminators will require duplicating parts of
2593 // the loop, so we need to be able to model that cost. Compute the ephemeral
2594 // values and set up a data structure to hold per-BB costs. We cache each
2595 // block's cost so that we don't recompute this when considering different
2596 // subsets of the loop for duplication during unswitching.
2597 SmallPtrSet<const Value *, 4> EphValues;
2598 CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2599 SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2600
2601 // Compute the cost of each block, as well as the total loop cost. Also, bail
2602 // out if we see instructions which are incompatible with loop unswitching
2603 // (convergent, noduplicate, or cross-basic-block tokens).
2604 // FIXME: We might be able to safely handle some of these in non-duplicated
2605 // regions.
2606 int LoopCost = 0;
2607 for (auto *BB : L.blocks()) {
2608 int Cost = 0;
2609 for (auto &I : *BB) {
2610 if (EphValues.count(&I))
2611 continue;
2612
2613 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002614 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002615 if (auto CS = CallSite(&I))
2616 if (CS.isConvergent() || CS.cannotDuplicate())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002617 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002618
2619 Cost += TTI.getUserCost(&I);
2620 }
2621 assert(Cost >= 0 && "Must not have negative costs!");
2622 LoopCost += Cost;
2623 assert(LoopCost >= 0 && "Must not have negative loop costs!");
2624 BBCostMap[BB] = Cost;
2625 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002626 LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002627
2628 // Now we find the best candidate by searching for the one with the following
2629 // properties in order:
2630 //
2631 // 1) An unswitching cost below the threshold
2632 // 2) The smallest number of duplicated unswitch candidates (to avoid
2633 // creating redundant subsequent unswitching)
2634 // 3) The smallest cost after unswitching.
2635 //
2636 // We prioritize reducing fanout of unswitch candidates provided the cost
2637 // remains below the threshold because this has a multiplicative effect.
2638 //
2639 // This requires memoizing each dominator subtree to avoid redundant work.
2640 //
2641 // FIXME: Need to actually do the number of candidates part above.
2642 SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2643 // Given a terminator which might be unswitched, computes the non-duplicated
2644 // cost for that terminator.
Chandler Carruth60b2e052018-10-18 00:40:26 +00002645 auto ComputeUnswitchedCost = [&](Instruction &TI, bool FullUnswitch) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002646 BasicBlock &BB = *TI.getParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002647 SmallPtrSet<BasicBlock *, 4> Visited;
2648
2649 int Cost = LoopCost;
2650 for (BasicBlock *SuccBB : successors(&BB)) {
2651 // Don't count successors more than once.
2652 if (!Visited.insert(SuccBB).second)
2653 continue;
2654
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002655 // If this is a partial unswitch candidate, then it must be a conditional
2656 // branch with a condition of either `or` or `and`. In that case, one of
2657 // the successors is necessarily duplicated, so don't even try to remove
2658 // its cost.
2659 if (!FullUnswitch) {
2660 auto &BI = cast<BranchInst>(TI);
2661 if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2662 Instruction::And) {
2663 if (SuccBB == BI.getSuccessor(1))
2664 continue;
2665 } else {
2666 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2667 Instruction::Or &&
2668 "Only `and` and `or` conditions can result in a partial "
2669 "unswitch!");
2670 if (SuccBB == BI.getSuccessor(0))
2671 continue;
2672 }
2673 }
2674
Chandler Carruth693eedb2017-11-17 19:58:36 +00002675 // This successor's domtree will not need to be duplicated after
2676 // unswitching if the edge to the successor dominates it (and thus the
2677 // entire tree). This essentially means there is no other path into this
2678 // subtree and so it will end up live in only one clone of the loop.
2679 if (SuccBB->getUniquePredecessor() ||
2680 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2681 return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2682 })) {
2683 Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2684 assert(Cost >= 0 &&
2685 "Non-duplicated cost should never exceed total loop cost!");
2686 }
2687 }
2688
2689 // Now scale the cost by the number of unique successors minus one. We
2690 // subtract one because there is already at least one copy of the entire
2691 // loop. This is computing the new cost of unswitching a condition.
Max Kazantsev619a8342018-10-26 14:20:11 +00002692 // Note that guards always have 2 unique successors that are implicit and
2693 // will be materialized if we decide to unswitch it.
2694 int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2695 assert(SuccessorsCount > 1 &&
Chandler Carruth693eedb2017-11-17 19:58:36 +00002696 "Cannot unswitch a condition without multiple distinct successors!");
Max Kazantsev619a8342018-10-26 14:20:11 +00002697 return Cost * (SuccessorsCount - 1);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002698 };
Chandler Carruth60b2e052018-10-18 00:40:26 +00002699 Instruction *BestUnswitchTI = nullptr;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002700 int BestUnswitchCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002701 ArrayRef<Value *> BestUnswitchInvariants;
2702 for (auto &TerminatorAndInvariants : UnswitchCandidates) {
Chandler Carruth60b2e052018-10-18 00:40:26 +00002703 Instruction &TI = *TerminatorAndInvariants.first;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002704 ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2705 BranchInst *BI = dyn_cast<BranchInst>(&TI);
Chandler Carruth16529962018-06-25 23:32:54 +00002706 int CandidateCost = ComputeUnswitchedCost(
2707 TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2708 Invariants[0] == BI->getCondition()));
Fedor Sergeev2e3e2242018-11-16 21:16:43 +00002709 // Calculate cost multiplier which is a tool to limit potentially
2710 // exponential behavior of loop-unswitch.
2711 if (EnableUnswitchCostMultiplier) {
2712 int CostMultiplier =
2713 calculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
2714 assert(
2715 (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
2716 "cost multiplier needs to be in the range of 1..UnswitchThreshold");
2717 CandidateCost *= CostMultiplier;
2718 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2719 << " (multiplier: " << CostMultiplier << ")"
2720 << " for unswitch candidate: " << TI << "\n");
2721 } else {
2722 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2723 << " for unswitch candidate: " << TI << "\n");
2724 }
2725
Chandler Carruth693eedb2017-11-17 19:58:36 +00002726 if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002727 BestUnswitchTI = &TI;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002728 BestUnswitchCost = CandidateCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002729 BestUnswitchInvariants = Invariants;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002730 }
2731 }
2732
Chandler Carruth71fd2702018-05-30 02:46:45 +00002733 if (BestUnswitchCost >= UnswitchThreshold) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002734 LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2735 << BestUnswitchCost << "\n");
Chandler Carruth71fd2702018-05-30 02:46:45 +00002736 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002737 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002738
Max Kazantsev619a8342018-10-26 14:20:11 +00002739 // If the best candidate is a guard, turn it into a branch.
2740 if (isGuard(BestUnswitchTI))
2741 BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002742 ExitBlocks, DT, LI, MSSAU);
Max Kazantsev619a8342018-10-26 14:20:11 +00002743
Max Kazantsevbde31002018-10-26 09:52:58 +00002744 LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = "
Chandler Carruth16529962018-06-25 23:32:54 +00002745 << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2746 << "\n");
Max Kazantsevbde31002018-10-26 09:52:58 +00002747 unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002748 ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU);
Max Kazantsevbde31002018-10-26 09:52:58 +00002749 return true;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002750}
2751
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002752/// Unswitch control flow predicated on loop invariant conditions.
2753///
2754/// This first hoists all branches or switches which are trivial (IE, do not
2755/// require duplicating any part of the loop) out of the loop body. It then
2756/// looks at other loop invariant control flows and tries to unswitch those as
2757/// well by cloning the loop if the result is small enough.
Chandler Carruth3897ded2018-07-03 09:13:27 +00002758///
2759/// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2760/// updated based on the unswitch.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002761/// The `MSSA` analysis is also updated if valid (i.e. its use is enabled).
Chandler Carruth3897ded2018-07-03 09:13:27 +00002762///
2763/// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2764/// true, we will attempt to do non-trivial unswitching as well as trivial
2765/// unswitching.
2766///
2767/// The `UnswitchCB` callback provided will be run after unswitching is
2768/// complete, with the first parameter set to `true` if the provided loop
2769/// remains a loop, and a list of new sibling loops created.
2770///
2771/// If `SE` is non-null, we will update that analysis based on the unswitching
2772/// done.
2773static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2774 AssumptionCache &AC, TargetTransformInfo &TTI,
2775 bool NonTrivial,
2776 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002777 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002778 assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2779 "Loops must be in LCSSA form before unswitching.");
2780 bool Changed = false;
2781
2782 // Must be in loop simplified form: we need a preheader and dedicated exits.
2783 if (!L.isLoopSimplifyForm())
2784 return false;
2785
2786 // Try trivial unswitch first before loop over other basic blocks in the loop.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002787 if (unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002788 // If we unswitched successfully we will want to clean up the loop before
2789 // processing it further so just mark it as unswitched and return.
2790 UnswitchCB(/*CurrentLoopValid*/ true, {});
2791 return true;
2792 }
2793
2794 // If we're not doing non-trivial unswitching, we're done. We both accept
2795 // a parameter but also check a local flag that can be used for testing
2796 // a debugging.
2797 if (!NonTrivial && !EnableNonTrivialUnswitch)
2798 return false;
2799
2800 // For non-trivial unswitching, because it often creates new loops, we rely on
2801 // the pass manager to iterate on the loops rather than trying to immediately
2802 // reach a fixed point. There is no substantial advantage to iterating
2803 // internally, and if any of the new loops are simplified enough to contain
2804 // trivial unswitching we want to prefer those.
2805
2806 // Try to unswitch the best invariant condition. We prefer this full unswitch to
2807 // a partial unswitch when possible below the threshold.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002808 if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE, MSSAU))
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002809 return true;
2810
2811 // No other opportunities to unswitch.
2812 return Changed;
2813}
2814
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002815PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2816 LoopStandardAnalysisResults &AR,
2817 LPMUpdater &U) {
2818 Function &F = *L.getHeader()->getParent();
2819 (void)F;
2820
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002821 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2822 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002823
Chandler Carruth693eedb2017-11-17 19:58:36 +00002824 // Save the current loop name in a variable so that we can report it even
2825 // after it has been deleted.
2826 std::string LoopName = L.getName();
2827
Chandler Carruth71fd2702018-05-30 02:46:45 +00002828 auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2829 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002830 // If we did a non-trivial unswitch, we have added new (cloned) loops.
Chandler Carruth71fd2702018-05-30 02:46:45 +00002831 if (!NewLoops.empty())
2832 U.addSiblingLoops(NewLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002833
2834 // If the current loop remains valid, we should revisit it to catch any
2835 // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2836 if (CurrentLoopValid)
2837 U.revisitCurrentLoop();
2838 else
2839 U.markLoopAsDeleted(L, LoopName);
2840 };
2841
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002842 Optional<MemorySSAUpdater> MSSAU;
2843 if (AR.MSSA) {
2844 MSSAU = MemorySSAUpdater(AR.MSSA);
2845 if (VerifyMemorySSA)
2846 AR.MSSA->verifyMemorySSA();
2847 }
Chandler Carruth3897ded2018-07-03 09:13:27 +00002848 if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002849 &AR.SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002850 return PreservedAnalyses::all();
2851
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002852 if (AR.MSSA && VerifyMemorySSA)
2853 AR.MSSA->verifyMemorySSA();
2854
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002855 // Historically this pass has had issues with the dominator tree so verify it
2856 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002857 assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002858 return getLoopPassPreservedAnalyses();
2859}
2860
2861namespace {
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002862
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002863class SimpleLoopUnswitchLegacyPass : public LoopPass {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002864 bool NonTrivial;
2865
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002866public:
2867 static char ID; // Pass ID, replacement for typeid
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002868
Chandler Carruth693eedb2017-11-17 19:58:36 +00002869 explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2870 : LoopPass(ID), NonTrivial(NonTrivial) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002871 initializeSimpleLoopUnswitchLegacyPassPass(
2872 *PassRegistry::getPassRegistry());
2873 }
2874
2875 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2876
2877 void getAnalysisUsage(AnalysisUsage &AU) const override {
2878 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002879 AU.addRequired<TargetTransformInfoWrapperPass>();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002880 if (EnableMSSALoopDependency) {
2881 AU.addRequired<MemorySSAWrapperPass>();
2882 AU.addPreserved<MemorySSAWrapperPass>();
2883 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002884 getLoopAnalysisUsage(AU);
2885 }
2886};
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002887
2888} // end anonymous namespace
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002889
2890bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2891 if (skipLoop(L))
2892 return false;
2893
2894 Function &F = *L->getHeader()->getParent();
2895
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002896 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2897 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002898
2899 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2900 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2901 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002902 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002903 MemorySSA *MSSA = nullptr;
2904 Optional<MemorySSAUpdater> MSSAU;
2905 if (EnableMSSALoopDependency) {
2906 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
2907 MSSAU = MemorySSAUpdater(MSSA);
2908 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002909
Chandler Carruth3897ded2018-07-03 09:13:27 +00002910 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2911 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2912
Chandler Carruth71fd2702018-05-30 02:46:45 +00002913 auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2914 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002915 // If we did a non-trivial unswitch, we have added new (cloned) loops.
2916 for (auto *NewL : NewLoops)
2917 LPM.addLoop(*NewL);
2918
2919 // If the current loop remains valid, re-add it to the queue. This is
2920 // a little wasteful as we'll finish processing the current loop as well,
2921 // but it is the best we can do in the old PM.
2922 if (CurrentLoopValid)
2923 LPM.addLoop(*L);
2924 else
2925 LPM.markLoopAsDeleted(*L);
2926 };
2927
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002928 if (MSSA && VerifyMemorySSA)
2929 MSSA->verifyMemorySSA();
2930
2931 bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE,
2932 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
2933
2934 if (MSSA && VerifyMemorySSA)
2935 MSSA->verifyMemorySSA();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002936
2937 // If anything was unswitched, also clear any cached information about this
2938 // loop.
2939 LPM.deleteSimpleAnalysisLoop(L);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002940
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002941 // Historically this pass has had issues with the dominator tree so verify it
2942 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002943 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2944
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002945 return Changed;
2946}
2947
2948char SimpleLoopUnswitchLegacyPass::ID = 0;
2949INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2950 "Simple unswitch loops", false, false)
2951INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002952INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2953INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002954INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002955INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002956INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2957INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2958 "Simple unswitch loops", false, false)
2959
Chandler Carruth693eedb2017-11-17 19:58:36 +00002960Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2961 return new SimpleLoopUnswitchLegacyPass(NonTrivial);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002962}