blob: a14182d81e0736bec6fb51c26f28f81120db464d [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"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080041#include "llvm/InitializePasses.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000042#include "llvm/Pass.h"
43#include "llvm/Support/Casting.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000044#include "llvm/Support/Debug.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000045#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/GenericDomTree.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000047#include "llvm/Support/raw_ostream.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000048#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000049#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000050#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000051#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000052#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000053#include <algorithm>
54#include <cassert>
55#include <iterator>
Chandler Carruth693eedb2017-11-17 19:58:36 +000056#include <numeric>
Eugene Zelenkoa369a452017-05-16 23:10:25 +000057#include <utility>
Chandler Carruth1353f9a2017-04-27 18:45:20 +000058
59#define DEBUG_TYPE "simple-loop-unswitch"
60
61using namespace llvm;
62
63STATISTIC(NumBranches, "Number of branches unswitched");
64STATISTIC(NumSwitches, "Number of switches unswitched");
Max Kazantsev619a8342018-10-26 14:20:11 +000065STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
Chandler Carruth1353f9a2017-04-27 18:45:20 +000066STATISTIC(NumTrivial, "Number of unswitches that are trivial");
Fedor Sergeev2e3e2242018-11-16 21:16:43 +000067STATISTIC(
68 NumCostMultiplierSkipped,
69 "Number of unswitch candidates that had their cost multiplier skipped");
Chandler Carruth1353f9a2017-04-27 18:45:20 +000070
Chandler Carruth693eedb2017-11-17 19:58:36 +000071static cl::opt<bool> EnableNonTrivialUnswitch(
72 "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
73 cl::desc("Forcibly enables non-trivial loop unswitching rather than "
74 "following the configuration passed into the pass."));
75
76static cl::opt<int>
77 UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
78 cl::desc("The cost threshold for unswitching a loop."));
79
Fedor Sergeev2e3e2242018-11-16 21:16:43 +000080static cl::opt<bool> EnableUnswitchCostMultiplier(
81 "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
82 cl::desc("Enable unswitch cost multiplier that prohibits exponential "
83 "explosion in nontrivial unswitch."));
84static cl::opt<int> UnswitchSiblingsToplevelDiv(
85 "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
86 cl::desc("Toplevel siblings divisor for cost multiplier."));
87static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
88 "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
89 cl::desc("Number of unswitch candidates that are ignored when calculating "
90 "cost multiplier."));
Max Kazantsev619a8342018-10-26 14:20:11 +000091static cl::opt<bool> UnswitchGuards(
92 "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
93 cl::desc("If enabled, simple loop unswitching will also consider "
94 "llvm.experimental.guard intrinsics as unswitch candidates."));
95
Chandler Carruth4da33312018-06-20 18:57:07 +000096/// Collect all of the loop invariant input values transitively used by the
97/// homogeneous instruction graph from a given root.
98///
99/// This essentially walks from a root recursively through loop variant operands
100/// which have the exact same opcode and finds all inputs which are loop
101/// invariant. For some operations these can be re-associated and unswitched out
102/// of the loop entirely.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000103static TinyPtrVector<Value *>
Chandler Carruth4da33312018-06-20 18:57:07 +0000104collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
105 LoopInfo &LI) {
Chandler Carruth4da33312018-06-20 18:57:07 +0000106 assert(!L.isLoopInvariant(&Root) &&
107 "Only need to walk the graph if root itself is not invariant.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000108 TinyPtrVector<Value *> Invariants;
Chandler Carruth4da33312018-06-20 18:57:07 +0000109
110 // Build a worklist and recurse through operators collecting invariants.
111 SmallVector<Instruction *, 4> Worklist;
112 SmallPtrSet<Instruction *, 8> Visited;
113 Worklist.push_back(&Root);
114 Visited.insert(&Root);
115 do {
116 Instruction &I = *Worklist.pop_back_val();
117 for (Value *OpV : I.operand_values()) {
118 // Skip constants as unswitching isn't interesting for them.
119 if (isa<Constant>(OpV))
120 continue;
121
122 // Add it to our result if loop invariant.
123 if (L.isLoopInvariant(OpV)) {
124 Invariants.push_back(OpV);
125 continue;
126 }
127
128 // If not an instruction with the same opcode, nothing we can do.
129 Instruction *OpI = dyn_cast<Instruction>(OpV);
130 if (!OpI || OpI->getOpcode() != Root.getOpcode())
131 continue;
132
133 // Visit this operand.
134 if (Visited.insert(OpI).second)
135 Worklist.push_back(OpI);
136 }
137 } while (!Worklist.empty());
138
139 return Invariants;
140}
141
142static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
143 Constant &Replacement) {
144 assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000145
146 // Replace uses of LIC in the loop with the given constant.
Chandler Carruth4da33312018-06-20 18:57:07 +0000147 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end(); UI != UE;) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000148 // Grab the use and walk past it so we can clobber it in the use list.
149 Use *U = &*UI++;
150 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000151
152 // Replace this use within the loop body.
Chandler Carruth4da33312018-06-20 18:57:07 +0000153 if (UserI && L.contains(UserI))
154 U->set(&Replacement);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000155 }
156}
157
Chandler Carruthd869b182017-05-12 02:19:59 +0000158/// Check that all the LCSSA PHI nodes in the loop exit block have trivial
159/// incoming values along this edge.
160static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
161 BasicBlock &ExitBB) {
162 for (Instruction &I : ExitBB) {
163 auto *PN = dyn_cast<PHINode>(&I);
164 if (!PN)
165 // No more PHIs to check.
166 return true;
167
168 // If the incoming value for this edge isn't loop invariant the unswitch
169 // won't be trivial.
170 if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
171 return false;
172 }
173 llvm_unreachable("Basic blocks should never be empty!");
174}
175
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000176/// Insert code to test a set of loop invariant values, and conditionally branch
177/// on them.
178static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
179 ArrayRef<Value *> Invariants,
180 bool Direction,
181 BasicBlock &UnswitchedSucc,
182 BasicBlock &NormalSucc) {
183 IRBuilder<> IRB(&BB);
Philip Reames9e62c862019-07-06 03:46:18 +0000184
185 Value *Cond = Direction ? IRB.CreateOr(Invariants) :
186 IRB.CreateAnd(Invariants);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000187 IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
188 Direction ? &NormalSucc : &UnswitchedSucc);
189}
190
Chandler Carruthd869b182017-05-12 02:19:59 +0000191/// Rewrite the PHI nodes in an unswitched loop exit basic block.
192///
193/// Requires that the loop exit and unswitched basic block are the same, and
194/// that the exiting block was a unique predecessor of that block. Rewrites the
195/// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
196/// PHI nodes from the old preheader that now contains the unswitched
197/// terminator.
198static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
199 BasicBlock &OldExitingBB,
200 BasicBlock &OldPH) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000201 for (PHINode &PN : UnswitchedBB.phis()) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000202 // When the loop exit is directly unswitched we just need to update the
203 // incoming basic block. We loop to handle weird cases with repeated
204 // incoming blocks, but expect to typically only have one operand here.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000205 for (auto i : seq<int>(0, PN.getNumOperands())) {
206 assert(PN.getIncomingBlock(i) == &OldExitingBB &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000207 "Found incoming block different from unique predecessor!");
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000208 PN.setIncomingBlock(i, &OldPH);
Chandler Carruthd869b182017-05-12 02:19:59 +0000209 }
210 }
211}
212
213/// Rewrite the PHI nodes in the loop exit basic block and the split off
214/// unswitched block.
215///
216/// Because the exit block remains an exit from the loop, this rewrites the
217/// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
218/// nodes into the unswitched basic block to select between the value in the
219/// old preheader and the loop exit.
220static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
221 BasicBlock &UnswitchedBB,
222 BasicBlock &OldExitingBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000223 BasicBlock &OldPH,
224 bool FullUnswitch) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000225 assert(&ExitBB != &UnswitchedBB &&
226 "Must have different loop exit and unswitched blocks!");
227 Instruction *InsertPt = &*UnswitchedBB.begin();
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000228 for (PHINode &PN : ExitBB.phis()) {
229 auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
230 PN.getName() + ".split", InsertPt);
Chandler Carruthd869b182017-05-12 02:19:59 +0000231
232 // Walk backwards over the old PHI node's inputs to minimize the cost of
233 // removing each one. We have to do this weird loop manually so that we
234 // create the same number of new incoming edges in the new PHI as we expect
235 // each case-based edge to be included in the unswitched switch in some
236 // cases.
237 // FIXME: This is really, really gross. It would be much cleaner if LLVM
238 // allowed us to create a single entry for a predecessor block without
239 // having separate entries for each "edge" even though these edges are
240 // required to produce identical results.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000241 for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
242 if (PN.getIncomingBlock(i) != &OldExitingBB)
Chandler Carruthd869b182017-05-12 02:19:59 +0000243 continue;
244
Chandler Carruth4da33312018-06-20 18:57:07 +0000245 Value *Incoming = PN.getIncomingValue(i);
246 if (FullUnswitch)
247 // No more edge from the old exiting block to the exit block.
248 PN.removeIncomingValue(i);
249
Chandler Carruthd869b182017-05-12 02:19:59 +0000250 NewPN->addIncoming(Incoming, &OldPH);
251 }
252
253 // Now replace the old PHI with the new one and wire the old one in as an
254 // input to the new one.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000255 PN.replaceAllUsesWith(NewPN);
256 NewPN->addIncoming(&PN, &ExitBB);
Chandler Carruthd869b182017-05-12 02:19:59 +0000257 }
258}
259
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000260/// Hoist the current loop up to the innermost loop containing a remaining exit.
261///
262/// Because we've removed an exit from the loop, we may have changed the set of
263/// loops reachable and need to move the current loop up the loop nest or even
264/// to an entirely separate nest.
265static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
Alina Sbirlea97468e92019-02-21 21:13:34 +0000266 DominatorTree &DT, LoopInfo &LI,
267 MemorySSAUpdater *MSSAU) {
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000268 // If the loop is already at the top level, we can't hoist it anywhere.
269 Loop *OldParentL = L.getParentLoop();
270 if (!OldParentL)
271 return;
272
273 SmallVector<BasicBlock *, 4> Exits;
274 L.getExitBlocks(Exits);
275 Loop *NewParentL = nullptr;
276 for (auto *ExitBB : Exits)
277 if (Loop *ExitL = LI.getLoopFor(ExitBB))
278 if (!NewParentL || NewParentL->contains(ExitL))
279 NewParentL = ExitL;
280
281 if (NewParentL == OldParentL)
282 return;
283
284 // The new parent loop (if different) should always contain the old one.
285 if (NewParentL)
286 assert(NewParentL->contains(OldParentL) &&
287 "Can only hoist this loop up the nest!");
288
289 // The preheader will need to move with the body of this loop. However,
290 // because it isn't in this loop we also need to update the primary loop map.
291 assert(OldParentL == LI.getLoopFor(&Preheader) &&
292 "Parent loop of this loop should contain this loop's preheader!");
293 LI.changeLoopFor(&Preheader, NewParentL);
294
295 // Remove this loop from its old parent.
296 OldParentL->removeChildLoop(&L);
297
298 // Add the loop either to the new parent or as a top-level loop.
299 if (NewParentL)
300 NewParentL->addChildLoop(&L);
301 else
302 LI.addTopLevelLoop(&L);
303
304 // Remove this loops blocks from the old parent and every other loop up the
305 // nest until reaching the new parent. Also update all of these
306 // no-longer-containing loops to reflect the nesting change.
307 for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
308 OldContainingL = OldContainingL->getParentLoop()) {
309 llvm::erase_if(OldContainingL->getBlocksVector(),
310 [&](const BasicBlock *BB) {
311 return BB == &Preheader || L.contains(BB);
312 });
313
314 OldContainingL->getBlocksSet().erase(&Preheader);
315 for (BasicBlock *BB : L.blocks())
316 OldContainingL->getBlocksSet().erase(BB);
317
318 // Because we just hoisted a loop out of this one, we have essentially
319 // created new exit paths from it. That means we need to form LCSSA PHI
320 // nodes for values used in the no-longer-nested loop.
321 formLCSSA(*OldContainingL, DT, &LI, nullptr);
322
323 // We shouldn't need to form dedicated exits because the exit introduced
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000324 // here is the (just split by unswitching) preheader. However, after trivial
325 // unswitching it is possible to get new non-dedicated exits out of parent
326 // loop so let's conservatively form dedicated exit blocks and figure out
327 // if we can optimize later.
Alina Sbirlea97468e92019-02-21 21:13:34 +0000328 formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
329 /*PreserveLCSSA*/ true);
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000330 }
331}
332
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000333/// Unswitch a trivial branch if the condition is loop invariant.
334///
335/// This routine should only be called when loop code leading to the branch has
336/// been validated as trivial (no side effects). This routine checks if the
337/// condition is invariant and one of the successors is a loop exit. This
338/// allows us to unswitch without duplicating the loop, making it trivial.
339///
340/// If this routine fails to unswitch the branch it returns false.
341///
342/// If the branch can be unswitched, this routine splits the preheader and
343/// hoists the branch above that split. Preserves loop simplified form
344/// (splitting the exit block as necessary). It simplifies the branch within
345/// the loop to an unconditional branch but doesn't remove it entirely. Further
346/// cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000347///
348/// If `SE` is not null, it will be updated based on the potential loop SCEVs
349/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000350static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000351 LoopInfo &LI, ScalarEvolution *SE,
352 MemorySSAUpdater *MSSAU) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000353 assert(BI.isConditional() && "Can only unswitch a conditional branch!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000354 LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000355
Chandler Carruth4da33312018-06-20 18:57:07 +0000356 // The loop invariant values that we want to unswitch.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000357 TinyPtrVector<Value *> Invariants;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000358
Chandler Carruth4da33312018-06-20 18:57:07 +0000359 // When true, we're fully unswitching the branch rather than just unswitching
360 // some input conditions to the branch.
361 bool FullUnswitch = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000362
Chandler Carruth4da33312018-06-20 18:57:07 +0000363 if (L.isLoopInvariant(BI.getCondition())) {
364 Invariants.push_back(BI.getCondition());
365 FullUnswitch = true;
366 } else {
367 if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
368 Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
369 if (Invariants.empty())
370 // Couldn't find invariant inputs!
371 return false;
372 }
373
374 // Check that one of the branch's successors exits, and which one.
375 bool ExitDirection = true;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000376 int LoopExitSuccIdx = 0;
377 auto *LoopExitBB = BI.getSuccessor(0);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000378 if (L.contains(LoopExitBB)) {
Chandler Carruth4da33312018-06-20 18:57:07 +0000379 ExitDirection = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000380 LoopExitSuccIdx = 1;
381 LoopExitBB = BI.getSuccessor(1);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000382 if (L.contains(LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000383 return false;
384 }
385 auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
Chandler Carruthd869b182017-05-12 02:19:59 +0000386 auto *ParentBB = BI.getParent();
387 if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000388 return false;
389
Chandler Carruth4da33312018-06-20 18:57:07 +0000390 // When unswitching only part of the branch's condition, we need the exit
391 // block to be reached directly from the partially unswitched input. This can
392 // be done when the exit block is along the true edge and the branch condition
393 // is a graph of `or` operations, or the exit block is along the false edge
394 // and the condition is a graph of `and` operations.
395 if (!FullUnswitch) {
396 if (ExitDirection) {
397 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or)
398 return false;
399 } else {
400 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And)
401 return false;
402 }
403 }
404
405 LLVM_DEBUG({
406 dbgs() << " unswitching trivial invariant conditions for: " << BI
407 << "\n";
408 for (Value *Invariant : Invariants) {
409 dbgs() << " " << *Invariant << " == true";
410 if (Invariant != Invariants.back())
411 dbgs() << " ||";
412 dbgs() << "\n";
413 }
414 });
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000415
Chandler Carruth3897ded2018-07-03 09:13:27 +0000416 // If we have scalar evolutions, we need to invalidate them including this
417 // loop and the loop containing the exit block.
418 if (SE) {
419 if (Loop *ExitL = LI.getLoopFor(LoopExitBB))
420 SE->forgetLoop(ExitL);
421 else
422 // Forget the entire nest as this exits the entire nest.
423 SE->forgetTopmostLoop(&L);
424 }
425
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000426 if (MSSAU && VerifyMemorySSA)
427 MSSAU->getMemorySSA()->verifyMemorySSA();
428
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000429 // Split the preheader, so that we know that there is a safe place to insert
430 // the conditional branch. We will change the preheader to have a conditional
431 // branch on LoopCond.
432 BasicBlock *OldPH = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000433 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000434
435 // Now that we have a place to insert the conditional branch, create a place
436 // to branch to: this is the exit block out of the loop that we are
437 // unswitching. We need to split this if there are other loop predecessors.
438 // Because the loop is in simplified form, *any* other predecessor is enough.
439 BasicBlock *UnswitchedBB;
Chandler Carruth4da33312018-06-20 18:57:07 +0000440 if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
441 assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000442 "A branch's parent isn't a predecessor!");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000443 UnswitchedBB = LoopExitBB;
444 } else {
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000445 UnswitchedBB =
446 SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000447 }
448
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000449 if (MSSAU && VerifyMemorySSA)
450 MSSAU->getMemorySSA()->verifyMemorySSA();
451
Chandler Carruth4da33312018-06-20 18:57:07 +0000452 // Actually move the invariant uses into the unswitched position. If possible,
453 // we do this by moving the instructions, but when doing partial unswitching
454 // we do it by building a new merge of the values in the unswitched position.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000455 OldPH->getTerminator()->eraseFromParent();
Chandler Carruth4da33312018-06-20 18:57:07 +0000456 if (FullUnswitch) {
457 // If fully unswitching, we can use the existing branch instruction.
458 // Splice it into the old PH to gate reaching the new preheader and re-point
459 // its successors.
460 OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
461 BI);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000462 if (MSSAU) {
463 // Temporarily clone the terminator, to make MSSA update cheaper by
464 // separating "insert edge" updates from "remove edge" ones.
465 ParentBB->getInstList().push_back(BI.clone());
466 } else {
467 // Create a new unconditional branch that will continue the loop as a new
468 // terminator.
469 BranchInst::Create(ContinueBB, ParentBB);
470 }
Chandler Carruth4da33312018-06-20 18:57:07 +0000471 BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
472 BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
Chandler Carruth4da33312018-06-20 18:57:07 +0000473 } else {
474 // Only unswitching a subset of inputs to the condition, so we will need to
475 // build a new branch that merges the invariant inputs.
Chandler Carruth4da33312018-06-20 18:57:07 +0000476 if (ExitDirection)
477 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
478 Instruction::Or &&
479 "Must have an `or` of `i1`s for the condition!");
480 else
481 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
482 Instruction::And &&
483 "Must have an `and` of `i1`s for the condition!");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000484 buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
485 *UnswitchedBB, *NewPH);
Chandler Carruth4da33312018-06-20 18:57:07 +0000486 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000487
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000488 // Update the dominator tree with the added edge.
489 DT.insertEdge(OldPH, UnswitchedBB);
490
491 // After the dominator tree was updated with the added edge, update MemorySSA
492 // if available.
493 if (MSSAU) {
494 SmallVector<CFGUpdate, 1> Updates;
495 Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
496 MSSAU->applyInsertUpdates(Updates, DT);
497 }
498
499 // Finish updating dominator tree and memory ssa for full unswitch.
500 if (FullUnswitch) {
501 if (MSSAU) {
502 // Remove the cloned branch instruction.
503 ParentBB->getTerminator()->eraseFromParent();
504 // Create unconditional branch now.
505 BranchInst::Create(ContinueBB, ParentBB);
506 MSSAU->removeEdge(ParentBB, LoopExitBB);
507 }
508 DT.deleteEdge(ParentBB, LoopExitBB);
509 }
510
511 if (MSSAU && VerifyMemorySSA)
512 MSSAU->getMemorySSA()->verifyMemorySSA();
513
Chandler Carruthd869b182017-05-12 02:19:59 +0000514 // Rewrite the relevant PHI nodes.
515 if (UnswitchedBB == LoopExitBB)
516 rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
517 else
518 rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000519 *ParentBB, *OldPH, FullUnswitch);
Chandler Carruthd869b182017-05-12 02:19:59 +0000520
Chandler Carruth4da33312018-06-20 18:57:07 +0000521 // The constant we can replace all of our invariants with inside the loop
522 // body. If any of the invariants have a value other than this the loop won't
523 // be entered.
524 ConstantInt *Replacement = ExitDirection
525 ? ConstantInt::getFalse(BI.getContext())
526 : ConstantInt::getTrue(BI.getContext());
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000527
528 // Since this is an i1 condition we can also trivially replace uses of it
529 // within the loop with a constant.
Chandler Carruth4da33312018-06-20 18:57:07 +0000530 for (Value *Invariant : Invariants)
531 replaceLoopInvariantUses(L, Invariant, *Replacement);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000532
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000533 // If this was full unswitching, we may have changed the nesting relationship
534 // for this loop so hoist it to its correct parent if needed.
535 if (FullUnswitch)
Alina Sbirlea97468e92019-02-21 21:13:34 +0000536 hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU);
537
538 if (MSSAU && VerifyMemorySSA)
539 MSSAU->getMemorySSA()->verifyMemorySSA();
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000540
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000541 LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000542 ++NumTrivial;
543 ++NumBranches;
544 return true;
545}
546
547/// Unswitch a trivial switch if the condition is loop invariant.
548///
549/// This routine should only be called when loop code leading to the switch has
550/// been validated as trivial (no side effects). This routine checks if the
551/// condition is invariant and that at least one of the successors is a loop
552/// exit. This allows us to unswitch without duplicating the loop, making it
553/// trivial.
554///
555/// If this routine fails to unswitch the switch it returns false.
556///
557/// If the switch can be unswitched, this routine splits the preheader and
558/// copies the switch above that split. If the default case is one of the
559/// exiting cases, it copies the non-exiting cases and points them at the new
560/// preheader. If the default case is not exiting, it copies the exiting cases
561/// and points the default at the preheader. It preserves loop simplified form
562/// (splitting the exit blocks as necessary). It simplifies the switch within
563/// the loop by removing now-dead cases. If the default case is one of those
564/// unswitched, it replaces its destination with a new basic block containing
565/// only unreachable. Such basic blocks, while technically loop exits, are not
566/// considered for unswitching so this is a stable transform and the same
567/// switch will not be revisited. If after unswitching there is only a single
568/// in-loop successor, the switch is further simplified to an unconditional
569/// branch. Still more cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000570///
571/// If `SE` is not null, it will be updated based on the potential loop SCEVs
572/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000573static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000574 LoopInfo &LI, ScalarEvolution *SE,
575 MemorySSAUpdater *MSSAU) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000576 LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000577 Value *LoopCond = SI.getCondition();
578
579 // If this isn't switching on an invariant condition, we can't unswitch it.
580 if (!L.isLoopInvariant(LoopCond))
581 return false;
582
Chandler Carruthd869b182017-05-12 02:19:59 +0000583 auto *ParentBB = SI.getParent();
584
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000585 SmallVector<int, 4> ExitCaseIndices;
586 for (auto Case : SI.cases()) {
587 auto *SuccBB = Case.getCaseSuccessor();
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000588 if (!L.contains(SuccBB) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000589 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000590 ExitCaseIndices.push_back(Case.getCaseIndex());
591 }
592 BasicBlock *DefaultExitBB = nullptr;
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000593 SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight =
594 SwitchInstProfUpdateWrapper::getSuccessorWeight(SI, 0);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000595 if (!L.contains(SI.getDefaultDest()) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000596 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) &&
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000597 !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator())) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000598 DefaultExitBB = SI.getDefaultDest();
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000599 } else if (ExitCaseIndices.empty())
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000600 return false;
601
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000602 LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000603
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000604 if (MSSAU && VerifyMemorySSA)
605 MSSAU->getMemorySSA()->verifyMemorySSA();
606
Chandler Carruth3897ded2018-07-03 09:13:27 +0000607 // We may need to invalidate SCEVs for the outermost loop reached by any of
608 // the exits.
609 Loop *OuterL = &L;
610
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000611 if (DefaultExitBB) {
612 // Clear out the default destination temporarily to allow accurate
613 // predecessor lists to be examined below.
614 SI.setDefaultDest(nullptr);
615 // Check the loop containing this exit.
616 Loop *ExitL = LI.getLoopFor(DefaultExitBB);
617 if (!ExitL || ExitL->contains(OuterL))
618 OuterL = ExitL;
619 }
620
621 // Store the exit cases into a separate data structure and remove them from
622 // the switch.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000623 SmallVector<std::tuple<ConstantInt *, BasicBlock *,
624 SwitchInstProfUpdateWrapper::CaseWeightOpt>,
625 4> ExitCases;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000626 ExitCases.reserve(ExitCaseIndices.size());
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000627 SwitchInstProfUpdateWrapper SIW(SI);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000628 // We walk the case indices backwards so that we remove the last case first
629 // and don't disrupt the earlier indices.
630 for (unsigned Index : reverse(ExitCaseIndices)) {
631 auto CaseI = SI.case_begin() + Index;
Chandler Carruth3897ded2018-07-03 09:13:27 +0000632 // Compute the outer loop from this exit.
633 Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
634 if (!ExitL || ExitL->contains(OuterL))
635 OuterL = ExitL;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000636 // Save the value of this case.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000637 auto W = SIW.getSuccessorWeight(CaseI->getSuccessorIndex());
638 ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000639 // Delete the unswitched cases.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000640 SIW.removeCase(CaseI);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000641 }
642
Chandler Carruth3897ded2018-07-03 09:13:27 +0000643 if (SE) {
644 if (OuterL)
645 SE->forgetLoop(OuterL);
646 else
647 SE->forgetTopmostLoop(&L);
648 }
649
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000650 // Check if after this all of the remaining cases point at the same
651 // successor.
652 BasicBlock *CommonSuccBB = nullptr;
653 if (SI.getNumCases() > 0 &&
654 std::all_of(std::next(SI.case_begin()), SI.case_end(),
655 [&SI](const SwitchInst::CaseHandle &Case) {
656 return Case.getCaseSuccessor() ==
657 SI.case_begin()->getCaseSuccessor();
658 }))
659 CommonSuccBB = SI.case_begin()->getCaseSuccessor();
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000660 if (!DefaultExitBB) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000661 // If we're not unswitching the default, we need it to match any cases to
662 // have a common successor or if we have no cases it is the common
663 // successor.
664 if (SI.getNumCases() == 0)
665 CommonSuccBB = SI.getDefaultDest();
666 else if (SI.getDefaultDest() != CommonSuccBB)
667 CommonSuccBB = nullptr;
668 }
669
670 // Split the preheader, so that we know that there is a safe place to insert
671 // the switch.
672 BasicBlock *OldPH = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000673 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000674 OldPH->getTerminator()->eraseFromParent();
675
676 // Now add the unswitched switch.
677 auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000678 SwitchInstProfUpdateWrapper NewSIW(*NewSI);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000679
Chandler Carruthd869b182017-05-12 02:19:59 +0000680 // Rewrite the IR for the unswitched basic blocks. This requires two steps.
681 // First, we split any exit blocks with remaining in-loop predecessors. Then
682 // we update the PHIs in one of two ways depending on if there was a split.
683 // We walk in reverse so that we split in the same order as the cases
684 // appeared. This is purely for convenience of reading the resulting IR, but
685 // it doesn't cost anything really.
686 SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000687 SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
688 // Handle the default exit if necessary.
689 // FIXME: It'd be great if we could merge this with the loop below but LLVM's
690 // ranges aren't quite powerful enough yet.
Chandler Carruthd869b182017-05-12 02:19:59 +0000691 if (DefaultExitBB) {
692 if (pred_empty(DefaultExitBB)) {
693 UnswitchedExitBBs.insert(DefaultExitBB);
694 rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
695 } else {
696 auto *SplitBB =
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000697 SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
698 rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
699 *ParentBB, *OldPH,
700 /*FullUnswitch*/ true);
Chandler Carruthd869b182017-05-12 02:19:59 +0000701 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
702 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000703 }
704 // Note that we must use a reference in the for loop so that we update the
705 // container.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000706 for (auto &ExitCase : reverse(ExitCases)) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000707 // Grab a reference to the exit block in the pair so that we can update it.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000708 BasicBlock *ExitBB = std::get<1>(ExitCase);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000709
710 // If this case is the last edge into the exit block, we can simply reuse it
711 // as it will no longer be a loop exit. No mapping necessary.
Chandler Carruthd869b182017-05-12 02:19:59 +0000712 if (pred_empty(ExitBB)) {
713 // Only rewrite once.
714 if (UnswitchedExitBBs.insert(ExitBB).second)
715 rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000716 continue;
Chandler Carruthd869b182017-05-12 02:19:59 +0000717 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000718
719 // Otherwise we need to split the exit block so that we retain an exit
720 // block from the loop and a target for the unswitched condition.
721 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
722 if (!SplitExitBB) {
723 // If this is the first time we see this, do the split and remember it.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000724 SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
725 rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
726 *ParentBB, *OldPH,
727 /*FullUnswitch*/ true);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000728 }
Chandler Carruthd869b182017-05-12 02:19:59 +0000729 // Update the case pair to point to the split block.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000730 std::get<1>(ExitCase) = SplitExitBB;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000731 }
732
733 // Now add the unswitched cases. We do this in reverse order as we built them
734 // in reverse order.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000735 for (auto &ExitCase : reverse(ExitCases)) {
736 ConstantInt *CaseVal = std::get<0>(ExitCase);
737 BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000738
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000739 NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000740 }
741
742 // If the default was unswitched, re-point it and add explicit cases for
743 // entering the loop.
744 if (DefaultExitBB) {
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000745 NewSIW->setDefaultDest(DefaultExitBB);
746 NewSIW.setSuccessorWeight(0, DefaultCaseWeight);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000747
748 // We removed all the exit cases, so we just copy the cases to the
749 // unswitched switch.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000750 for (const auto &Case : SI.cases())
751 NewSIW.addCase(Case.getCaseValue(), NewPH,
752 SIW.getSuccessorWeight(Case.getSuccessorIndex()));
753 } else if (DefaultCaseWeight) {
754 // We have to set branch weight of the default case.
755 uint64_t SW = *DefaultCaseWeight;
756 for (const auto &Case : SI.cases()) {
757 auto W = SIW.getSuccessorWeight(Case.getSuccessorIndex());
758 assert(W &&
759 "case weight must be defined as default case weight is defined");
760 SW += *W;
761 }
762 NewSIW.setSuccessorWeight(0, SW);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000763 }
764
765 // If we ended up with a common successor for every path through the switch
766 // after unswitching, rewrite it to an unconditional branch to make it easy
767 // to recognize. Otherwise we potentially have to recognize the default case
768 // pointing at unreachable and other complexity.
769 if (CommonSuccBB) {
770 BasicBlock *BB = SI.getParent();
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000771 // We may have had multiple edges to this common successor block, so remove
772 // them as predecessors. We skip the first one, either the default or the
773 // actual first case.
774 bool SkippedFirst = DefaultExitBB == nullptr;
775 for (auto Case : SI.cases()) {
776 assert(Case.getCaseSuccessor() == CommonSuccBB &&
777 "Non-common successor!");
Chandler Carruth148861f2018-07-10 08:57:04 +0000778 (void)Case;
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000779 if (!SkippedFirst) {
780 SkippedFirst = true;
781 continue;
782 }
783 CommonSuccBB->removePredecessor(BB,
Max Kazantsev20b91892019-02-12 07:09:29 +0000784 /*KeepOneInputPHIs*/ true);
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000785 }
786 // Now nuke the switch and replace it with a direct branch.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000787 SIW.eraseFromParent();
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000788 BranchInst::Create(CommonSuccBB, BB);
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000789 } else if (DefaultExitBB) {
790 assert(SI.getNumCases() > 0 &&
791 "If we had no cases we'd have a common successor!");
792 // Move the last case to the default successor. This is valid as if the
793 // default got unswitched it cannot be reached. This has the advantage of
794 // being simple and keeping the number of edges from this switch to
795 // successors the same, and avoiding any PHI update complexity.
796 auto LastCaseI = std::prev(SI.case_end());
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000797
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000798 SI.setDefaultDest(LastCaseI->getCaseSuccessor());
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000799 SIW.setSuccessorWeight(
800 0, SIW.getSuccessorWeight(LastCaseI->getSuccessorIndex()));
801 SIW.removeCase(LastCaseI);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000802 }
803
Chandler Carruth2c85a232018-05-01 09:54:39 +0000804 // Walk the unswitched exit blocks and the unswitched split blocks and update
805 // the dominator tree based on the CFG edits. While we are walking unordered
806 // containers here, the API for applyUpdates takes an unordered list of
807 // updates and requires them to not contain duplicates.
808 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
809 for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
810 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
811 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
812 }
813 for (auto SplitUnswitchedPair : SplitExitBBMap) {
Alina Sbirlea90d2e3a2019-02-22 07:18:37 +0000814 DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first});
815 DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second});
Chandler Carruth2c85a232018-05-01 09:54:39 +0000816 }
817 DT.applyUpdates(DTUpdates);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000818
819 if (MSSAU) {
820 MSSAU->applyUpdates(DTUpdates, DT);
821 if (VerifyMemorySSA)
822 MSSAU->getMemorySSA()->verifyMemorySSA();
823 }
824
David Green7c35de12018-02-28 11:00:08 +0000825 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000826
827 // We may have changed the nesting relationship for this loop so hoist it to
828 // its correct parent if needed.
Alina Sbirlea97468e92019-02-21 21:13:34 +0000829 hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU);
830
831 if (MSSAU && VerifyMemorySSA)
832 MSSAU->getMemorySSA()->verifyMemorySSA();
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000833
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000834 ++NumTrivial;
835 ++NumSwitches;
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000836 LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000837 return true;
838}
839
840/// This routine scans the loop to find a branch or switch which occurs before
841/// any side effects occur. These can potentially be unswitched without
842/// duplicating the loop. If a branch or switch is successfully unswitched the
843/// scanning continues to see if subsequent branches or switches have become
844/// trivial. Once all trivial candidates have been unswitched, this routine
845/// returns.
846///
847/// The return value indicates whether anything was unswitched (and therefore
848/// changed).
Chandler Carruth3897ded2018-07-03 09:13:27 +0000849///
850/// If `SE` is not null, it will be updated based on the potential loop SCEVs
851/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000852static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000853 LoopInfo &LI, ScalarEvolution *SE,
854 MemorySSAUpdater *MSSAU) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000855 bool Changed = false;
856
857 // If loop header has only one reachable successor we should keep looking for
858 // trivial condition candidates in the successor as well. An alternative is
859 // to constant fold conditions and merge successors into loop header (then we
860 // only need to check header's terminator). The reason for not doing this in
861 // LoopUnswitch pass is that it could potentially break LoopPassManager's
862 // invariants. Folding dead branches could either eliminate the current loop
863 // or make other loops unreachable. LCSSA form might also not be preserved
864 // after deleting branches. The following code keeps traversing loop header's
865 // successors until it finds the trivial condition candidate (condition that
866 // is not a constant). Since unswitching generates branches with constant
867 // conditions, this scenario could be very common in practice.
868 BasicBlock *CurrentBB = L.getHeader();
869 SmallPtrSet<BasicBlock *, 8> Visited;
870 Visited.insert(CurrentBB);
871 do {
872 // Check if there are any side-effecting instructions (e.g. stores, calls,
873 // volatile loads) in the part of the loop that the code *would* execute
874 // without unswitching.
Alina Sbirlea93210872019-01-28 17:48:45 +0000875 if (MSSAU) // Possible early exit with MSSA
876 if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
877 if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
878 return Changed;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000879 if (llvm::any_of(*CurrentBB,
880 [](Instruction &I) { return I.mayHaveSideEffects(); }))
881 return Changed;
882
Chandler Carruthedb12a82018-10-15 10:04:59 +0000883 Instruction *CurrentTerm = CurrentBB->getTerminator();
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000884
885 if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
886 // Don't bother trying to unswitch past a switch with a constant
887 // condition. This should be removed prior to running this pass by
888 // simplify-cfg.
889 if (isa<Constant>(SI->getCondition()))
890 return Changed;
891
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000892 if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
Hiroshi Inouef2096492018-06-14 05:41:49 +0000893 // Couldn't unswitch this one so we're done.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000894 return Changed;
895
896 // Mark that we managed to unswitch something.
897 Changed = true;
898
899 // If unswitching turned the terminator into an unconditional branch then
900 // we can continue. The unswitching logic specifically works to fold any
901 // cases it can into an unconditional branch to make it easier to
902 // recognize here.
903 auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
904 if (!BI || BI->isConditional())
905 return Changed;
906
907 CurrentBB = BI->getSuccessor(0);
908 continue;
909 }
910
911 auto *BI = dyn_cast<BranchInst>(CurrentTerm);
912 if (!BI)
913 // We do not understand other terminator instructions.
914 return Changed;
915
916 // Don't bother trying to unswitch past an unconditional branch or a branch
917 // with a constant value. These should be removed by simplify-cfg prior to
918 // running this pass.
919 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
920 return Changed;
921
922 // Found a trivial condition candidate: non-foldable conditional branch. If
923 // we fail to unswitch this, we can't do anything else that is trivial.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000924 if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000925 return Changed;
926
927 // Mark that we managed to unswitch something.
928 Changed = true;
929
Chandler Carruth4da33312018-06-20 18:57:07 +0000930 // If we only unswitched some of the conditions feeding the branch, we won't
931 // have collapsed it to a single successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000932 BI = cast<BranchInst>(CurrentBB->getTerminator());
Chandler Carruth4da33312018-06-20 18:57:07 +0000933 if (BI->isConditional())
934 return Changed;
935
936 // Follow the newly unconditional branch into its successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000937 CurrentBB = BI->getSuccessor(0);
938
939 // When continuing, if we exit the loop or reach a previous visited block,
940 // then we can not reach any trivial condition candidates (unfoldable
941 // branch instructions or switch instructions) and no unswitch can happen.
942 } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
943
944 return Changed;
945}
946
Chandler Carruth693eedb2017-11-17 19:58:36 +0000947/// Build the cloned blocks for an unswitched copy of the given loop.
948///
949/// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
950/// after the split block (`SplitBB`) that will be used to select between the
951/// cloned and original loop.
952///
953/// This routine handles cloning all of the necessary loop blocks and exit
954/// blocks including rewriting their instructions and the relevant PHI nodes.
Chandler Carruth16529962018-06-25 23:32:54 +0000955/// Any loop blocks or exit blocks which are dominated by a different successor
956/// than the one for this clone of the loop blocks can be trivially skipped. We
957/// use the `DominatingSucc` map to determine whether a block satisfies that
958/// property with a simple map lookup.
959///
960/// It also correctly creates the unconditional branch in the cloned
Chandler Carruth693eedb2017-11-17 19:58:36 +0000961/// unswitched parent block to only point at the unswitched successor.
962///
963/// This does not handle most of the necessary updates to `LoopInfo`. Only exit
964/// block splitting is correctly reflected in `LoopInfo`, essentially all of
965/// the cloned blocks (and their loops) are left without full `LoopInfo`
966/// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
967/// blocks to them but doesn't create the cloned `DominatorTree` structure and
968/// instead the caller must recompute an accurate DT. It *does* correctly
969/// update the `AssumptionCache` provided in `AC`.
970static BasicBlock *buildClonedLoopBlocks(
971 Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
972 ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
973 BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
Chandler Carruth16529962018-06-25 23:32:54 +0000974 const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
Chandler Carruth69e68f82018-04-25 00:18:07 +0000975 ValueToValueMapTy &VMap,
976 SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000977 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Chandler Carruth693eedb2017-11-17 19:58:36 +0000978 SmallVector<BasicBlock *, 4> NewBlocks;
979 NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
980
981 // We will need to clone a bunch of blocks, wrap up the clone operation in
982 // a helper.
983 auto CloneBlock = [&](BasicBlock *OldBB) {
984 // Clone the basic block and insert it before the new preheader.
985 BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
986 NewBB->moveBefore(LoopPH);
987
988 // Record this block and the mapping.
989 NewBlocks.push_back(NewBB);
990 VMap[OldBB] = NewBB;
991
Chandler Carruth693eedb2017-11-17 19:58:36 +0000992 return NewBB;
993 };
994
Chandler Carruth16529962018-06-25 23:32:54 +0000995 // We skip cloning blocks when they have a dominating succ that is not the
996 // succ we are cloning for.
997 auto SkipBlock = [&](BasicBlock *BB) {
998 auto It = DominatingSucc.find(BB);
999 return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
1000 };
1001
Chandler Carruth693eedb2017-11-17 19:58:36 +00001002 // First, clone the preheader.
1003 auto *ClonedPH = CloneBlock(LoopPH);
1004
1005 // Then clone all the loop blocks, skipping the ones that aren't necessary.
1006 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +00001007 if (!SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001008 CloneBlock(LoopBB);
1009
1010 // Split all the loop exit edges so that when we clone the exit blocks, if
1011 // any of the exit blocks are *also* a preheader for some other loop, we
1012 // don't create multiple predecessors entering the loop header.
1013 for (auto *ExitBB : ExitBlocks) {
Chandler Carruth16529962018-06-25 23:32:54 +00001014 if (SkipBlock(ExitBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001015 continue;
1016
1017 // When we are going to clone an exit, we don't need to clone all the
1018 // instructions in the exit block and we want to ensure we have an easy
1019 // place to merge the CFG, so split the exit first. This is always safe to
1020 // do because there cannot be any non-loop predecessors of a loop exit in
1021 // loop simplified form.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001022 auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001023
1024 // Rearrange the names to make it easier to write test cases by having the
1025 // exit block carry the suffix rather than the merge block carrying the
1026 // suffix.
1027 MergeBB->takeName(ExitBB);
1028 ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1029
1030 // Now clone the original exit block.
1031 auto *ClonedExitBB = CloneBlock(ExitBB);
1032 assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1033 "Exit block should have been split to have one successor!");
1034 assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1035 "Cloned exit block has the wrong successor!");
1036
Chandler Carruth693eedb2017-11-17 19:58:36 +00001037 // Remap any cloned instructions and create a merge phi node for them.
1038 for (auto ZippedInsts : llvm::zip_first(
1039 llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1040 llvm::make_range(ClonedExitBB->begin(),
1041 std::prev(ClonedExitBB->end())))) {
1042 Instruction &I = std::get<0>(ZippedInsts);
1043 Instruction &ClonedI = std::get<1>(ZippedInsts);
1044
1045 // The only instructions in the exit block should be PHI nodes and
1046 // potentially a landing pad.
1047 assert(
1048 (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1049 "Bad instruction in exit block!");
1050 // We should have a value map between the instruction and its clone.
1051 assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1052
1053 auto *MergePN =
1054 PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1055 &*MergeBB->getFirstInsertionPt());
1056 I.replaceAllUsesWith(MergePN);
1057 MergePN->addIncoming(&I, ExitBB);
1058 MergePN->addIncoming(&ClonedI, ClonedExitBB);
1059 }
1060 }
1061
1062 // Rewrite the instructions in the cloned blocks to refer to the instructions
1063 // in the cloned blocks. We have to do this as a second pass so that we have
1064 // everything available. Also, we have inserted new instructions which may
1065 // include assume intrinsics, so we update the assumption cache while
1066 // processing this.
1067 for (auto *ClonedBB : NewBlocks)
1068 for (Instruction &I : *ClonedBB) {
1069 RemapInstruction(&I, VMap,
1070 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1071 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1072 if (II->getIntrinsicID() == Intrinsic::assume)
1073 AC.registerAssumption(II);
1074 }
1075
Chandler Carruth693eedb2017-11-17 19:58:36 +00001076 // Update any PHI nodes in the cloned successors of the skipped blocks to not
1077 // have spurious incoming values.
1078 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +00001079 if (SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001080 for (auto *SuccBB : successors(LoopBB))
1081 if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1082 for (PHINode &PN : ClonedSuccBB->phis())
1083 PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1084
Chandler Carruthed296542018-07-09 10:30:48 +00001085 // Remove the cloned parent as a predecessor of any successor we ended up
1086 // cloning other than the unswitched one.
1087 auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1088 for (auto *SuccBB : successors(ParentBB)) {
1089 if (SuccBB == UnswitchedSuccBB)
1090 continue;
1091
1092 auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1093 if (!ClonedSuccBB)
1094 continue;
1095
1096 ClonedSuccBB->removePredecessor(ClonedParentBB,
Max Kazantsev20b91892019-02-12 07:09:29 +00001097 /*KeepOneInputPHIs*/ true);
Chandler Carruthed296542018-07-09 10:30:48 +00001098 }
1099
1100 // Replace the cloned branch with an unconditional branch to the cloned
1101 // unswitched successor.
1102 auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1103 ClonedParentBB->getTerminator()->eraseFromParent();
1104 BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1105
1106 // If there are duplicate entries in the PHI nodes because of multiple edges
1107 // to the unswitched successor, we need to nuke all but one as we replaced it
1108 // with a direct branch.
1109 for (PHINode &PN : ClonedSuccBB->phis()) {
1110 bool Found = false;
1111 // Loop over the incoming operands backwards so we can easily delete as we
1112 // go without invalidating the index.
1113 for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1114 if (PN.getIncomingBlock(i) != ClonedParentBB)
1115 continue;
1116 if (!Found) {
1117 Found = true;
1118 continue;
1119 }
1120 PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1121 }
1122 }
1123
Chandler Carruth69e68f82018-04-25 00:18:07 +00001124 // Record the domtree updates for the new blocks.
Chandler Carruth44aab922018-05-01 09:42:09 +00001125 SmallPtrSet<BasicBlock *, 4> SuccSet;
1126 for (auto *ClonedBB : NewBlocks) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001127 for (auto *SuccBB : successors(ClonedBB))
Chandler Carruth44aab922018-05-01 09:42:09 +00001128 if (SuccSet.insert(SuccBB).second)
1129 DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1130 SuccSet.clear();
1131 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001132
Chandler Carruth693eedb2017-11-17 19:58:36 +00001133 return ClonedPH;
1134}
1135
1136/// Recursively clone the specified loop and all of its children.
1137///
1138/// The target parent loop for the clone should be provided, or can be null if
1139/// the clone is a top-level loop. While cloning, all the blocks are mapped
1140/// with the provided value map. The entire original loop must be present in
1141/// the value map. The cloned loop is returned.
1142static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1143 const ValueToValueMapTy &VMap, LoopInfo &LI) {
1144 auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1145 assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1146 ClonedL.reserveBlocks(OrigL.getNumBlocks());
1147 for (auto *BB : OrigL.blocks()) {
1148 auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1149 ClonedL.addBlockEntry(ClonedBB);
Chandler Carruth0ace1482018-04-24 03:27:00 +00001150 if (LI.getLoopFor(BB) == &OrigL)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001151 LI.changeLoopFor(ClonedBB, &ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001152 }
1153 };
1154
1155 // We specially handle the first loop because it may get cloned into
1156 // a different parent and because we most commonly are cloning leaf loops.
1157 Loop *ClonedRootL = LI.AllocateLoop();
1158 if (RootParentL)
1159 RootParentL->addChildLoop(ClonedRootL);
1160 else
1161 LI.addTopLevelLoop(ClonedRootL);
1162 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1163
1164 if (OrigRootL.empty())
1165 return ClonedRootL;
1166
1167 // If we have a nest, we can quickly clone the entire loop nest using an
1168 // iterative approach because it is a tree. We keep the cloned parent in the
1169 // data structure to avoid repeatedly querying through a map to find it.
1170 SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1171 // Build up the loops to clone in reverse order as we'll clone them from the
1172 // back.
1173 for (Loop *ChildL : llvm::reverse(OrigRootL))
1174 LoopsToClone.push_back({ClonedRootL, ChildL});
1175 do {
1176 Loop *ClonedParentL, *L;
1177 std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1178 Loop *ClonedL = LI.AllocateLoop();
1179 ClonedParentL->addChildLoop(ClonedL);
1180 AddClonedBlocksToLoop(*L, *ClonedL);
1181 for (Loop *ChildL : llvm::reverse(*L))
1182 LoopsToClone.push_back({ClonedL, ChildL});
1183 } while (!LoopsToClone.empty());
1184
1185 return ClonedRootL;
1186}
1187
1188/// Build the cloned loops of an original loop from unswitching.
1189///
1190/// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1191/// operation. We need to re-verify that there even is a loop (as the backedge
1192/// may not have been cloned), and even if there are remaining backedges the
1193/// backedge set may be different. However, we know that each child loop is
1194/// undisturbed, we only need to find where to place each child loop within
1195/// either any parent loop or within a cloned version of the original loop.
1196///
1197/// Because child loops may end up cloned outside of any cloned version of the
1198/// original loop, multiple cloned sibling loops may be created. All of them
1199/// are returned so that the newly introduced loop nest roots can be
1200/// identified.
Chandler Carruth92815032018-06-02 01:29:01 +00001201static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1202 const ValueToValueMapTy &VMap, LoopInfo &LI,
1203 SmallVectorImpl<Loop *> &NonChildClonedLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00001204 Loop *ClonedL = nullptr;
1205
1206 auto *OrigPH = OrigL.getLoopPreheader();
1207 auto *OrigHeader = OrigL.getHeader();
1208
1209 auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1210 auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1211
1212 // We need to know the loops of the cloned exit blocks to even compute the
1213 // accurate parent loop. If we only clone exits to some parent of the
1214 // original parent, we want to clone into that outer loop. We also keep track
1215 // of the loops that our cloned exit blocks participate in.
1216 Loop *ParentL = nullptr;
1217 SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1218 SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1219 ClonedExitsInLoops.reserve(ExitBlocks.size());
1220 for (auto *ExitBB : ExitBlocks)
1221 if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1222 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1223 ExitLoopMap[ClonedExitBB] = ExitL;
1224 ClonedExitsInLoops.push_back(ClonedExitBB);
1225 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1226 ParentL = ExitL;
1227 }
1228 assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1229 ParentL->contains(OrigL.getParentLoop())) &&
1230 "The computed parent loop should always contain (or be) the parent of "
1231 "the original loop.");
1232
1233 // We build the set of blocks dominated by the cloned header from the set of
1234 // cloned blocks out of the original loop. While not all of these will
1235 // necessarily be in the cloned loop, it is enough to establish that they
1236 // aren't in unreachable cycles, etc.
1237 SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1238 for (auto *BB : OrigL.blocks())
1239 if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1240 ClonedLoopBlocks.insert(ClonedBB);
1241
1242 // Rebuild the set of blocks that will end up in the cloned loop. We may have
1243 // skipped cloning some region of this loop which can in turn skip some of
1244 // the backedges so we have to rebuild the blocks in the loop based on the
1245 // backedges that remain after cloning.
1246 SmallVector<BasicBlock *, 16> Worklist;
1247 SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1248 for (auto *Pred : predecessors(ClonedHeader)) {
1249 // The only possible non-loop header predecessor is the preheader because
1250 // we know we cloned the loop in simplified form.
1251 if (Pred == ClonedPH)
1252 continue;
1253
1254 // Because the loop was in simplified form, the only non-loop predecessor
1255 // should be the preheader.
1256 assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1257 "header other than the preheader "
1258 "that is not part of the loop!");
1259
1260 // Insert this block into the loop set and on the first visit (and if it
1261 // isn't the header we're currently walking) put it into the worklist to
1262 // recurse through.
1263 if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1264 Worklist.push_back(Pred);
1265 }
1266
1267 // If we had any backedges then there *is* a cloned loop. Put the header into
1268 // the loop set and then walk the worklist backwards to find all the blocks
1269 // that remain within the loop after cloning.
1270 if (!BlocksInClonedLoop.empty()) {
1271 BlocksInClonedLoop.insert(ClonedHeader);
1272
1273 while (!Worklist.empty()) {
1274 BasicBlock *BB = Worklist.pop_back_val();
1275 assert(BlocksInClonedLoop.count(BB) &&
1276 "Didn't put block into the loop set!");
1277
1278 // Insert any predecessors that are in the possible set into the cloned
1279 // set, and if the insert is successful, add them to the worklist. Note
1280 // that we filter on the blocks that are definitely reachable via the
1281 // backedge to the loop header so we may prune out dead code within the
1282 // cloned loop.
1283 for (auto *Pred : predecessors(BB))
1284 if (ClonedLoopBlocks.count(Pred) &&
1285 BlocksInClonedLoop.insert(Pred).second)
1286 Worklist.push_back(Pred);
1287 }
1288
1289 ClonedL = LI.AllocateLoop();
1290 if (ParentL) {
1291 ParentL->addBasicBlockToLoop(ClonedPH, LI);
1292 ParentL->addChildLoop(ClonedL);
1293 } else {
1294 LI.addTopLevelLoop(ClonedL);
1295 }
Chandler Carruth92815032018-06-02 01:29:01 +00001296 NonChildClonedLoops.push_back(ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001297
1298 ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1299 // We don't want to just add the cloned loop blocks based on how we
1300 // discovered them. The original order of blocks was carefully built in
1301 // a way that doesn't rely on predecessor ordering. Rather than re-invent
1302 // that logic, we just re-walk the original blocks (and those of the child
1303 // loops) and filter them as we add them into the cloned loop.
1304 for (auto *BB : OrigL.blocks()) {
1305 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1306 if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1307 continue;
1308
1309 // Directly add the blocks that are only in this loop.
1310 if (LI.getLoopFor(BB) == &OrigL) {
1311 ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1312 continue;
1313 }
1314
1315 // We want to manually add it to this loop and parents.
1316 // Registering it with LoopInfo will happen when we clone the top
1317 // loop for this block.
1318 for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1319 PL->addBlockEntry(ClonedBB);
1320 }
1321
1322 // Now add each child loop whose header remains within the cloned loop. All
1323 // of the blocks within the loop must satisfy the same constraints as the
1324 // header so once we pass the header checks we can just clone the entire
1325 // child loop nest.
1326 for (Loop *ChildL : OrigL) {
1327 auto *ClonedChildHeader =
1328 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1329 if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1330 continue;
1331
1332#ifndef NDEBUG
1333 // We should never have a cloned child loop header but fail to have
1334 // all of the blocks for that child loop.
1335 for (auto *ChildLoopBB : ChildL->blocks())
1336 assert(BlocksInClonedLoop.count(
1337 cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1338 "Child cloned loop has a header within the cloned outer "
1339 "loop but not all of its blocks!");
1340#endif
1341
1342 cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1343 }
1344 }
1345
1346 // Now that we've handled all the components of the original loop that were
1347 // cloned into a new loop, we still need to handle anything from the original
1348 // loop that wasn't in a cloned loop.
1349
1350 // Figure out what blocks are left to place within any loop nest containing
1351 // the unswitched loop. If we never formed a loop, the cloned PH is one of
1352 // them.
1353 SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1354 if (BlocksInClonedLoop.empty())
1355 UnloopedBlockSet.insert(ClonedPH);
1356 for (auto *ClonedBB : ClonedLoopBlocks)
1357 if (!BlocksInClonedLoop.count(ClonedBB))
1358 UnloopedBlockSet.insert(ClonedBB);
1359
1360 // Copy the cloned exits and sort them in ascending loop depth, we'll work
1361 // backwards across these to process them inside out. The order shouldn't
1362 // matter as we're just trying to build up the map from inside-out; we use
1363 // the map in a more stably ordered way below.
1364 auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
Fangrui Song0cac7262018-09-27 02:13:45 +00001365 llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1366 return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1367 ExitLoopMap.lookup(RHS)->getLoopDepth();
1368 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001369
1370 // Populate the existing ExitLoopMap with everything reachable from each
1371 // exit, starting from the inner most exit.
1372 while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1373 assert(Worklist.empty() && "Didn't clear worklist!");
1374
1375 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1376 Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1377
1378 // Walk the CFG back until we hit the cloned PH adding everything reachable
1379 // and in the unlooped set to this exit block's loop.
1380 Worklist.push_back(ExitBB);
1381 do {
1382 BasicBlock *BB = Worklist.pop_back_val();
1383 // We can stop recursing at the cloned preheader (if we get there).
1384 if (BB == ClonedPH)
1385 continue;
1386
1387 for (BasicBlock *PredBB : predecessors(BB)) {
1388 // If this pred has already been moved to our set or is part of some
1389 // (inner) loop, no update needed.
1390 if (!UnloopedBlockSet.erase(PredBB)) {
1391 assert(
1392 (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1393 "Predecessor not mapped to a loop!");
1394 continue;
1395 }
1396
1397 // We just insert into the loop set here. We'll add these blocks to the
1398 // exit loop after we build up the set in an order that doesn't rely on
1399 // predecessor order (which in turn relies on use list order).
1400 bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1401 (void)Inserted;
1402 assert(Inserted && "Should only visit an unlooped block once!");
1403
1404 // And recurse through to its predecessors.
1405 Worklist.push_back(PredBB);
1406 }
1407 } while (!Worklist.empty());
1408 }
1409
1410 // Now that the ExitLoopMap gives as mapping for all the non-looping cloned
1411 // blocks to their outer loops, walk the cloned blocks and the cloned exits
1412 // in their original order adding them to the correct loop.
1413
1414 // We need a stable insertion order. We use the order of the original loop
1415 // order and map into the correct parent loop.
1416 for (auto *BB : llvm::concat<BasicBlock *const>(
1417 makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1418 if (Loop *OuterL = ExitLoopMap.lookup(BB))
1419 OuterL->addBasicBlockToLoop(BB, LI);
1420
1421#ifndef NDEBUG
1422 for (auto &BBAndL : ExitLoopMap) {
1423 auto *BB = BBAndL.first;
1424 auto *OuterL = BBAndL.second;
1425 assert(LI.getLoopFor(BB) == OuterL &&
1426 "Failed to put all blocks into outer loops!");
1427 }
1428#endif
1429
1430 // Now that all the blocks are placed into the correct containing loop in the
1431 // absence of child loops, find all the potentially cloned child loops and
1432 // clone them into whatever outer loop we placed their header into.
1433 for (Loop *ChildL : OrigL) {
1434 auto *ClonedChildHeader =
1435 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1436 if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1437 continue;
1438
1439#ifndef NDEBUG
1440 for (auto *ChildLoopBB : ChildL->blocks())
1441 assert(VMap.count(ChildLoopBB) &&
1442 "Cloned a child loop header but not all of that loops blocks!");
1443#endif
1444
1445 NonChildClonedLoops.push_back(cloneLoopNest(
1446 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1447 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001448}
1449
Chandler Carruth69e68f82018-04-25 00:18:07 +00001450static void
Chandler Carruth16529962018-06-25 23:32:54 +00001451deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1452 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001453 DominatorTree &DT, MemorySSAUpdater *MSSAU) {
Chandler Carruth16529962018-06-25 23:32:54 +00001454 // Find all the dead clones, and remove them from their successors.
1455 SmallVector<BasicBlock *, 16> DeadBlocks;
1456 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1457 for (auto &VMap : VMaps)
1458 if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1459 if (!DT.isReachableFromEntry(ClonedBB)) {
1460 for (BasicBlock *SuccBB : successors(ClonedBB))
1461 SuccBB->removePredecessor(ClonedBB);
1462 DeadBlocks.push_back(ClonedBB);
1463 }
1464
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001465 // Remove all MemorySSA in the dead blocks
1466 if (MSSAU) {
Alina Sbirleadb101862019-07-12 22:30:30 +00001467 SmallSetVector<BasicBlock *, 8> DeadBlockSet(DeadBlocks.begin(),
1468 DeadBlocks.end());
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001469 MSSAU->removeBlocks(DeadBlockSet);
1470 }
1471
Chandler Carruth16529962018-06-25 23:32:54 +00001472 // Drop any remaining references to break cycles.
1473 for (BasicBlock *BB : DeadBlocks)
1474 BB->dropAllReferences();
1475 // Erase them from the IR.
1476 for (BasicBlock *BB : DeadBlocks)
1477 BB->eraseFromParent();
1478}
1479
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001480static void deleteDeadBlocksFromLoop(Loop &L,
1481 SmallVectorImpl<BasicBlock *> &ExitBlocks,
1482 DominatorTree &DT, LoopInfo &LI,
1483 MemorySSAUpdater *MSSAU) {
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001484 // Find all the dead blocks tied to this loop, and remove them from their
1485 // successors.
Alina Sbirleadb101862019-07-12 22:30:30 +00001486 SmallSetVector<BasicBlock *, 8> DeadBlockSet;
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001487
1488 // Start with loop/exit blocks and get a transitive closure of reachable dead
1489 // blocks.
1490 SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
1491 ExitBlocks.end());
1492 DeathCandidates.append(L.blocks().begin(), L.blocks().end());
1493 while (!DeathCandidates.empty()) {
1494 auto *BB = DeathCandidates.pop_back_val();
1495 if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
1496 for (BasicBlock *SuccBB : successors(BB)) {
Chandler Carruth16529962018-06-25 23:32:54 +00001497 SuccBB->removePredecessor(BB);
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001498 DeathCandidates.push_back(SuccBB);
Fedor Sergeev7b49aa02018-08-29 19:10:44 +00001499 }
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001500 DeadBlockSet.insert(BB);
1501 }
1502 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001503
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001504 // Remove all MemorySSA in the dead blocks
1505 if (MSSAU)
1506 MSSAU->removeBlocks(DeadBlockSet);
1507
Chandler Carruth693eedb2017-11-17 19:58:36 +00001508 // Filter out the dead blocks from the exit blocks list so that it can be
1509 // used in the caller.
1510 llvm::erase_if(ExitBlocks,
Chandler Carruth69e68f82018-04-25 00:18:07 +00001511 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001512
Chandler Carruth693eedb2017-11-17 19:58:36 +00001513 // Walk from this loop up through its parents removing all of the dead blocks.
1514 for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001515 for (auto *BB : DeadBlockSet)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001516 ParentL->getBlocksSet().erase(BB);
1517 llvm::erase_if(ParentL->getBlocksVector(),
Chandler Carruth69e68f82018-04-25 00:18:07 +00001518 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001519 }
1520
1521 // Now delete the dead child loops. This raw delete will clear them
1522 // recursively.
1523 llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001524 if (!DeadBlockSet.count(ChildL->getHeader()))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001525 return false;
1526
1527 assert(llvm::all_of(ChildL->blocks(),
1528 [&](BasicBlock *ChildBB) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001529 return DeadBlockSet.count(ChildBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001530 }) &&
1531 "If the child loop header is dead all blocks in the child loop must "
1532 "be dead as well!");
1533 LI.destroy(ChildL);
1534 return true;
1535 });
1536
Chandler Carruth69e68f82018-04-25 00:18:07 +00001537 // Remove the loop mappings for the dead blocks and drop all the references
1538 // from these blocks to others to handle cyclic references as we start
1539 // deleting the blocks themselves.
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001540 for (auto *BB : DeadBlockSet) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001541 // Check that the dominator tree has already been updated.
1542 assert(!DT.getNode(BB) && "Should already have cleared domtree!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001543 LI.changeLoopFor(BB, nullptr);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001544 BB->dropAllReferences();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001545 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001546
1547 // Actually delete the blocks now that they've been fully unhooked from the
1548 // IR.
Fedor Sergeev7b49aa02018-08-29 19:10:44 +00001549 for (auto *BB : DeadBlockSet)
Chandler Carruth69e68f82018-04-25 00:18:07 +00001550 BB->eraseFromParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001551}
1552
1553/// Recompute the set of blocks in a loop after unswitching.
1554///
1555/// This walks from the original headers predecessors to rebuild the loop. We
1556/// take advantage of the fact that new blocks can't have been added, and so we
1557/// filter by the original loop's blocks. This also handles potentially
1558/// unreachable code that we don't want to explore but might be found examining
1559/// the predecessors of the header.
1560///
1561/// If the original loop is no longer a loop, this will return an empty set. If
1562/// it remains a loop, all the blocks within it will be added to the set
1563/// (including those blocks in inner loops).
1564static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1565 LoopInfo &LI) {
1566 SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1567
1568 auto *PH = L.getLoopPreheader();
1569 auto *Header = L.getHeader();
1570
1571 // A worklist to use while walking backwards from the header.
1572 SmallVector<BasicBlock *, 16> Worklist;
1573
1574 // First walk the predecessors of the header to find the backedges. This will
1575 // form the basis of our walk.
1576 for (auto *Pred : predecessors(Header)) {
1577 // Skip the preheader.
1578 if (Pred == PH)
1579 continue;
1580
1581 // Because the loop was in simplified form, the only non-loop predecessor
1582 // is the preheader.
1583 assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1584 "than the preheader that is not part of the "
1585 "loop!");
1586
1587 // Insert this block into the loop set and on the first visit and, if it
1588 // isn't the header we're currently walking, put it into the worklist to
1589 // recurse through.
1590 if (LoopBlockSet.insert(Pred).second && Pred != Header)
1591 Worklist.push_back(Pred);
1592 }
1593
1594 // If no backedges were found, we're done.
1595 if (LoopBlockSet.empty())
1596 return LoopBlockSet;
1597
Chandler Carruth693eedb2017-11-17 19:58:36 +00001598 // We found backedges, recurse through them to identify the loop blocks.
1599 while (!Worklist.empty()) {
1600 BasicBlock *BB = Worklist.pop_back_val();
1601 assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1602
Chandler Carruth43acdb32018-04-24 10:33:08 +00001603 // No need to walk past the header.
1604 if (BB == Header)
1605 continue;
1606
Chandler Carruth693eedb2017-11-17 19:58:36 +00001607 // Because we know the inner loop structure remains valid we can use the
1608 // loop structure to jump immediately across the entire nested loop.
1609 // Further, because it is in loop simplified form, we can directly jump
1610 // to its preheader afterward.
1611 if (Loop *InnerL = LI.getLoopFor(BB))
1612 if (InnerL != &L) {
1613 assert(L.contains(InnerL) &&
1614 "Should not reach a loop *outside* this loop!");
1615 // The preheader is the only possible predecessor of the loop so
1616 // insert it into the set and check whether it was already handled.
1617 auto *InnerPH = InnerL->getLoopPreheader();
1618 assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1619 "but not contain the inner loop "
1620 "preheader!");
1621 if (!LoopBlockSet.insert(InnerPH).second)
1622 // The only way to reach the preheader is through the loop body
1623 // itself so if it has been visited the loop is already handled.
1624 continue;
1625
1626 // Insert all of the blocks (other than those already present) into
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001627 // the loop set. We expect at least the block that led us to find the
1628 // inner loop to be in the block set, but we may also have other loop
1629 // blocks if they were already enqueued as predecessors of some other
1630 // outer loop block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00001631 for (auto *InnerBB : InnerL->blocks()) {
1632 if (InnerBB == BB) {
1633 assert(LoopBlockSet.count(InnerBB) &&
1634 "Block should already be in the set!");
1635 continue;
1636 }
1637
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001638 LoopBlockSet.insert(InnerBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001639 }
1640
1641 // Add the preheader to the worklist so we will continue past the
1642 // loop body.
1643 Worklist.push_back(InnerPH);
1644 continue;
1645 }
1646
1647 // Insert any predecessors that were in the original loop into the new
1648 // set, and if the insert is successful, add them to the worklist.
1649 for (auto *Pred : predecessors(BB))
1650 if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1651 Worklist.push_back(Pred);
1652 }
1653
Chandler Carruth43acdb32018-04-24 10:33:08 +00001654 assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1655
Chandler Carruth693eedb2017-11-17 19:58:36 +00001656 // We've found all the blocks participating in the loop, return our completed
1657 // set.
1658 return LoopBlockSet;
1659}
1660
1661/// Rebuild a loop after unswitching removes some subset of blocks and edges.
1662///
1663/// The removal may have removed some child loops entirely but cannot have
1664/// disturbed any remaining child loops. However, they may need to be hoisted
1665/// to the parent loop (or to be top-level loops). The original loop may be
1666/// completely removed.
1667///
1668/// The sibling loops resulting from this update are returned. If the original
1669/// loop remains a valid loop, it will be the first entry in this list with all
1670/// of the newly sibling loops following it.
1671///
1672/// Returns true if the loop remains a loop after unswitching, and false if it
1673/// is no longer a loop after unswitching (and should not continue to be
1674/// referenced).
1675static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1676 LoopInfo &LI,
1677 SmallVectorImpl<Loop *> &HoistedLoops) {
1678 auto *PH = L.getLoopPreheader();
1679
1680 // Compute the actual parent loop from the exit blocks. Because we may have
1681 // pruned some exits the loop may be different from the original parent.
1682 Loop *ParentL = nullptr;
1683 SmallVector<Loop *, 4> ExitLoops;
1684 SmallVector<BasicBlock *, 4> ExitsInLoops;
1685 ExitsInLoops.reserve(ExitBlocks.size());
1686 for (auto *ExitBB : ExitBlocks)
1687 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1688 ExitLoops.push_back(ExitL);
1689 ExitsInLoops.push_back(ExitBB);
1690 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1691 ParentL = ExitL;
1692 }
1693
1694 // Recompute the blocks participating in this loop. This may be empty if it
1695 // is no longer a loop.
1696 auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1697
1698 // If we still have a loop, we need to re-set the loop's parent as the exit
1699 // block set changing may have moved it within the loop nest. Note that this
1700 // can only happen when this loop has a parent as it can only hoist the loop
1701 // *up* the nest.
1702 if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1703 // Remove this loop's (original) blocks from all of the intervening loops.
1704 for (Loop *IL = L.getParentLoop(); IL != ParentL;
1705 IL = IL->getParentLoop()) {
1706 IL->getBlocksSet().erase(PH);
1707 for (auto *BB : L.blocks())
1708 IL->getBlocksSet().erase(BB);
1709 llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1710 return BB == PH || L.contains(BB);
1711 });
1712 }
1713
1714 LI.changeLoopFor(PH, ParentL);
1715 L.getParentLoop()->removeChildLoop(&L);
1716 if (ParentL)
1717 ParentL->addChildLoop(&L);
1718 else
1719 LI.addTopLevelLoop(&L);
1720 }
1721
1722 // Now we update all the blocks which are no longer within the loop.
1723 auto &Blocks = L.getBlocksVector();
1724 auto BlocksSplitI =
1725 LoopBlockSet.empty()
1726 ? Blocks.begin()
1727 : std::stable_partition(
1728 Blocks.begin(), Blocks.end(),
1729 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1730
1731 // Before we erase the list of unlooped blocks, build a set of them.
1732 SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1733 if (LoopBlockSet.empty())
1734 UnloopedBlocks.insert(PH);
1735
1736 // Now erase these blocks from the loop.
1737 for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1738 L.getBlocksSet().erase(BB);
1739 Blocks.erase(BlocksSplitI, Blocks.end());
1740
1741 // Sort the exits in ascending loop depth, we'll work backwards across these
1742 // to process them inside out.
Fangrui Songefd94c52019-04-23 14:51:27 +00001743 llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1744 return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1745 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001746
1747 // We'll build up a set for each exit loop.
1748 SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1749 Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1750
1751 auto RemoveUnloopedBlocksFromLoop =
1752 [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1753 for (auto *BB : UnloopedBlocks)
1754 L.getBlocksSet().erase(BB);
1755 llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1756 return UnloopedBlocks.count(BB);
1757 });
1758 };
1759
1760 SmallVector<BasicBlock *, 16> Worklist;
1761 while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1762 assert(Worklist.empty() && "Didn't clear worklist!");
1763 assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1764
1765 // Grab the next exit block, in decreasing loop depth order.
1766 BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1767 Loop &ExitL = *LI.getLoopFor(ExitBB);
1768 assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1769
1770 // Erase all of the unlooped blocks from the loops between the previous
1771 // exit loop and this exit loop. This works because the ExitInLoops list is
1772 // sorted in increasing order of loop depth and thus we visit loops in
1773 // decreasing order of loop depth.
1774 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1775 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1776
1777 // Walk the CFG back until we hit the cloned PH adding everything reachable
1778 // and in the unlooped set to this exit block's loop.
1779 Worklist.push_back(ExitBB);
1780 do {
1781 BasicBlock *BB = Worklist.pop_back_val();
1782 // We can stop recursing at the cloned preheader (if we get there).
1783 if (BB == PH)
1784 continue;
1785
1786 for (BasicBlock *PredBB : predecessors(BB)) {
1787 // If this pred has already been moved to our set or is part of some
1788 // (inner) loop, no update needed.
1789 if (!UnloopedBlocks.erase(PredBB)) {
1790 assert((NewExitLoopBlocks.count(PredBB) ||
1791 ExitL.contains(LI.getLoopFor(PredBB))) &&
1792 "Predecessor not in a nested loop (or already visited)!");
1793 continue;
1794 }
1795
1796 // We just insert into the loop set here. We'll add these blocks to the
1797 // exit loop after we build up the set in a deterministic order rather
1798 // than the predecessor-influenced visit order.
1799 bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1800 (void)Inserted;
1801 assert(Inserted && "Should only visit an unlooped block once!");
1802
1803 // And recurse through to its predecessors.
1804 Worklist.push_back(PredBB);
1805 }
1806 } while (!Worklist.empty());
1807
1808 // If blocks in this exit loop were directly part of the original loop (as
1809 // opposed to a child loop) update the map to point to this exit loop. This
1810 // just updates a map and so the fact that the order is unstable is fine.
1811 for (auto *BB : NewExitLoopBlocks)
1812 if (Loop *BBL = LI.getLoopFor(BB))
1813 if (BBL == &L || !L.contains(BBL))
1814 LI.changeLoopFor(BB, &ExitL);
1815
1816 // We will remove the remaining unlooped blocks from this loop in the next
1817 // iteration or below.
1818 NewExitLoopBlocks.clear();
1819 }
1820
1821 // Any remaining unlooped blocks are no longer part of any loop unless they
1822 // are part of some child loop.
1823 for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1824 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1825 for (auto *BB : UnloopedBlocks)
1826 if (Loop *BBL = LI.getLoopFor(BB))
1827 if (BBL == &L || !L.contains(BBL))
1828 LI.changeLoopFor(BB, nullptr);
1829
1830 // Sink all the child loops whose headers are no longer in the loop set to
1831 // the parent (or to be top level loops). We reach into the loop and directly
1832 // update its subloop vector to make this batch update efficient.
1833 auto &SubLoops = L.getSubLoopsVector();
1834 auto SubLoopsSplitI =
1835 LoopBlockSet.empty()
1836 ? SubLoops.begin()
1837 : std::stable_partition(
1838 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1839 return LoopBlockSet.count(SubL->getHeader());
1840 });
1841 for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1842 HoistedLoops.push_back(HoistedL);
1843 HoistedL->setParentLoop(nullptr);
1844
1845 // To compute the new parent of this hoisted loop we look at where we
1846 // placed the preheader above. We can't lookup the header itself because we
1847 // retained the mapping from the header to the hoisted loop. But the
1848 // preheader and header should have the exact same new parent computed
1849 // based on the set of exit blocks from the original loop as the preheader
1850 // is a predecessor of the header and so reached in the reverse walk. And
1851 // because the loops were all in simplified form the preheader of the
1852 // hoisted loop can't be part of some *other* loop.
1853 if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1854 NewParentL->addChildLoop(HoistedL);
1855 else
1856 LI.addTopLevelLoop(HoistedL);
1857 }
1858 SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1859
1860 // Actually delete the loop if nothing remained within it.
1861 if (Blocks.empty()) {
1862 assert(SubLoops.empty() &&
1863 "Failed to remove all subloops from the original loop!");
1864 if (Loop *ParentL = L.getParentLoop())
1865 ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1866 else
1867 LI.removeLoop(llvm::find(LI, &L));
1868 LI.destroy(&L);
1869 return false;
1870 }
1871
1872 return true;
1873}
1874
1875/// Helper to visit a dominator subtree, invoking a callable on each node.
1876///
1877/// Returning false at any point will stop walking past that node of the tree.
1878template <typename CallableT>
1879void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1880 SmallVector<DomTreeNode *, 4> DomWorklist;
1881 DomWorklist.push_back(DT[BB]);
1882#ifndef NDEBUG
1883 SmallPtrSet<DomTreeNode *, 4> Visited;
1884 Visited.insert(DT[BB]);
1885#endif
1886 do {
1887 DomTreeNode *N = DomWorklist.pop_back_val();
1888
1889 // Visit this node.
1890 if (!Callable(N->getBlock()))
1891 continue;
1892
1893 // Accumulate the child nodes.
1894 for (DomTreeNode *ChildN : *N) {
1895 assert(Visited.insert(ChildN).second &&
1896 "Cannot visit a node twice when walking a tree!");
1897 DomWorklist.push_back(ChildN);
1898 }
1899 } while (!DomWorklist.empty());
1900}
1901
Max Kazantsevbde31002018-10-26 09:52:58 +00001902static void unswitchNontrivialInvariants(
Chandler Carruth60b2e052018-10-18 00:40:26 +00001903 Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
Max Kazantsevbde31002018-10-26 09:52:58 +00001904 SmallVectorImpl<BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI,
1905 AssumptionCache &AC, function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001906 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruth16529962018-06-25 23:32:54 +00001907 auto *ParentBB = TI.getParent();
1908 BranchInst *BI = dyn_cast<BranchInst>(&TI);
1909 SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001910
Chandler Carruth16529962018-06-25 23:32:54 +00001911 // We can only unswitch switches, conditional branches with an invariant
1912 // condition, or combining invariant conditions with an instruction.
Simon Pilgrimc598ef72019-10-16 10:38:18 +00001913 assert((SI || (BI && BI->isConditional())) &&
Chandler Carruth16529962018-06-25 23:32:54 +00001914 "Can only unswitch switches and conditional branch!");
1915 bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001916 if (FullUnswitch)
1917 assert(Invariants.size() == 1 &&
1918 "Cannot have other invariants with full unswitching!");
1919 else
Chandler Carruth16529962018-06-25 23:32:54 +00001920 assert(isa<Instruction>(BI->getCondition()) &&
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001921 "Partial unswitching requires an instruction as the condition!");
1922
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001923 if (MSSAU && VerifyMemorySSA)
1924 MSSAU->getMemorySSA()->verifyMemorySSA();
1925
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001926 // Constant and BBs tracking the cloned and continuing successor. When we are
1927 // unswitching the entire condition, this can just be trivially chosen to
1928 // unswitch towards `true`. However, when we are unswitching a set of
1929 // invariants combined with `and` or `or`, the combining operation determines
1930 // the best direction to unswitch: we want to unswitch the direction that will
1931 // collapse the branch.
1932 bool Direction = true;
1933 int ClonedSucc = 0;
1934 if (!FullUnswitch) {
Chandler Carruth16529962018-06-25 23:32:54 +00001935 if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1936 assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1937 Instruction::And &&
1938 "Only `or` and `and` instructions can combine invariants being "
1939 "unswitched.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001940 Direction = false;
1941 ClonedSucc = 1;
1942 }
1943 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001944
Chandler Carruth16529962018-06-25 23:32:54 +00001945 BasicBlock *RetainedSuccBB =
1946 BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1947 SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1948 if (BI)
1949 UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1950 else
1951 for (auto Case : SI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00001952 if (Case.getCaseSuccessor() != RetainedSuccBB)
1953 UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
Chandler Carruth16529962018-06-25 23:32:54 +00001954
1955 assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1956 "Should not unswitch the same successor we are retaining!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001957
1958 // The branch should be in this exact loop. Any inner loop's invariant branch
1959 // should be handled by unswitching that inner loop. The caller of this
1960 // routine should filter out any candidates that remain (but were skipped for
1961 // whatever reason).
1962 assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1963
Chandler Carruth693eedb2017-11-17 19:58:36 +00001964 // Compute the parent loop now before we start hacking on things.
1965 Loop *ParentL = L.getParentLoop();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001966 // Get blocks in RPO order for MSSA update, before changing the CFG.
1967 LoopBlocksRPO LBRPO(&L);
1968 if (MSSAU)
1969 LBRPO.perform(&LI);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001970
1971 // Compute the outer-most loop containing one of our exit blocks. This is the
1972 // furthest up our loopnest which can be mutated, which we will use below to
1973 // update things.
1974 Loop *OuterExitL = &L;
1975 for (auto *ExitBB : ExitBlocks) {
1976 Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1977 if (!NewOuterExitL) {
1978 // We exited the entire nest with this block, so we're done.
1979 OuterExitL = nullptr;
1980 break;
1981 }
1982 if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1983 OuterExitL = NewOuterExitL;
1984 }
1985
Chandler Carruth3897ded2018-07-03 09:13:27 +00001986 // At this point, we're definitely going to unswitch something so invalidate
1987 // any cached information in ScalarEvolution for the outer most loop
1988 // containing an exit block and all nested loops.
1989 if (SE) {
1990 if (OuterExitL)
1991 SE->forgetLoop(OuterExitL);
1992 else
1993 SE->forgetTopmostLoop(&L);
1994 }
1995
Chandler Carruth16529962018-06-25 23:32:54 +00001996 // If the edge from this terminator to a successor dominates that successor,
1997 // store a map from each block in its dominator subtree to it. This lets us
1998 // tell when cloning for a particular successor if a block is dominated by
1999 // some *other* successor with a single data structure. We use this to
2000 // significantly reduce cloning.
2001 SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
2002 for (auto *SuccBB : llvm::concat<BasicBlock *const>(
2003 makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
2004 if (SuccBB->getUniquePredecessor() ||
2005 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2006 return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
2007 }))
2008 visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
2009 DominatingSucc[BB] = SuccBB;
2010 return true;
2011 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00002012
2013 // Split the preheader, so that we know that there is a safe place to insert
2014 // the conditional branch. We will change the preheader to have a conditional
2015 // branch on LoopCond. The original preheader will become the split point
2016 // between the unswitched versions, and we will have a new preheader for the
2017 // original loop.
2018 BasicBlock *SplitBB = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002019 BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002020
Chandler Carruth69e68f82018-04-25 00:18:07 +00002021 // Keep track of the dominator tree updates needed.
2022 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2023
Chandler Carruth16529962018-06-25 23:32:54 +00002024 // Clone the loop for each unswitched successor.
2025 SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
2026 VMaps.reserve(UnswitchedSuccBBs.size());
2027 SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
2028 for (auto *SuccBB : UnswitchedSuccBBs) {
2029 VMaps.emplace_back(new ValueToValueMapTy());
2030 ClonedPHs[SuccBB] = buildClonedLoopBlocks(
2031 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002032 DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
Chandler Carruth16529962018-06-25 23:32:54 +00002033 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002034
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002035 // The stitching of the branched code back together depends on whether we're
2036 // doing full unswitching or not with the exception that we always want to
2037 // nuke the initial terminator placed in the split block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002038 SplitBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002039 if (FullUnswitch) {
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002040 // Splice the terminator from the original loop and rewrite its
2041 // successors.
2042 SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2043
2044 // Keep a clone of the terminator for MSSA updates.
2045 Instruction *NewTI = TI.clone();
2046 ParentBB->getInstList().push_back(NewTI);
2047
2048 // First wire up the moved terminator to the preheaders.
2049 if (BI) {
2050 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2051 BI->setSuccessor(ClonedSucc, ClonedPH);
2052 BI->setSuccessor(1 - ClonedSucc, LoopPH);
2053 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2054 } else {
2055 assert(SI && "Must either be a branch or switch!");
2056
2057 // Walk the cases and directly update their successors.
2058 assert(SI->getDefaultDest() == RetainedSuccBB &&
2059 "Not retaining default successor!");
2060 SI->setDefaultDest(LoopPH);
2061 for (auto &Case : SI->cases())
2062 if (Case.getCaseSuccessor() == RetainedSuccBB)
2063 Case.setSuccessor(LoopPH);
2064 else
2065 Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2066
2067 // We need to use the set to populate domtree updates as even when there
2068 // are multiple cases pointing at the same successor we only want to
2069 // remove and insert one edge in the domtree.
2070 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2071 DTUpdates.push_back(
2072 {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2073 }
2074
2075 if (MSSAU) {
2076 DT.applyUpdates(DTUpdates);
2077 DTUpdates.clear();
2078
2079 // Remove all but one edge to the retained block and all unswitched
2080 // blocks. This is to avoid having duplicate entries in the cloned Phis,
2081 // when we know we only keep a single edge for each case.
2082 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2083 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2084 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2085
2086 for (auto &VMap : VMaps)
2087 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2088 /*IgnoreIncomingWithNoClones=*/true);
2089 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2090
2091 // Remove all edges to unswitched blocks.
2092 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2093 MSSAU->removeEdge(ParentBB, SuccBB);
2094 }
2095
2096 // Now unhook the successor relationship as we'll be replacing
Chandler Carruthed296542018-07-09 10:30:48 +00002097 // the terminator with a direct branch. This is much simpler for branches
2098 // than switches so we handle those first.
Chandler Carruth16529962018-06-25 23:32:54 +00002099 if (BI) {
Chandler Carruthed296542018-07-09 10:30:48 +00002100 // Remove the parent as a predecessor of the unswitched successor.
Chandler Carruth16529962018-06-25 23:32:54 +00002101 assert(UnswitchedSuccBBs.size() == 1 &&
2102 "Only one possible unswitched block for a branch!");
Chandler Carruthed296542018-07-09 10:30:48 +00002103 BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2104 UnswitchedSuccBB->removePredecessor(ParentBB,
Max Kazantsev20b91892019-02-12 07:09:29 +00002105 /*KeepOneInputPHIs*/ true);
Chandler Carruthed296542018-07-09 10:30:48 +00002106 DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2107 } else {
2108 // Note that we actually want to remove the parent block as a predecessor
2109 // of *every* case successor. The case successor is either unswitched,
2110 // completely eliminating an edge from the parent to that successor, or it
2111 // is a duplicate edge to the retained successor as the retained successor
2112 // is always the default successor and as we'll replace this with a direct
2113 // branch we no longer need the duplicate entries in the PHI nodes.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002114 SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2115 assert(NewSI->getDefaultDest() == RetainedSuccBB &&
Chandler Carruthed296542018-07-09 10:30:48 +00002116 "Not retaining default successor!");
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002117 for (auto &Case : NewSI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00002118 Case.getCaseSuccessor()->removePredecessor(
2119 ParentBB,
Max Kazantsev20b91892019-02-12 07:09:29 +00002120 /*KeepOneInputPHIs*/ true);
Chandler Carruthed296542018-07-09 10:30:48 +00002121
2122 // We need to use the set to populate domtree updates as even when there
2123 // are multiple cases pointing at the same successor we only want to
2124 // remove and insert one edge in the domtree.
2125 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2126 DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
2127 }
2128
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002129 // After MSSAU update, remove the cloned terminator instruction NewTI.
2130 ParentBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002131
2132 // Create a new unconditional branch to the continuing block (as opposed to
2133 // the one cloned).
Chandler Carruth16529962018-06-25 23:32:54 +00002134 BranchInst::Create(RetainedSuccBB, ParentBB);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002135 } else {
Chandler Carruth16529962018-06-25 23:32:54 +00002136 assert(BI && "Only branches have partial unswitching.");
2137 assert(UnswitchedSuccBBs.size() == 1 &&
2138 "Only one possible unswitched block for a branch!");
2139 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002140 // When doing a partial unswitch, we have to do a bit more work to build up
2141 // the branch in the split block.
2142 buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
2143 *ClonedPH, *LoopPH);
Alina Sbirlea35c8af12019-10-15 17:15:19 +00002144 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2145
Alina Sbirleab7a33532019-10-14 23:52:39 +00002146 if (MSSAU) {
Alina Sbirlea35c8af12019-10-15 17:15:19 +00002147 DT.applyUpdates(DTUpdates);
2148 DTUpdates.clear();
2149
Alina Sbirleab7a33532019-10-14 23:52:39 +00002150 // Perform MSSA cloning updates.
2151 for (auto &VMap : VMaps)
2152 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2153 /*IgnoreIncomingWithNoClones=*/true);
2154 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2155 }
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002156 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002157
Chandler Carruth16529962018-06-25 23:32:54 +00002158 // Apply the updates accumulated above to get an up-to-date dominator tree.
Chandler Carruth69e68f82018-04-25 00:18:07 +00002159 DT.applyUpdates(DTUpdates);
2160
Chandler Carruth16529962018-06-25 23:32:54 +00002161 // Now that we have an accurate dominator tree, first delete the dead cloned
2162 // blocks so that we can accurately build any cloned loops. It is important to
2163 // not delete the blocks from the original loop yet because we still want to
2164 // reference the original loop to understand the cloned loop's structure.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002165 deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
Chandler Carruth16529962018-06-25 23:32:54 +00002166
Chandler Carruth69e68f82018-04-25 00:18:07 +00002167 // Build the cloned loop structure itself. This may be substantially
2168 // different from the original structure due to the simplified CFG. This also
2169 // handles inserting all the cloned blocks into the correct loops.
2170 SmallVector<Loop *, 4> NonChildClonedLoops;
Chandler Carruth16529962018-06-25 23:32:54 +00002171 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2172 buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
Chandler Carruth69e68f82018-04-25 00:18:07 +00002173
Chandler Carruth16529962018-06-25 23:32:54 +00002174 // Now that our cloned loops have been built, we can update the original loop.
2175 // First we delete the dead blocks from it and then we rebuild the loop
2176 // structure taking these deletions into account.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002177 deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU);
2178
2179 if (MSSAU && VerifyMemorySSA)
2180 MSSAU->getMemorySSA()->verifyMemorySSA();
2181
Chandler Carruth693eedb2017-11-17 19:58:36 +00002182 SmallVector<Loop *, 4> HoistedLoops;
2183 bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2184
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002185 if (MSSAU && VerifyMemorySSA)
2186 MSSAU->getMemorySSA()->verifyMemorySSA();
2187
Chandler Carruth69e68f82018-04-25 00:18:07 +00002188 // This transformation has a high risk of corrupting the dominator tree, and
2189 // the below steps to rebuild loop structures will result in hard to debug
2190 // errors in that case so verify that the dominator tree is sane first.
2191 // FIXME: Remove this when the bugs stop showing up and rely on existing
2192 // verification steps.
2193 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth693eedb2017-11-17 19:58:36 +00002194
Chandler Carruth16529962018-06-25 23:32:54 +00002195 if (BI) {
2196 // If we unswitched a branch which collapses the condition to a known
2197 // constant we want to replace all the uses of the invariants within both
2198 // the original and cloned blocks. We do this here so that we can use the
2199 // now updated dominator tree to identify which side the users are on.
2200 assert(UnswitchedSuccBBs.size() == 1 &&
2201 "Only one possible unswitched block for a branch!");
2202 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Fedor Sergeevf9a02a72018-11-07 20:05:11 +00002203
2204 // When considering multiple partially-unswitched invariants
2205 // we cant just go replace them with constants in both branches.
2206 //
2207 // For 'AND' we infer that true branch ("continue") means true
2208 // for each invariant operand.
2209 // For 'OR' we can infer that false branch ("continue") means false
2210 // for each invariant operand.
2211 // So it happens that for multiple-partial case we dont replace
2212 // in the unswitched branch.
2213 bool ReplaceUnswitched = FullUnswitch || (Invariants.size() == 1);
2214
Chandler Carruth16529962018-06-25 23:32:54 +00002215 ConstantInt *UnswitchedReplacement =
2216 Direction ? ConstantInt::getTrue(BI->getContext())
2217 : ConstantInt::getFalse(BI->getContext());
2218 ConstantInt *ContinueReplacement =
2219 Direction ? ConstantInt::getFalse(BI->getContext())
2220 : ConstantInt::getTrue(BI->getContext());
2221 for (Value *Invariant : Invariants)
2222 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2223 UI != UE;) {
2224 // Grab the use and walk past it so we can clobber it in the use list.
2225 Use *U = &*UI++;
2226 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2227 if (!UserI)
2228 continue;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002229
Chandler Carruth16529962018-06-25 23:32:54 +00002230 // Replace it with the 'continue' side if in the main loop body, and the
2231 // unswitched if in the cloned blocks.
2232 if (DT.dominates(LoopPH, UserI->getParent()))
2233 U->set(ContinueReplacement);
Fedor Sergeevf9a02a72018-11-07 20:05:11 +00002234 else if (ReplaceUnswitched &&
2235 DT.dominates(ClonedPH, UserI->getParent()))
Chandler Carruth16529962018-06-25 23:32:54 +00002236 U->set(UnswitchedReplacement);
2237 }
2238 }
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002239
Chandler Carruth693eedb2017-11-17 19:58:36 +00002240 // We can change which blocks are exit blocks of all the cloned sibling
2241 // loops, the current loop, and any parent loops which shared exit blocks
2242 // with the current loop. As a consequence, we need to re-form LCSSA for
2243 // them. But we shouldn't need to re-form LCSSA for any child loops.
2244 // FIXME: This could be made more efficient by tracking which exit blocks are
2245 // new, and focusing on them, but that isn't likely to be necessary.
2246 //
2247 // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2248 // loop nest and update every loop that could have had its exits changed. We
2249 // also need to cover any intervening loops. We add all of these loops to
2250 // a list and sort them by loop depth to achieve this without updating
2251 // unnecessary loops.
Chandler Carruth92815032018-06-02 01:29:01 +00002252 auto UpdateLoop = [&](Loop &UpdateL) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002253#ifndef NDEBUG
Chandler Carruth43acdb32018-04-24 10:33:08 +00002254 UpdateL.verifyLoop();
2255 for (Loop *ChildL : UpdateL) {
2256 ChildL->verifyLoop();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002257 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2258 "Perturbed a child loop's LCSSA form!");
Chandler Carruth43acdb32018-04-24 10:33:08 +00002259 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002260#endif
Chandler Carruth92815032018-06-02 01:29:01 +00002261 // First build LCSSA for this loop so that we can preserve it when
2262 // forming dedicated exits. We don't want to perturb some other loop's
2263 // LCSSA while doing that CFG edit.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002264 formLCSSA(UpdateL, DT, &LI, nullptr);
Chandler Carruth92815032018-06-02 01:29:01 +00002265
2266 // For loops reached by this loop's original exit blocks we may
2267 // introduced new, non-dedicated exits. At least try to re-form dedicated
2268 // exits for these loops. This may fail if they couldn't have dedicated
2269 // exits to start with.
Alina Sbirlea97468e92019-02-21 21:13:34 +00002270 formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002271 };
2272
2273 // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2274 // and we can do it in any order as they don't nest relative to each other.
Chandler Carruth92815032018-06-02 01:29:01 +00002275 //
2276 // Also check if any of the loops we have updated have become top-level loops
2277 // as that will necessitate widening the outer loop scope.
2278 for (Loop *UpdatedL :
2279 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2280 UpdateLoop(*UpdatedL);
2281 if (!UpdatedL->getParentLoop())
2282 OuterExitL = nullptr;
2283 }
2284 if (IsStillLoop) {
2285 UpdateLoop(L);
2286 if (!L.getParentLoop())
2287 OuterExitL = nullptr;
2288 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002289
2290 // If the original loop had exit blocks, walk up through the outer most loop
2291 // of those exit blocks to update LCSSA and form updated dedicated exits.
Chandler Carruth92815032018-06-02 01:29:01 +00002292 if (OuterExitL != &L)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002293 for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2294 OuterL = OuterL->getParentLoop())
Chandler Carruth92815032018-06-02 01:29:01 +00002295 UpdateLoop(*OuterL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002296
2297#ifndef NDEBUG
2298 // Verify the entire loop structure to catch any incorrect updates before we
2299 // progress in the pass pipeline.
2300 LI.verify(DT);
2301#endif
2302
2303 // Now that we've unswitched something, make callbacks to report the changes.
2304 // For that we need to merge together the updated loops and the cloned loops
2305 // and check whether the original loop survived.
2306 SmallVector<Loop *, 4> SibLoops;
2307 for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2308 if (UpdatedL->getParentLoop() == ParentL)
2309 SibLoops.push_back(UpdatedL);
Chandler Carruth71fd2702018-05-30 02:46:45 +00002310 UnswitchCB(IsStillLoop, SibLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002311
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002312 if (MSSAU && VerifyMemorySSA)
2313 MSSAU->getMemorySSA()->verifyMemorySSA();
2314
Zaara Syedab7dff9c2019-01-15 15:08:01 +00002315 if (BI)
2316 ++NumBranches;
2317 else
2318 ++NumSwitches;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002319}
2320
2321/// Recursively compute the cost of a dominator subtree based on the per-block
2322/// cost map provided.
2323///
2324/// The recursive computation is memozied into the provided DT-indexed cost map
2325/// to allow querying it for most nodes in the domtree without it becoming
2326/// quadratic.
2327static int
2328computeDomSubtreeCost(DomTreeNode &N,
2329 const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2330 SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2331 // Don't accumulate cost (or recurse through) blocks not in our block cost
2332 // map and thus not part of the duplication cost being considered.
2333 auto BBCostIt = BBCostMap.find(N.getBlock());
2334 if (BBCostIt == BBCostMap.end())
2335 return 0;
2336
2337 // Lookup this node to see if we already computed its cost.
2338 auto DTCostIt = DTCostMap.find(&N);
2339 if (DTCostIt != DTCostMap.end())
2340 return DTCostIt->second;
2341
2342 // If not, we have to compute it. We can't use insert above and update
2343 // because computing the cost may insert more things into the map.
2344 int Cost = std::accumulate(
2345 N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2346 return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2347 });
2348 bool Inserted = DTCostMap.insert({&N, Cost}).second;
2349 (void)Inserted;
2350 assert(Inserted && "Should not insert a node while visiting children!");
2351 return Cost;
2352}
2353
Max Kazantsev619a8342018-10-26 14:20:11 +00002354/// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2355/// making the following replacement:
2356///
Simon Pilgrima1320162018-10-27 15:14:42 +00002357/// --code before guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002358/// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
Simon Pilgrima1320162018-10-27 15:14:42 +00002359/// --code after guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002360///
2361/// into
2362///
Simon Pilgrima1320162018-10-27 15:14:42 +00002363/// --code before guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002364/// br i1 %cond, label %guarded, label %deopt
2365///
2366/// guarded:
Simon Pilgrima1320162018-10-27 15:14:42 +00002367/// --code after guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002368///
2369/// deopt:
2370/// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2371/// unreachable
2372///
2373/// It also makes all relevant DT and LI updates, so that all structures are in
2374/// valid state after this transform.
2375static BranchInst *
2376turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2377 SmallVectorImpl<BasicBlock *> &ExitBlocks,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002378 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Max Kazantsev619a8342018-10-26 14:20:11 +00002379 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2380 LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2381 BasicBlock *CheckBB = GI->getParent();
2382
Alina Sbirlea797935f2018-12-04 14:43:24 +00002383 if (MSSAU && VerifyMemorySSA)
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002384 MSSAU->getMemorySSA()->verifyMemorySSA();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002385
Max Kazantsev619a8342018-10-26 14:20:11 +00002386 // Remove all CheckBB's successors from DomTree. A block can be seen among
2387 // successors more than once, but for DomTree it should be added only once.
2388 SmallPtrSet<BasicBlock *, 4> Successors;
2389 for (auto *Succ : successors(CheckBB))
2390 if (Successors.insert(Succ).second)
2391 DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2392
2393 Instruction *DeoptBlockTerm =
2394 SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2395 BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2396 // SplitBlockAndInsertIfThen inserts control flow that branches to
2397 // DeoptBlockTerm if the condition is true. We want the opposite.
2398 CheckBI->swapSuccessors();
2399
2400 BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2401 GuardedBlock->setName("guarded");
2402 CheckBI->getSuccessor(1)->setName("deopt");
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002403 BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
Max Kazantsev619a8342018-10-26 14:20:11 +00002404
2405 // We now have a new exit block.
2406 ExitBlocks.push_back(CheckBI->getSuccessor(1));
2407
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002408 if (MSSAU)
2409 MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2410
Max Kazantsev619a8342018-10-26 14:20:11 +00002411 GI->moveBefore(DeoptBlockTerm);
2412 GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2413
2414 // Add new successors of CheckBB into DomTree.
2415 for (auto *Succ : successors(CheckBB))
2416 DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2417
2418 // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2419 // successors.
2420 for (auto *Succ : Successors)
2421 DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2422
2423 // Make proper changes to DT.
2424 DT.applyUpdates(DTUpdates);
2425 // Inform LI of a new loop block.
2426 L.addBasicBlockToLoop(GuardedBlock, LI);
2427
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002428 if (MSSAU) {
2429 MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2430 MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::End);
2431 if (VerifyMemorySSA)
2432 MSSAU->getMemorySSA()->verifyMemorySSA();
2433 }
2434
Max Kazantsev619a8342018-10-26 14:20:11 +00002435 ++NumGuards;
2436 return CheckBI;
2437}
2438
Fedor Sergeev2e3e2242018-11-16 21:16:43 +00002439/// Cost multiplier is a way to limit potentially exponential behavior
2440/// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2441/// candidates available. Also accounting for the number of "sibling" loops with
2442/// the idea to account for previous unswitches that already happened on this
2443/// cluster of loops. There was an attempt to keep this formula simple,
2444/// just enough to limit the worst case behavior. Even if it is not that simple
2445/// now it is still not an attempt to provide a detailed heuristic size
2446/// prediction.
2447///
2448/// TODO: Make a proper accounting of "explosion" effect for all kinds of
2449/// unswitch candidates, making adequate predictions instead of wild guesses.
2450/// That requires knowing not just the number of "remaining" candidates but
2451/// also costs of unswitching for each of these candidates.
2452static int calculateUnswitchCostMultiplier(
2453 Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
2454 ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
2455 UnswitchCandidates) {
2456
2457 // Guards and other exiting conditions do not contribute to exponential
2458 // explosion as soon as they dominate the latch (otherwise there might be
2459 // another path to the latch remaining that does not allow to eliminate the
2460 // loop copy on unswitch).
2461 BasicBlock *Latch = L.getLoopLatch();
2462 BasicBlock *CondBlock = TI.getParent();
2463 if (DT.dominates(CondBlock, Latch) &&
2464 (isGuard(&TI) ||
2465 llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
2466 return L.contains(SuccBB);
2467 }) <= 1)) {
2468 NumCostMultiplierSkipped++;
2469 return 1;
2470 }
2471
2472 auto *ParentL = L.getParentLoop();
2473 int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2474 : std::distance(LI.begin(), LI.end()));
2475 // Count amount of clones that all the candidates might cause during
2476 // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2477 int UnswitchedClones = 0;
2478 for (auto Candidate : UnswitchCandidates) {
2479 Instruction *CI = Candidate.first;
2480 BasicBlock *CondBlock = CI->getParent();
2481 bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2482 if (isGuard(CI)) {
2483 if (!SkipExitingSuccessors)
2484 UnswitchedClones++;
2485 continue;
2486 }
2487 int NonExitingSuccessors = llvm::count_if(
2488 successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
2489 return !SkipExitingSuccessors || L.contains(SuccBB);
2490 });
2491 UnswitchedClones += Log2_32(NonExitingSuccessors);
2492 }
2493
2494 // Ignore up to the "unscaled candidates" number of unswitch candidates
2495 // when calculating the power-of-two scaling of the cost. The main idea
2496 // with this control is to allow a small number of unswitches to happen
2497 // and rely more on siblings multiplier (see below) when the number
2498 // of candidates is small.
2499 unsigned ClonesPower =
2500 std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
2501
2502 // Allowing top-level loops to spread a bit more than nested ones.
2503 int SiblingsMultiplier =
2504 std::max((ParentL ? SiblingsCount
2505 : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
2506 1);
2507 // Compute the cost multiplier in a way that won't overflow by saturating
2508 // at an upper bound.
2509 int CostMultiplier;
2510 if (ClonesPower > Log2_32(UnswitchThreshold) ||
2511 SiblingsMultiplier > UnswitchThreshold)
2512 CostMultiplier = UnswitchThreshold;
2513 else
2514 CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2515 (int)UnswitchThreshold);
2516
2517 LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier
2518 << " (siblings " << SiblingsMultiplier << " * clones "
2519 << (1 << ClonesPower) << ")"
2520 << " for unswitch candidate: " << TI << "\n");
2521 return CostMultiplier;
2522}
2523
Chandler Carruth3897ded2018-07-03 09:13:27 +00002524static bool
2525unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2526 AssumptionCache &AC, TargetTransformInfo &TTI,
2527 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002528 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002529 // Collect all invariant conditions within this loop (as opposed to an inner
2530 // loop which would be handled when visiting that inner loop).
Chandler Carruth60b2e052018-10-18 00:40:26 +00002531 SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002532 UnswitchCandidates;
Max Kazantsev619a8342018-10-26 14:20:11 +00002533
2534 // Whether or not we should also collect guards in the loop.
2535 bool CollectGuards = false;
2536 if (UnswitchGuards) {
2537 auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2538 Intrinsic::getName(Intrinsic::experimental_guard));
2539 if (GuardDecl && !GuardDecl->use_empty())
2540 CollectGuards = true;
2541 }
2542
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002543 for (auto *BB : L.blocks()) {
2544 if (LI.getLoopFor(BB) != &L)
2545 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002546
Max Kazantsev619a8342018-10-26 14:20:11 +00002547 if (CollectGuards)
2548 for (auto &I : *BB)
2549 if (isGuard(&I)) {
2550 auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2551 // TODO: Support AND, OR conditions and partial unswitching.
2552 if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2553 UnswitchCandidates.push_back({&I, {Cond}});
2554 }
2555
Chandler Carruth16529962018-06-25 23:32:54 +00002556 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2557 // We can only consider fully loop-invariant switch conditions as we need
2558 // to completely eliminate the switch after unswitching.
2559 if (!isa<Constant>(SI->getCondition()) &&
Serguei Katkovd000f8b2019-07-10 10:25:22 +00002560 L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor())
Chandler Carruth16529962018-06-25 23:32:54 +00002561 UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2562 continue;
2563 }
2564
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002565 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002566 if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2567 BI->getSuccessor(0) == BI->getSuccessor(1))
2568 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002569
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002570 if (L.isLoopInvariant(BI->getCondition())) {
2571 UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2572 continue;
2573 }
2574
2575 Instruction &CondI = *cast<Instruction>(BI->getCondition());
2576 if (CondI.getOpcode() != Instruction::And &&
2577 CondI.getOpcode() != Instruction::Or)
2578 continue;
2579
2580 TinyPtrVector<Value *> Invariants =
2581 collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2582 if (Invariants.empty())
2583 continue;
2584
2585 UnswitchCandidates.push_back({BI, std::move(Invariants)});
Chandler Carruth71fd2702018-05-30 02:46:45 +00002586 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002587
Chandler Carruth693eedb2017-11-17 19:58:36 +00002588 // If we didn't find any candidates, we're done.
2589 if (UnswitchCandidates.empty())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002590 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002591
Chandler Carruth32e62f92018-04-19 18:44:25 +00002592 // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2593 // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2594 // irreducible control flow into reducible control flow and introduce new
2595 // loops "out of thin air". If we ever discover important use cases for doing
2596 // this, we can add support to loop unswitch, but it is a lot of complexity
Hiroshi Inouef2096492018-06-14 05:41:49 +00002597 // for what seems little or no real world benefit.
Chandler Carruth32e62f92018-04-19 18:44:25 +00002598 LoopBlocksRPO RPOT(&L);
2599 RPOT.perform(&LI);
2600 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002601 return false;
Chandler Carruth32e62f92018-04-19 18:44:25 +00002602
Max Kazantsevbde31002018-10-26 09:52:58 +00002603 SmallVector<BasicBlock *, 4> ExitBlocks;
2604 L.getUniqueExitBlocks(ExitBlocks);
2605
2606 // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
2607 // don't know how to split those exit blocks.
2608 // FIXME: We should teach SplitBlock to handle this and remove this
2609 // restriction.
2610 for (auto *ExitBB : ExitBlocks)
2611 if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) {
2612 dbgs() << "Cannot unswitch because of cleanuppad in exit block\n";
2613 return false;
2614 }
2615
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002616 LLVM_DEBUG(
2617 dbgs() << "Considering " << UnswitchCandidates.size()
2618 << " non-trivial loop invariant conditions for unswitching.\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002619
2620 // Given that unswitching these terminators will require duplicating parts of
2621 // the loop, so we need to be able to model that cost. Compute the ephemeral
2622 // values and set up a data structure to hold per-BB costs. We cache each
2623 // block's cost so that we don't recompute this when considering different
2624 // subsets of the loop for duplication during unswitching.
2625 SmallPtrSet<const Value *, 4> EphValues;
2626 CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2627 SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2628
2629 // Compute the cost of each block, as well as the total loop cost. Also, bail
2630 // out if we see instructions which are incompatible with loop unswitching
2631 // (convergent, noduplicate, or cross-basic-block tokens).
2632 // FIXME: We might be able to safely handle some of these in non-duplicated
2633 // regions.
2634 int LoopCost = 0;
2635 for (auto *BB : L.blocks()) {
2636 int Cost = 0;
2637 for (auto &I : *BB) {
2638 if (EphValues.count(&I))
2639 continue;
2640
2641 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002642 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002643 if (auto CS = CallSite(&I))
2644 if (CS.isConvergent() || CS.cannotDuplicate())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002645 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002646
2647 Cost += TTI.getUserCost(&I);
2648 }
2649 assert(Cost >= 0 && "Must not have negative costs!");
2650 LoopCost += Cost;
2651 assert(LoopCost >= 0 && "Must not have negative loop costs!");
2652 BBCostMap[BB] = Cost;
2653 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002654 LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002655
2656 // Now we find the best candidate by searching for the one with the following
2657 // properties in order:
2658 //
2659 // 1) An unswitching cost below the threshold
2660 // 2) The smallest number of duplicated unswitch candidates (to avoid
2661 // creating redundant subsequent unswitching)
2662 // 3) The smallest cost after unswitching.
2663 //
2664 // We prioritize reducing fanout of unswitch candidates provided the cost
2665 // remains below the threshold because this has a multiplicative effect.
2666 //
2667 // This requires memoizing each dominator subtree to avoid redundant work.
2668 //
2669 // FIXME: Need to actually do the number of candidates part above.
2670 SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2671 // Given a terminator which might be unswitched, computes the non-duplicated
2672 // cost for that terminator.
Chandler Carruth60b2e052018-10-18 00:40:26 +00002673 auto ComputeUnswitchedCost = [&](Instruction &TI, bool FullUnswitch) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002674 BasicBlock &BB = *TI.getParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002675 SmallPtrSet<BasicBlock *, 4> Visited;
2676
2677 int Cost = LoopCost;
2678 for (BasicBlock *SuccBB : successors(&BB)) {
2679 // Don't count successors more than once.
2680 if (!Visited.insert(SuccBB).second)
2681 continue;
2682
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002683 // If this is a partial unswitch candidate, then it must be a conditional
2684 // branch with a condition of either `or` or `and`. In that case, one of
2685 // the successors is necessarily duplicated, so don't even try to remove
2686 // its cost.
2687 if (!FullUnswitch) {
2688 auto &BI = cast<BranchInst>(TI);
2689 if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2690 Instruction::And) {
2691 if (SuccBB == BI.getSuccessor(1))
2692 continue;
2693 } else {
2694 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2695 Instruction::Or &&
2696 "Only `and` and `or` conditions can result in a partial "
2697 "unswitch!");
2698 if (SuccBB == BI.getSuccessor(0))
2699 continue;
2700 }
2701 }
2702
Chandler Carruth693eedb2017-11-17 19:58:36 +00002703 // This successor's domtree will not need to be duplicated after
2704 // unswitching if the edge to the successor dominates it (and thus the
2705 // entire tree). This essentially means there is no other path into this
2706 // subtree and so it will end up live in only one clone of the loop.
2707 if (SuccBB->getUniquePredecessor() ||
2708 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2709 return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2710 })) {
2711 Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2712 assert(Cost >= 0 &&
2713 "Non-duplicated cost should never exceed total loop cost!");
2714 }
2715 }
2716
2717 // Now scale the cost by the number of unique successors minus one. We
2718 // subtract one because there is already at least one copy of the entire
2719 // loop. This is computing the new cost of unswitching a condition.
Max Kazantsev619a8342018-10-26 14:20:11 +00002720 // Note that guards always have 2 unique successors that are implicit and
2721 // will be materialized if we decide to unswitch it.
2722 int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2723 assert(SuccessorsCount > 1 &&
Chandler Carruth693eedb2017-11-17 19:58:36 +00002724 "Cannot unswitch a condition without multiple distinct successors!");
Max Kazantsev619a8342018-10-26 14:20:11 +00002725 return Cost * (SuccessorsCount - 1);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002726 };
Chandler Carruth60b2e052018-10-18 00:40:26 +00002727 Instruction *BestUnswitchTI = nullptr;
Simon Pilgrimc598ef72019-10-16 10:38:18 +00002728 int BestUnswitchCost = 0;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002729 ArrayRef<Value *> BestUnswitchInvariants;
2730 for (auto &TerminatorAndInvariants : UnswitchCandidates) {
Chandler Carruth60b2e052018-10-18 00:40:26 +00002731 Instruction &TI = *TerminatorAndInvariants.first;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002732 ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2733 BranchInst *BI = dyn_cast<BranchInst>(&TI);
Chandler Carruth16529962018-06-25 23:32:54 +00002734 int CandidateCost = ComputeUnswitchedCost(
2735 TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2736 Invariants[0] == BI->getCondition()));
Fedor Sergeev2e3e2242018-11-16 21:16:43 +00002737 // Calculate cost multiplier which is a tool to limit potentially
2738 // exponential behavior of loop-unswitch.
2739 if (EnableUnswitchCostMultiplier) {
2740 int CostMultiplier =
2741 calculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
2742 assert(
2743 (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
2744 "cost multiplier needs to be in the range of 1..UnswitchThreshold");
2745 CandidateCost *= CostMultiplier;
2746 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2747 << " (multiplier: " << CostMultiplier << ")"
2748 << " for unswitch candidate: " << TI << "\n");
2749 } else {
2750 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2751 << " for unswitch candidate: " << TI << "\n");
2752 }
2753
Chandler Carruth693eedb2017-11-17 19:58:36 +00002754 if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002755 BestUnswitchTI = &TI;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002756 BestUnswitchCost = CandidateCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002757 BestUnswitchInvariants = Invariants;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002758 }
2759 }
Simon Pilgrimc598ef72019-10-16 10:38:18 +00002760 assert(BestUnswitchTI && "Failed to find loop unswitch candidate");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002761
Chandler Carruth71fd2702018-05-30 02:46:45 +00002762 if (BestUnswitchCost >= UnswitchThreshold) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002763 LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2764 << BestUnswitchCost << "\n");
Chandler Carruth71fd2702018-05-30 02:46:45 +00002765 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002766 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002767
Max Kazantsev619a8342018-10-26 14:20:11 +00002768 // If the best candidate is a guard, turn it into a branch.
2769 if (isGuard(BestUnswitchTI))
2770 BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002771 ExitBlocks, DT, LI, MSSAU);
Max Kazantsev619a8342018-10-26 14:20:11 +00002772
Max Kazantsevbde31002018-10-26 09:52:58 +00002773 LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = "
Chandler Carruth16529962018-06-25 23:32:54 +00002774 << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2775 << "\n");
Max Kazantsevbde31002018-10-26 09:52:58 +00002776 unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002777 ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU);
Max Kazantsevbde31002018-10-26 09:52:58 +00002778 return true;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002779}
2780
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002781/// Unswitch control flow predicated on loop invariant conditions.
2782///
2783/// This first hoists all branches or switches which are trivial (IE, do not
2784/// require duplicating any part of the loop) out of the loop body. It then
2785/// looks at other loop invariant control flows and tries to unswitch those as
2786/// well by cloning the loop if the result is small enough.
Chandler Carruth3897ded2018-07-03 09:13:27 +00002787///
2788/// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2789/// updated based on the unswitch.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002790/// The `MSSA` analysis is also updated if valid (i.e. its use is enabled).
Chandler Carruth3897ded2018-07-03 09:13:27 +00002791///
2792/// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2793/// true, we will attempt to do non-trivial unswitching as well as trivial
2794/// unswitching.
2795///
2796/// The `UnswitchCB` callback provided will be run after unswitching is
2797/// complete, with the first parameter set to `true` if the provided loop
2798/// remains a loop, and a list of new sibling loops created.
2799///
2800/// If `SE` is non-null, we will update that analysis based on the unswitching
2801/// done.
2802static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2803 AssumptionCache &AC, TargetTransformInfo &TTI,
2804 bool NonTrivial,
2805 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002806 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002807 assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2808 "Loops must be in LCSSA form before unswitching.");
2809 bool Changed = false;
2810
2811 // Must be in loop simplified form: we need a preheader and dedicated exits.
2812 if (!L.isLoopSimplifyForm())
2813 return false;
2814
2815 // Try trivial unswitch first before loop over other basic blocks in the loop.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002816 if (unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002817 // If we unswitched successfully we will want to clean up the loop before
2818 // processing it further so just mark it as unswitched and return.
2819 UnswitchCB(/*CurrentLoopValid*/ true, {});
2820 return true;
2821 }
2822
2823 // If we're not doing non-trivial unswitching, we're done. We both accept
2824 // a parameter but also check a local flag that can be used for testing
2825 // a debugging.
2826 if (!NonTrivial && !EnableNonTrivialUnswitch)
2827 return false;
2828
2829 // For non-trivial unswitching, because it often creates new loops, we rely on
2830 // the pass manager to iterate on the loops rather than trying to immediately
2831 // reach a fixed point. There is no substantial advantage to iterating
2832 // internally, and if any of the new loops are simplified enough to contain
2833 // trivial unswitching we want to prefer those.
2834
2835 // Try to unswitch the best invariant condition. We prefer this full unswitch to
2836 // a partial unswitch when possible below the threshold.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002837 if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE, MSSAU))
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002838 return true;
2839
2840 // No other opportunities to unswitch.
2841 return Changed;
2842}
2843
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002844PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2845 LoopStandardAnalysisResults &AR,
2846 LPMUpdater &U) {
2847 Function &F = *L.getHeader()->getParent();
2848 (void)F;
2849
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002850 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2851 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002852
Chandler Carruth693eedb2017-11-17 19:58:36 +00002853 // Save the current loop name in a variable so that we can report it even
2854 // after it has been deleted.
2855 std::string LoopName = L.getName();
2856
Chandler Carruth71fd2702018-05-30 02:46:45 +00002857 auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2858 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002859 // If we did a non-trivial unswitch, we have added new (cloned) loops.
Chandler Carruth71fd2702018-05-30 02:46:45 +00002860 if (!NewLoops.empty())
2861 U.addSiblingLoops(NewLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002862
2863 // If the current loop remains valid, we should revisit it to catch any
2864 // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2865 if (CurrentLoopValid)
2866 U.revisitCurrentLoop();
2867 else
2868 U.markLoopAsDeleted(L, LoopName);
2869 };
2870
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002871 Optional<MemorySSAUpdater> MSSAU;
2872 if (AR.MSSA) {
2873 MSSAU = MemorySSAUpdater(AR.MSSA);
2874 if (VerifyMemorySSA)
2875 AR.MSSA->verifyMemorySSA();
2876 }
Chandler Carruth3897ded2018-07-03 09:13:27 +00002877 if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002878 &AR.SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002879 return PreservedAnalyses::all();
2880
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002881 if (AR.MSSA && VerifyMemorySSA)
2882 AR.MSSA->verifyMemorySSA();
2883
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002884 // Historically this pass has had issues with the dominator tree so verify it
2885 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002886 assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
Alina Sbirlea3cef1f72019-06-11 18:27:49 +00002887
2888 auto PA = getLoopPassPreservedAnalyses();
Alina Sbirleaf92109d2019-08-17 01:02:12 +00002889 if (AR.MSSA)
Alina Sbirlea3cef1f72019-06-11 18:27:49 +00002890 PA.preserve<MemorySSAAnalysis>();
2891 return PA;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002892}
2893
2894namespace {
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002895
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002896class SimpleLoopUnswitchLegacyPass : public LoopPass {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002897 bool NonTrivial;
2898
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002899public:
2900 static char ID; // Pass ID, replacement for typeid
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002901
Chandler Carruth693eedb2017-11-17 19:58:36 +00002902 explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2903 : LoopPass(ID), NonTrivial(NonTrivial) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002904 initializeSimpleLoopUnswitchLegacyPassPass(
2905 *PassRegistry::getPassRegistry());
2906 }
2907
2908 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2909
2910 void getAnalysisUsage(AnalysisUsage &AU) const override {
2911 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002912 AU.addRequired<TargetTransformInfoWrapperPass>();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002913 if (EnableMSSALoopDependency) {
2914 AU.addRequired<MemorySSAWrapperPass>();
2915 AU.addPreserved<MemorySSAWrapperPass>();
2916 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002917 getLoopAnalysisUsage(AU);
2918 }
2919};
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002920
2921} // end anonymous namespace
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002922
2923bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2924 if (skipLoop(L))
2925 return false;
2926
2927 Function &F = *L->getHeader()->getParent();
2928
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002929 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2930 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002931
2932 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2933 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2934 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002935 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002936 MemorySSA *MSSA = nullptr;
2937 Optional<MemorySSAUpdater> MSSAU;
2938 if (EnableMSSALoopDependency) {
2939 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
2940 MSSAU = MemorySSAUpdater(MSSA);
2941 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002942
Chandler Carruth3897ded2018-07-03 09:13:27 +00002943 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2944 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2945
Chandler Carruth71fd2702018-05-30 02:46:45 +00002946 auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2947 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002948 // If we did a non-trivial unswitch, we have added new (cloned) loops.
2949 for (auto *NewL : NewLoops)
2950 LPM.addLoop(*NewL);
2951
2952 // If the current loop remains valid, re-add it to the queue. This is
2953 // a little wasteful as we'll finish processing the current loop as well,
2954 // but it is the best we can do in the old PM.
2955 if (CurrentLoopValid)
2956 LPM.addLoop(*L);
2957 else
2958 LPM.markLoopAsDeleted(*L);
2959 };
2960
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002961 if (MSSA && VerifyMemorySSA)
2962 MSSA->verifyMemorySSA();
2963
2964 bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE,
2965 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
2966
2967 if (MSSA && VerifyMemorySSA)
2968 MSSA->verifyMemorySSA();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002969
2970 // If anything was unswitched, also clear any cached information about this
2971 // loop.
2972 LPM.deleteSimpleAnalysisLoop(L);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002973
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002974 // Historically this pass has had issues with the dominator tree so verify it
2975 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002976 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2977
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002978 return Changed;
2979}
2980
2981char SimpleLoopUnswitchLegacyPass::ID = 0;
2982INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2983 "Simple unswitch loops", false, false)
2984INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002985INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2986INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002987INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002988INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002989INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2990INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2991 "Simple unswitch loops", false, false)
2992
Chandler Carruth693eedb2017-11-17 19:58:36 +00002993Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2994 return new SimpleLoopUnswitchLegacyPass(NonTrivial);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002995}