1 ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
10 #include "llvm/ADT/DenseMap.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/Sequence.h"
13 #include "llvm/ADT/SetVector.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/CFG.h"
20 #include "llvm/Analysis/CodeMetrics.h"
21 #include "llvm/Analysis/GuardUtils.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/LoopAnalysisManager.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/LoopIterator.h"
26 #include "llvm/Analysis/LoopPass.h"
27 #include "llvm/Analysis/MemorySSA.h"
28 #include "llvm/Analysis/MemorySSAUpdater.h"
29 #include "llvm/Analysis/Utils/Local.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/Constant.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/InstrTypes.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Use.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/GenericDomTree.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Cloning.h"
50 #include "llvm/Transforms/Utils/LoopUtils.h"
51 #include "llvm/Transforms/Utils/ValueMapper.h"
58 #define DEBUG_TYPE "simple-loop-unswitch"
62 STATISTIC(NumBranches
, "Number of branches unswitched");
63 STATISTIC(NumSwitches
, "Number of switches unswitched");
64 STATISTIC(NumGuards
, "Number of guards turned into branches for unswitching");
65 STATISTIC(NumTrivial
, "Number of unswitches that are trivial");
67 NumCostMultiplierSkipped
,
68 "Number of unswitch candidates that had their cost multiplier skipped");
70 static cl::opt
<bool> EnableNonTrivialUnswitch(
71 "enable-nontrivial-unswitch", cl::init(false), cl::Hidden
,
72 cl::desc("Forcibly enables non-trivial loop unswitching rather than "
73 "following the configuration passed into the pass."));
76 UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden
,
77 cl::desc("The cost threshold for unswitching a loop."));
79 static cl::opt
<bool> EnableUnswitchCostMultiplier(
80 "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden
,
81 cl::desc("Enable unswitch cost multiplier that prohibits exponential "
82 "explosion in nontrivial unswitch."));
83 static cl::opt
<int> UnswitchSiblingsToplevelDiv(
84 "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden
,
85 cl::desc("Toplevel siblings divisor for cost multiplier."));
86 static cl::opt
<int> UnswitchNumInitialUnscaledCandidates(
87 "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden
,
88 cl::desc("Number of unswitch candidates that are ignored when calculating "
90 static cl::opt
<bool> UnswitchGuards(
91 "simple-loop-unswitch-guards", cl::init(true), cl::Hidden
,
92 cl::desc("If enabled, simple loop unswitching will also consider "
93 "llvm.experimental.guard intrinsics as unswitch candidates."));
95 /// Collect all of the loop invariant input values transitively used by the
96 /// homogeneous instruction graph from a given root.
98 /// This essentially walks from a root recursively through loop variant operands
99 /// which have the exact same opcode and finds all inputs which are loop
100 /// invariant. For some operations these can be re-associated and unswitched out
101 /// of the loop entirely.
102 static TinyPtrVector
<Value
*>
103 collectHomogenousInstGraphLoopInvariants(Loop
&L
, Instruction
&Root
,
105 assert(!L
.isLoopInvariant(&Root
) &&
106 "Only need to walk the graph if root itself is not invariant.");
107 TinyPtrVector
<Value
*> Invariants
;
109 // Build a worklist and recurse through operators collecting invariants.
110 SmallVector
<Instruction
*, 4> Worklist
;
111 SmallPtrSet
<Instruction
*, 8> Visited
;
112 Worklist
.push_back(&Root
);
113 Visited
.insert(&Root
);
115 Instruction
&I
= *Worklist
.pop_back_val();
116 for (Value
*OpV
: I
.operand_values()) {
117 // Skip constants as unswitching isn't interesting for them.
118 if (isa
<Constant
>(OpV
))
121 // Add it to our result if loop invariant.
122 if (L
.isLoopInvariant(OpV
)) {
123 Invariants
.push_back(OpV
);
127 // If not an instruction with the same opcode, nothing we can do.
128 Instruction
*OpI
= dyn_cast
<Instruction
>(OpV
);
129 if (!OpI
|| OpI
->getOpcode() != Root
.getOpcode())
132 // Visit this operand.
133 if (Visited
.insert(OpI
).second
)
134 Worklist
.push_back(OpI
);
136 } while (!Worklist
.empty());
141 static void replaceLoopInvariantUses(Loop
&L
, Value
*Invariant
,
142 Constant
&Replacement
) {
143 assert(!isa
<Constant
>(Invariant
) && "Why are we unswitching on a constant?");
145 // Replace uses of LIC in the loop with the given constant.
146 for (auto UI
= Invariant
->use_begin(), UE
= Invariant
->use_end(); UI
!= UE
;) {
147 // Grab the use and walk past it so we can clobber it in the use list.
149 Instruction
*UserI
= dyn_cast
<Instruction
>(U
->getUser());
151 // Replace this use within the loop body.
152 if (UserI
&& L
.contains(UserI
))
153 U
->set(&Replacement
);
157 /// Check that all the LCSSA PHI nodes in the loop exit block have trivial
158 /// incoming values along this edge.
159 static bool areLoopExitPHIsLoopInvariant(Loop
&L
, BasicBlock
&ExitingBB
,
160 BasicBlock
&ExitBB
) {
161 for (Instruction
&I
: ExitBB
) {
162 auto *PN
= dyn_cast
<PHINode
>(&I
);
164 // No more PHIs to check.
167 // If the incoming value for this edge isn't loop invariant the unswitch
169 if (!L
.isLoopInvariant(PN
->getIncomingValueForBlock(&ExitingBB
)))
172 llvm_unreachable("Basic blocks should never be empty!");
175 /// Insert code to test a set of loop invariant values, and conditionally branch
177 static void buildPartialUnswitchConditionalBranch(BasicBlock
&BB
,
178 ArrayRef
<Value
*> Invariants
,
180 BasicBlock
&UnswitchedSucc
,
181 BasicBlock
&NormalSucc
) {
182 IRBuilder
<> IRB(&BB
);
184 Value
*Cond
= Direction
? IRB
.CreateOr(Invariants
) :
185 IRB
.CreateAnd(Invariants
);
186 IRB
.CreateCondBr(Cond
, Direction
? &UnswitchedSucc
: &NormalSucc
,
187 Direction
? &NormalSucc
: &UnswitchedSucc
);
190 /// Rewrite the PHI nodes in an unswitched loop exit basic block.
192 /// Requires that the loop exit and unswitched basic block are the same, and
193 /// that the exiting block was a unique predecessor of that block. Rewrites the
194 /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
195 /// PHI nodes from the old preheader that now contains the unswitched
197 static void rewritePHINodesForUnswitchedExitBlock(BasicBlock
&UnswitchedBB
,
198 BasicBlock
&OldExitingBB
,
200 for (PHINode
&PN
: UnswitchedBB
.phis()) {
201 // When the loop exit is directly unswitched we just need to update the
202 // incoming basic block. We loop to handle weird cases with repeated
203 // incoming blocks, but expect to typically only have one operand here.
204 for (auto i
: seq
<int>(0, PN
.getNumOperands())) {
205 assert(PN
.getIncomingBlock(i
) == &OldExitingBB
&&
206 "Found incoming block different from unique predecessor!");
207 PN
.setIncomingBlock(i
, &OldPH
);
212 /// Rewrite the PHI nodes in the loop exit basic block and the split off
213 /// unswitched block.
215 /// Because the exit block remains an exit from the loop, this rewrites the
216 /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
217 /// nodes into the unswitched basic block to select between the value in the
218 /// old preheader and the loop exit.
219 static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock
&ExitBB
,
220 BasicBlock
&UnswitchedBB
,
221 BasicBlock
&OldExitingBB
,
224 assert(&ExitBB
!= &UnswitchedBB
&&
225 "Must have different loop exit and unswitched blocks!");
226 Instruction
*InsertPt
= &*UnswitchedBB
.begin();
227 for (PHINode
&PN
: ExitBB
.phis()) {
228 auto *NewPN
= PHINode::Create(PN
.getType(), /*NumReservedValues*/ 2,
229 PN
.getName() + ".split", InsertPt
);
231 // Walk backwards over the old PHI node's inputs to minimize the cost of
232 // removing each one. We have to do this weird loop manually so that we
233 // create the same number of new incoming edges in the new PHI as we expect
234 // each case-based edge to be included in the unswitched switch in some
236 // FIXME: This is really, really gross. It would be much cleaner if LLVM
237 // allowed us to create a single entry for a predecessor block without
238 // having separate entries for each "edge" even though these edges are
239 // required to produce identical results.
240 for (int i
= PN
.getNumIncomingValues() - 1; i
>= 0; --i
) {
241 if (PN
.getIncomingBlock(i
) != &OldExitingBB
)
244 Value
*Incoming
= PN
.getIncomingValue(i
);
246 // No more edge from the old exiting block to the exit block.
247 PN
.removeIncomingValue(i
);
249 NewPN
->addIncoming(Incoming
, &OldPH
);
252 // Now replace the old PHI with the new one and wire the old one in as an
253 // input to the new one.
254 PN
.replaceAllUsesWith(NewPN
);
255 NewPN
->addIncoming(&PN
, &ExitBB
);
259 /// Hoist the current loop up to the innermost loop containing a remaining exit.
261 /// Because we've removed an exit from the loop, we may have changed the set of
262 /// loops reachable and need to move the current loop up the loop nest or even
263 /// to an entirely separate nest.
264 static void hoistLoopToNewParent(Loop
&L
, BasicBlock
&Preheader
,
265 DominatorTree
&DT
, LoopInfo
&LI
,
266 MemorySSAUpdater
*MSSAU
) {
267 // If the loop is already at the top level, we can't hoist it anywhere.
268 Loop
*OldParentL
= L
.getParentLoop();
272 SmallVector
<BasicBlock
*, 4> Exits
;
273 L
.getExitBlocks(Exits
);
274 Loop
*NewParentL
= nullptr;
275 for (auto *ExitBB
: Exits
)
276 if (Loop
*ExitL
= LI
.getLoopFor(ExitBB
))
277 if (!NewParentL
|| NewParentL
->contains(ExitL
))
280 if (NewParentL
== OldParentL
)
283 // The new parent loop (if different) should always contain the old one.
285 assert(NewParentL
->contains(OldParentL
) &&
286 "Can only hoist this loop up the nest!");
288 // The preheader will need to move with the body of this loop. However,
289 // because it isn't in this loop we also need to update the primary loop map.
290 assert(OldParentL
== LI
.getLoopFor(&Preheader
) &&
291 "Parent loop of this loop should contain this loop's preheader!");
292 LI
.changeLoopFor(&Preheader
, NewParentL
);
294 // Remove this loop from its old parent.
295 OldParentL
->removeChildLoop(&L
);
297 // Add the loop either to the new parent or as a top-level loop.
299 NewParentL
->addChildLoop(&L
);
301 LI
.addTopLevelLoop(&L
);
303 // Remove this loops blocks from the old parent and every other loop up the
304 // nest until reaching the new parent. Also update all of these
305 // no-longer-containing loops to reflect the nesting change.
306 for (Loop
*OldContainingL
= OldParentL
; OldContainingL
!= NewParentL
;
307 OldContainingL
= OldContainingL
->getParentLoop()) {
308 llvm::erase_if(OldContainingL
->getBlocksVector(),
309 [&](const BasicBlock
*BB
) {
310 return BB
== &Preheader
|| L
.contains(BB
);
313 OldContainingL
->getBlocksSet().erase(&Preheader
);
314 for (BasicBlock
*BB
: L
.blocks())
315 OldContainingL
->getBlocksSet().erase(BB
);
317 // Because we just hoisted a loop out of this one, we have essentially
318 // created new exit paths from it. That means we need to form LCSSA PHI
319 // nodes for values used in the no-longer-nested loop.
320 formLCSSA(*OldContainingL
, DT
, &LI
, nullptr);
322 // We shouldn't need to form dedicated exits because the exit introduced
323 // here is the (just split by unswitching) preheader. However, after trivial
324 // unswitching it is possible to get new non-dedicated exits out of parent
325 // loop so let's conservatively form dedicated exit blocks and figure out
326 // if we can optimize later.
327 formDedicatedExitBlocks(OldContainingL
, &DT
, &LI
, MSSAU
,
328 /*PreserveLCSSA*/ true);
332 /// Unswitch a trivial branch if the condition is loop invariant.
334 /// This routine should only be called when loop code leading to the branch has
335 /// been validated as trivial (no side effects). This routine checks if the
336 /// condition is invariant and one of the successors is a loop exit. This
337 /// allows us to unswitch without duplicating the loop, making it trivial.
339 /// If this routine fails to unswitch the branch it returns false.
341 /// If the branch can be unswitched, this routine splits the preheader and
342 /// hoists the branch above that split. Preserves loop simplified form
343 /// (splitting the exit block as necessary). It simplifies the branch within
344 /// the loop to an unconditional branch but doesn't remove it entirely. Further
345 /// cleanup can be done with some simplify-cfg like pass.
347 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
348 /// invalidated by this.
349 static bool unswitchTrivialBranch(Loop
&L
, BranchInst
&BI
, DominatorTree
&DT
,
350 LoopInfo
&LI
, ScalarEvolution
*SE
,
351 MemorySSAUpdater
*MSSAU
) {
352 assert(BI
.isConditional() && "Can only unswitch a conditional branch!");
353 LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI
<< "\n");
355 // The loop invariant values that we want to unswitch.
356 TinyPtrVector
<Value
*> Invariants
;
358 // When true, we're fully unswitching the branch rather than just unswitching
359 // some input conditions to the branch.
360 bool FullUnswitch
= false;
362 if (L
.isLoopInvariant(BI
.getCondition())) {
363 Invariants
.push_back(BI
.getCondition());
366 if (auto *CondInst
= dyn_cast
<Instruction
>(BI
.getCondition()))
367 Invariants
= collectHomogenousInstGraphLoopInvariants(L
, *CondInst
, LI
);
368 if (Invariants
.empty())
369 // Couldn't find invariant inputs!
373 // Check that one of the branch's successors exits, and which one.
374 bool ExitDirection
= true;
375 int LoopExitSuccIdx
= 0;
376 auto *LoopExitBB
= BI
.getSuccessor(0);
377 if (L
.contains(LoopExitBB
)) {
378 ExitDirection
= false;
380 LoopExitBB
= BI
.getSuccessor(1);
381 if (L
.contains(LoopExitBB
))
384 auto *ContinueBB
= BI
.getSuccessor(1 - LoopExitSuccIdx
);
385 auto *ParentBB
= BI
.getParent();
386 if (!areLoopExitPHIsLoopInvariant(L
, *ParentBB
, *LoopExitBB
))
389 // When unswitching only part of the branch's condition, we need the exit
390 // block to be reached directly from the partially unswitched input. This can
391 // be done when the exit block is along the true edge and the branch condition
392 // is a graph of `or` operations, or the exit block is along the false edge
393 // and the condition is a graph of `and` operations.
396 if (cast
<Instruction
>(BI
.getCondition())->getOpcode() != Instruction::Or
)
399 if (cast
<Instruction
>(BI
.getCondition())->getOpcode() != Instruction::And
)
405 dbgs() << " unswitching trivial invariant conditions for: " << BI
407 for (Value
*Invariant
: Invariants
) {
408 dbgs() << " " << *Invariant
<< " == true";
409 if (Invariant
!= Invariants
.back())
415 // If we have scalar evolutions, we need to invalidate them including this
416 // loop and the loop containing the exit block.
418 if (Loop
*ExitL
= LI
.getLoopFor(LoopExitBB
))
419 SE
->forgetLoop(ExitL
);
421 // Forget the entire nest as this exits the entire nest.
422 SE
->forgetTopmostLoop(&L
);
425 if (MSSAU
&& VerifyMemorySSA
)
426 MSSAU
->getMemorySSA()->verifyMemorySSA();
428 // Split the preheader, so that we know that there is a safe place to insert
429 // the conditional branch. We will change the preheader to have a conditional
430 // branch on LoopCond.
431 BasicBlock
*OldPH
= L
.getLoopPreheader();
432 BasicBlock
*NewPH
= SplitEdge(OldPH
, L
.getHeader(), &DT
, &LI
, MSSAU
);
434 // Now that we have a place to insert the conditional branch, create a place
435 // to branch to: this is the exit block out of the loop that we are
436 // unswitching. We need to split this if there are other loop predecessors.
437 // Because the loop is in simplified form, *any* other predecessor is enough.
438 BasicBlock
*UnswitchedBB
;
439 if (FullUnswitch
&& LoopExitBB
->getUniquePredecessor()) {
440 assert(LoopExitBB
->getUniquePredecessor() == BI
.getParent() &&
441 "A branch's parent isn't a predecessor!");
442 UnswitchedBB
= LoopExitBB
;
445 SplitBlock(LoopExitBB
, &LoopExitBB
->front(), &DT
, &LI
, MSSAU
);
448 if (MSSAU
&& VerifyMemorySSA
)
449 MSSAU
->getMemorySSA()->verifyMemorySSA();
451 // Actually move the invariant uses into the unswitched position. If possible,
452 // we do this by moving the instructions, but when doing partial unswitching
453 // we do it by building a new merge of the values in the unswitched position.
454 OldPH
->getTerminator()->eraseFromParent();
456 // If fully unswitching, we can use the existing branch instruction.
457 // Splice it into the old PH to gate reaching the new preheader and re-point
459 OldPH
->getInstList().splice(OldPH
->end(), BI
.getParent()->getInstList(),
462 // Temporarily clone the terminator, to make MSSA update cheaper by
463 // separating "insert edge" updates from "remove edge" ones.
464 ParentBB
->getInstList().push_back(BI
.clone());
466 // Create a new unconditional branch that will continue the loop as a new
468 BranchInst::Create(ContinueBB
, ParentBB
);
470 BI
.setSuccessor(LoopExitSuccIdx
, UnswitchedBB
);
471 BI
.setSuccessor(1 - LoopExitSuccIdx
, NewPH
);
473 // Only unswitching a subset of inputs to the condition, so we will need to
474 // build a new branch that merges the invariant inputs.
476 assert(cast
<Instruction
>(BI
.getCondition())->getOpcode() ==
478 "Must have an `or` of `i1`s for the condition!");
480 assert(cast
<Instruction
>(BI
.getCondition())->getOpcode() ==
482 "Must have an `and` of `i1`s for the condition!");
483 buildPartialUnswitchConditionalBranch(*OldPH
, Invariants
, ExitDirection
,
484 *UnswitchedBB
, *NewPH
);
487 // Update the dominator tree with the added edge.
488 DT
.insertEdge(OldPH
, UnswitchedBB
);
490 // After the dominator tree was updated with the added edge, update MemorySSA
493 SmallVector
<CFGUpdate
, 1> Updates
;
494 Updates
.push_back({cfg::UpdateKind::Insert
, OldPH
, UnswitchedBB
});
495 MSSAU
->applyInsertUpdates(Updates
, DT
);
498 // Finish updating dominator tree and memory ssa for full unswitch.
501 // Remove the cloned branch instruction.
502 ParentBB
->getTerminator()->eraseFromParent();
503 // Create unconditional branch now.
504 BranchInst::Create(ContinueBB
, ParentBB
);
505 MSSAU
->removeEdge(ParentBB
, LoopExitBB
);
507 DT
.deleteEdge(ParentBB
, LoopExitBB
);
510 if (MSSAU
&& VerifyMemorySSA
)
511 MSSAU
->getMemorySSA()->verifyMemorySSA();
513 // Rewrite the relevant PHI nodes.
514 if (UnswitchedBB
== LoopExitBB
)
515 rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB
, *ParentBB
, *OldPH
);
517 rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB
, *UnswitchedBB
,
518 *ParentBB
, *OldPH
, FullUnswitch
);
520 // The constant we can replace all of our invariants with inside the loop
521 // body. If any of the invariants have a value other than this the loop won't
523 ConstantInt
*Replacement
= ExitDirection
524 ? ConstantInt::getFalse(BI
.getContext())
525 : ConstantInt::getTrue(BI
.getContext());
527 // Since this is an i1 condition we can also trivially replace uses of it
528 // within the loop with a constant.
529 for (Value
*Invariant
: Invariants
)
530 replaceLoopInvariantUses(L
, Invariant
, *Replacement
);
532 // If this was full unswitching, we may have changed the nesting relationship
533 // for this loop so hoist it to its correct parent if needed.
535 hoistLoopToNewParent(L
, *NewPH
, DT
, LI
, MSSAU
);
537 if (MSSAU
&& VerifyMemorySSA
)
538 MSSAU
->getMemorySSA()->verifyMemorySSA();
540 LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n");
546 /// Unswitch a trivial switch if the condition is loop invariant.
548 /// This routine should only be called when loop code leading to the switch has
549 /// been validated as trivial (no side effects). This routine checks if the
550 /// condition is invariant and that at least one of the successors is a loop
551 /// exit. This allows us to unswitch without duplicating the loop, making it
554 /// If this routine fails to unswitch the switch it returns false.
556 /// If the switch can be unswitched, this routine splits the preheader and
557 /// copies the switch above that split. If the default case is one of the
558 /// exiting cases, it copies the non-exiting cases and points them at the new
559 /// preheader. If the default case is not exiting, it copies the exiting cases
560 /// and points the default at the preheader. It preserves loop simplified form
561 /// (splitting the exit blocks as necessary). It simplifies the switch within
562 /// the loop by removing now-dead cases. If the default case is one of those
563 /// unswitched, it replaces its destination with a new basic block containing
564 /// only unreachable. Such basic blocks, while technically loop exits, are not
565 /// considered for unswitching so this is a stable transform and the same
566 /// switch will not be revisited. If after unswitching there is only a single
567 /// in-loop successor, the switch is further simplified to an unconditional
568 /// branch. Still more cleanup can be done with some simplify-cfg like pass.
570 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
571 /// invalidated by this.
572 static bool unswitchTrivialSwitch(Loop
&L
, SwitchInst
&SI
, DominatorTree
&DT
,
573 LoopInfo
&LI
, ScalarEvolution
*SE
,
574 MemorySSAUpdater
*MSSAU
) {
575 LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI
<< "\n");
576 Value
*LoopCond
= SI
.getCondition();
578 // If this isn't switching on an invariant condition, we can't unswitch it.
579 if (!L
.isLoopInvariant(LoopCond
))
582 auto *ParentBB
= SI
.getParent();
584 SmallVector
<int, 4> ExitCaseIndices
;
585 for (auto Case
: SI
.cases()) {
586 auto *SuccBB
= Case
.getCaseSuccessor();
587 if (!L
.contains(SuccBB
) &&
588 areLoopExitPHIsLoopInvariant(L
, *ParentBB
, *SuccBB
))
589 ExitCaseIndices
.push_back(Case
.getCaseIndex());
591 BasicBlock
*DefaultExitBB
= nullptr;
592 SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight
=
593 SwitchInstProfUpdateWrapper::getSuccessorWeight(SI
, 0);
594 if (!L
.contains(SI
.getDefaultDest()) &&
595 areLoopExitPHIsLoopInvariant(L
, *ParentBB
, *SI
.getDefaultDest()) &&
596 !isa
<UnreachableInst
>(SI
.getDefaultDest()->getTerminator())) {
597 DefaultExitBB
= SI
.getDefaultDest();
598 } else if (ExitCaseIndices
.empty())
601 LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n");
603 if (MSSAU
&& VerifyMemorySSA
)
604 MSSAU
->getMemorySSA()->verifyMemorySSA();
606 // We may need to invalidate SCEVs for the outermost loop reached by any of
611 // Clear out the default destination temporarily to allow accurate
612 // predecessor lists to be examined below.
613 SI
.setDefaultDest(nullptr);
614 // Check the loop containing this exit.
615 Loop
*ExitL
= LI
.getLoopFor(DefaultExitBB
);
616 if (!ExitL
|| ExitL
->contains(OuterL
))
620 // Store the exit cases into a separate data structure and remove them from
622 SmallVector
<std::tuple
<ConstantInt
*, BasicBlock
*,
623 SwitchInstProfUpdateWrapper::CaseWeightOpt
>,
625 ExitCases
.reserve(ExitCaseIndices
.size());
626 SwitchInstProfUpdateWrapper
SIW(SI
);
627 // We walk the case indices backwards so that we remove the last case first
628 // and don't disrupt the earlier indices.
629 for (unsigned Index
: reverse(ExitCaseIndices
)) {
630 auto CaseI
= SI
.case_begin() + Index
;
631 // Compute the outer loop from this exit.
632 Loop
*ExitL
= LI
.getLoopFor(CaseI
->getCaseSuccessor());
633 if (!ExitL
|| ExitL
->contains(OuterL
))
635 // Save the value of this case.
636 auto W
= SIW
.getSuccessorWeight(CaseI
->getSuccessorIndex());
637 ExitCases
.emplace_back(CaseI
->getCaseValue(), CaseI
->getCaseSuccessor(), W
);
638 // Delete the unswitched cases.
639 SIW
.removeCase(CaseI
);
644 SE
->forgetLoop(OuterL
);
646 SE
->forgetTopmostLoop(&L
);
649 // Check if after this all of the remaining cases point at the same
651 BasicBlock
*CommonSuccBB
= nullptr;
652 if (SI
.getNumCases() > 0 &&
653 std::all_of(std::next(SI
.case_begin()), SI
.case_end(),
654 [&SI
](const SwitchInst::CaseHandle
&Case
) {
655 return Case
.getCaseSuccessor() ==
656 SI
.case_begin()->getCaseSuccessor();
658 CommonSuccBB
= SI
.case_begin()->getCaseSuccessor();
659 if (!DefaultExitBB
) {
660 // If we're not unswitching the default, we need it to match any cases to
661 // have a common successor or if we have no cases it is the common
663 if (SI
.getNumCases() == 0)
664 CommonSuccBB
= SI
.getDefaultDest();
665 else if (SI
.getDefaultDest() != CommonSuccBB
)
666 CommonSuccBB
= nullptr;
669 // Split the preheader, so that we know that there is a safe place to insert
671 BasicBlock
*OldPH
= L
.getLoopPreheader();
672 BasicBlock
*NewPH
= SplitEdge(OldPH
, L
.getHeader(), &DT
, &LI
, MSSAU
);
673 OldPH
->getTerminator()->eraseFromParent();
675 // Now add the unswitched switch.
676 auto *NewSI
= SwitchInst::Create(LoopCond
, NewPH
, ExitCases
.size(), OldPH
);
677 SwitchInstProfUpdateWrapper
NewSIW(*NewSI
);
679 // Rewrite the IR for the unswitched basic blocks. This requires two steps.
680 // First, we split any exit blocks with remaining in-loop predecessors. Then
681 // we update the PHIs in one of two ways depending on if there was a split.
682 // We walk in reverse so that we split in the same order as the cases
683 // appeared. This is purely for convenience of reading the resulting IR, but
684 // it doesn't cost anything really.
685 SmallPtrSet
<BasicBlock
*, 2> UnswitchedExitBBs
;
686 SmallDenseMap
<BasicBlock
*, BasicBlock
*, 2> SplitExitBBMap
;
687 // Handle the default exit if necessary.
688 // FIXME: It'd be great if we could merge this with the loop below but LLVM's
689 // ranges aren't quite powerful enough yet.
691 if (pred_empty(DefaultExitBB
)) {
692 UnswitchedExitBBs
.insert(DefaultExitBB
);
693 rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB
, *ParentBB
, *OldPH
);
696 SplitBlock(DefaultExitBB
, &DefaultExitBB
->front(), &DT
, &LI
, MSSAU
);
697 rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB
, *SplitBB
,
699 /*FullUnswitch*/ true);
700 DefaultExitBB
= SplitExitBBMap
[DefaultExitBB
] = SplitBB
;
703 // Note that we must use a reference in the for loop so that we update the
705 for (auto &ExitCase
: reverse(ExitCases
)) {
706 // Grab a reference to the exit block in the pair so that we can update it.
707 BasicBlock
*ExitBB
= std::get
<1>(ExitCase
);
709 // If this case is the last edge into the exit block, we can simply reuse it
710 // as it will no longer be a loop exit. No mapping necessary.
711 if (pred_empty(ExitBB
)) {
712 // Only rewrite once.
713 if (UnswitchedExitBBs
.insert(ExitBB
).second
)
714 rewritePHINodesForUnswitchedExitBlock(*ExitBB
, *ParentBB
, *OldPH
);
718 // Otherwise we need to split the exit block so that we retain an exit
719 // block from the loop and a target for the unswitched condition.
720 BasicBlock
*&SplitExitBB
= SplitExitBBMap
[ExitBB
];
722 // If this is the first time we see this, do the split and remember it.
723 SplitExitBB
= SplitBlock(ExitBB
, &ExitBB
->front(), &DT
, &LI
, MSSAU
);
724 rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB
, *SplitExitBB
,
726 /*FullUnswitch*/ true);
728 // Update the case pair to point to the split block.
729 std::get
<1>(ExitCase
) = SplitExitBB
;
732 // Now add the unswitched cases. We do this in reverse order as we built them
734 for (auto &ExitCase
: reverse(ExitCases
)) {
735 ConstantInt
*CaseVal
= std::get
<0>(ExitCase
);
736 BasicBlock
*UnswitchedBB
= std::get
<1>(ExitCase
);
738 NewSIW
.addCase(CaseVal
, UnswitchedBB
, std::get
<2>(ExitCase
));
741 // If the default was unswitched, re-point it and add explicit cases for
742 // entering the loop.
744 NewSIW
->setDefaultDest(DefaultExitBB
);
745 NewSIW
.setSuccessorWeight(0, DefaultCaseWeight
);
747 // We removed all the exit cases, so we just copy the cases to the
748 // unswitched switch.
749 for (const auto &Case
: SI
.cases())
750 NewSIW
.addCase(Case
.getCaseValue(), NewPH
,
751 SIW
.getSuccessorWeight(Case
.getSuccessorIndex()));
752 } else if (DefaultCaseWeight
) {
753 // We have to set branch weight of the default case.
754 uint64_t SW
= *DefaultCaseWeight
;
755 for (const auto &Case
: SI
.cases()) {
756 auto W
= SIW
.getSuccessorWeight(Case
.getSuccessorIndex());
758 "case weight must be defined as default case weight is defined");
761 NewSIW
.setSuccessorWeight(0, SW
);
764 // If we ended up with a common successor for every path through the switch
765 // after unswitching, rewrite it to an unconditional branch to make it easy
766 // to recognize. Otherwise we potentially have to recognize the default case
767 // pointing at unreachable and other complexity.
769 BasicBlock
*BB
= SI
.getParent();
770 // We may have had multiple edges to this common successor block, so remove
771 // them as predecessors. We skip the first one, either the default or the
772 // actual first case.
773 bool SkippedFirst
= DefaultExitBB
== nullptr;
774 for (auto Case
: SI
.cases()) {
775 assert(Case
.getCaseSuccessor() == CommonSuccBB
&&
776 "Non-common successor!");
782 CommonSuccBB
->removePredecessor(BB
,
783 /*KeepOneInputPHIs*/ true);
785 // Now nuke the switch and replace it with a direct branch.
786 SIW
.eraseFromParent();
787 BranchInst::Create(CommonSuccBB
, BB
);
788 } else if (DefaultExitBB
) {
789 assert(SI
.getNumCases() > 0 &&
790 "If we had no cases we'd have a common successor!");
791 // Move the last case to the default successor. This is valid as if the
792 // default got unswitched it cannot be reached. This has the advantage of
793 // being simple and keeping the number of edges from this switch to
794 // successors the same, and avoiding any PHI update complexity.
795 auto LastCaseI
= std::prev(SI
.case_end());
797 SI
.setDefaultDest(LastCaseI
->getCaseSuccessor());
798 SIW
.setSuccessorWeight(
799 0, SIW
.getSuccessorWeight(LastCaseI
->getSuccessorIndex()));
800 SIW
.removeCase(LastCaseI
);
803 // Walk the unswitched exit blocks and the unswitched split blocks and update
804 // the dominator tree based on the CFG edits. While we are walking unordered
805 // containers here, the API for applyUpdates takes an unordered list of
806 // updates and requires them to not contain duplicates.
807 SmallVector
<DominatorTree::UpdateType
, 4> DTUpdates
;
808 for (auto *UnswitchedExitBB
: UnswitchedExitBBs
) {
809 DTUpdates
.push_back({DT
.Delete
, ParentBB
, UnswitchedExitBB
});
810 DTUpdates
.push_back({DT
.Insert
, OldPH
, UnswitchedExitBB
});
812 for (auto SplitUnswitchedPair
: SplitExitBBMap
) {
813 DTUpdates
.push_back({DT
.Delete
, ParentBB
, SplitUnswitchedPair
.first
});
814 DTUpdates
.push_back({DT
.Insert
, OldPH
, SplitUnswitchedPair
.second
});
816 DT
.applyUpdates(DTUpdates
);
819 MSSAU
->applyUpdates(DTUpdates
, DT
);
821 MSSAU
->getMemorySSA()->verifyMemorySSA();
824 assert(DT
.verify(DominatorTree::VerificationLevel::Fast
));
826 // We may have changed the nesting relationship for this loop so hoist it to
827 // its correct parent if needed.
828 hoistLoopToNewParent(L
, *NewPH
, DT
, LI
, MSSAU
);
830 if (MSSAU
&& VerifyMemorySSA
)
831 MSSAU
->getMemorySSA()->verifyMemorySSA();
835 LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n");
839 /// This routine scans the loop to find a branch or switch which occurs before
840 /// any side effects occur. These can potentially be unswitched without
841 /// duplicating the loop. If a branch or switch is successfully unswitched the
842 /// scanning continues to see if subsequent branches or switches have become
843 /// trivial. Once all trivial candidates have been unswitched, this routine
846 /// The return value indicates whether anything was unswitched (and therefore
849 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
850 /// invalidated by this.
851 static bool unswitchAllTrivialConditions(Loop
&L
, DominatorTree
&DT
,
852 LoopInfo
&LI
, ScalarEvolution
*SE
,
853 MemorySSAUpdater
*MSSAU
) {
854 bool Changed
= false;
856 // If loop header has only one reachable successor we should keep looking for
857 // trivial condition candidates in the successor as well. An alternative is
858 // to constant fold conditions and merge successors into loop header (then we
859 // only need to check header's terminator). The reason for not doing this in
860 // LoopUnswitch pass is that it could potentially break LoopPassManager's
861 // invariants. Folding dead branches could either eliminate the current loop
862 // or make other loops unreachable. LCSSA form might also not be preserved
863 // after deleting branches. The following code keeps traversing loop header's
864 // successors until it finds the trivial condition candidate (condition that
865 // is not a constant). Since unswitching generates branches with constant
866 // conditions, this scenario could be very common in practice.
867 BasicBlock
*CurrentBB
= L
.getHeader();
868 SmallPtrSet
<BasicBlock
*, 8> Visited
;
869 Visited
.insert(CurrentBB
);
871 // Check if there are any side-effecting instructions (e.g. stores, calls,
872 // volatile loads) in the part of the loop that the code *would* execute
873 // without unswitching.
874 if (MSSAU
) // Possible early exit with MSSA
875 if (auto *Defs
= MSSAU
->getMemorySSA()->getBlockDefs(CurrentBB
))
876 if (!isa
<MemoryPhi
>(*Defs
->begin()) || (++Defs
->begin() != Defs
->end()))
878 if (llvm::any_of(*CurrentBB
,
879 [](Instruction
&I
) { return I
.mayHaveSideEffects(); }))
882 Instruction
*CurrentTerm
= CurrentBB
->getTerminator();
884 if (auto *SI
= dyn_cast
<SwitchInst
>(CurrentTerm
)) {
885 // Don't bother trying to unswitch past a switch with a constant
886 // condition. This should be removed prior to running this pass by
888 if (isa
<Constant
>(SI
->getCondition()))
891 if (!unswitchTrivialSwitch(L
, *SI
, DT
, LI
, SE
, MSSAU
))
892 // Couldn't unswitch this one so we're done.
895 // Mark that we managed to unswitch something.
898 // If unswitching turned the terminator into an unconditional branch then
899 // we can continue. The unswitching logic specifically works to fold any
900 // cases it can into an unconditional branch to make it easier to
902 auto *BI
= dyn_cast
<BranchInst
>(CurrentBB
->getTerminator());
903 if (!BI
|| BI
->isConditional())
906 CurrentBB
= BI
->getSuccessor(0);
910 auto *BI
= dyn_cast
<BranchInst
>(CurrentTerm
);
912 // We do not understand other terminator instructions.
915 // Don't bother trying to unswitch past an unconditional branch or a branch
916 // with a constant value. These should be removed by simplify-cfg prior to
917 // running this pass.
918 if (!BI
->isConditional() || isa
<Constant
>(BI
->getCondition()))
921 // Found a trivial condition candidate: non-foldable conditional branch. If
922 // we fail to unswitch this, we can't do anything else that is trivial.
923 if (!unswitchTrivialBranch(L
, *BI
, DT
, LI
, SE
, MSSAU
))
926 // Mark that we managed to unswitch something.
929 // If we only unswitched some of the conditions feeding the branch, we won't
930 // have collapsed it to a single successor.
931 BI
= cast
<BranchInst
>(CurrentBB
->getTerminator());
932 if (BI
->isConditional())
935 // Follow the newly unconditional branch into its successor.
936 CurrentBB
= BI
->getSuccessor(0);
938 // When continuing, if we exit the loop or reach a previous visited block,
939 // then we can not reach any trivial condition candidates (unfoldable
940 // branch instructions or switch instructions) and no unswitch can happen.
941 } while (L
.contains(CurrentBB
) && Visited
.insert(CurrentBB
).second
);
946 /// Build the cloned blocks for an unswitched copy of the given loop.
948 /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
949 /// after the split block (`SplitBB`) that will be used to select between the
950 /// cloned and original loop.
952 /// This routine handles cloning all of the necessary loop blocks and exit
953 /// blocks including rewriting their instructions and the relevant PHI nodes.
954 /// Any loop blocks or exit blocks which are dominated by a different successor
955 /// than the one for this clone of the loop blocks can be trivially skipped. We
956 /// use the `DominatingSucc` map to determine whether a block satisfies that
957 /// property with a simple map lookup.
959 /// It also correctly creates the unconditional branch in the cloned
960 /// unswitched parent block to only point at the unswitched successor.
962 /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
963 /// block splitting is correctly reflected in `LoopInfo`, essentially all of
964 /// the cloned blocks (and their loops) are left without full `LoopInfo`
965 /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
966 /// blocks to them but doesn't create the cloned `DominatorTree` structure and
967 /// instead the caller must recompute an accurate DT. It *does* correctly
968 /// update the `AssumptionCache` provided in `AC`.
969 static BasicBlock
*buildClonedLoopBlocks(
970 Loop
&L
, BasicBlock
*LoopPH
, BasicBlock
*SplitBB
,
971 ArrayRef
<BasicBlock
*> ExitBlocks
, BasicBlock
*ParentBB
,
972 BasicBlock
*UnswitchedSuccBB
, BasicBlock
*ContinueSuccBB
,
973 const SmallDenseMap
<BasicBlock
*, BasicBlock
*, 16> &DominatingSucc
,
974 ValueToValueMapTy
&VMap
,
975 SmallVectorImpl
<DominatorTree::UpdateType
> &DTUpdates
, AssumptionCache
&AC
,
976 DominatorTree
&DT
, LoopInfo
&LI
, MemorySSAUpdater
*MSSAU
) {
977 SmallVector
<BasicBlock
*, 4> NewBlocks
;
978 NewBlocks
.reserve(L
.getNumBlocks() + ExitBlocks
.size());
980 // We will need to clone a bunch of blocks, wrap up the clone operation in
982 auto CloneBlock
= [&](BasicBlock
*OldBB
) {
983 // Clone the basic block and insert it before the new preheader.
984 BasicBlock
*NewBB
= CloneBasicBlock(OldBB
, VMap
, ".us", OldBB
->getParent());
985 NewBB
->moveBefore(LoopPH
);
987 // Record this block and the mapping.
988 NewBlocks
.push_back(NewBB
);
994 // We skip cloning blocks when they have a dominating succ that is not the
995 // succ we are cloning for.
996 auto SkipBlock
= [&](BasicBlock
*BB
) {
997 auto It
= DominatingSucc
.find(BB
);
998 return It
!= DominatingSucc
.end() && It
->second
!= UnswitchedSuccBB
;
1001 // First, clone the preheader.
1002 auto *ClonedPH
= CloneBlock(LoopPH
);
1004 // Then clone all the loop blocks, skipping the ones that aren't necessary.
1005 for (auto *LoopBB
: L
.blocks())
1006 if (!SkipBlock(LoopBB
))
1009 // Split all the loop exit edges so that when we clone the exit blocks, if
1010 // any of the exit blocks are *also* a preheader for some other loop, we
1011 // don't create multiple predecessors entering the loop header.
1012 for (auto *ExitBB
: ExitBlocks
) {
1013 if (SkipBlock(ExitBB
))
1016 // When we are going to clone an exit, we don't need to clone all the
1017 // instructions in the exit block and we want to ensure we have an easy
1018 // place to merge the CFG, so split the exit first. This is always safe to
1019 // do because there cannot be any non-loop predecessors of a loop exit in
1020 // loop simplified form.
1021 auto *MergeBB
= SplitBlock(ExitBB
, &ExitBB
->front(), &DT
, &LI
, MSSAU
);
1023 // Rearrange the names to make it easier to write test cases by having the
1024 // exit block carry the suffix rather than the merge block carrying the
1026 MergeBB
->takeName(ExitBB
);
1027 ExitBB
->setName(Twine(MergeBB
->getName()) + ".split");
1029 // Now clone the original exit block.
1030 auto *ClonedExitBB
= CloneBlock(ExitBB
);
1031 assert(ClonedExitBB
->getTerminator()->getNumSuccessors() == 1 &&
1032 "Exit block should have been split to have one successor!");
1033 assert(ClonedExitBB
->getTerminator()->getSuccessor(0) == MergeBB
&&
1034 "Cloned exit block has the wrong successor!");
1036 // Remap any cloned instructions and create a merge phi node for them.
1037 for (auto ZippedInsts
: llvm::zip_first(
1038 llvm::make_range(ExitBB
->begin(), std::prev(ExitBB
->end())),
1039 llvm::make_range(ClonedExitBB
->begin(),
1040 std::prev(ClonedExitBB
->end())))) {
1041 Instruction
&I
= std::get
<0>(ZippedInsts
);
1042 Instruction
&ClonedI
= std::get
<1>(ZippedInsts
);
1044 // The only instructions in the exit block should be PHI nodes and
1045 // potentially a landing pad.
1047 (isa
<PHINode
>(I
) || isa
<LandingPadInst
>(I
) || isa
<CatchPadInst
>(I
)) &&
1048 "Bad instruction in exit block!");
1049 // We should have a value map between the instruction and its clone.
1050 assert(VMap
.lookup(&I
) == &ClonedI
&& "Mismatch in the value map!");
1053 PHINode::Create(I
.getType(), /*NumReservedValues*/ 2, ".us-phi",
1054 &*MergeBB
->getFirstInsertionPt());
1055 I
.replaceAllUsesWith(MergePN
);
1056 MergePN
->addIncoming(&I
, ExitBB
);
1057 MergePN
->addIncoming(&ClonedI
, ClonedExitBB
);
1061 // Rewrite the instructions in the cloned blocks to refer to the instructions
1062 // in the cloned blocks. We have to do this as a second pass so that we have
1063 // everything available. Also, we have inserted new instructions which may
1064 // include assume intrinsics, so we update the assumption cache while
1066 for (auto *ClonedBB
: NewBlocks
)
1067 for (Instruction
&I
: *ClonedBB
) {
1068 RemapInstruction(&I
, VMap
,
1069 RF_NoModuleLevelChanges
| RF_IgnoreMissingLocals
);
1070 if (auto *II
= dyn_cast
<IntrinsicInst
>(&I
))
1071 if (II
->getIntrinsicID() == Intrinsic::assume
)
1072 AC
.registerAssumption(II
);
1075 // Update any PHI nodes in the cloned successors of the skipped blocks to not
1076 // have spurious incoming values.
1077 for (auto *LoopBB
: L
.blocks())
1078 if (SkipBlock(LoopBB
))
1079 for (auto *SuccBB
: successors(LoopBB
))
1080 if (auto *ClonedSuccBB
= cast_or_null
<BasicBlock
>(VMap
.lookup(SuccBB
)))
1081 for (PHINode
&PN
: ClonedSuccBB
->phis())
1082 PN
.removeIncomingValue(LoopBB
, /*DeletePHIIfEmpty*/ false);
1084 // Remove the cloned parent as a predecessor of any successor we ended up
1085 // cloning other than the unswitched one.
1086 auto *ClonedParentBB
= cast
<BasicBlock
>(VMap
.lookup(ParentBB
));
1087 for (auto *SuccBB
: successors(ParentBB
)) {
1088 if (SuccBB
== UnswitchedSuccBB
)
1091 auto *ClonedSuccBB
= cast_or_null
<BasicBlock
>(VMap
.lookup(SuccBB
));
1095 ClonedSuccBB
->removePredecessor(ClonedParentBB
,
1096 /*KeepOneInputPHIs*/ true);
1099 // Replace the cloned branch with an unconditional branch to the cloned
1100 // unswitched successor.
1101 auto *ClonedSuccBB
= cast
<BasicBlock
>(VMap
.lookup(UnswitchedSuccBB
));
1102 ClonedParentBB
->getTerminator()->eraseFromParent();
1103 BranchInst::Create(ClonedSuccBB
, ClonedParentBB
);
1105 // If there are duplicate entries in the PHI nodes because of multiple edges
1106 // to the unswitched successor, we need to nuke all but one as we replaced it
1107 // with a direct branch.
1108 for (PHINode
&PN
: ClonedSuccBB
->phis()) {
1110 // Loop over the incoming operands backwards so we can easily delete as we
1111 // go without invalidating the index.
1112 for (int i
= PN
.getNumOperands() - 1; i
>= 0; --i
) {
1113 if (PN
.getIncomingBlock(i
) != ClonedParentBB
)
1119 PN
.removeIncomingValue(i
, /*DeletePHIIfEmpty*/ false);
1123 // Record the domtree updates for the new blocks.
1124 SmallPtrSet
<BasicBlock
*, 4> SuccSet
;
1125 for (auto *ClonedBB
: NewBlocks
) {
1126 for (auto *SuccBB
: successors(ClonedBB
))
1127 if (SuccSet
.insert(SuccBB
).second
)
1128 DTUpdates
.push_back({DominatorTree::Insert
, ClonedBB
, SuccBB
});
1135 /// Recursively clone the specified loop and all of its children.
1137 /// The target parent loop for the clone should be provided, or can be null if
1138 /// the clone is a top-level loop. While cloning, all the blocks are mapped
1139 /// with the provided value map. The entire original loop must be present in
1140 /// the value map. The cloned loop is returned.
1141 static Loop
*cloneLoopNest(Loop
&OrigRootL
, Loop
*RootParentL
,
1142 const ValueToValueMapTy
&VMap
, LoopInfo
&LI
) {
1143 auto AddClonedBlocksToLoop
= [&](Loop
&OrigL
, Loop
&ClonedL
) {
1144 assert(ClonedL
.getBlocks().empty() && "Must start with an empty loop!");
1145 ClonedL
.reserveBlocks(OrigL
.getNumBlocks());
1146 for (auto *BB
: OrigL
.blocks()) {
1147 auto *ClonedBB
= cast
<BasicBlock
>(VMap
.lookup(BB
));
1148 ClonedL
.addBlockEntry(ClonedBB
);
1149 if (LI
.getLoopFor(BB
) == &OrigL
)
1150 LI
.changeLoopFor(ClonedBB
, &ClonedL
);
1154 // We specially handle the first loop because it may get cloned into
1155 // a different parent and because we most commonly are cloning leaf loops.
1156 Loop
*ClonedRootL
= LI
.AllocateLoop();
1158 RootParentL
->addChildLoop(ClonedRootL
);
1160 LI
.addTopLevelLoop(ClonedRootL
);
1161 AddClonedBlocksToLoop(OrigRootL
, *ClonedRootL
);
1163 if (OrigRootL
.empty())
1166 // If we have a nest, we can quickly clone the entire loop nest using an
1167 // iterative approach because it is a tree. We keep the cloned parent in the
1168 // data structure to avoid repeatedly querying through a map to find it.
1169 SmallVector
<std::pair
<Loop
*, Loop
*>, 16> LoopsToClone
;
1170 // Build up the loops to clone in reverse order as we'll clone them from the
1172 for (Loop
*ChildL
: llvm::reverse(OrigRootL
))
1173 LoopsToClone
.push_back({ClonedRootL
, ChildL
});
1175 Loop
*ClonedParentL
, *L
;
1176 std::tie(ClonedParentL
, L
) = LoopsToClone
.pop_back_val();
1177 Loop
*ClonedL
= LI
.AllocateLoop();
1178 ClonedParentL
->addChildLoop(ClonedL
);
1179 AddClonedBlocksToLoop(*L
, *ClonedL
);
1180 for (Loop
*ChildL
: llvm::reverse(*L
))
1181 LoopsToClone
.push_back({ClonedL
, ChildL
});
1182 } while (!LoopsToClone
.empty());
1187 /// Build the cloned loops of an original loop from unswitching.
1189 /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1190 /// operation. We need to re-verify that there even is a loop (as the backedge
1191 /// may not have been cloned), and even if there are remaining backedges the
1192 /// backedge set may be different. However, we know that each child loop is
1193 /// undisturbed, we only need to find where to place each child loop within
1194 /// either any parent loop or within a cloned version of the original loop.
1196 /// Because child loops may end up cloned outside of any cloned version of the
1197 /// original loop, multiple cloned sibling loops may be created. All of them
1198 /// are returned so that the newly introduced loop nest roots can be
1200 static void buildClonedLoops(Loop
&OrigL
, ArrayRef
<BasicBlock
*> ExitBlocks
,
1201 const ValueToValueMapTy
&VMap
, LoopInfo
&LI
,
1202 SmallVectorImpl
<Loop
*> &NonChildClonedLoops
) {
1203 Loop
*ClonedL
= nullptr;
1205 auto *OrigPH
= OrigL
.getLoopPreheader();
1206 auto *OrigHeader
= OrigL
.getHeader();
1208 auto *ClonedPH
= cast
<BasicBlock
>(VMap
.lookup(OrigPH
));
1209 auto *ClonedHeader
= cast
<BasicBlock
>(VMap
.lookup(OrigHeader
));
1211 // We need to know the loops of the cloned exit blocks to even compute the
1212 // accurate parent loop. If we only clone exits to some parent of the
1213 // original parent, we want to clone into that outer loop. We also keep track
1214 // of the loops that our cloned exit blocks participate in.
1215 Loop
*ParentL
= nullptr;
1216 SmallVector
<BasicBlock
*, 4> ClonedExitsInLoops
;
1217 SmallDenseMap
<BasicBlock
*, Loop
*, 16> ExitLoopMap
;
1218 ClonedExitsInLoops
.reserve(ExitBlocks
.size());
1219 for (auto *ExitBB
: ExitBlocks
)
1220 if (auto *ClonedExitBB
= cast_or_null
<BasicBlock
>(VMap
.lookup(ExitBB
)))
1221 if (Loop
*ExitL
= LI
.getLoopFor(ExitBB
)) {
1222 ExitLoopMap
[ClonedExitBB
] = ExitL
;
1223 ClonedExitsInLoops
.push_back(ClonedExitBB
);
1224 if (!ParentL
|| (ParentL
!= ExitL
&& ParentL
->contains(ExitL
)))
1227 assert((!ParentL
|| ParentL
== OrigL
.getParentLoop() ||
1228 ParentL
->contains(OrigL
.getParentLoop())) &&
1229 "The computed parent loop should always contain (or be) the parent of "
1230 "the original loop.");
1232 // We build the set of blocks dominated by the cloned header from the set of
1233 // cloned blocks out of the original loop. While not all of these will
1234 // necessarily be in the cloned loop, it is enough to establish that they
1235 // aren't in unreachable cycles, etc.
1236 SmallSetVector
<BasicBlock
*, 16> ClonedLoopBlocks
;
1237 for (auto *BB
: OrigL
.blocks())
1238 if (auto *ClonedBB
= cast_or_null
<BasicBlock
>(VMap
.lookup(BB
)))
1239 ClonedLoopBlocks
.insert(ClonedBB
);
1241 // Rebuild the set of blocks that will end up in the cloned loop. We may have
1242 // skipped cloning some region of this loop which can in turn skip some of
1243 // the backedges so we have to rebuild the blocks in the loop based on the
1244 // backedges that remain after cloning.
1245 SmallVector
<BasicBlock
*, 16> Worklist
;
1246 SmallPtrSet
<BasicBlock
*, 16> BlocksInClonedLoop
;
1247 for (auto *Pred
: predecessors(ClonedHeader
)) {
1248 // The only possible non-loop header predecessor is the preheader because
1249 // we know we cloned the loop in simplified form.
1250 if (Pred
== ClonedPH
)
1253 // Because the loop was in simplified form, the only non-loop predecessor
1254 // should be the preheader.
1255 assert(ClonedLoopBlocks
.count(Pred
) && "Found a predecessor of the loop "
1256 "header other than the preheader "
1257 "that is not part of the loop!");
1259 // Insert this block into the loop set and on the first visit (and if it
1260 // isn't the header we're currently walking) put it into the worklist to
1262 if (BlocksInClonedLoop
.insert(Pred
).second
&& Pred
!= ClonedHeader
)
1263 Worklist
.push_back(Pred
);
1266 // If we had any backedges then there *is* a cloned loop. Put the header into
1267 // the loop set and then walk the worklist backwards to find all the blocks
1268 // that remain within the loop after cloning.
1269 if (!BlocksInClonedLoop
.empty()) {
1270 BlocksInClonedLoop
.insert(ClonedHeader
);
1272 while (!Worklist
.empty()) {
1273 BasicBlock
*BB
= Worklist
.pop_back_val();
1274 assert(BlocksInClonedLoop
.count(BB
) &&
1275 "Didn't put block into the loop set!");
1277 // Insert any predecessors that are in the possible set into the cloned
1278 // set, and if the insert is successful, add them to the worklist. Note
1279 // that we filter on the blocks that are definitely reachable via the
1280 // backedge to the loop header so we may prune out dead code within the
1282 for (auto *Pred
: predecessors(BB
))
1283 if (ClonedLoopBlocks
.count(Pred
) &&
1284 BlocksInClonedLoop
.insert(Pred
).second
)
1285 Worklist
.push_back(Pred
);
1288 ClonedL
= LI
.AllocateLoop();
1290 ParentL
->addBasicBlockToLoop(ClonedPH
, LI
);
1291 ParentL
->addChildLoop(ClonedL
);
1293 LI
.addTopLevelLoop(ClonedL
);
1295 NonChildClonedLoops
.push_back(ClonedL
);
1297 ClonedL
->reserveBlocks(BlocksInClonedLoop
.size());
1298 // We don't want to just add the cloned loop blocks based on how we
1299 // discovered them. The original order of blocks was carefully built in
1300 // a way that doesn't rely on predecessor ordering. Rather than re-invent
1301 // that logic, we just re-walk the original blocks (and those of the child
1302 // loops) and filter them as we add them into the cloned loop.
1303 for (auto *BB
: OrigL
.blocks()) {
1304 auto *ClonedBB
= cast_or_null
<BasicBlock
>(VMap
.lookup(BB
));
1305 if (!ClonedBB
|| !BlocksInClonedLoop
.count(ClonedBB
))
1308 // Directly add the blocks that are only in this loop.
1309 if (LI
.getLoopFor(BB
) == &OrigL
) {
1310 ClonedL
->addBasicBlockToLoop(ClonedBB
, LI
);
1314 // We want to manually add it to this loop and parents.
1315 // Registering it with LoopInfo will happen when we clone the top
1316 // loop for this block.
1317 for (Loop
*PL
= ClonedL
; PL
; PL
= PL
->getParentLoop())
1318 PL
->addBlockEntry(ClonedBB
);
1321 // Now add each child loop whose header remains within the cloned loop. All
1322 // of the blocks within the loop must satisfy the same constraints as the
1323 // header so once we pass the header checks we can just clone the entire
1325 for (Loop
*ChildL
: OrigL
) {
1326 auto *ClonedChildHeader
=
1327 cast_or_null
<BasicBlock
>(VMap
.lookup(ChildL
->getHeader()));
1328 if (!ClonedChildHeader
|| !BlocksInClonedLoop
.count(ClonedChildHeader
))
1332 // We should never have a cloned child loop header but fail to have
1333 // all of the blocks for that child loop.
1334 for (auto *ChildLoopBB
: ChildL
->blocks())
1335 assert(BlocksInClonedLoop
.count(
1336 cast
<BasicBlock
>(VMap
.lookup(ChildLoopBB
))) &&
1337 "Child cloned loop has a header within the cloned outer "
1338 "loop but not all of its blocks!");
1341 cloneLoopNest(*ChildL
, ClonedL
, VMap
, LI
);
1345 // Now that we've handled all the components of the original loop that were
1346 // cloned into a new loop, we still need to handle anything from the original
1347 // loop that wasn't in a cloned loop.
1349 // Figure out what blocks are left to place within any loop nest containing
1350 // the unswitched loop. If we never formed a loop, the cloned PH is one of
1352 SmallPtrSet
<BasicBlock
*, 16> UnloopedBlockSet
;
1353 if (BlocksInClonedLoop
.empty())
1354 UnloopedBlockSet
.insert(ClonedPH
);
1355 for (auto *ClonedBB
: ClonedLoopBlocks
)
1356 if (!BlocksInClonedLoop
.count(ClonedBB
))
1357 UnloopedBlockSet
.insert(ClonedBB
);
1359 // Copy the cloned exits and sort them in ascending loop depth, we'll work
1360 // backwards across these to process them inside out. The order shouldn't
1361 // matter as we're just trying to build up the map from inside-out; we use
1362 // the map in a more stably ordered way below.
1363 auto OrderedClonedExitsInLoops
= ClonedExitsInLoops
;
1364 llvm::sort(OrderedClonedExitsInLoops
, [&](BasicBlock
*LHS
, BasicBlock
*RHS
) {
1365 return ExitLoopMap
.lookup(LHS
)->getLoopDepth() <
1366 ExitLoopMap
.lookup(RHS
)->getLoopDepth();
1369 // Populate the existing ExitLoopMap with everything reachable from each
1370 // exit, starting from the inner most exit.
1371 while (!UnloopedBlockSet
.empty() && !OrderedClonedExitsInLoops
.empty()) {
1372 assert(Worklist
.empty() && "Didn't clear worklist!");
1374 BasicBlock
*ExitBB
= OrderedClonedExitsInLoops
.pop_back_val();
1375 Loop
*ExitL
= ExitLoopMap
.lookup(ExitBB
);
1377 // Walk the CFG back until we hit the cloned PH adding everything reachable
1378 // and in the unlooped set to this exit block's loop.
1379 Worklist
.push_back(ExitBB
);
1381 BasicBlock
*BB
= Worklist
.pop_back_val();
1382 // We can stop recursing at the cloned preheader (if we get there).
1386 for (BasicBlock
*PredBB
: predecessors(BB
)) {
1387 // If this pred has already been moved to our set or is part of some
1388 // (inner) loop, no update needed.
1389 if (!UnloopedBlockSet
.erase(PredBB
)) {
1391 (BlocksInClonedLoop
.count(PredBB
) || ExitLoopMap
.count(PredBB
)) &&
1392 "Predecessor not mapped to a loop!");
1396 // We just insert into the loop set here. We'll add these blocks to the
1397 // exit loop after we build up the set in an order that doesn't rely on
1398 // predecessor order (which in turn relies on use list order).
1399 bool Inserted
= ExitLoopMap
.insert({PredBB
, ExitL
}).second
;
1401 assert(Inserted
&& "Should only visit an unlooped block once!");
1403 // And recurse through to its predecessors.
1404 Worklist
.push_back(PredBB
);
1406 } while (!Worklist
.empty());
1409 // Now that the ExitLoopMap gives as mapping for all the non-looping cloned
1410 // blocks to their outer loops, walk the cloned blocks and the cloned exits
1411 // in their original order adding them to the correct loop.
1413 // We need a stable insertion order. We use the order of the original loop
1414 // order and map into the correct parent loop.
1415 for (auto *BB
: llvm::concat
<BasicBlock
*const>(
1416 makeArrayRef(ClonedPH
), ClonedLoopBlocks
, ClonedExitsInLoops
))
1417 if (Loop
*OuterL
= ExitLoopMap
.lookup(BB
))
1418 OuterL
->addBasicBlockToLoop(BB
, LI
);
1421 for (auto &BBAndL
: ExitLoopMap
) {
1422 auto *BB
= BBAndL
.first
;
1423 auto *OuterL
= BBAndL
.second
;
1424 assert(LI
.getLoopFor(BB
) == OuterL
&&
1425 "Failed to put all blocks into outer loops!");
1429 // Now that all the blocks are placed into the correct containing loop in the
1430 // absence of child loops, find all the potentially cloned child loops and
1431 // clone them into whatever outer loop we placed their header into.
1432 for (Loop
*ChildL
: OrigL
) {
1433 auto *ClonedChildHeader
=
1434 cast_or_null
<BasicBlock
>(VMap
.lookup(ChildL
->getHeader()));
1435 if (!ClonedChildHeader
|| BlocksInClonedLoop
.count(ClonedChildHeader
))
1439 for (auto *ChildLoopBB
: ChildL
->blocks())
1440 assert(VMap
.count(ChildLoopBB
) &&
1441 "Cloned a child loop header but not all of that loops blocks!");
1444 NonChildClonedLoops
.push_back(cloneLoopNest(
1445 *ChildL
, ExitLoopMap
.lookup(ClonedChildHeader
), VMap
, LI
));
1450 deleteDeadClonedBlocks(Loop
&L
, ArrayRef
<BasicBlock
*> ExitBlocks
,
1451 ArrayRef
<std::unique_ptr
<ValueToValueMapTy
>> VMaps
,
1452 DominatorTree
&DT
, MemorySSAUpdater
*MSSAU
) {
1453 // Find all the dead clones, and remove them from their successors.
1454 SmallVector
<BasicBlock
*, 16> DeadBlocks
;
1455 for (BasicBlock
*BB
: llvm::concat
<BasicBlock
*const>(L
.blocks(), ExitBlocks
))
1456 for (auto &VMap
: VMaps
)
1457 if (BasicBlock
*ClonedBB
= cast_or_null
<BasicBlock
>(VMap
->lookup(BB
)))
1458 if (!DT
.isReachableFromEntry(ClonedBB
)) {
1459 for (BasicBlock
*SuccBB
: successors(ClonedBB
))
1460 SuccBB
->removePredecessor(ClonedBB
);
1461 DeadBlocks
.push_back(ClonedBB
);
1464 // Remove all MemorySSA in the dead blocks
1466 SmallSetVector
<BasicBlock
*, 8> DeadBlockSet(DeadBlocks
.begin(),
1468 MSSAU
->removeBlocks(DeadBlockSet
);
1471 // Drop any remaining references to break cycles.
1472 for (BasicBlock
*BB
: DeadBlocks
)
1473 BB
->dropAllReferences();
1474 // Erase them from the IR.
1475 for (BasicBlock
*BB
: DeadBlocks
)
1476 BB
->eraseFromParent();
1479 static void deleteDeadBlocksFromLoop(Loop
&L
,
1480 SmallVectorImpl
<BasicBlock
*> &ExitBlocks
,
1481 DominatorTree
&DT
, LoopInfo
&LI
,
1482 MemorySSAUpdater
*MSSAU
) {
1483 // Find all the dead blocks tied to this loop, and remove them from their
1485 SmallSetVector
<BasicBlock
*, 8> DeadBlockSet
;
1487 // Start with loop/exit blocks and get a transitive closure of reachable dead
1489 SmallVector
<BasicBlock
*, 16> DeathCandidates(ExitBlocks
.begin(),
1491 DeathCandidates
.append(L
.blocks().begin(), L
.blocks().end());
1492 while (!DeathCandidates
.empty()) {
1493 auto *BB
= DeathCandidates
.pop_back_val();
1494 if (!DeadBlockSet
.count(BB
) && !DT
.isReachableFromEntry(BB
)) {
1495 for (BasicBlock
*SuccBB
: successors(BB
)) {
1496 SuccBB
->removePredecessor(BB
);
1497 DeathCandidates
.push_back(SuccBB
);
1499 DeadBlockSet
.insert(BB
);
1503 // Remove all MemorySSA in the dead blocks
1505 MSSAU
->removeBlocks(DeadBlockSet
);
1507 // Filter out the dead blocks from the exit blocks list so that it can be
1508 // used in the caller.
1509 llvm::erase_if(ExitBlocks
,
1510 [&](BasicBlock
*BB
) { return DeadBlockSet
.count(BB
); });
1512 // Walk from this loop up through its parents removing all of the dead blocks.
1513 for (Loop
*ParentL
= &L
; ParentL
; ParentL
= ParentL
->getParentLoop()) {
1514 for (auto *BB
: DeadBlockSet
)
1515 ParentL
->getBlocksSet().erase(BB
);
1516 llvm::erase_if(ParentL
->getBlocksVector(),
1517 [&](BasicBlock
*BB
) { return DeadBlockSet
.count(BB
); });
1520 // Now delete the dead child loops. This raw delete will clear them
1522 llvm::erase_if(L
.getSubLoopsVector(), [&](Loop
*ChildL
) {
1523 if (!DeadBlockSet
.count(ChildL
->getHeader()))
1526 assert(llvm::all_of(ChildL
->blocks(),
1527 [&](BasicBlock
*ChildBB
) {
1528 return DeadBlockSet
.count(ChildBB
);
1530 "If the child loop header is dead all blocks in the child loop must "
1531 "be dead as well!");
1536 // Remove the loop mappings for the dead blocks and drop all the references
1537 // from these blocks to others to handle cyclic references as we start
1538 // deleting the blocks themselves.
1539 for (auto *BB
: DeadBlockSet
) {
1540 // Check that the dominator tree has already been updated.
1541 assert(!DT
.getNode(BB
) && "Should already have cleared domtree!");
1542 LI
.changeLoopFor(BB
, nullptr);
1543 BB
->dropAllReferences();
1546 // Actually delete the blocks now that they've been fully unhooked from the
1548 for (auto *BB
: DeadBlockSet
)
1549 BB
->eraseFromParent();
1552 /// Recompute the set of blocks in a loop after unswitching.
1554 /// This walks from the original headers predecessors to rebuild the loop. We
1555 /// take advantage of the fact that new blocks can't have been added, and so we
1556 /// filter by the original loop's blocks. This also handles potentially
1557 /// unreachable code that we don't want to explore but might be found examining
1558 /// the predecessors of the header.
1560 /// If the original loop is no longer a loop, this will return an empty set. If
1561 /// it remains a loop, all the blocks within it will be added to the set
1562 /// (including those blocks in inner loops).
1563 static SmallPtrSet
<const BasicBlock
*, 16> recomputeLoopBlockSet(Loop
&L
,
1565 SmallPtrSet
<const BasicBlock
*, 16> LoopBlockSet
;
1567 auto *PH
= L
.getLoopPreheader();
1568 auto *Header
= L
.getHeader();
1570 // A worklist to use while walking backwards from the header.
1571 SmallVector
<BasicBlock
*, 16> Worklist
;
1573 // First walk the predecessors of the header to find the backedges. This will
1574 // form the basis of our walk.
1575 for (auto *Pred
: predecessors(Header
)) {
1576 // Skip the preheader.
1580 // Because the loop was in simplified form, the only non-loop predecessor
1581 // is the preheader.
1582 assert(L
.contains(Pred
) && "Found a predecessor of the loop header other "
1583 "than the preheader that is not part of the "
1586 // Insert this block into the loop set and on the first visit and, if it
1587 // isn't the header we're currently walking, put it into the worklist to
1589 if (LoopBlockSet
.insert(Pred
).second
&& Pred
!= Header
)
1590 Worklist
.push_back(Pred
);
1593 // If no backedges were found, we're done.
1594 if (LoopBlockSet
.empty())
1595 return LoopBlockSet
;
1597 // We found backedges, recurse through them to identify the loop blocks.
1598 while (!Worklist
.empty()) {
1599 BasicBlock
*BB
= Worklist
.pop_back_val();
1600 assert(LoopBlockSet
.count(BB
) && "Didn't put block into the loop set!");
1602 // No need to walk past the header.
1606 // Because we know the inner loop structure remains valid we can use the
1607 // loop structure to jump immediately across the entire nested loop.
1608 // Further, because it is in loop simplified form, we can directly jump
1609 // to its preheader afterward.
1610 if (Loop
*InnerL
= LI
.getLoopFor(BB
))
1612 assert(L
.contains(InnerL
) &&
1613 "Should not reach a loop *outside* this loop!");
1614 // The preheader is the only possible predecessor of the loop so
1615 // insert it into the set and check whether it was already handled.
1616 auto *InnerPH
= InnerL
->getLoopPreheader();
1617 assert(L
.contains(InnerPH
) && "Cannot contain an inner loop block "
1618 "but not contain the inner loop "
1620 if (!LoopBlockSet
.insert(InnerPH
).second
)
1621 // The only way to reach the preheader is through the loop body
1622 // itself so if it has been visited the loop is already handled.
1625 // Insert all of the blocks (other than those already present) into
1626 // the loop set. We expect at least the block that led us to find the
1627 // inner loop to be in the block set, but we may also have other loop
1628 // blocks if they were already enqueued as predecessors of some other
1629 // outer loop block.
1630 for (auto *InnerBB
: InnerL
->blocks()) {
1631 if (InnerBB
== BB
) {
1632 assert(LoopBlockSet
.count(InnerBB
) &&
1633 "Block should already be in the set!");
1637 LoopBlockSet
.insert(InnerBB
);
1640 // Add the preheader to the worklist so we will continue past the
1642 Worklist
.push_back(InnerPH
);
1646 // Insert any predecessors that were in the original loop into the new
1647 // set, and if the insert is successful, add them to the worklist.
1648 for (auto *Pred
: predecessors(BB
))
1649 if (L
.contains(Pred
) && LoopBlockSet
.insert(Pred
).second
)
1650 Worklist
.push_back(Pred
);
1653 assert(LoopBlockSet
.count(Header
) && "Cannot fail to add the header!");
1655 // We've found all the blocks participating in the loop, return our completed
1657 return LoopBlockSet
;
1660 /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1662 /// The removal may have removed some child loops entirely but cannot have
1663 /// disturbed any remaining child loops. However, they may need to be hoisted
1664 /// to the parent loop (or to be top-level loops). The original loop may be
1665 /// completely removed.
1667 /// The sibling loops resulting from this update are returned. If the original
1668 /// loop remains a valid loop, it will be the first entry in this list with all
1669 /// of the newly sibling loops following it.
1671 /// Returns true if the loop remains a loop after unswitching, and false if it
1672 /// is no longer a loop after unswitching (and should not continue to be
1674 static bool rebuildLoopAfterUnswitch(Loop
&L
, ArrayRef
<BasicBlock
*> ExitBlocks
,
1676 SmallVectorImpl
<Loop
*> &HoistedLoops
) {
1677 auto *PH
= L
.getLoopPreheader();
1679 // Compute the actual parent loop from the exit blocks. Because we may have
1680 // pruned some exits the loop may be different from the original parent.
1681 Loop
*ParentL
= nullptr;
1682 SmallVector
<Loop
*, 4> ExitLoops
;
1683 SmallVector
<BasicBlock
*, 4> ExitsInLoops
;
1684 ExitsInLoops
.reserve(ExitBlocks
.size());
1685 for (auto *ExitBB
: ExitBlocks
)
1686 if (Loop
*ExitL
= LI
.getLoopFor(ExitBB
)) {
1687 ExitLoops
.push_back(ExitL
);
1688 ExitsInLoops
.push_back(ExitBB
);
1689 if (!ParentL
|| (ParentL
!= ExitL
&& ParentL
->contains(ExitL
)))
1693 // Recompute the blocks participating in this loop. This may be empty if it
1694 // is no longer a loop.
1695 auto LoopBlockSet
= recomputeLoopBlockSet(L
, LI
);
1697 // If we still have a loop, we need to re-set the loop's parent as the exit
1698 // block set changing may have moved it within the loop nest. Note that this
1699 // can only happen when this loop has a parent as it can only hoist the loop
1701 if (!LoopBlockSet
.empty() && L
.getParentLoop() != ParentL
) {
1702 // Remove this loop's (original) blocks from all of the intervening loops.
1703 for (Loop
*IL
= L
.getParentLoop(); IL
!= ParentL
;
1704 IL
= IL
->getParentLoop()) {
1705 IL
->getBlocksSet().erase(PH
);
1706 for (auto *BB
: L
.blocks())
1707 IL
->getBlocksSet().erase(BB
);
1708 llvm::erase_if(IL
->getBlocksVector(), [&](BasicBlock
*BB
) {
1709 return BB
== PH
|| L
.contains(BB
);
1713 LI
.changeLoopFor(PH
, ParentL
);
1714 L
.getParentLoop()->removeChildLoop(&L
);
1716 ParentL
->addChildLoop(&L
);
1718 LI
.addTopLevelLoop(&L
);
1721 // Now we update all the blocks which are no longer within the loop.
1722 auto &Blocks
= L
.getBlocksVector();
1724 LoopBlockSet
.empty()
1726 : std::stable_partition(
1727 Blocks
.begin(), Blocks
.end(),
1728 [&](BasicBlock
*BB
) { return LoopBlockSet
.count(BB
); });
1730 // Before we erase the list of unlooped blocks, build a set of them.
1731 SmallPtrSet
<BasicBlock
*, 16> UnloopedBlocks(BlocksSplitI
, Blocks
.end());
1732 if (LoopBlockSet
.empty())
1733 UnloopedBlocks
.insert(PH
);
1735 // Now erase these blocks from the loop.
1736 for (auto *BB
: make_range(BlocksSplitI
, Blocks
.end()))
1737 L
.getBlocksSet().erase(BB
);
1738 Blocks
.erase(BlocksSplitI
, Blocks
.end());
1740 // Sort the exits in ascending loop depth, we'll work backwards across these
1741 // to process them inside out.
1742 llvm::stable_sort(ExitsInLoops
, [&](BasicBlock
*LHS
, BasicBlock
*RHS
) {
1743 return LI
.getLoopDepth(LHS
) < LI
.getLoopDepth(RHS
);
1746 // We'll build up a set for each exit loop.
1747 SmallPtrSet
<BasicBlock
*, 16> NewExitLoopBlocks
;
1748 Loop
*PrevExitL
= L
.getParentLoop(); // The deepest possible exit loop.
1750 auto RemoveUnloopedBlocksFromLoop
=
1751 [](Loop
&L
, SmallPtrSetImpl
<BasicBlock
*> &UnloopedBlocks
) {
1752 for (auto *BB
: UnloopedBlocks
)
1753 L
.getBlocksSet().erase(BB
);
1754 llvm::erase_if(L
.getBlocksVector(), [&](BasicBlock
*BB
) {
1755 return UnloopedBlocks
.count(BB
);
1759 SmallVector
<BasicBlock
*, 16> Worklist
;
1760 while (!UnloopedBlocks
.empty() && !ExitsInLoops
.empty()) {
1761 assert(Worklist
.empty() && "Didn't clear worklist!");
1762 assert(NewExitLoopBlocks
.empty() && "Didn't clear loop set!");
1764 // Grab the next exit block, in decreasing loop depth order.
1765 BasicBlock
*ExitBB
= ExitsInLoops
.pop_back_val();
1766 Loop
&ExitL
= *LI
.getLoopFor(ExitBB
);
1767 assert(ExitL
.contains(&L
) && "Exit loop must contain the inner loop!");
1769 // Erase all of the unlooped blocks from the loops between the previous
1770 // exit loop and this exit loop. This works because the ExitInLoops list is
1771 // sorted in increasing order of loop depth and thus we visit loops in
1772 // decreasing order of loop depth.
1773 for (; PrevExitL
!= &ExitL
; PrevExitL
= PrevExitL
->getParentLoop())
1774 RemoveUnloopedBlocksFromLoop(*PrevExitL
, UnloopedBlocks
);
1776 // Walk the CFG back until we hit the cloned PH adding everything reachable
1777 // and in the unlooped set to this exit block's loop.
1778 Worklist
.push_back(ExitBB
);
1780 BasicBlock
*BB
= Worklist
.pop_back_val();
1781 // We can stop recursing at the cloned preheader (if we get there).
1785 for (BasicBlock
*PredBB
: predecessors(BB
)) {
1786 // If this pred has already been moved to our set or is part of some
1787 // (inner) loop, no update needed.
1788 if (!UnloopedBlocks
.erase(PredBB
)) {
1789 assert((NewExitLoopBlocks
.count(PredBB
) ||
1790 ExitL
.contains(LI
.getLoopFor(PredBB
))) &&
1791 "Predecessor not in a nested loop (or already visited)!");
1795 // We just insert into the loop set here. We'll add these blocks to the
1796 // exit loop after we build up the set in a deterministic order rather
1797 // than the predecessor-influenced visit order.
1798 bool Inserted
= NewExitLoopBlocks
.insert(PredBB
).second
;
1800 assert(Inserted
&& "Should only visit an unlooped block once!");
1802 // And recurse through to its predecessors.
1803 Worklist
.push_back(PredBB
);
1805 } while (!Worklist
.empty());
1807 // If blocks in this exit loop were directly part of the original loop (as
1808 // opposed to a child loop) update the map to point to this exit loop. This
1809 // just updates a map and so the fact that the order is unstable is fine.
1810 for (auto *BB
: NewExitLoopBlocks
)
1811 if (Loop
*BBL
= LI
.getLoopFor(BB
))
1812 if (BBL
== &L
|| !L
.contains(BBL
))
1813 LI
.changeLoopFor(BB
, &ExitL
);
1815 // We will remove the remaining unlooped blocks from this loop in the next
1816 // iteration or below.
1817 NewExitLoopBlocks
.clear();
1820 // Any remaining unlooped blocks are no longer part of any loop unless they
1821 // are part of some child loop.
1822 for (; PrevExitL
; PrevExitL
= PrevExitL
->getParentLoop())
1823 RemoveUnloopedBlocksFromLoop(*PrevExitL
, UnloopedBlocks
);
1824 for (auto *BB
: UnloopedBlocks
)
1825 if (Loop
*BBL
= LI
.getLoopFor(BB
))
1826 if (BBL
== &L
|| !L
.contains(BBL
))
1827 LI
.changeLoopFor(BB
, nullptr);
1829 // Sink all the child loops whose headers are no longer in the loop set to
1830 // the parent (or to be top level loops). We reach into the loop and directly
1831 // update its subloop vector to make this batch update efficient.
1832 auto &SubLoops
= L
.getSubLoopsVector();
1833 auto SubLoopsSplitI
=
1834 LoopBlockSet
.empty()
1836 : std::stable_partition(
1837 SubLoops
.begin(), SubLoops
.end(), [&](Loop
*SubL
) {
1838 return LoopBlockSet
.count(SubL
->getHeader());
1840 for (auto *HoistedL
: make_range(SubLoopsSplitI
, SubLoops
.end())) {
1841 HoistedLoops
.push_back(HoistedL
);
1842 HoistedL
->setParentLoop(nullptr);
1844 // To compute the new parent of this hoisted loop we look at where we
1845 // placed the preheader above. We can't lookup the header itself because we
1846 // retained the mapping from the header to the hoisted loop. But the
1847 // preheader and header should have the exact same new parent computed
1848 // based on the set of exit blocks from the original loop as the preheader
1849 // is a predecessor of the header and so reached in the reverse walk. And
1850 // because the loops were all in simplified form the preheader of the
1851 // hoisted loop can't be part of some *other* loop.
1852 if (auto *NewParentL
= LI
.getLoopFor(HoistedL
->getLoopPreheader()))
1853 NewParentL
->addChildLoop(HoistedL
);
1855 LI
.addTopLevelLoop(HoistedL
);
1857 SubLoops
.erase(SubLoopsSplitI
, SubLoops
.end());
1859 // Actually delete the loop if nothing remained within it.
1860 if (Blocks
.empty()) {
1861 assert(SubLoops
.empty() &&
1862 "Failed to remove all subloops from the original loop!");
1863 if (Loop
*ParentL
= L
.getParentLoop())
1864 ParentL
->removeChildLoop(llvm::find(*ParentL
, &L
));
1866 LI
.removeLoop(llvm::find(LI
, &L
));
1874 /// Helper to visit a dominator subtree, invoking a callable on each node.
1876 /// Returning false at any point will stop walking past that node of the tree.
1877 template <typename CallableT
>
1878 void visitDomSubTree(DominatorTree
&DT
, BasicBlock
*BB
, CallableT Callable
) {
1879 SmallVector
<DomTreeNode
*, 4> DomWorklist
;
1880 DomWorklist
.push_back(DT
[BB
]);
1882 SmallPtrSet
<DomTreeNode
*, 4> Visited
;
1883 Visited
.insert(DT
[BB
]);
1886 DomTreeNode
*N
= DomWorklist
.pop_back_val();
1889 if (!Callable(N
->getBlock()))
1892 // Accumulate the child nodes.
1893 for (DomTreeNode
*ChildN
: *N
) {
1894 assert(Visited
.insert(ChildN
).second
&&
1895 "Cannot visit a node twice when walking a tree!");
1896 DomWorklist
.push_back(ChildN
);
1898 } while (!DomWorklist
.empty());
1901 static void unswitchNontrivialInvariants(
1902 Loop
&L
, Instruction
&TI
, ArrayRef
<Value
*> Invariants
,
1903 SmallVectorImpl
<BasicBlock
*> &ExitBlocks
, DominatorTree
&DT
, LoopInfo
&LI
,
1904 AssumptionCache
&AC
, function_ref
<void(bool, ArrayRef
<Loop
*>)> UnswitchCB
,
1905 ScalarEvolution
*SE
, MemorySSAUpdater
*MSSAU
) {
1906 auto *ParentBB
= TI
.getParent();
1907 BranchInst
*BI
= dyn_cast
<BranchInst
>(&TI
);
1908 SwitchInst
*SI
= BI
? nullptr : cast
<SwitchInst
>(&TI
);
1910 // We can only unswitch switches, conditional branches with an invariant
1911 // condition, or combining invariant conditions with an instruction.
1912 assert((SI
|| (BI
&& BI
->isConditional())) &&
1913 "Can only unswitch switches and conditional branch!");
1914 bool FullUnswitch
= SI
|| BI
->getCondition() == Invariants
[0];
1916 assert(Invariants
.size() == 1 &&
1917 "Cannot have other invariants with full unswitching!");
1919 assert(isa
<Instruction
>(BI
->getCondition()) &&
1920 "Partial unswitching requires an instruction as the condition!");
1922 if (MSSAU
&& VerifyMemorySSA
)
1923 MSSAU
->getMemorySSA()->verifyMemorySSA();
1925 // Constant and BBs tracking the cloned and continuing successor. When we are
1926 // unswitching the entire condition, this can just be trivially chosen to
1927 // unswitch towards `true`. However, when we are unswitching a set of
1928 // invariants combined with `and` or `or`, the combining operation determines
1929 // the best direction to unswitch: we want to unswitch the direction that will
1930 // collapse the branch.
1931 bool Direction
= true;
1933 if (!FullUnswitch
) {
1934 if (cast
<Instruction
>(BI
->getCondition())->getOpcode() != Instruction::Or
) {
1935 assert(cast
<Instruction
>(BI
->getCondition())->getOpcode() ==
1937 "Only `or` and `and` instructions can combine invariants being "
1944 BasicBlock
*RetainedSuccBB
=
1945 BI
? BI
->getSuccessor(1 - ClonedSucc
) : SI
->getDefaultDest();
1946 SmallSetVector
<BasicBlock
*, 4> UnswitchedSuccBBs
;
1948 UnswitchedSuccBBs
.insert(BI
->getSuccessor(ClonedSucc
));
1950 for (auto Case
: SI
->cases())
1951 if (Case
.getCaseSuccessor() != RetainedSuccBB
)
1952 UnswitchedSuccBBs
.insert(Case
.getCaseSuccessor());
1954 assert(!UnswitchedSuccBBs
.count(RetainedSuccBB
) &&
1955 "Should not unswitch the same successor we are retaining!");
1957 // The branch should be in this exact loop. Any inner loop's invariant branch
1958 // should be handled by unswitching that inner loop. The caller of this
1959 // routine should filter out any candidates that remain (but were skipped for
1960 // whatever reason).
1961 assert(LI
.getLoopFor(ParentBB
) == &L
&& "Branch in an inner loop!");
1963 // Compute the parent loop now before we start hacking on things.
1964 Loop
*ParentL
= L
.getParentLoop();
1965 // Get blocks in RPO order for MSSA update, before changing the CFG.
1966 LoopBlocksRPO
LBRPO(&L
);
1970 // Compute the outer-most loop containing one of our exit blocks. This is the
1971 // furthest up our loopnest which can be mutated, which we will use below to
1973 Loop
*OuterExitL
= &L
;
1974 for (auto *ExitBB
: ExitBlocks
) {
1975 Loop
*NewOuterExitL
= LI
.getLoopFor(ExitBB
);
1976 if (!NewOuterExitL
) {
1977 // We exited the entire nest with this block, so we're done.
1978 OuterExitL
= nullptr;
1981 if (NewOuterExitL
!= OuterExitL
&& NewOuterExitL
->contains(OuterExitL
))
1982 OuterExitL
= NewOuterExitL
;
1985 // At this point, we're definitely going to unswitch something so invalidate
1986 // any cached information in ScalarEvolution for the outer most loop
1987 // containing an exit block and all nested loops.
1990 SE
->forgetLoop(OuterExitL
);
1992 SE
->forgetTopmostLoop(&L
);
1995 // If the edge from this terminator to a successor dominates that successor,
1996 // store a map from each block in its dominator subtree to it. This lets us
1997 // tell when cloning for a particular successor if a block is dominated by
1998 // some *other* successor with a single data structure. We use this to
1999 // significantly reduce cloning.
2000 SmallDenseMap
<BasicBlock
*, BasicBlock
*, 16> DominatingSucc
;
2001 for (auto *SuccBB
: llvm::concat
<BasicBlock
*const>(
2002 makeArrayRef(RetainedSuccBB
), UnswitchedSuccBBs
))
2003 if (SuccBB
->getUniquePredecessor() ||
2004 llvm::all_of(predecessors(SuccBB
), [&](BasicBlock
*PredBB
) {
2005 return PredBB
== ParentBB
|| DT
.dominates(SuccBB
, PredBB
);
2007 visitDomSubTree(DT
, SuccBB
, [&](BasicBlock
*BB
) {
2008 DominatingSucc
[BB
] = SuccBB
;
2012 // Split the preheader, so that we know that there is a safe place to insert
2013 // the conditional branch. We will change the preheader to have a conditional
2014 // branch on LoopCond. The original preheader will become the split point
2015 // between the unswitched versions, and we will have a new preheader for the
2017 BasicBlock
*SplitBB
= L
.getLoopPreheader();
2018 BasicBlock
*LoopPH
= SplitEdge(SplitBB
, L
.getHeader(), &DT
, &LI
, MSSAU
);
2020 // Keep track of the dominator tree updates needed.
2021 SmallVector
<DominatorTree::UpdateType
, 4> DTUpdates
;
2023 // Clone the loop for each unswitched successor.
2024 SmallVector
<std::unique_ptr
<ValueToValueMapTy
>, 4> VMaps
;
2025 VMaps
.reserve(UnswitchedSuccBBs
.size());
2026 SmallDenseMap
<BasicBlock
*, BasicBlock
*, 4> ClonedPHs
;
2027 for (auto *SuccBB
: UnswitchedSuccBBs
) {
2028 VMaps
.emplace_back(new ValueToValueMapTy());
2029 ClonedPHs
[SuccBB
] = buildClonedLoopBlocks(
2030 L
, LoopPH
, SplitBB
, ExitBlocks
, ParentBB
, SuccBB
, RetainedSuccBB
,
2031 DominatingSucc
, *VMaps
.back(), DTUpdates
, AC
, DT
, LI
, MSSAU
);
2034 // The stitching of the branched code back together depends on whether we're
2035 // doing full unswitching or not with the exception that we always want to
2036 // nuke the initial terminator placed in the split block.
2037 SplitBB
->getTerminator()->eraseFromParent();
2039 // Splice the terminator from the original loop and rewrite its
2041 SplitBB
->getInstList().splice(SplitBB
->end(), ParentBB
->getInstList(), TI
);
2043 // Keep a clone of the terminator for MSSA updates.
2044 Instruction
*NewTI
= TI
.clone();
2045 ParentBB
->getInstList().push_back(NewTI
);
2047 // First wire up the moved terminator to the preheaders.
2049 BasicBlock
*ClonedPH
= ClonedPHs
.begin()->second
;
2050 BI
->setSuccessor(ClonedSucc
, ClonedPH
);
2051 BI
->setSuccessor(1 - ClonedSucc
, LoopPH
);
2052 DTUpdates
.push_back({DominatorTree::Insert
, SplitBB
, ClonedPH
});
2054 assert(SI
&& "Must either be a branch or switch!");
2056 // Walk the cases and directly update their successors.
2057 assert(SI
->getDefaultDest() == RetainedSuccBB
&&
2058 "Not retaining default successor!");
2059 SI
->setDefaultDest(LoopPH
);
2060 for (auto &Case
: SI
->cases())
2061 if (Case
.getCaseSuccessor() == RetainedSuccBB
)
2062 Case
.setSuccessor(LoopPH
);
2064 Case
.setSuccessor(ClonedPHs
.find(Case
.getCaseSuccessor())->second
);
2066 // We need to use the set to populate domtree updates as even when there
2067 // are multiple cases pointing at the same successor we only want to
2068 // remove and insert one edge in the domtree.
2069 for (BasicBlock
*SuccBB
: UnswitchedSuccBBs
)
2070 DTUpdates
.push_back(
2071 {DominatorTree::Insert
, SplitBB
, ClonedPHs
.find(SuccBB
)->second
});
2075 DT
.applyUpdates(DTUpdates
);
2078 // Remove all but one edge to the retained block and all unswitched
2079 // blocks. This is to avoid having duplicate entries in the cloned Phis,
2080 // when we know we only keep a single edge for each case.
2081 MSSAU
->removeDuplicatePhiEdgesBetween(ParentBB
, RetainedSuccBB
);
2082 for (BasicBlock
*SuccBB
: UnswitchedSuccBBs
)
2083 MSSAU
->removeDuplicatePhiEdgesBetween(ParentBB
, SuccBB
);
2085 for (auto &VMap
: VMaps
)
2086 MSSAU
->updateForClonedLoop(LBRPO
, ExitBlocks
, *VMap
,
2087 /*IgnoreIncomingWithNoClones=*/true);
2088 MSSAU
->updateExitBlocksForClonedLoop(ExitBlocks
, VMaps
, DT
);
2090 // Remove all edges to unswitched blocks.
2091 for (BasicBlock
*SuccBB
: UnswitchedSuccBBs
)
2092 MSSAU
->removeEdge(ParentBB
, SuccBB
);
2095 // Now unhook the successor relationship as we'll be replacing
2096 // the terminator with a direct branch. This is much simpler for branches
2097 // than switches so we handle those first.
2099 // Remove the parent as a predecessor of the unswitched successor.
2100 assert(UnswitchedSuccBBs
.size() == 1 &&
2101 "Only one possible unswitched block for a branch!");
2102 BasicBlock
*UnswitchedSuccBB
= *UnswitchedSuccBBs
.begin();
2103 UnswitchedSuccBB
->removePredecessor(ParentBB
,
2104 /*KeepOneInputPHIs*/ true);
2105 DTUpdates
.push_back({DominatorTree::Delete
, ParentBB
, UnswitchedSuccBB
});
2107 // Note that we actually want to remove the parent block as a predecessor
2108 // of *every* case successor. The case successor is either unswitched,
2109 // completely eliminating an edge from the parent to that successor, or it
2110 // is a duplicate edge to the retained successor as the retained successor
2111 // is always the default successor and as we'll replace this with a direct
2112 // branch we no longer need the duplicate entries in the PHI nodes.
2113 SwitchInst
*NewSI
= cast
<SwitchInst
>(NewTI
);
2114 assert(NewSI
->getDefaultDest() == RetainedSuccBB
&&
2115 "Not retaining default successor!");
2116 for (auto &Case
: NewSI
->cases())
2117 Case
.getCaseSuccessor()->removePredecessor(
2119 /*KeepOneInputPHIs*/ true);
2121 // We need to use the set to populate domtree updates as even when there
2122 // are multiple cases pointing at the same successor we only want to
2123 // remove and insert one edge in the domtree.
2124 for (BasicBlock
*SuccBB
: UnswitchedSuccBBs
)
2125 DTUpdates
.push_back({DominatorTree::Delete
, ParentBB
, SuccBB
});
2128 // After MSSAU update, remove the cloned terminator instruction NewTI.
2129 ParentBB
->getTerminator()->eraseFromParent();
2131 // Create a new unconditional branch to the continuing block (as opposed to
2133 BranchInst::Create(RetainedSuccBB
, ParentBB
);
2135 assert(BI
&& "Only branches have partial unswitching.");
2136 assert(UnswitchedSuccBBs
.size() == 1 &&
2137 "Only one possible unswitched block for a branch!");
2138 BasicBlock
*ClonedPH
= ClonedPHs
.begin()->second
;
2139 // When doing a partial unswitch, we have to do a bit more work to build up
2140 // the branch in the split block.
2141 buildPartialUnswitchConditionalBranch(*SplitBB
, Invariants
, Direction
,
2142 *ClonedPH
, *LoopPH
);
2143 DTUpdates
.push_back({DominatorTree::Insert
, SplitBB
, ClonedPH
});
2146 DT
.applyUpdates(DTUpdates
);
2149 // Perform MSSA cloning updates.
2150 for (auto &VMap
: VMaps
)
2151 MSSAU
->updateForClonedLoop(LBRPO
, ExitBlocks
, *VMap
,
2152 /*IgnoreIncomingWithNoClones=*/true);
2153 MSSAU
->updateExitBlocksForClonedLoop(ExitBlocks
, VMaps
, DT
);
2157 // Apply the updates accumulated above to get an up-to-date dominator tree.
2158 DT
.applyUpdates(DTUpdates
);
2160 // Now that we have an accurate dominator tree, first delete the dead cloned
2161 // blocks so that we can accurately build any cloned loops. It is important to
2162 // not delete the blocks from the original loop yet because we still want to
2163 // reference the original loop to understand the cloned loop's structure.
2164 deleteDeadClonedBlocks(L
, ExitBlocks
, VMaps
, DT
, MSSAU
);
2166 // Build the cloned loop structure itself. This may be substantially
2167 // different from the original structure due to the simplified CFG. This also
2168 // handles inserting all the cloned blocks into the correct loops.
2169 SmallVector
<Loop
*, 4> NonChildClonedLoops
;
2170 for (std::unique_ptr
<ValueToValueMapTy
> &VMap
: VMaps
)
2171 buildClonedLoops(L
, ExitBlocks
, *VMap
, LI
, NonChildClonedLoops
);
2173 // Now that our cloned loops have been built, we can update the original loop.
2174 // First we delete the dead blocks from it and then we rebuild the loop
2175 // structure taking these deletions into account.
2176 deleteDeadBlocksFromLoop(L
, ExitBlocks
, DT
, LI
, MSSAU
);
2178 if (MSSAU
&& VerifyMemorySSA
)
2179 MSSAU
->getMemorySSA()->verifyMemorySSA();
2181 SmallVector
<Loop
*, 4> HoistedLoops
;
2182 bool IsStillLoop
= rebuildLoopAfterUnswitch(L
, ExitBlocks
, LI
, HoistedLoops
);
2184 if (MSSAU
&& VerifyMemorySSA
)
2185 MSSAU
->getMemorySSA()->verifyMemorySSA();
2187 // This transformation has a high risk of corrupting the dominator tree, and
2188 // the below steps to rebuild loop structures will result in hard to debug
2189 // errors in that case so verify that the dominator tree is sane first.
2190 // FIXME: Remove this when the bugs stop showing up and rely on existing
2191 // verification steps.
2192 assert(DT
.verify(DominatorTree::VerificationLevel::Fast
));
2195 // If we unswitched a branch which collapses the condition to a known
2196 // constant we want to replace all the uses of the invariants within both
2197 // the original and cloned blocks. We do this here so that we can use the
2198 // now updated dominator tree to identify which side the users are on.
2199 assert(UnswitchedSuccBBs
.size() == 1 &&
2200 "Only one possible unswitched block for a branch!");
2201 BasicBlock
*ClonedPH
= ClonedPHs
.begin()->second
;
2203 // When considering multiple partially-unswitched invariants
2204 // we cant just go replace them with constants in both branches.
2206 // For 'AND' we infer that true branch ("continue") means true
2207 // for each invariant operand.
2208 // For 'OR' we can infer that false branch ("continue") means false
2209 // for each invariant operand.
2210 // So it happens that for multiple-partial case we dont replace
2211 // in the unswitched branch.
2212 bool ReplaceUnswitched
= FullUnswitch
|| (Invariants
.size() == 1);
2214 ConstantInt
*UnswitchedReplacement
=
2215 Direction
? ConstantInt::getTrue(BI
->getContext())
2216 : ConstantInt::getFalse(BI
->getContext());
2217 ConstantInt
*ContinueReplacement
=
2218 Direction
? ConstantInt::getFalse(BI
->getContext())
2219 : ConstantInt::getTrue(BI
->getContext());
2220 for (Value
*Invariant
: Invariants
)
2221 for (auto UI
= Invariant
->use_begin(), UE
= Invariant
->use_end();
2223 // Grab the use and walk past it so we can clobber it in the use list.
2225 Instruction
*UserI
= dyn_cast
<Instruction
>(U
->getUser());
2229 // Replace it with the 'continue' side if in the main loop body, and the
2230 // unswitched if in the cloned blocks.
2231 if (DT
.dominates(LoopPH
, UserI
->getParent()))
2232 U
->set(ContinueReplacement
);
2233 else if (ReplaceUnswitched
&&
2234 DT
.dominates(ClonedPH
, UserI
->getParent()))
2235 U
->set(UnswitchedReplacement
);
2239 // We can change which blocks are exit blocks of all the cloned sibling
2240 // loops, the current loop, and any parent loops which shared exit blocks
2241 // with the current loop. As a consequence, we need to re-form LCSSA for
2242 // them. But we shouldn't need to re-form LCSSA for any child loops.
2243 // FIXME: This could be made more efficient by tracking which exit blocks are
2244 // new, and focusing on them, but that isn't likely to be necessary.
2246 // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2247 // loop nest and update every loop that could have had its exits changed. We
2248 // also need to cover any intervening loops. We add all of these loops to
2249 // a list and sort them by loop depth to achieve this without updating
2250 // unnecessary loops.
2251 auto UpdateLoop
= [&](Loop
&UpdateL
) {
2253 UpdateL
.verifyLoop();
2254 for (Loop
*ChildL
: UpdateL
) {
2255 ChildL
->verifyLoop();
2256 assert(ChildL
->isRecursivelyLCSSAForm(DT
, LI
) &&
2257 "Perturbed a child loop's LCSSA form!");
2260 // First build LCSSA for this loop so that we can preserve it when
2261 // forming dedicated exits. We don't want to perturb some other loop's
2262 // LCSSA while doing that CFG edit.
2263 formLCSSA(UpdateL
, DT
, &LI
, nullptr);
2265 // For loops reached by this loop's original exit blocks we may
2266 // introduced new, non-dedicated exits. At least try to re-form dedicated
2267 // exits for these loops. This may fail if they couldn't have dedicated
2268 // exits to start with.
2269 formDedicatedExitBlocks(&UpdateL
, &DT
, &LI
, MSSAU
, /*PreserveLCSSA*/ true);
2272 // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2273 // and we can do it in any order as they don't nest relative to each other.
2275 // Also check if any of the loops we have updated have become top-level loops
2276 // as that will necessitate widening the outer loop scope.
2277 for (Loop
*UpdatedL
:
2278 llvm::concat
<Loop
*>(NonChildClonedLoops
, HoistedLoops
)) {
2279 UpdateLoop(*UpdatedL
);
2280 if (!UpdatedL
->getParentLoop())
2281 OuterExitL
= nullptr;
2285 if (!L
.getParentLoop())
2286 OuterExitL
= nullptr;
2289 // If the original loop had exit blocks, walk up through the outer most loop
2290 // of those exit blocks to update LCSSA and form updated dedicated exits.
2291 if (OuterExitL
!= &L
)
2292 for (Loop
*OuterL
= ParentL
; OuterL
!= OuterExitL
;
2293 OuterL
= OuterL
->getParentLoop())
2294 UpdateLoop(*OuterL
);
2297 // Verify the entire loop structure to catch any incorrect updates before we
2298 // progress in the pass pipeline.
2302 // Now that we've unswitched something, make callbacks to report the changes.
2303 // For that we need to merge together the updated loops and the cloned loops
2304 // and check whether the original loop survived.
2305 SmallVector
<Loop
*, 4> SibLoops
;
2306 for (Loop
*UpdatedL
: llvm::concat
<Loop
*>(NonChildClonedLoops
, HoistedLoops
))
2307 if (UpdatedL
->getParentLoop() == ParentL
)
2308 SibLoops
.push_back(UpdatedL
);
2309 UnswitchCB(IsStillLoop
, SibLoops
);
2311 if (MSSAU
&& VerifyMemorySSA
)
2312 MSSAU
->getMemorySSA()->verifyMemorySSA();
2320 /// Recursively compute the cost of a dominator subtree based on the per-block
2321 /// cost map provided.
2323 /// The recursive computation is memozied into the provided DT-indexed cost map
2324 /// to allow querying it for most nodes in the domtree without it becoming
2327 computeDomSubtreeCost(DomTreeNode
&N
,
2328 const SmallDenseMap
<BasicBlock
*, int, 4> &BBCostMap
,
2329 SmallDenseMap
<DomTreeNode
*, int, 4> &DTCostMap
) {
2330 // Don't accumulate cost (or recurse through) blocks not in our block cost
2331 // map and thus not part of the duplication cost being considered.
2332 auto BBCostIt
= BBCostMap
.find(N
.getBlock());
2333 if (BBCostIt
== BBCostMap
.end())
2336 // Lookup this node to see if we already computed its cost.
2337 auto DTCostIt
= DTCostMap
.find(&N
);
2338 if (DTCostIt
!= DTCostMap
.end())
2339 return DTCostIt
->second
;
2341 // If not, we have to compute it. We can't use insert above and update
2342 // because computing the cost may insert more things into the map.
2343 int Cost
= std::accumulate(
2344 N
.begin(), N
.end(), BBCostIt
->second
, [&](int Sum
, DomTreeNode
*ChildN
) {
2345 return Sum
+ computeDomSubtreeCost(*ChildN
, BBCostMap
, DTCostMap
);
2347 bool Inserted
= DTCostMap
.insert({&N
, Cost
}).second
;
2349 assert(Inserted
&& "Should not insert a node while visiting children!");
2353 /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2354 /// making the following replacement:
2356 /// --code before guard--
2357 /// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
2358 /// --code after guard--
2362 /// --code before guard--
2363 /// br i1 %cond, label %guarded, label %deopt
2366 /// --code after guard--
2369 /// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2372 /// It also makes all relevant DT and LI updates, so that all structures are in
2373 /// valid state after this transform.
2375 turnGuardIntoBranch(IntrinsicInst
*GI
, Loop
&L
,
2376 SmallVectorImpl
<BasicBlock
*> &ExitBlocks
,
2377 DominatorTree
&DT
, LoopInfo
&LI
, MemorySSAUpdater
*MSSAU
) {
2378 SmallVector
<DominatorTree::UpdateType
, 4> DTUpdates
;
2379 LLVM_DEBUG(dbgs() << "Turning " << *GI
<< " into a branch.\n");
2380 BasicBlock
*CheckBB
= GI
->getParent();
2382 if (MSSAU
&& VerifyMemorySSA
)
2383 MSSAU
->getMemorySSA()->verifyMemorySSA();
2385 // Remove all CheckBB's successors from DomTree. A block can be seen among
2386 // successors more than once, but for DomTree it should be added only once.
2387 SmallPtrSet
<BasicBlock
*, 4> Successors
;
2388 for (auto *Succ
: successors(CheckBB
))
2389 if (Successors
.insert(Succ
).second
)
2390 DTUpdates
.push_back({DominatorTree::Delete
, CheckBB
, Succ
});
2392 Instruction
*DeoptBlockTerm
=
2393 SplitBlockAndInsertIfThen(GI
->getArgOperand(0), GI
, true);
2394 BranchInst
*CheckBI
= cast
<BranchInst
>(CheckBB
->getTerminator());
2395 // SplitBlockAndInsertIfThen inserts control flow that branches to
2396 // DeoptBlockTerm if the condition is true. We want the opposite.
2397 CheckBI
->swapSuccessors();
2399 BasicBlock
*GuardedBlock
= CheckBI
->getSuccessor(0);
2400 GuardedBlock
->setName("guarded");
2401 CheckBI
->getSuccessor(1)->setName("deopt");
2402 BasicBlock
*DeoptBlock
= CheckBI
->getSuccessor(1);
2404 // We now have a new exit block.
2405 ExitBlocks
.push_back(CheckBI
->getSuccessor(1));
2408 MSSAU
->moveAllAfterSpliceBlocks(CheckBB
, GuardedBlock
, GI
);
2410 GI
->moveBefore(DeoptBlockTerm
);
2411 GI
->setArgOperand(0, ConstantInt::getFalse(GI
->getContext()));
2413 // Add new successors of CheckBB into DomTree.
2414 for (auto *Succ
: successors(CheckBB
))
2415 DTUpdates
.push_back({DominatorTree::Insert
, CheckBB
, Succ
});
2417 // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2419 for (auto *Succ
: Successors
)
2420 DTUpdates
.push_back({DominatorTree::Insert
, GuardedBlock
, Succ
});
2422 // Make proper changes to DT.
2423 DT
.applyUpdates(DTUpdates
);
2424 // Inform LI of a new loop block.
2425 L
.addBasicBlockToLoop(GuardedBlock
, LI
);
2428 MemoryDef
*MD
= cast
<MemoryDef
>(MSSAU
->getMemorySSA()->getMemoryAccess(GI
));
2429 MSSAU
->moveToPlace(MD
, DeoptBlock
, MemorySSA::End
);
2430 if (VerifyMemorySSA
)
2431 MSSAU
->getMemorySSA()->verifyMemorySSA();
2438 /// Cost multiplier is a way to limit potentially exponential behavior
2439 /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2440 /// candidates available. Also accounting for the number of "sibling" loops with
2441 /// the idea to account for previous unswitches that already happened on this
2442 /// cluster of loops. There was an attempt to keep this formula simple,
2443 /// just enough to limit the worst case behavior. Even if it is not that simple
2444 /// now it is still not an attempt to provide a detailed heuristic size
2447 /// TODO: Make a proper accounting of "explosion" effect for all kinds of
2448 /// unswitch candidates, making adequate predictions instead of wild guesses.
2449 /// That requires knowing not just the number of "remaining" candidates but
2450 /// also costs of unswitching for each of these candidates.
2451 static int calculateUnswitchCostMultiplier(
2452 Instruction
&TI
, Loop
&L
, LoopInfo
&LI
, DominatorTree
&DT
,
2453 ArrayRef
<std::pair
<Instruction
*, TinyPtrVector
<Value
*>>>
2454 UnswitchCandidates
) {
2456 // Guards and other exiting conditions do not contribute to exponential
2457 // explosion as soon as they dominate the latch (otherwise there might be
2458 // another path to the latch remaining that does not allow to eliminate the
2459 // loop copy on unswitch).
2460 BasicBlock
*Latch
= L
.getLoopLatch();
2461 BasicBlock
*CondBlock
= TI
.getParent();
2462 if (DT
.dominates(CondBlock
, Latch
) &&
2464 llvm::count_if(successors(&TI
), [&L
](BasicBlock
*SuccBB
) {
2465 return L
.contains(SuccBB
);
2467 NumCostMultiplierSkipped
++;
2471 auto *ParentL
= L
.getParentLoop();
2472 int SiblingsCount
= (ParentL
? ParentL
->getSubLoopsVector().size()
2473 : std::distance(LI
.begin(), LI
.end()));
2474 // Count amount of clones that all the candidates might cause during
2475 // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2476 int UnswitchedClones
= 0;
2477 for (auto Candidate
: UnswitchCandidates
) {
2478 Instruction
*CI
= Candidate
.first
;
2479 BasicBlock
*CondBlock
= CI
->getParent();
2480 bool SkipExitingSuccessors
= DT
.dominates(CondBlock
, Latch
);
2482 if (!SkipExitingSuccessors
)
2486 int NonExitingSuccessors
= llvm::count_if(
2487 successors(CondBlock
), [SkipExitingSuccessors
, &L
](BasicBlock
*SuccBB
) {
2488 return !SkipExitingSuccessors
|| L
.contains(SuccBB
);
2490 UnswitchedClones
+= Log2_32(NonExitingSuccessors
);
2493 // Ignore up to the "unscaled candidates" number of unswitch candidates
2494 // when calculating the power-of-two scaling of the cost. The main idea
2495 // with this control is to allow a small number of unswitches to happen
2496 // and rely more on siblings multiplier (see below) when the number
2497 // of candidates is small.
2498 unsigned ClonesPower
=
2499 std::max(UnswitchedClones
- (int)UnswitchNumInitialUnscaledCandidates
, 0);
2501 // Allowing top-level loops to spread a bit more than nested ones.
2502 int SiblingsMultiplier
=
2503 std::max((ParentL
? SiblingsCount
2504 : SiblingsCount
/ (int)UnswitchSiblingsToplevelDiv
),
2506 // Compute the cost multiplier in a way that won't overflow by saturating
2507 // at an upper bound.
2509 if (ClonesPower
> Log2_32(UnswitchThreshold
) ||
2510 SiblingsMultiplier
> UnswitchThreshold
)
2511 CostMultiplier
= UnswitchThreshold
;
2513 CostMultiplier
= std::min(SiblingsMultiplier
* (1 << ClonesPower
),
2514 (int)UnswitchThreshold
);
2516 LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier
2517 << " (siblings " << SiblingsMultiplier
<< " * clones "
2518 << (1 << ClonesPower
) << ")"
2519 << " for unswitch candidate: " << TI
<< "\n");
2520 return CostMultiplier
;
2524 unswitchBestCondition(Loop
&L
, DominatorTree
&DT
, LoopInfo
&LI
,
2525 AssumptionCache
&AC
, TargetTransformInfo
&TTI
,
2526 function_ref
<void(bool, ArrayRef
<Loop
*>)> UnswitchCB
,
2527 ScalarEvolution
*SE
, MemorySSAUpdater
*MSSAU
) {
2528 // Collect all invariant conditions within this loop (as opposed to an inner
2529 // loop which would be handled when visiting that inner loop).
2530 SmallVector
<std::pair
<Instruction
*, TinyPtrVector
<Value
*>>, 4>
2533 // Whether or not we should also collect guards in the loop.
2534 bool CollectGuards
= false;
2535 if (UnswitchGuards
) {
2536 auto *GuardDecl
= L
.getHeader()->getParent()->getParent()->getFunction(
2537 Intrinsic::getName(Intrinsic::experimental_guard
));
2538 if (GuardDecl
&& !GuardDecl
->use_empty())
2539 CollectGuards
= true;
2542 for (auto *BB
: L
.blocks()) {
2543 if (LI
.getLoopFor(BB
) != &L
)
2549 auto *Cond
= cast
<IntrinsicInst
>(&I
)->getArgOperand(0);
2550 // TODO: Support AND, OR conditions and partial unswitching.
2551 if (!isa
<Constant
>(Cond
) && L
.isLoopInvariant(Cond
))
2552 UnswitchCandidates
.push_back({&I
, {Cond
}});
2555 if (auto *SI
= dyn_cast
<SwitchInst
>(BB
->getTerminator())) {
2556 // We can only consider fully loop-invariant switch conditions as we need
2557 // to completely eliminate the switch after unswitching.
2558 if (!isa
<Constant
>(SI
->getCondition()) &&
2559 L
.isLoopInvariant(SI
->getCondition()) && !BB
->getUniqueSuccessor())
2560 UnswitchCandidates
.push_back({SI
, {SI
->getCondition()}});
2564 auto *BI
= dyn_cast
<BranchInst
>(BB
->getTerminator());
2565 if (!BI
|| !BI
->isConditional() || isa
<Constant
>(BI
->getCondition()) ||
2566 BI
->getSuccessor(0) == BI
->getSuccessor(1))
2569 if (L
.isLoopInvariant(BI
->getCondition())) {
2570 UnswitchCandidates
.push_back({BI
, {BI
->getCondition()}});
2574 Instruction
&CondI
= *cast
<Instruction
>(BI
->getCondition());
2575 if (CondI
.getOpcode() != Instruction::And
&&
2576 CondI
.getOpcode() != Instruction::Or
)
2579 TinyPtrVector
<Value
*> Invariants
=
2580 collectHomogenousInstGraphLoopInvariants(L
, CondI
, LI
);
2581 if (Invariants
.empty())
2584 UnswitchCandidates
.push_back({BI
, std::move(Invariants
)});
2587 // If we didn't find any candidates, we're done.
2588 if (UnswitchCandidates
.empty())
2591 // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2592 // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2593 // irreducible control flow into reducible control flow and introduce new
2594 // loops "out of thin air". If we ever discover important use cases for doing
2595 // this, we can add support to loop unswitch, but it is a lot of complexity
2596 // for what seems little or no real world benefit.
2597 LoopBlocksRPO
RPOT(&L
);
2599 if (containsIrreducibleCFG
<const BasicBlock
*>(RPOT
, LI
))
2602 SmallVector
<BasicBlock
*, 4> ExitBlocks
;
2603 L
.getUniqueExitBlocks(ExitBlocks
);
2605 // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
2606 // don't know how to split those exit blocks.
2607 // FIXME: We should teach SplitBlock to handle this and remove this
2609 for (auto *ExitBB
: ExitBlocks
)
2610 if (isa
<CleanupPadInst
>(ExitBB
->getFirstNonPHI())) {
2611 dbgs() << "Cannot unswitch because of cleanuppad in exit block\n";
2616 dbgs() << "Considering " << UnswitchCandidates
.size()
2617 << " non-trivial loop invariant conditions for unswitching.\n");
2619 // Given that unswitching these terminators will require duplicating parts of
2620 // the loop, so we need to be able to model that cost. Compute the ephemeral
2621 // values and set up a data structure to hold per-BB costs. We cache each
2622 // block's cost so that we don't recompute this when considering different
2623 // subsets of the loop for duplication during unswitching.
2624 SmallPtrSet
<const Value
*, 4> EphValues
;
2625 CodeMetrics::collectEphemeralValues(&L
, &AC
, EphValues
);
2626 SmallDenseMap
<BasicBlock
*, int, 4> BBCostMap
;
2628 // Compute the cost of each block, as well as the total loop cost. Also, bail
2629 // out if we see instructions which are incompatible with loop unswitching
2630 // (convergent, noduplicate, or cross-basic-block tokens).
2631 // FIXME: We might be able to safely handle some of these in non-duplicated
2634 for (auto *BB
: L
.blocks()) {
2636 for (auto &I
: *BB
) {
2637 if (EphValues
.count(&I
))
2640 if (I
.getType()->isTokenTy() && I
.isUsedOutsideOfBlock(BB
))
2642 if (auto CS
= CallSite(&I
))
2643 if (CS
.isConvergent() || CS
.cannotDuplicate())
2646 Cost
+= TTI
.getUserCost(&I
);
2648 assert(Cost
>= 0 && "Must not have negative costs!");
2650 assert(LoopCost
>= 0 && "Must not have negative loop costs!");
2651 BBCostMap
[BB
] = Cost
;
2653 LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost
<< "\n");
2655 // Now we find the best candidate by searching for the one with the following
2656 // properties in order:
2658 // 1) An unswitching cost below the threshold
2659 // 2) The smallest number of duplicated unswitch candidates (to avoid
2660 // creating redundant subsequent unswitching)
2661 // 3) The smallest cost after unswitching.
2663 // We prioritize reducing fanout of unswitch candidates provided the cost
2664 // remains below the threshold because this has a multiplicative effect.
2666 // This requires memoizing each dominator subtree to avoid redundant work.
2668 // FIXME: Need to actually do the number of candidates part above.
2669 SmallDenseMap
<DomTreeNode
*, int, 4> DTCostMap
;
2670 // Given a terminator which might be unswitched, computes the non-duplicated
2671 // cost for that terminator.
2672 auto ComputeUnswitchedCost
= [&](Instruction
&TI
, bool FullUnswitch
) {
2673 BasicBlock
&BB
= *TI
.getParent();
2674 SmallPtrSet
<BasicBlock
*, 4> Visited
;
2676 int Cost
= LoopCost
;
2677 for (BasicBlock
*SuccBB
: successors(&BB
)) {
2678 // Don't count successors more than once.
2679 if (!Visited
.insert(SuccBB
).second
)
2682 // If this is a partial unswitch candidate, then it must be a conditional
2683 // branch with a condition of either `or` or `and`. In that case, one of
2684 // the successors is necessarily duplicated, so don't even try to remove
2686 if (!FullUnswitch
) {
2687 auto &BI
= cast
<BranchInst
>(TI
);
2688 if (cast
<Instruction
>(BI
.getCondition())->getOpcode() ==
2690 if (SuccBB
== BI
.getSuccessor(1))
2693 assert(cast
<Instruction
>(BI
.getCondition())->getOpcode() ==
2695 "Only `and` and `or` conditions can result in a partial "
2697 if (SuccBB
== BI
.getSuccessor(0))
2702 // This successor's domtree will not need to be duplicated after
2703 // unswitching if the edge to the successor dominates it (and thus the
2704 // entire tree). This essentially means there is no other path into this
2705 // subtree and so it will end up live in only one clone of the loop.
2706 if (SuccBB
->getUniquePredecessor() ||
2707 llvm::all_of(predecessors(SuccBB
), [&](BasicBlock
*PredBB
) {
2708 return PredBB
== &BB
|| DT
.dominates(SuccBB
, PredBB
);
2710 Cost
-= computeDomSubtreeCost(*DT
[SuccBB
], BBCostMap
, DTCostMap
);
2712 "Non-duplicated cost should never exceed total loop cost!");
2716 // Now scale the cost by the number of unique successors minus one. We
2717 // subtract one because there is already at least one copy of the entire
2718 // loop. This is computing the new cost of unswitching a condition.
2719 // Note that guards always have 2 unique successors that are implicit and
2720 // will be materialized if we decide to unswitch it.
2721 int SuccessorsCount
= isGuard(&TI
) ? 2 : Visited
.size();
2722 assert(SuccessorsCount
> 1 &&
2723 "Cannot unswitch a condition without multiple distinct successors!");
2724 return Cost
* (SuccessorsCount
- 1);
2726 Instruction
*BestUnswitchTI
= nullptr;
2727 int BestUnswitchCost
= 0;
2728 ArrayRef
<Value
*> BestUnswitchInvariants
;
2729 for (auto &TerminatorAndInvariants
: UnswitchCandidates
) {
2730 Instruction
&TI
= *TerminatorAndInvariants
.first
;
2731 ArrayRef
<Value
*> Invariants
= TerminatorAndInvariants
.second
;
2732 BranchInst
*BI
= dyn_cast
<BranchInst
>(&TI
);
2733 int CandidateCost
= ComputeUnswitchedCost(
2734 TI
, /*FullUnswitch*/ !BI
|| (Invariants
.size() == 1 &&
2735 Invariants
[0] == BI
->getCondition()));
2736 // Calculate cost multiplier which is a tool to limit potentially
2737 // exponential behavior of loop-unswitch.
2738 if (EnableUnswitchCostMultiplier
) {
2739 int CostMultiplier
=
2740 calculateUnswitchCostMultiplier(TI
, L
, LI
, DT
, UnswitchCandidates
);
2742 (CostMultiplier
> 0 && CostMultiplier
<= UnswitchThreshold
) &&
2743 "cost multiplier needs to be in the range of 1..UnswitchThreshold");
2744 CandidateCost
*= CostMultiplier
;
2745 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2746 << " (multiplier: " << CostMultiplier
<< ")"
2747 << " for unswitch candidate: " << TI
<< "\n");
2749 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2750 << " for unswitch candidate: " << TI
<< "\n");
2753 if (!BestUnswitchTI
|| CandidateCost
< BestUnswitchCost
) {
2754 BestUnswitchTI
= &TI
;
2755 BestUnswitchCost
= CandidateCost
;
2756 BestUnswitchInvariants
= Invariants
;
2759 assert(BestUnswitchTI
&& "Failed to find loop unswitch candidate");
2761 if (BestUnswitchCost
>= UnswitchThreshold
) {
2762 LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2763 << BestUnswitchCost
<< "\n");
2767 // If the best candidate is a guard, turn it into a branch.
2768 if (isGuard(BestUnswitchTI
))
2769 BestUnswitchTI
= turnGuardIntoBranch(cast
<IntrinsicInst
>(BestUnswitchTI
), L
,
2770 ExitBlocks
, DT
, LI
, MSSAU
);
2772 LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = "
2773 << BestUnswitchCost
<< ") terminator: " << *BestUnswitchTI
2775 unswitchNontrivialInvariants(L
, *BestUnswitchTI
, BestUnswitchInvariants
,
2776 ExitBlocks
, DT
, LI
, AC
, UnswitchCB
, SE
, MSSAU
);
2780 /// Unswitch control flow predicated on loop invariant conditions.
2782 /// This first hoists all branches or switches which are trivial (IE, do not
2783 /// require duplicating any part of the loop) out of the loop body. It then
2784 /// looks at other loop invariant control flows and tries to unswitch those as
2785 /// well by cloning the loop if the result is small enough.
2787 /// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2788 /// updated based on the unswitch.
2789 /// The `MSSA` analysis is also updated if valid (i.e. its use is enabled).
2791 /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2792 /// true, we will attempt to do non-trivial unswitching as well as trivial
2795 /// The `UnswitchCB` callback provided will be run after unswitching is
2796 /// complete, with the first parameter set to `true` if the provided loop
2797 /// remains a loop, and a list of new sibling loops created.
2799 /// If `SE` is non-null, we will update that analysis based on the unswitching
2801 static bool unswitchLoop(Loop
&L
, DominatorTree
&DT
, LoopInfo
&LI
,
2802 AssumptionCache
&AC
, TargetTransformInfo
&TTI
,
2804 function_ref
<void(bool, ArrayRef
<Loop
*>)> UnswitchCB
,
2805 ScalarEvolution
*SE
, MemorySSAUpdater
*MSSAU
) {
2806 assert(L
.isRecursivelyLCSSAForm(DT
, LI
) &&
2807 "Loops must be in LCSSA form before unswitching.");
2808 bool Changed
= false;
2810 // Must be in loop simplified form: we need a preheader and dedicated exits.
2811 if (!L
.isLoopSimplifyForm())
2814 // Try trivial unswitch first before loop over other basic blocks in the loop.
2815 if (unswitchAllTrivialConditions(L
, DT
, LI
, SE
, MSSAU
)) {
2816 // If we unswitched successfully we will want to clean up the loop before
2817 // processing it further so just mark it as unswitched and return.
2818 UnswitchCB(/*CurrentLoopValid*/ true, {});
2822 // If we're not doing non-trivial unswitching, we're done. We both accept
2823 // a parameter but also check a local flag that can be used for testing
2825 if (!NonTrivial
&& !EnableNonTrivialUnswitch
)
2828 // For non-trivial unswitching, because it often creates new loops, we rely on
2829 // the pass manager to iterate on the loops rather than trying to immediately
2830 // reach a fixed point. There is no substantial advantage to iterating
2831 // internally, and if any of the new loops are simplified enough to contain
2832 // trivial unswitching we want to prefer those.
2834 // Try to unswitch the best invariant condition. We prefer this full unswitch to
2835 // a partial unswitch when possible below the threshold.
2836 if (unswitchBestCondition(L
, DT
, LI
, AC
, TTI
, UnswitchCB
, SE
, MSSAU
))
2839 // No other opportunities to unswitch.
2843 PreservedAnalyses
SimpleLoopUnswitchPass::run(Loop
&L
, LoopAnalysisManager
&AM
,
2844 LoopStandardAnalysisResults
&AR
,
2846 Function
&F
= *L
.getHeader()->getParent();
2849 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F
.getName() << ": " << L
2852 // Save the current loop name in a variable so that we can report it even
2853 // after it has been deleted.
2854 std::string LoopName
= L
.getName();
2856 auto UnswitchCB
= [&L
, &U
, &LoopName
](bool CurrentLoopValid
,
2857 ArrayRef
<Loop
*> NewLoops
) {
2858 // If we did a non-trivial unswitch, we have added new (cloned) loops.
2859 if (!NewLoops
.empty())
2860 U
.addSiblingLoops(NewLoops
);
2862 // If the current loop remains valid, we should revisit it to catch any
2863 // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2864 if (CurrentLoopValid
)
2865 U
.revisitCurrentLoop();
2867 U
.markLoopAsDeleted(L
, LoopName
);
2870 Optional
<MemorySSAUpdater
> MSSAU
;
2872 MSSAU
= MemorySSAUpdater(AR
.MSSA
);
2873 if (VerifyMemorySSA
)
2874 AR
.MSSA
->verifyMemorySSA();
2876 if (!unswitchLoop(L
, AR
.DT
, AR
.LI
, AR
.AC
, AR
.TTI
, NonTrivial
, UnswitchCB
,
2877 &AR
.SE
, MSSAU
.hasValue() ? MSSAU
.getPointer() : nullptr))
2878 return PreservedAnalyses::all();
2880 if (AR
.MSSA
&& VerifyMemorySSA
)
2881 AR
.MSSA
->verifyMemorySSA();
2883 // Historically this pass has had issues with the dominator tree so verify it
2884 // in asserts builds.
2885 assert(AR
.DT
.verify(DominatorTree::VerificationLevel::Fast
));
2887 auto PA
= getLoopPassPreservedAnalyses();
2889 PA
.preserve
<MemorySSAAnalysis
>();
2895 class SimpleLoopUnswitchLegacyPass
: public LoopPass
{
2899 static char ID
; // Pass ID, replacement for typeid
2901 explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial
= false)
2902 : LoopPass(ID
), NonTrivial(NonTrivial
) {
2903 initializeSimpleLoopUnswitchLegacyPassPass(
2904 *PassRegistry::getPassRegistry());
2907 bool runOnLoop(Loop
*L
, LPPassManager
&LPM
) override
;
2909 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
2910 AU
.addRequired
<AssumptionCacheTracker
>();
2911 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
2912 if (EnableMSSALoopDependency
) {
2913 AU
.addRequired
<MemorySSAWrapperPass
>();
2914 AU
.addPreserved
<MemorySSAWrapperPass
>();
2916 getLoopAnalysisUsage(AU
);
2920 } // end anonymous namespace
2922 bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
2926 Function
&F
= *L
->getHeader()->getParent();
2928 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F
.getName() << ": " << *L
2931 auto &DT
= getAnalysis
<DominatorTreeWrapperPass
>().getDomTree();
2932 auto &LI
= getAnalysis
<LoopInfoWrapperPass
>().getLoopInfo();
2933 auto &AC
= getAnalysis
<AssumptionCacheTracker
>().getAssumptionCache(F
);
2934 auto &TTI
= getAnalysis
<TargetTransformInfoWrapperPass
>().getTTI(F
);
2935 MemorySSA
*MSSA
= nullptr;
2936 Optional
<MemorySSAUpdater
> MSSAU
;
2937 if (EnableMSSALoopDependency
) {
2938 MSSA
= &getAnalysis
<MemorySSAWrapperPass
>().getMSSA();
2939 MSSAU
= MemorySSAUpdater(MSSA
);
2942 auto *SEWP
= getAnalysisIfAvailable
<ScalarEvolutionWrapperPass
>();
2943 auto *SE
= SEWP
? &SEWP
->getSE() : nullptr;
2945 auto UnswitchCB
= [&L
, &LPM
](bool CurrentLoopValid
,
2946 ArrayRef
<Loop
*> NewLoops
) {
2947 // If we did a non-trivial unswitch, we have added new (cloned) loops.
2948 for (auto *NewL
: NewLoops
)
2951 // If the current loop remains valid, re-add it to the queue. This is
2952 // a little wasteful as we'll finish processing the current loop as well,
2953 // but it is the best we can do in the old PM.
2954 if (CurrentLoopValid
)
2957 LPM
.markLoopAsDeleted(*L
);
2960 if (MSSA
&& VerifyMemorySSA
)
2961 MSSA
->verifyMemorySSA();
2963 bool Changed
= unswitchLoop(*L
, DT
, LI
, AC
, TTI
, NonTrivial
, UnswitchCB
, SE
,
2964 MSSAU
.hasValue() ? MSSAU
.getPointer() : nullptr);
2966 if (MSSA
&& VerifyMemorySSA
)
2967 MSSA
->verifyMemorySSA();
2969 // If anything was unswitched, also clear any cached information about this
2971 LPM
.deleteSimpleAnalysisLoop(L
);
2973 // Historically this pass has had issues with the dominator tree so verify it
2974 // in asserts builds.
2975 assert(DT
.verify(DominatorTree::VerificationLevel::Fast
));
2980 char SimpleLoopUnswitchLegacyPass::ID
= 0;
2981 INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass
, "simple-loop-unswitch",
2982 "Simple unswitch loops", false, false)
2983 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker
)
2984 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
2985 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass
)
2986 INITIALIZE_PASS_DEPENDENCY(LoopPass
)
2987 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass
)
2988 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass
)
2989 INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass
, "simple-loop-unswitch",
2990 "Simple unswitch loops", false, false)
2992 Pass
*llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial
) {
2993 return new SimpleLoopUnswitchLegacyPass(NonTrivial
);