xref: /llvm-project/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp (revision 97468e9282b25639de0181c94eba6972519f4e84)
1 ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #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"
52 #include <algorithm>
53 #include <cassert>
54 #include <iterator>
55 #include <numeric>
56 #include <utility>
57 
58 #define DEBUG_TYPE "simple-loop-unswitch"
59 
60 using namespace llvm;
61 
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");
66 STATISTIC(
67     NumCostMultiplierSkipped,
68     "Number of unswitch candidates that had their cost multiplier skipped");
69 
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."));
74 
75 static cl::opt<int>
76     UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
77                       cl::desc("The cost threshold for unswitching a loop."));
78 
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 "
89              "cost multiplier."));
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."));
94 
95 /// Collect all of the loop invariant input values transitively used by the
96 /// homogeneous instruction graph from a given root.
97 ///
98 /// This essentially walks from a root recursively through loop variant operands
99 /// which have the exact same opcode and finds all inputs which are loop
100 /// invariant. For some operations these can be re-associated and unswitched out
101 /// of the loop entirely.
102 static TinyPtrVector<Value *>
103 collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
104                                          LoopInfo &LI) {
105   assert(!L.isLoopInvariant(&Root) &&
106          "Only need to walk the graph if root itself is not invariant.");
107   TinyPtrVector<Value *> Invariants;
108 
109   // Build a worklist and recurse through operators collecting invariants.
110   SmallVector<Instruction *, 4> Worklist;
111   SmallPtrSet<Instruction *, 8> Visited;
112   Worklist.push_back(&Root);
113   Visited.insert(&Root);
114   do {
115     Instruction &I = *Worklist.pop_back_val();
116     for (Value *OpV : I.operand_values()) {
117       // Skip constants as unswitching isn't interesting for them.
118       if (isa<Constant>(OpV))
119         continue;
120 
121       // Add it to our result if loop invariant.
122       if (L.isLoopInvariant(OpV)) {
123         Invariants.push_back(OpV);
124         continue;
125       }
126 
127       // If not an instruction with the same opcode, nothing we can do.
128       Instruction *OpI = dyn_cast<Instruction>(OpV);
129       if (!OpI || OpI->getOpcode() != Root.getOpcode())
130         continue;
131 
132       // Visit this operand.
133       if (Visited.insert(OpI).second)
134         Worklist.push_back(OpI);
135     }
136   } while (!Worklist.empty());
137 
138   return Invariants;
139 }
140 
141 static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
142                                      Constant &Replacement) {
143   assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
144 
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.
148     Use *U = &*UI++;
149     Instruction *UserI = dyn_cast<Instruction>(U->getUser());
150 
151     // Replace this use within the loop body.
152     if (UserI && L.contains(UserI))
153       U->set(&Replacement);
154   }
155 }
156 
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);
163     if (!PN)
164       // No more PHIs to check.
165       return true;
166 
167     // If the incoming value for this edge isn't loop invariant the unswitch
168     // won't be trivial.
169     if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
170       return false;
171   }
172   llvm_unreachable("Basic blocks should never be empty!");
173 }
174 
175 /// Insert code to test a set of loop invariant values, and conditionally branch
176 /// on them.
177 static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
178                                                   ArrayRef<Value *> Invariants,
179                                                   bool Direction,
180                                                   BasicBlock &UnswitchedSucc,
181                                                   BasicBlock &NormalSucc) {
182   IRBuilder<> IRB(&BB);
183   Value *Cond = Invariants.front();
184   for (Value *Invariant :
185        make_range(std::next(Invariants.begin()), Invariants.end()))
186     if (Direction)
187       Cond = IRB.CreateOr(Cond, Invariant);
188     else
189       Cond = IRB.CreateAnd(Cond, Invariant);
190 
191   IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
192                    Direction ? &NormalSucc : &UnswitchedSucc);
193 }
194 
195 /// Rewrite the PHI nodes in an unswitched loop exit basic block.
196 ///
197 /// Requires that the loop exit and unswitched basic block are the same, and
198 /// that the exiting block was a unique predecessor of that block. Rewrites the
199 /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
200 /// PHI nodes from the old preheader that now contains the unswitched
201 /// terminator.
202 static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
203                                                   BasicBlock &OldExitingBB,
204                                                   BasicBlock &OldPH) {
205   for (PHINode &PN : UnswitchedBB.phis()) {
206     // When the loop exit is directly unswitched we just need to update the
207     // incoming basic block. We loop to handle weird cases with repeated
208     // incoming blocks, but expect to typically only have one operand here.
209     for (auto i : seq<int>(0, PN.getNumOperands())) {
210       assert(PN.getIncomingBlock(i) == &OldExitingBB &&
211              "Found incoming block different from unique predecessor!");
212       PN.setIncomingBlock(i, &OldPH);
213     }
214   }
215 }
216 
217 /// Rewrite the PHI nodes in the loop exit basic block and the split off
218 /// unswitched block.
219 ///
220 /// Because the exit block remains an exit from the loop, this rewrites the
221 /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
222 /// nodes into the unswitched basic block to select between the value in the
223 /// old preheader and the loop exit.
224 static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
225                                                       BasicBlock &UnswitchedBB,
226                                                       BasicBlock &OldExitingBB,
227                                                       BasicBlock &OldPH,
228                                                       bool FullUnswitch) {
229   assert(&ExitBB != &UnswitchedBB &&
230          "Must have different loop exit and unswitched blocks!");
231   Instruction *InsertPt = &*UnswitchedBB.begin();
232   for (PHINode &PN : ExitBB.phis()) {
233     auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
234                                   PN.getName() + ".split", InsertPt);
235 
236     // Walk backwards over the old PHI node's inputs to minimize the cost of
237     // removing each one. We have to do this weird loop manually so that we
238     // create the same number of new incoming edges in the new PHI as we expect
239     // each case-based edge to be included in the unswitched switch in some
240     // cases.
241     // FIXME: This is really, really gross. It would be much cleaner if LLVM
242     // allowed us to create a single entry for a predecessor block without
243     // having separate entries for each "edge" even though these edges are
244     // required to produce identical results.
245     for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
246       if (PN.getIncomingBlock(i) != &OldExitingBB)
247         continue;
248 
249       Value *Incoming = PN.getIncomingValue(i);
250       if (FullUnswitch)
251         // No more edge from the old exiting block to the exit block.
252         PN.removeIncomingValue(i);
253 
254       NewPN->addIncoming(Incoming, &OldPH);
255     }
256 
257     // Now replace the old PHI with the new one and wire the old one in as an
258     // input to the new one.
259     PN.replaceAllUsesWith(NewPN);
260     NewPN->addIncoming(&PN, &ExitBB);
261   }
262 }
263 
264 /// Hoist the current loop up to the innermost loop containing a remaining exit.
265 ///
266 /// Because we've removed an exit from the loop, we may have changed the set of
267 /// loops reachable and need to move the current loop up the loop nest or even
268 /// to an entirely separate nest.
269 static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
270                                  DominatorTree &DT, LoopInfo &LI,
271                                  MemorySSAUpdater *MSSAU) {
272   // If the loop is already at the top level, we can't hoist it anywhere.
273   Loop *OldParentL = L.getParentLoop();
274   if (!OldParentL)
275     return;
276 
277   SmallVector<BasicBlock *, 4> Exits;
278   L.getExitBlocks(Exits);
279   Loop *NewParentL = nullptr;
280   for (auto *ExitBB : Exits)
281     if (Loop *ExitL = LI.getLoopFor(ExitBB))
282       if (!NewParentL || NewParentL->contains(ExitL))
283         NewParentL = ExitL;
284 
285   if (NewParentL == OldParentL)
286     return;
287 
288   // The new parent loop (if different) should always contain the old one.
289   if (NewParentL)
290     assert(NewParentL->contains(OldParentL) &&
291            "Can only hoist this loop up the nest!");
292 
293   // The preheader will need to move with the body of this loop. However,
294   // because it isn't in this loop we also need to update the primary loop map.
295   assert(OldParentL == LI.getLoopFor(&Preheader) &&
296          "Parent loop of this loop should contain this loop's preheader!");
297   LI.changeLoopFor(&Preheader, NewParentL);
298 
299   // Remove this loop from its old parent.
300   OldParentL->removeChildLoop(&L);
301 
302   // Add the loop either to the new parent or as a top-level loop.
303   if (NewParentL)
304     NewParentL->addChildLoop(&L);
305   else
306     LI.addTopLevelLoop(&L);
307 
308   // Remove this loops blocks from the old parent and every other loop up the
309   // nest until reaching the new parent. Also update all of these
310   // no-longer-containing loops to reflect the nesting change.
311   for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
312        OldContainingL = OldContainingL->getParentLoop()) {
313     llvm::erase_if(OldContainingL->getBlocksVector(),
314                    [&](const BasicBlock *BB) {
315                      return BB == &Preheader || L.contains(BB);
316                    });
317 
318     OldContainingL->getBlocksSet().erase(&Preheader);
319     for (BasicBlock *BB : L.blocks())
320       OldContainingL->getBlocksSet().erase(BB);
321 
322     // Because we just hoisted a loop out of this one, we have essentially
323     // created new exit paths from it. That means we need to form LCSSA PHI
324     // nodes for values used in the no-longer-nested loop.
325     formLCSSA(*OldContainingL, DT, &LI, nullptr);
326 
327     // We shouldn't need to form dedicated exits because the exit introduced
328     // here is the (just split by unswitching) preheader. However, after trivial
329     // unswitching it is possible to get new non-dedicated exits out of parent
330     // loop so let's conservatively form dedicated exit blocks and figure out
331     // if we can optimize later.
332     formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
333                             /*PreserveLCSSA*/ true);
334   }
335 }
336 
337 /// Unswitch a trivial branch if the condition is loop invariant.
338 ///
339 /// This routine should only be called when loop code leading to the branch has
340 /// been validated as trivial (no side effects). This routine checks if the
341 /// condition is invariant and one of the successors is a loop exit. This
342 /// allows us to unswitch without duplicating the loop, making it trivial.
343 ///
344 /// If this routine fails to unswitch the branch it returns false.
345 ///
346 /// If the branch can be unswitched, this routine splits the preheader and
347 /// hoists the branch above that split. Preserves loop simplified form
348 /// (splitting the exit block as necessary). It simplifies the branch within
349 /// the loop to an unconditional branch but doesn't remove it entirely. Further
350 /// cleanup can be done with some simplify-cfg like pass.
351 ///
352 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
353 /// invalidated by this.
354 static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
355                                   LoopInfo &LI, ScalarEvolution *SE,
356                                   MemorySSAUpdater *MSSAU) {
357   assert(BI.isConditional() && "Can only unswitch a conditional branch!");
358   LLVM_DEBUG(dbgs() << "  Trying to unswitch branch: " << BI << "\n");
359 
360   // The loop invariant values that we want to unswitch.
361   TinyPtrVector<Value *> Invariants;
362 
363   // When true, we're fully unswitching the branch rather than just unswitching
364   // some input conditions to the branch.
365   bool FullUnswitch = false;
366 
367   if (L.isLoopInvariant(BI.getCondition())) {
368     Invariants.push_back(BI.getCondition());
369     FullUnswitch = true;
370   } else {
371     if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
372       Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
373     if (Invariants.empty())
374       // Couldn't find invariant inputs!
375       return false;
376   }
377 
378   // Check that one of the branch's successors exits, and which one.
379   bool ExitDirection = true;
380   int LoopExitSuccIdx = 0;
381   auto *LoopExitBB = BI.getSuccessor(0);
382   if (L.contains(LoopExitBB)) {
383     ExitDirection = false;
384     LoopExitSuccIdx = 1;
385     LoopExitBB = BI.getSuccessor(1);
386     if (L.contains(LoopExitBB))
387       return false;
388   }
389   auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
390   auto *ParentBB = BI.getParent();
391   if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
392     return false;
393 
394   // When unswitching only part of the branch's condition, we need the exit
395   // block to be reached directly from the partially unswitched input. This can
396   // be done when the exit block is along the true edge and the branch condition
397   // is a graph of `or` operations, or the exit block is along the false edge
398   // and the condition is a graph of `and` operations.
399   if (!FullUnswitch) {
400     if (ExitDirection) {
401       if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or)
402         return false;
403     } else {
404       if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And)
405         return false;
406     }
407   }
408 
409   LLVM_DEBUG({
410     dbgs() << "    unswitching trivial invariant conditions for: " << BI
411            << "\n";
412     for (Value *Invariant : Invariants) {
413       dbgs() << "      " << *Invariant << " == true";
414       if (Invariant != Invariants.back())
415         dbgs() << " ||";
416       dbgs() << "\n";
417     }
418   });
419 
420   // If we have scalar evolutions, we need to invalidate them including this
421   // loop and the loop containing the exit block.
422   if (SE) {
423     if (Loop *ExitL = LI.getLoopFor(LoopExitBB))
424       SE->forgetLoop(ExitL);
425     else
426       // Forget the entire nest as this exits the entire nest.
427       SE->forgetTopmostLoop(&L);
428   }
429 
430   if (MSSAU && VerifyMemorySSA)
431     MSSAU->getMemorySSA()->verifyMemorySSA();
432 
433   // Split the preheader, so that we know that there is a safe place to insert
434   // the conditional branch. We will change the preheader to have a conditional
435   // branch on LoopCond.
436   BasicBlock *OldPH = L.getLoopPreheader();
437   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
438 
439   // Now that we have a place to insert the conditional branch, create a place
440   // to branch to: this is the exit block out of the loop that we are
441   // unswitching. We need to split this if there are other loop predecessors.
442   // Because the loop is in simplified form, *any* other predecessor is enough.
443   BasicBlock *UnswitchedBB;
444   if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
445     assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
446            "A branch's parent isn't a predecessor!");
447     UnswitchedBB = LoopExitBB;
448   } else {
449     UnswitchedBB =
450         SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
451   }
452 
453   if (MSSAU && VerifyMemorySSA)
454     MSSAU->getMemorySSA()->verifyMemorySSA();
455 
456   // Actually move the invariant uses into the unswitched position. If possible,
457   // we do this by moving the instructions, but when doing partial unswitching
458   // we do it by building a new merge of the values in the unswitched position.
459   OldPH->getTerminator()->eraseFromParent();
460   if (FullUnswitch) {
461     // If fully unswitching, we can use the existing branch instruction.
462     // Splice it into the old PH to gate reaching the new preheader and re-point
463     // its successors.
464     OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
465                                 BI);
466     if (MSSAU) {
467       // Temporarily clone the terminator, to make MSSA update cheaper by
468       // separating "insert edge" updates from "remove edge" ones.
469       ParentBB->getInstList().push_back(BI.clone());
470     } else {
471       // Create a new unconditional branch that will continue the loop as a new
472       // terminator.
473       BranchInst::Create(ContinueBB, ParentBB);
474     }
475     BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
476     BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
477   } else {
478     // Only unswitching a subset of inputs to the condition, so we will need to
479     // build a new branch that merges the invariant inputs.
480     if (ExitDirection)
481       assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
482                  Instruction::Or &&
483              "Must have an `or` of `i1`s for the condition!");
484     else
485       assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
486                  Instruction::And &&
487              "Must have an `and` of `i1`s for the condition!");
488     buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
489                                           *UnswitchedBB, *NewPH);
490   }
491 
492   // Update the dominator tree with the added edge.
493   DT.insertEdge(OldPH, UnswitchedBB);
494 
495   // After the dominator tree was updated with the added edge, update MemorySSA
496   // if available.
497   if (MSSAU) {
498     SmallVector<CFGUpdate, 1> Updates;
499     Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
500     MSSAU->applyInsertUpdates(Updates, DT);
501   }
502 
503   // Finish updating dominator tree and memory ssa for full unswitch.
504   if (FullUnswitch) {
505     if (MSSAU) {
506       // Remove the cloned branch instruction.
507       ParentBB->getTerminator()->eraseFromParent();
508       // Create unconditional branch now.
509       BranchInst::Create(ContinueBB, ParentBB);
510       MSSAU->removeEdge(ParentBB, LoopExitBB);
511     }
512     DT.deleteEdge(ParentBB, LoopExitBB);
513   }
514 
515   if (MSSAU && VerifyMemorySSA)
516     MSSAU->getMemorySSA()->verifyMemorySSA();
517 
518   // Rewrite the relevant PHI nodes.
519   if (UnswitchedBB == LoopExitBB)
520     rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
521   else
522     rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
523                                               *ParentBB, *OldPH, FullUnswitch);
524 
525   // The constant we can replace all of our invariants with inside the loop
526   // body. If any of the invariants have a value other than this the loop won't
527   // be entered.
528   ConstantInt *Replacement = ExitDirection
529                                  ? ConstantInt::getFalse(BI.getContext())
530                                  : ConstantInt::getTrue(BI.getContext());
531 
532   // Since this is an i1 condition we can also trivially replace uses of it
533   // within the loop with a constant.
534   for (Value *Invariant : Invariants)
535     replaceLoopInvariantUses(L, Invariant, *Replacement);
536 
537   // If this was full unswitching, we may have changed the nesting relationship
538   // for this loop so hoist it to its correct parent if needed.
539   if (FullUnswitch)
540     hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU);
541 
542   if (MSSAU && VerifyMemorySSA)
543     MSSAU->getMemorySSA()->verifyMemorySSA();
544 
545   LLVM_DEBUG(dbgs() << "    done: unswitching trivial branch...\n");
546   ++NumTrivial;
547   ++NumBranches;
548   return true;
549 }
550 
551 /// Unswitch a trivial switch if the condition is loop invariant.
552 ///
553 /// This routine should only be called when loop code leading to the switch has
554 /// been validated as trivial (no side effects). This routine checks if the
555 /// condition is invariant and that at least one of the successors is a loop
556 /// exit. This allows us to unswitch without duplicating the loop, making it
557 /// trivial.
558 ///
559 /// If this routine fails to unswitch the switch it returns false.
560 ///
561 /// If the switch can be unswitched, this routine splits the preheader and
562 /// copies the switch above that split. If the default case is one of the
563 /// exiting cases, it copies the non-exiting cases and points them at the new
564 /// preheader. If the default case is not exiting, it copies the exiting cases
565 /// and points the default at the preheader. It preserves loop simplified form
566 /// (splitting the exit blocks as necessary). It simplifies the switch within
567 /// the loop by removing now-dead cases. If the default case is one of those
568 /// unswitched, it replaces its destination with a new basic block containing
569 /// only unreachable. Such basic blocks, while technically loop exits, are not
570 /// considered for unswitching so this is a stable transform and the same
571 /// switch will not be revisited. If after unswitching there is only a single
572 /// in-loop successor, the switch is further simplified to an unconditional
573 /// branch. Still more cleanup can be done with some simplify-cfg like pass.
574 ///
575 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
576 /// invalidated by this.
577 static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
578                                   LoopInfo &LI, ScalarEvolution *SE,
579                                   MemorySSAUpdater *MSSAU) {
580   LLVM_DEBUG(dbgs() << "  Trying to unswitch switch: " << SI << "\n");
581   Value *LoopCond = SI.getCondition();
582 
583   // If this isn't switching on an invariant condition, we can't unswitch it.
584   if (!L.isLoopInvariant(LoopCond))
585     return false;
586 
587   auto *ParentBB = SI.getParent();
588 
589   SmallVector<int, 4> ExitCaseIndices;
590   for (auto Case : SI.cases()) {
591     auto *SuccBB = Case.getCaseSuccessor();
592     if (!L.contains(SuccBB) &&
593         areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB))
594       ExitCaseIndices.push_back(Case.getCaseIndex());
595   }
596   BasicBlock *DefaultExitBB = nullptr;
597   if (!L.contains(SI.getDefaultDest()) &&
598       areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) &&
599       !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator()))
600     DefaultExitBB = SI.getDefaultDest();
601   else if (ExitCaseIndices.empty())
602     return false;
603 
604   LLVM_DEBUG(dbgs() << "    unswitching trivial switch...\n");
605 
606   if (MSSAU && VerifyMemorySSA)
607     MSSAU->getMemorySSA()->verifyMemorySSA();
608 
609   // We may need to invalidate SCEVs for the outermost loop reached by any of
610   // the exits.
611   Loop *OuterL = &L;
612 
613   if (DefaultExitBB) {
614     // Clear out the default destination temporarily to allow accurate
615     // predecessor lists to be examined below.
616     SI.setDefaultDest(nullptr);
617     // Check the loop containing this exit.
618     Loop *ExitL = LI.getLoopFor(DefaultExitBB);
619     if (!ExitL || ExitL->contains(OuterL))
620       OuterL = ExitL;
621   }
622 
623   // Store the exit cases into a separate data structure and remove them from
624   // the switch.
625   SmallVector<std::pair<ConstantInt *, BasicBlock *>, 4> ExitCases;
626   ExitCases.reserve(ExitCaseIndices.size());
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))
634       OuterL = ExitL;
635     // Save the value of this case.
636     ExitCases.push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()});
637     // Delete the unswitched cases.
638     SI.removeCase(CaseI);
639   }
640 
641   if (SE) {
642     if (OuterL)
643       SE->forgetLoop(OuterL);
644     else
645       SE->forgetTopmostLoop(&L);
646   }
647 
648   // Check if after this all of the remaining cases point at the same
649   // successor.
650   BasicBlock *CommonSuccBB = nullptr;
651   if (SI.getNumCases() > 0 &&
652       std::all_of(std::next(SI.case_begin()), SI.case_end(),
653                   [&SI](const SwitchInst::CaseHandle &Case) {
654                     return Case.getCaseSuccessor() ==
655                            SI.case_begin()->getCaseSuccessor();
656                   }))
657     CommonSuccBB = SI.case_begin()->getCaseSuccessor();
658   if (!DefaultExitBB) {
659     // If we're not unswitching the default, we need it to match any cases to
660     // have a common successor or if we have no cases it is the common
661     // successor.
662     if (SI.getNumCases() == 0)
663       CommonSuccBB = SI.getDefaultDest();
664     else if (SI.getDefaultDest() != CommonSuccBB)
665       CommonSuccBB = nullptr;
666   }
667 
668   // Split the preheader, so that we know that there is a safe place to insert
669   // the switch.
670   BasicBlock *OldPH = L.getLoopPreheader();
671   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
672   OldPH->getTerminator()->eraseFromParent();
673 
674   // Now add the unswitched switch.
675   auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
676 
677   // Rewrite the IR for the unswitched basic blocks. This requires two steps.
678   // First, we split any exit blocks with remaining in-loop predecessors. Then
679   // we update the PHIs in one of two ways depending on if there was a split.
680   // We walk in reverse so that we split in the same order as the cases
681   // appeared. This is purely for convenience of reading the resulting IR, but
682   // it doesn't cost anything really.
683   SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
684   SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
685   // Handle the default exit if necessary.
686   // FIXME: It'd be great if we could merge this with the loop below but LLVM's
687   // ranges aren't quite powerful enough yet.
688   if (DefaultExitBB) {
689     if (pred_empty(DefaultExitBB)) {
690       UnswitchedExitBBs.insert(DefaultExitBB);
691       rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
692     } else {
693       auto *SplitBB =
694           SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
695       rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
696                                                 *ParentBB, *OldPH,
697                                                 /*FullUnswitch*/ true);
698       DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
699     }
700   }
701   // Note that we must use a reference in the for loop so that we update the
702   // container.
703   for (auto &CasePair : reverse(ExitCases)) {
704     // Grab a reference to the exit block in the pair so that we can update it.
705     BasicBlock *ExitBB = CasePair.second;
706 
707     // If this case is the last edge into the exit block, we can simply reuse it
708     // as it will no longer be a loop exit. No mapping necessary.
709     if (pred_empty(ExitBB)) {
710       // Only rewrite once.
711       if (UnswitchedExitBBs.insert(ExitBB).second)
712         rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
713       continue;
714     }
715 
716     // Otherwise we need to split the exit block so that we retain an exit
717     // block from the loop and a target for the unswitched condition.
718     BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
719     if (!SplitExitBB) {
720       // If this is the first time we see this, do the split and remember it.
721       SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
722       rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
723                                                 *ParentBB, *OldPH,
724                                                 /*FullUnswitch*/ true);
725     }
726     // Update the case pair to point to the split block.
727     CasePair.second = SplitExitBB;
728   }
729 
730   // Now add the unswitched cases. We do this in reverse order as we built them
731   // in reverse order.
732   for (auto CasePair : reverse(ExitCases)) {
733     ConstantInt *CaseVal = CasePair.first;
734     BasicBlock *UnswitchedBB = CasePair.second;
735 
736     NewSI->addCase(CaseVal, UnswitchedBB);
737   }
738 
739   // If the default was unswitched, re-point it and add explicit cases for
740   // entering the loop.
741   if (DefaultExitBB) {
742     NewSI->setDefaultDest(DefaultExitBB);
743 
744     // We removed all the exit cases, so we just copy the cases to the
745     // unswitched switch.
746     for (auto Case : SI.cases())
747       NewSI->addCase(Case.getCaseValue(), NewPH);
748   }
749 
750   // If we ended up with a common successor for every path through the switch
751   // after unswitching, rewrite it to an unconditional branch to make it easy
752   // to recognize. Otherwise we potentially have to recognize the default case
753   // pointing at unreachable and other complexity.
754   if (CommonSuccBB) {
755     BasicBlock *BB = SI.getParent();
756     // We may have had multiple edges to this common successor block, so remove
757     // them as predecessors. We skip the first one, either the default or the
758     // actual first case.
759     bool SkippedFirst = DefaultExitBB == nullptr;
760     for (auto Case : SI.cases()) {
761       assert(Case.getCaseSuccessor() == CommonSuccBB &&
762              "Non-common successor!");
763       (void)Case;
764       if (!SkippedFirst) {
765         SkippedFirst = true;
766         continue;
767       }
768       CommonSuccBB->removePredecessor(BB,
769                                       /*KeepOneInputPHIs*/ true);
770     }
771     // Now nuke the switch and replace it with a direct branch.
772     SI.eraseFromParent();
773     BranchInst::Create(CommonSuccBB, BB);
774   } else if (DefaultExitBB) {
775     assert(SI.getNumCases() > 0 &&
776            "If we had no cases we'd have a common successor!");
777     // Move the last case to the default successor. This is valid as if the
778     // default got unswitched it cannot be reached. This has the advantage of
779     // being simple and keeping the number of edges from this switch to
780     // successors the same, and avoiding any PHI update complexity.
781     auto LastCaseI = std::prev(SI.case_end());
782     SI.setDefaultDest(LastCaseI->getCaseSuccessor());
783     SI.removeCase(LastCaseI);
784   }
785 
786   // Walk the unswitched exit blocks and the unswitched split blocks and update
787   // the dominator tree based on the CFG edits. While we are walking unordered
788   // containers here, the API for applyUpdates takes an unordered list of
789   // updates and requires them to not contain duplicates.
790   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
791   for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
792     DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
793     DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
794   }
795   for (auto SplitUnswitchedPair : SplitExitBBMap) {
796     auto *UnswitchedBB = SplitUnswitchedPair.second;
797     DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedBB});
798     DTUpdates.push_back({DT.Insert, OldPH, UnswitchedBB});
799   }
800   DT.applyUpdates(DTUpdates);
801 
802   if (MSSAU) {
803     MSSAU->applyUpdates(DTUpdates, DT);
804     if (VerifyMemorySSA)
805       MSSAU->getMemorySSA()->verifyMemorySSA();
806   }
807 
808   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
809 
810   // We may have changed the nesting relationship for this loop so hoist it to
811   // its correct parent if needed.
812   hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU);
813 
814   if (MSSAU && VerifyMemorySSA)
815     MSSAU->getMemorySSA()->verifyMemorySSA();
816 
817   ++NumTrivial;
818   ++NumSwitches;
819   LLVM_DEBUG(dbgs() << "    done: unswitching trivial switch...\n");
820   return true;
821 }
822 
823 /// This routine scans the loop to find a branch or switch which occurs before
824 /// any side effects occur. These can potentially be unswitched without
825 /// duplicating the loop. If a branch or switch is successfully unswitched the
826 /// scanning continues to see if subsequent branches or switches have become
827 /// trivial. Once all trivial candidates have been unswitched, this routine
828 /// returns.
829 ///
830 /// The return value indicates whether anything was unswitched (and therefore
831 /// changed).
832 ///
833 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
834 /// invalidated by this.
835 static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
836                                          LoopInfo &LI, ScalarEvolution *SE,
837                                          MemorySSAUpdater *MSSAU) {
838   bool Changed = false;
839 
840   // If loop header has only one reachable successor we should keep looking for
841   // trivial condition candidates in the successor as well. An alternative is
842   // to constant fold conditions and merge successors into loop header (then we
843   // only need to check header's terminator). The reason for not doing this in
844   // LoopUnswitch pass is that it could potentially break LoopPassManager's
845   // invariants. Folding dead branches could either eliminate the current loop
846   // or make other loops unreachable. LCSSA form might also not be preserved
847   // after deleting branches. The following code keeps traversing loop header's
848   // successors until it finds the trivial condition candidate (condition that
849   // is not a constant). Since unswitching generates branches with constant
850   // conditions, this scenario could be very common in practice.
851   BasicBlock *CurrentBB = L.getHeader();
852   SmallPtrSet<BasicBlock *, 8> Visited;
853   Visited.insert(CurrentBB);
854   do {
855     // Check if there are any side-effecting instructions (e.g. stores, calls,
856     // volatile loads) in the part of the loop that the code *would* execute
857     // without unswitching.
858     if (MSSAU) // Possible early exit with MSSA
859       if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
860         if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
861           return Changed;
862     if (llvm::any_of(*CurrentBB,
863                      [](Instruction &I) { return I.mayHaveSideEffects(); }))
864       return Changed;
865 
866     Instruction *CurrentTerm = CurrentBB->getTerminator();
867 
868     if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
869       // Don't bother trying to unswitch past a switch with a constant
870       // condition. This should be removed prior to running this pass by
871       // simplify-cfg.
872       if (isa<Constant>(SI->getCondition()))
873         return Changed;
874 
875       if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
876         // Couldn't unswitch this one so we're done.
877         return Changed;
878 
879       // Mark that we managed to unswitch something.
880       Changed = true;
881 
882       // If unswitching turned the terminator into an unconditional branch then
883       // we can continue. The unswitching logic specifically works to fold any
884       // cases it can into an unconditional branch to make it easier to
885       // recognize here.
886       auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
887       if (!BI || BI->isConditional())
888         return Changed;
889 
890       CurrentBB = BI->getSuccessor(0);
891       continue;
892     }
893 
894     auto *BI = dyn_cast<BranchInst>(CurrentTerm);
895     if (!BI)
896       // We do not understand other terminator instructions.
897       return Changed;
898 
899     // Don't bother trying to unswitch past an unconditional branch or a branch
900     // with a constant value. These should be removed by simplify-cfg prior to
901     // running this pass.
902     if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
903       return Changed;
904 
905     // Found a trivial condition candidate: non-foldable conditional branch. If
906     // we fail to unswitch this, we can't do anything else that is trivial.
907     if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
908       return Changed;
909 
910     // Mark that we managed to unswitch something.
911     Changed = true;
912 
913     // If we only unswitched some of the conditions feeding the branch, we won't
914     // have collapsed it to a single successor.
915     BI = cast<BranchInst>(CurrentBB->getTerminator());
916     if (BI->isConditional())
917       return Changed;
918 
919     // Follow the newly unconditional branch into its successor.
920     CurrentBB = BI->getSuccessor(0);
921 
922     // When continuing, if we exit the loop or reach a previous visited block,
923     // then we can not reach any trivial condition candidates (unfoldable
924     // branch instructions or switch instructions) and no unswitch can happen.
925   } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
926 
927   return Changed;
928 }
929 
930 /// Build the cloned blocks for an unswitched copy of the given loop.
931 ///
932 /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
933 /// after the split block (`SplitBB`) that will be used to select between the
934 /// cloned and original loop.
935 ///
936 /// This routine handles cloning all of the necessary loop blocks and exit
937 /// blocks including rewriting their instructions and the relevant PHI nodes.
938 /// Any loop blocks or exit blocks which are dominated by a different successor
939 /// than the one for this clone of the loop blocks can be trivially skipped. We
940 /// use the `DominatingSucc` map to determine whether a block satisfies that
941 /// property with a simple map lookup.
942 ///
943 /// It also correctly creates the unconditional branch in the cloned
944 /// unswitched parent block to only point at the unswitched successor.
945 ///
946 /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
947 /// block splitting is correctly reflected in `LoopInfo`, essentially all of
948 /// the cloned blocks (and their loops) are left without full `LoopInfo`
949 /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
950 /// blocks to them but doesn't create the cloned `DominatorTree` structure and
951 /// instead the caller must recompute an accurate DT. It *does* correctly
952 /// update the `AssumptionCache` provided in `AC`.
953 static BasicBlock *buildClonedLoopBlocks(
954     Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
955     ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
956     BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
957     const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
958     ValueToValueMapTy &VMap,
959     SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
960     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
961   SmallVector<BasicBlock *, 4> NewBlocks;
962   NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
963 
964   // We will need to clone a bunch of blocks, wrap up the clone operation in
965   // a helper.
966   auto CloneBlock = [&](BasicBlock *OldBB) {
967     // Clone the basic block and insert it before the new preheader.
968     BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
969     NewBB->moveBefore(LoopPH);
970 
971     // Record this block and the mapping.
972     NewBlocks.push_back(NewBB);
973     VMap[OldBB] = NewBB;
974 
975     return NewBB;
976   };
977 
978   // We skip cloning blocks when they have a dominating succ that is not the
979   // succ we are cloning for.
980   auto SkipBlock = [&](BasicBlock *BB) {
981     auto It = DominatingSucc.find(BB);
982     return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
983   };
984 
985   // First, clone the preheader.
986   auto *ClonedPH = CloneBlock(LoopPH);
987 
988   // Then clone all the loop blocks, skipping the ones that aren't necessary.
989   for (auto *LoopBB : L.blocks())
990     if (!SkipBlock(LoopBB))
991       CloneBlock(LoopBB);
992 
993   // Split all the loop exit edges so that when we clone the exit blocks, if
994   // any of the exit blocks are *also* a preheader for some other loop, we
995   // don't create multiple predecessors entering the loop header.
996   for (auto *ExitBB : ExitBlocks) {
997     if (SkipBlock(ExitBB))
998       continue;
999 
1000     // When we are going to clone an exit, we don't need to clone all the
1001     // instructions in the exit block and we want to ensure we have an easy
1002     // place to merge the CFG, so split the exit first. This is always safe to
1003     // do because there cannot be any non-loop predecessors of a loop exit in
1004     // loop simplified form.
1005     auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
1006 
1007     // Rearrange the names to make it easier to write test cases by having the
1008     // exit block carry the suffix rather than the merge block carrying the
1009     // suffix.
1010     MergeBB->takeName(ExitBB);
1011     ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1012 
1013     // Now clone the original exit block.
1014     auto *ClonedExitBB = CloneBlock(ExitBB);
1015     assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1016            "Exit block should have been split to have one successor!");
1017     assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1018            "Cloned exit block has the wrong successor!");
1019 
1020     // Remap any cloned instructions and create a merge phi node for them.
1021     for (auto ZippedInsts : llvm::zip_first(
1022              llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1023              llvm::make_range(ClonedExitBB->begin(),
1024                               std::prev(ClonedExitBB->end())))) {
1025       Instruction &I = std::get<0>(ZippedInsts);
1026       Instruction &ClonedI = std::get<1>(ZippedInsts);
1027 
1028       // The only instructions in the exit block should be PHI nodes and
1029       // potentially a landing pad.
1030       assert(
1031           (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1032           "Bad instruction in exit block!");
1033       // We should have a value map between the instruction and its clone.
1034       assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1035 
1036       auto *MergePN =
1037           PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1038                           &*MergeBB->getFirstInsertionPt());
1039       I.replaceAllUsesWith(MergePN);
1040       MergePN->addIncoming(&I, ExitBB);
1041       MergePN->addIncoming(&ClonedI, ClonedExitBB);
1042     }
1043   }
1044 
1045   // Rewrite the instructions in the cloned blocks to refer to the instructions
1046   // in the cloned blocks. We have to do this as a second pass so that we have
1047   // everything available. Also, we have inserted new instructions which may
1048   // include assume intrinsics, so we update the assumption cache while
1049   // processing this.
1050   for (auto *ClonedBB : NewBlocks)
1051     for (Instruction &I : *ClonedBB) {
1052       RemapInstruction(&I, VMap,
1053                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1054       if (auto *II = dyn_cast<IntrinsicInst>(&I))
1055         if (II->getIntrinsicID() == Intrinsic::assume)
1056           AC.registerAssumption(II);
1057     }
1058 
1059   // Update any PHI nodes in the cloned successors of the skipped blocks to not
1060   // have spurious incoming values.
1061   for (auto *LoopBB : L.blocks())
1062     if (SkipBlock(LoopBB))
1063       for (auto *SuccBB : successors(LoopBB))
1064         if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1065           for (PHINode &PN : ClonedSuccBB->phis())
1066             PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1067 
1068   // Remove the cloned parent as a predecessor of any successor we ended up
1069   // cloning other than the unswitched one.
1070   auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1071   for (auto *SuccBB : successors(ParentBB)) {
1072     if (SuccBB == UnswitchedSuccBB)
1073       continue;
1074 
1075     auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1076     if (!ClonedSuccBB)
1077       continue;
1078 
1079     ClonedSuccBB->removePredecessor(ClonedParentBB,
1080                                     /*KeepOneInputPHIs*/ true);
1081   }
1082 
1083   // Replace the cloned branch with an unconditional branch to the cloned
1084   // unswitched successor.
1085   auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1086   ClonedParentBB->getTerminator()->eraseFromParent();
1087   BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1088 
1089   // If there are duplicate entries in the PHI nodes because of multiple edges
1090   // to the unswitched successor, we need to nuke all but one as we replaced it
1091   // with a direct branch.
1092   for (PHINode &PN : ClonedSuccBB->phis()) {
1093     bool Found = false;
1094     // Loop over the incoming operands backwards so we can easily delete as we
1095     // go without invalidating the index.
1096     for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1097       if (PN.getIncomingBlock(i) != ClonedParentBB)
1098         continue;
1099       if (!Found) {
1100         Found = true;
1101         continue;
1102       }
1103       PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1104     }
1105   }
1106 
1107   // Record the domtree updates for the new blocks.
1108   SmallPtrSet<BasicBlock *, 4> SuccSet;
1109   for (auto *ClonedBB : NewBlocks) {
1110     for (auto *SuccBB : successors(ClonedBB))
1111       if (SuccSet.insert(SuccBB).second)
1112         DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1113     SuccSet.clear();
1114   }
1115 
1116   return ClonedPH;
1117 }
1118 
1119 /// Recursively clone the specified loop and all of its children.
1120 ///
1121 /// The target parent loop for the clone should be provided, or can be null if
1122 /// the clone is a top-level loop. While cloning, all the blocks are mapped
1123 /// with the provided value map. The entire original loop must be present in
1124 /// the value map. The cloned loop is returned.
1125 static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1126                            const ValueToValueMapTy &VMap, LoopInfo &LI) {
1127   auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1128     assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1129     ClonedL.reserveBlocks(OrigL.getNumBlocks());
1130     for (auto *BB : OrigL.blocks()) {
1131       auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1132       ClonedL.addBlockEntry(ClonedBB);
1133       if (LI.getLoopFor(BB) == &OrigL)
1134         LI.changeLoopFor(ClonedBB, &ClonedL);
1135     }
1136   };
1137 
1138   // We specially handle the first loop because it may get cloned into
1139   // a different parent and because we most commonly are cloning leaf loops.
1140   Loop *ClonedRootL = LI.AllocateLoop();
1141   if (RootParentL)
1142     RootParentL->addChildLoop(ClonedRootL);
1143   else
1144     LI.addTopLevelLoop(ClonedRootL);
1145   AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1146 
1147   if (OrigRootL.empty())
1148     return ClonedRootL;
1149 
1150   // If we have a nest, we can quickly clone the entire loop nest using an
1151   // iterative approach because it is a tree. We keep the cloned parent in the
1152   // data structure to avoid repeatedly querying through a map to find it.
1153   SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1154   // Build up the loops to clone in reverse order as we'll clone them from the
1155   // back.
1156   for (Loop *ChildL : llvm::reverse(OrigRootL))
1157     LoopsToClone.push_back({ClonedRootL, ChildL});
1158   do {
1159     Loop *ClonedParentL, *L;
1160     std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1161     Loop *ClonedL = LI.AllocateLoop();
1162     ClonedParentL->addChildLoop(ClonedL);
1163     AddClonedBlocksToLoop(*L, *ClonedL);
1164     for (Loop *ChildL : llvm::reverse(*L))
1165       LoopsToClone.push_back({ClonedL, ChildL});
1166   } while (!LoopsToClone.empty());
1167 
1168   return ClonedRootL;
1169 }
1170 
1171 /// Build the cloned loops of an original loop from unswitching.
1172 ///
1173 /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1174 /// operation. We need to re-verify that there even is a loop (as the backedge
1175 /// may not have been cloned), and even if there are remaining backedges the
1176 /// backedge set may be different. However, we know that each child loop is
1177 /// undisturbed, we only need to find where to place each child loop within
1178 /// either any parent loop or within a cloned version of the original loop.
1179 ///
1180 /// Because child loops may end up cloned outside of any cloned version of the
1181 /// original loop, multiple cloned sibling loops may be created. All of them
1182 /// are returned so that the newly introduced loop nest roots can be
1183 /// identified.
1184 static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1185                              const ValueToValueMapTy &VMap, LoopInfo &LI,
1186                              SmallVectorImpl<Loop *> &NonChildClonedLoops) {
1187   Loop *ClonedL = nullptr;
1188 
1189   auto *OrigPH = OrigL.getLoopPreheader();
1190   auto *OrigHeader = OrigL.getHeader();
1191 
1192   auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1193   auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1194 
1195   // We need to know the loops of the cloned exit blocks to even compute the
1196   // accurate parent loop. If we only clone exits to some parent of the
1197   // original parent, we want to clone into that outer loop. We also keep track
1198   // of the loops that our cloned exit blocks participate in.
1199   Loop *ParentL = nullptr;
1200   SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1201   SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1202   ClonedExitsInLoops.reserve(ExitBlocks.size());
1203   for (auto *ExitBB : ExitBlocks)
1204     if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1205       if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1206         ExitLoopMap[ClonedExitBB] = ExitL;
1207         ClonedExitsInLoops.push_back(ClonedExitBB);
1208         if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1209           ParentL = ExitL;
1210       }
1211   assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1212           ParentL->contains(OrigL.getParentLoop())) &&
1213          "The computed parent loop should always contain (or be) the parent of "
1214          "the original loop.");
1215 
1216   // We build the set of blocks dominated by the cloned header from the set of
1217   // cloned blocks out of the original loop. While not all of these will
1218   // necessarily be in the cloned loop, it is enough to establish that they
1219   // aren't in unreachable cycles, etc.
1220   SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1221   for (auto *BB : OrigL.blocks())
1222     if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1223       ClonedLoopBlocks.insert(ClonedBB);
1224 
1225   // Rebuild the set of blocks that will end up in the cloned loop. We may have
1226   // skipped cloning some region of this loop which can in turn skip some of
1227   // the backedges so we have to rebuild the blocks in the loop based on the
1228   // backedges that remain after cloning.
1229   SmallVector<BasicBlock *, 16> Worklist;
1230   SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1231   for (auto *Pred : predecessors(ClonedHeader)) {
1232     // The only possible non-loop header predecessor is the preheader because
1233     // we know we cloned the loop in simplified form.
1234     if (Pred == ClonedPH)
1235       continue;
1236 
1237     // Because the loop was in simplified form, the only non-loop predecessor
1238     // should be the preheader.
1239     assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1240                                            "header other than the preheader "
1241                                            "that is not part of the loop!");
1242 
1243     // Insert this block into the loop set and on the first visit (and if it
1244     // isn't the header we're currently walking) put it into the worklist to
1245     // recurse through.
1246     if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1247       Worklist.push_back(Pred);
1248   }
1249 
1250   // If we had any backedges then there *is* a cloned loop. Put the header into
1251   // the loop set and then walk the worklist backwards to find all the blocks
1252   // that remain within the loop after cloning.
1253   if (!BlocksInClonedLoop.empty()) {
1254     BlocksInClonedLoop.insert(ClonedHeader);
1255 
1256     while (!Worklist.empty()) {
1257       BasicBlock *BB = Worklist.pop_back_val();
1258       assert(BlocksInClonedLoop.count(BB) &&
1259              "Didn't put block into the loop set!");
1260 
1261       // Insert any predecessors that are in the possible set into the cloned
1262       // set, and if the insert is successful, add them to the worklist. Note
1263       // that we filter on the blocks that are definitely reachable via the
1264       // backedge to the loop header so we may prune out dead code within the
1265       // cloned loop.
1266       for (auto *Pred : predecessors(BB))
1267         if (ClonedLoopBlocks.count(Pred) &&
1268             BlocksInClonedLoop.insert(Pred).second)
1269           Worklist.push_back(Pred);
1270     }
1271 
1272     ClonedL = LI.AllocateLoop();
1273     if (ParentL) {
1274       ParentL->addBasicBlockToLoop(ClonedPH, LI);
1275       ParentL->addChildLoop(ClonedL);
1276     } else {
1277       LI.addTopLevelLoop(ClonedL);
1278     }
1279     NonChildClonedLoops.push_back(ClonedL);
1280 
1281     ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1282     // We don't want to just add the cloned loop blocks based on how we
1283     // discovered them. The original order of blocks was carefully built in
1284     // a way that doesn't rely on predecessor ordering. Rather than re-invent
1285     // that logic, we just re-walk the original blocks (and those of the child
1286     // loops) and filter them as we add them into the cloned loop.
1287     for (auto *BB : OrigL.blocks()) {
1288       auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1289       if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1290         continue;
1291 
1292       // Directly add the blocks that are only in this loop.
1293       if (LI.getLoopFor(BB) == &OrigL) {
1294         ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1295         continue;
1296       }
1297 
1298       // We want to manually add it to this loop and parents.
1299       // Registering it with LoopInfo will happen when we clone the top
1300       // loop for this block.
1301       for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1302         PL->addBlockEntry(ClonedBB);
1303     }
1304 
1305     // Now add each child loop whose header remains within the cloned loop. All
1306     // of the blocks within the loop must satisfy the same constraints as the
1307     // header so once we pass the header checks we can just clone the entire
1308     // child loop nest.
1309     for (Loop *ChildL : OrigL) {
1310       auto *ClonedChildHeader =
1311           cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1312       if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1313         continue;
1314 
1315 #ifndef NDEBUG
1316       // We should never have a cloned child loop header but fail to have
1317       // all of the blocks for that child loop.
1318       for (auto *ChildLoopBB : ChildL->blocks())
1319         assert(BlocksInClonedLoop.count(
1320                    cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1321                "Child cloned loop has a header within the cloned outer "
1322                "loop but not all of its blocks!");
1323 #endif
1324 
1325       cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1326     }
1327   }
1328 
1329   // Now that we've handled all the components of the original loop that were
1330   // cloned into a new loop, we still need to handle anything from the original
1331   // loop that wasn't in a cloned loop.
1332 
1333   // Figure out what blocks are left to place within any loop nest containing
1334   // the unswitched loop. If we never formed a loop, the cloned PH is one of
1335   // them.
1336   SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1337   if (BlocksInClonedLoop.empty())
1338     UnloopedBlockSet.insert(ClonedPH);
1339   for (auto *ClonedBB : ClonedLoopBlocks)
1340     if (!BlocksInClonedLoop.count(ClonedBB))
1341       UnloopedBlockSet.insert(ClonedBB);
1342 
1343   // Copy the cloned exits and sort them in ascending loop depth, we'll work
1344   // backwards across these to process them inside out. The order shouldn't
1345   // matter as we're just trying to build up the map from inside-out; we use
1346   // the map in a more stably ordered way below.
1347   auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
1348   llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1349     return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1350            ExitLoopMap.lookup(RHS)->getLoopDepth();
1351   });
1352 
1353   // Populate the existing ExitLoopMap with everything reachable from each
1354   // exit, starting from the inner most exit.
1355   while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1356     assert(Worklist.empty() && "Didn't clear worklist!");
1357 
1358     BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1359     Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1360 
1361     // Walk the CFG back until we hit the cloned PH adding everything reachable
1362     // and in the unlooped set to this exit block's loop.
1363     Worklist.push_back(ExitBB);
1364     do {
1365       BasicBlock *BB = Worklist.pop_back_val();
1366       // We can stop recursing at the cloned preheader (if we get there).
1367       if (BB == ClonedPH)
1368         continue;
1369 
1370       for (BasicBlock *PredBB : predecessors(BB)) {
1371         // If this pred has already been moved to our set or is part of some
1372         // (inner) loop, no update needed.
1373         if (!UnloopedBlockSet.erase(PredBB)) {
1374           assert(
1375               (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1376               "Predecessor not mapped to a loop!");
1377           continue;
1378         }
1379 
1380         // We just insert into the loop set here. We'll add these blocks to the
1381         // exit loop after we build up the set in an order that doesn't rely on
1382         // predecessor order (which in turn relies on use list order).
1383         bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1384         (void)Inserted;
1385         assert(Inserted && "Should only visit an unlooped block once!");
1386 
1387         // And recurse through to its predecessors.
1388         Worklist.push_back(PredBB);
1389       }
1390     } while (!Worklist.empty());
1391   }
1392 
1393   // Now that the ExitLoopMap gives as  mapping for all the non-looping cloned
1394   // blocks to their outer loops, walk the cloned blocks and the cloned exits
1395   // in their original order adding them to the correct loop.
1396 
1397   // We need a stable insertion order. We use the order of the original loop
1398   // order and map into the correct parent loop.
1399   for (auto *BB : llvm::concat<BasicBlock *const>(
1400            makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1401     if (Loop *OuterL = ExitLoopMap.lookup(BB))
1402       OuterL->addBasicBlockToLoop(BB, LI);
1403 
1404 #ifndef NDEBUG
1405   for (auto &BBAndL : ExitLoopMap) {
1406     auto *BB = BBAndL.first;
1407     auto *OuterL = BBAndL.second;
1408     assert(LI.getLoopFor(BB) == OuterL &&
1409            "Failed to put all blocks into outer loops!");
1410   }
1411 #endif
1412 
1413   // Now that all the blocks are placed into the correct containing loop in the
1414   // absence of child loops, find all the potentially cloned child loops and
1415   // clone them into whatever outer loop we placed their header into.
1416   for (Loop *ChildL : OrigL) {
1417     auto *ClonedChildHeader =
1418         cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1419     if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1420       continue;
1421 
1422 #ifndef NDEBUG
1423     for (auto *ChildLoopBB : ChildL->blocks())
1424       assert(VMap.count(ChildLoopBB) &&
1425              "Cloned a child loop header but not all of that loops blocks!");
1426 #endif
1427 
1428     NonChildClonedLoops.push_back(cloneLoopNest(
1429         *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1430   }
1431 }
1432 
1433 static void
1434 deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1435                        ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1436                        DominatorTree &DT, MemorySSAUpdater *MSSAU) {
1437   // Find all the dead clones, and remove them from their successors.
1438   SmallVector<BasicBlock *, 16> DeadBlocks;
1439   for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1440     for (auto &VMap : VMaps)
1441       if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1442         if (!DT.isReachableFromEntry(ClonedBB)) {
1443           for (BasicBlock *SuccBB : successors(ClonedBB))
1444             SuccBB->removePredecessor(ClonedBB);
1445           DeadBlocks.push_back(ClonedBB);
1446         }
1447 
1448   // Remove all MemorySSA in the dead blocks
1449   if (MSSAU) {
1450     SmallPtrSet<BasicBlock *, 16> DeadBlockSet(DeadBlocks.begin(),
1451                                                DeadBlocks.end());
1452     MSSAU->removeBlocks(DeadBlockSet);
1453   }
1454 
1455   // Drop any remaining references to break cycles.
1456   for (BasicBlock *BB : DeadBlocks)
1457     BB->dropAllReferences();
1458   // Erase them from the IR.
1459   for (BasicBlock *BB : DeadBlocks)
1460     BB->eraseFromParent();
1461 }
1462 
1463 static void deleteDeadBlocksFromLoop(Loop &L,
1464                                      SmallVectorImpl<BasicBlock *> &ExitBlocks,
1465                                      DominatorTree &DT, LoopInfo &LI,
1466                                      MemorySSAUpdater *MSSAU) {
1467   // Find all the dead blocks tied to this loop, and remove them from their
1468   // successors.
1469   SmallPtrSet<BasicBlock *, 16> DeadBlockSet;
1470 
1471   // Start with loop/exit blocks and get a transitive closure of reachable dead
1472   // blocks.
1473   SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
1474                                                 ExitBlocks.end());
1475   DeathCandidates.append(L.blocks().begin(), L.blocks().end());
1476   while (!DeathCandidates.empty()) {
1477     auto *BB = DeathCandidates.pop_back_val();
1478     if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
1479       for (BasicBlock *SuccBB : successors(BB)) {
1480         SuccBB->removePredecessor(BB);
1481         DeathCandidates.push_back(SuccBB);
1482       }
1483       DeadBlockSet.insert(BB);
1484     }
1485   }
1486 
1487   // Remove all MemorySSA in the dead blocks
1488   if (MSSAU)
1489     MSSAU->removeBlocks(DeadBlockSet);
1490 
1491   // Filter out the dead blocks from the exit blocks list so that it can be
1492   // used in the caller.
1493   llvm::erase_if(ExitBlocks,
1494                  [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1495 
1496   // Walk from this loop up through its parents removing all of the dead blocks.
1497   for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
1498     for (auto *BB : DeadBlockSet)
1499       ParentL->getBlocksSet().erase(BB);
1500     llvm::erase_if(ParentL->getBlocksVector(),
1501                    [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1502   }
1503 
1504   // Now delete the dead child loops. This raw delete will clear them
1505   // recursively.
1506   llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
1507     if (!DeadBlockSet.count(ChildL->getHeader()))
1508       return false;
1509 
1510     assert(llvm::all_of(ChildL->blocks(),
1511                         [&](BasicBlock *ChildBB) {
1512                           return DeadBlockSet.count(ChildBB);
1513                         }) &&
1514            "If the child loop header is dead all blocks in the child loop must "
1515            "be dead as well!");
1516     LI.destroy(ChildL);
1517     return true;
1518   });
1519 
1520   // Remove the loop mappings for the dead blocks and drop all the references
1521   // from these blocks to others to handle cyclic references as we start
1522   // deleting the blocks themselves.
1523   for (auto *BB : DeadBlockSet) {
1524     // Check that the dominator tree has already been updated.
1525     assert(!DT.getNode(BB) && "Should already have cleared domtree!");
1526     LI.changeLoopFor(BB, nullptr);
1527     BB->dropAllReferences();
1528   }
1529 
1530   // Actually delete the blocks now that they've been fully unhooked from the
1531   // IR.
1532   for (auto *BB : DeadBlockSet)
1533     BB->eraseFromParent();
1534 }
1535 
1536 /// Recompute the set of blocks in a loop after unswitching.
1537 ///
1538 /// This walks from the original headers predecessors to rebuild the loop. We
1539 /// take advantage of the fact that new blocks can't have been added, and so we
1540 /// filter by the original loop's blocks. This also handles potentially
1541 /// unreachable code that we don't want to explore but might be found examining
1542 /// the predecessors of the header.
1543 ///
1544 /// If the original loop is no longer a loop, this will return an empty set. If
1545 /// it remains a loop, all the blocks within it will be added to the set
1546 /// (including those blocks in inner loops).
1547 static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1548                                                                  LoopInfo &LI) {
1549   SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1550 
1551   auto *PH = L.getLoopPreheader();
1552   auto *Header = L.getHeader();
1553 
1554   // A worklist to use while walking backwards from the header.
1555   SmallVector<BasicBlock *, 16> Worklist;
1556 
1557   // First walk the predecessors of the header to find the backedges. This will
1558   // form the basis of our walk.
1559   for (auto *Pred : predecessors(Header)) {
1560     // Skip the preheader.
1561     if (Pred == PH)
1562       continue;
1563 
1564     // Because the loop was in simplified form, the only non-loop predecessor
1565     // is the preheader.
1566     assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1567                                "than the preheader that is not part of the "
1568                                "loop!");
1569 
1570     // Insert this block into the loop set and on the first visit and, if it
1571     // isn't the header we're currently walking, put it into the worklist to
1572     // recurse through.
1573     if (LoopBlockSet.insert(Pred).second && Pred != Header)
1574       Worklist.push_back(Pred);
1575   }
1576 
1577   // If no backedges were found, we're done.
1578   if (LoopBlockSet.empty())
1579     return LoopBlockSet;
1580 
1581   // We found backedges, recurse through them to identify the loop blocks.
1582   while (!Worklist.empty()) {
1583     BasicBlock *BB = Worklist.pop_back_val();
1584     assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1585 
1586     // No need to walk past the header.
1587     if (BB == Header)
1588       continue;
1589 
1590     // Because we know the inner loop structure remains valid we can use the
1591     // loop structure to jump immediately across the entire nested loop.
1592     // Further, because it is in loop simplified form, we can directly jump
1593     // to its preheader afterward.
1594     if (Loop *InnerL = LI.getLoopFor(BB))
1595       if (InnerL != &L) {
1596         assert(L.contains(InnerL) &&
1597                "Should not reach a loop *outside* this loop!");
1598         // The preheader is the only possible predecessor of the loop so
1599         // insert it into the set and check whether it was already handled.
1600         auto *InnerPH = InnerL->getLoopPreheader();
1601         assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1602                                       "but not contain the inner loop "
1603                                       "preheader!");
1604         if (!LoopBlockSet.insert(InnerPH).second)
1605           // The only way to reach the preheader is through the loop body
1606           // itself so if it has been visited the loop is already handled.
1607           continue;
1608 
1609         // Insert all of the blocks (other than those already present) into
1610         // the loop set. We expect at least the block that led us to find the
1611         // inner loop to be in the block set, but we may also have other loop
1612         // blocks if they were already enqueued as predecessors of some other
1613         // outer loop block.
1614         for (auto *InnerBB : InnerL->blocks()) {
1615           if (InnerBB == BB) {
1616             assert(LoopBlockSet.count(InnerBB) &&
1617                    "Block should already be in the set!");
1618             continue;
1619           }
1620 
1621           LoopBlockSet.insert(InnerBB);
1622         }
1623 
1624         // Add the preheader to the worklist so we will continue past the
1625         // loop body.
1626         Worklist.push_back(InnerPH);
1627         continue;
1628       }
1629 
1630     // Insert any predecessors that were in the original loop into the new
1631     // set, and if the insert is successful, add them to the worklist.
1632     for (auto *Pred : predecessors(BB))
1633       if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1634         Worklist.push_back(Pred);
1635   }
1636 
1637   assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1638 
1639   // We've found all the blocks participating in the loop, return our completed
1640   // set.
1641   return LoopBlockSet;
1642 }
1643 
1644 /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1645 ///
1646 /// The removal may have removed some child loops entirely but cannot have
1647 /// disturbed any remaining child loops. However, they may need to be hoisted
1648 /// to the parent loop (or to be top-level loops). The original loop may be
1649 /// completely removed.
1650 ///
1651 /// The sibling loops resulting from this update are returned. If the original
1652 /// loop remains a valid loop, it will be the first entry in this list with all
1653 /// of the newly sibling loops following it.
1654 ///
1655 /// Returns true if the loop remains a loop after unswitching, and false if it
1656 /// is no longer a loop after unswitching (and should not continue to be
1657 /// referenced).
1658 static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1659                                      LoopInfo &LI,
1660                                      SmallVectorImpl<Loop *> &HoistedLoops) {
1661   auto *PH = L.getLoopPreheader();
1662 
1663   // Compute the actual parent loop from the exit blocks. Because we may have
1664   // pruned some exits the loop may be different from the original parent.
1665   Loop *ParentL = nullptr;
1666   SmallVector<Loop *, 4> ExitLoops;
1667   SmallVector<BasicBlock *, 4> ExitsInLoops;
1668   ExitsInLoops.reserve(ExitBlocks.size());
1669   for (auto *ExitBB : ExitBlocks)
1670     if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1671       ExitLoops.push_back(ExitL);
1672       ExitsInLoops.push_back(ExitBB);
1673       if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1674         ParentL = ExitL;
1675     }
1676 
1677   // Recompute the blocks participating in this loop. This may be empty if it
1678   // is no longer a loop.
1679   auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1680 
1681   // If we still have a loop, we need to re-set the loop's parent as the exit
1682   // block set changing may have moved it within the loop nest. Note that this
1683   // can only happen when this loop has a parent as it can only hoist the loop
1684   // *up* the nest.
1685   if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1686     // Remove this loop's (original) blocks from all of the intervening loops.
1687     for (Loop *IL = L.getParentLoop(); IL != ParentL;
1688          IL = IL->getParentLoop()) {
1689       IL->getBlocksSet().erase(PH);
1690       for (auto *BB : L.blocks())
1691         IL->getBlocksSet().erase(BB);
1692       llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1693         return BB == PH || L.contains(BB);
1694       });
1695     }
1696 
1697     LI.changeLoopFor(PH, ParentL);
1698     L.getParentLoop()->removeChildLoop(&L);
1699     if (ParentL)
1700       ParentL->addChildLoop(&L);
1701     else
1702       LI.addTopLevelLoop(&L);
1703   }
1704 
1705   // Now we update all the blocks which are no longer within the loop.
1706   auto &Blocks = L.getBlocksVector();
1707   auto BlocksSplitI =
1708       LoopBlockSet.empty()
1709           ? Blocks.begin()
1710           : std::stable_partition(
1711                 Blocks.begin(), Blocks.end(),
1712                 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1713 
1714   // Before we erase the list of unlooped blocks, build a set of them.
1715   SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1716   if (LoopBlockSet.empty())
1717     UnloopedBlocks.insert(PH);
1718 
1719   // Now erase these blocks from the loop.
1720   for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1721     L.getBlocksSet().erase(BB);
1722   Blocks.erase(BlocksSplitI, Blocks.end());
1723 
1724   // Sort the exits in ascending loop depth, we'll work backwards across these
1725   // to process them inside out.
1726   std::stable_sort(ExitsInLoops.begin(), ExitsInLoops.end(),
1727                    [&](BasicBlock *LHS, BasicBlock *RHS) {
1728                      return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1729                    });
1730 
1731   // We'll build up a set for each exit loop.
1732   SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1733   Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1734 
1735   auto RemoveUnloopedBlocksFromLoop =
1736       [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1737         for (auto *BB : UnloopedBlocks)
1738           L.getBlocksSet().erase(BB);
1739         llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1740           return UnloopedBlocks.count(BB);
1741         });
1742       };
1743 
1744   SmallVector<BasicBlock *, 16> Worklist;
1745   while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1746     assert(Worklist.empty() && "Didn't clear worklist!");
1747     assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1748 
1749     // Grab the next exit block, in decreasing loop depth order.
1750     BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1751     Loop &ExitL = *LI.getLoopFor(ExitBB);
1752     assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1753 
1754     // Erase all of the unlooped blocks from the loops between the previous
1755     // exit loop and this exit loop. This works because the ExitInLoops list is
1756     // sorted in increasing order of loop depth and thus we visit loops in
1757     // decreasing order of loop depth.
1758     for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1759       RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1760 
1761     // Walk the CFG back until we hit the cloned PH adding everything reachable
1762     // and in the unlooped set to this exit block's loop.
1763     Worklist.push_back(ExitBB);
1764     do {
1765       BasicBlock *BB = Worklist.pop_back_val();
1766       // We can stop recursing at the cloned preheader (if we get there).
1767       if (BB == PH)
1768         continue;
1769 
1770       for (BasicBlock *PredBB : predecessors(BB)) {
1771         // If this pred has already been moved to our set or is part of some
1772         // (inner) loop, no update needed.
1773         if (!UnloopedBlocks.erase(PredBB)) {
1774           assert((NewExitLoopBlocks.count(PredBB) ||
1775                   ExitL.contains(LI.getLoopFor(PredBB))) &&
1776                  "Predecessor not in a nested loop (or already visited)!");
1777           continue;
1778         }
1779 
1780         // We just insert into the loop set here. We'll add these blocks to the
1781         // exit loop after we build up the set in a deterministic order rather
1782         // than the predecessor-influenced visit order.
1783         bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1784         (void)Inserted;
1785         assert(Inserted && "Should only visit an unlooped block once!");
1786 
1787         // And recurse through to its predecessors.
1788         Worklist.push_back(PredBB);
1789       }
1790     } while (!Worklist.empty());
1791 
1792     // If blocks in this exit loop were directly part of the original loop (as
1793     // opposed to a child loop) update the map to point to this exit loop. This
1794     // just updates a map and so the fact that the order is unstable is fine.
1795     for (auto *BB : NewExitLoopBlocks)
1796       if (Loop *BBL = LI.getLoopFor(BB))
1797         if (BBL == &L || !L.contains(BBL))
1798           LI.changeLoopFor(BB, &ExitL);
1799 
1800     // We will remove the remaining unlooped blocks from this loop in the next
1801     // iteration or below.
1802     NewExitLoopBlocks.clear();
1803   }
1804 
1805   // Any remaining unlooped blocks are no longer part of any loop unless they
1806   // are part of some child loop.
1807   for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1808     RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1809   for (auto *BB : UnloopedBlocks)
1810     if (Loop *BBL = LI.getLoopFor(BB))
1811       if (BBL == &L || !L.contains(BBL))
1812         LI.changeLoopFor(BB, nullptr);
1813 
1814   // Sink all the child loops whose headers are no longer in the loop set to
1815   // the parent (or to be top level loops). We reach into the loop and directly
1816   // update its subloop vector to make this batch update efficient.
1817   auto &SubLoops = L.getSubLoopsVector();
1818   auto SubLoopsSplitI =
1819       LoopBlockSet.empty()
1820           ? SubLoops.begin()
1821           : std::stable_partition(
1822                 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1823                   return LoopBlockSet.count(SubL->getHeader());
1824                 });
1825   for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1826     HoistedLoops.push_back(HoistedL);
1827     HoistedL->setParentLoop(nullptr);
1828 
1829     // To compute the new parent of this hoisted loop we look at where we
1830     // placed the preheader above. We can't lookup the header itself because we
1831     // retained the mapping from the header to the hoisted loop. But the
1832     // preheader and header should have the exact same new parent computed
1833     // based on the set of exit blocks from the original loop as the preheader
1834     // is a predecessor of the header and so reached in the reverse walk. And
1835     // because the loops were all in simplified form the preheader of the
1836     // hoisted loop can't be part of some *other* loop.
1837     if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1838       NewParentL->addChildLoop(HoistedL);
1839     else
1840       LI.addTopLevelLoop(HoistedL);
1841   }
1842   SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1843 
1844   // Actually delete the loop if nothing remained within it.
1845   if (Blocks.empty()) {
1846     assert(SubLoops.empty() &&
1847            "Failed to remove all subloops from the original loop!");
1848     if (Loop *ParentL = L.getParentLoop())
1849       ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1850     else
1851       LI.removeLoop(llvm::find(LI, &L));
1852     LI.destroy(&L);
1853     return false;
1854   }
1855 
1856   return true;
1857 }
1858 
1859 /// Helper to visit a dominator subtree, invoking a callable on each node.
1860 ///
1861 /// Returning false at any point will stop walking past that node of the tree.
1862 template <typename CallableT>
1863 void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1864   SmallVector<DomTreeNode *, 4> DomWorklist;
1865   DomWorklist.push_back(DT[BB]);
1866 #ifndef NDEBUG
1867   SmallPtrSet<DomTreeNode *, 4> Visited;
1868   Visited.insert(DT[BB]);
1869 #endif
1870   do {
1871     DomTreeNode *N = DomWorklist.pop_back_val();
1872 
1873     // Visit this node.
1874     if (!Callable(N->getBlock()))
1875       continue;
1876 
1877     // Accumulate the child nodes.
1878     for (DomTreeNode *ChildN : *N) {
1879       assert(Visited.insert(ChildN).second &&
1880              "Cannot visit a node twice when walking a tree!");
1881       DomWorklist.push_back(ChildN);
1882     }
1883   } while (!DomWorklist.empty());
1884 }
1885 
1886 static void unswitchNontrivialInvariants(
1887     Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
1888     SmallVectorImpl<BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI,
1889     AssumptionCache &AC, function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
1890     ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
1891   auto *ParentBB = TI.getParent();
1892   BranchInst *BI = dyn_cast<BranchInst>(&TI);
1893   SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
1894 
1895   // We can only unswitch switches, conditional branches with an invariant
1896   // condition, or combining invariant conditions with an instruction.
1897   assert((SI || BI->isConditional()) &&
1898          "Can only unswitch switches and conditional branch!");
1899   bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
1900   if (FullUnswitch)
1901     assert(Invariants.size() == 1 &&
1902            "Cannot have other invariants with full unswitching!");
1903   else
1904     assert(isa<Instruction>(BI->getCondition()) &&
1905            "Partial unswitching requires an instruction as the condition!");
1906 
1907   if (MSSAU && VerifyMemorySSA)
1908     MSSAU->getMemorySSA()->verifyMemorySSA();
1909 
1910   // Constant and BBs tracking the cloned and continuing successor. When we are
1911   // unswitching the entire condition, this can just be trivially chosen to
1912   // unswitch towards `true`. However, when we are unswitching a set of
1913   // invariants combined with `and` or `or`, the combining operation determines
1914   // the best direction to unswitch: we want to unswitch the direction that will
1915   // collapse the branch.
1916   bool Direction = true;
1917   int ClonedSucc = 0;
1918   if (!FullUnswitch) {
1919     if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1920       assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1921                  Instruction::And &&
1922              "Only `or` and `and` instructions can combine invariants being "
1923              "unswitched.");
1924       Direction = false;
1925       ClonedSucc = 1;
1926     }
1927   }
1928 
1929   BasicBlock *RetainedSuccBB =
1930       BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1931   SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1932   if (BI)
1933     UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1934   else
1935     for (auto Case : SI->cases())
1936       if (Case.getCaseSuccessor() != RetainedSuccBB)
1937         UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
1938 
1939   assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1940          "Should not unswitch the same successor we are retaining!");
1941 
1942   // The branch should be in this exact loop. Any inner loop's invariant branch
1943   // should be handled by unswitching that inner loop. The caller of this
1944   // routine should filter out any candidates that remain (but were skipped for
1945   // whatever reason).
1946   assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1947 
1948   // Compute the parent loop now before we start hacking on things.
1949   Loop *ParentL = L.getParentLoop();
1950   // Get blocks in RPO order for MSSA update, before changing the CFG.
1951   LoopBlocksRPO LBRPO(&L);
1952   if (MSSAU)
1953     LBRPO.perform(&LI);
1954 
1955   // Compute the outer-most loop containing one of our exit blocks. This is the
1956   // furthest up our loopnest which can be mutated, which we will use below to
1957   // update things.
1958   Loop *OuterExitL = &L;
1959   for (auto *ExitBB : ExitBlocks) {
1960     Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1961     if (!NewOuterExitL) {
1962       // We exited the entire nest with this block, so we're done.
1963       OuterExitL = nullptr;
1964       break;
1965     }
1966     if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1967       OuterExitL = NewOuterExitL;
1968   }
1969 
1970   // At this point, we're definitely going to unswitch something so invalidate
1971   // any cached information in ScalarEvolution for the outer most loop
1972   // containing an exit block and all nested loops.
1973   if (SE) {
1974     if (OuterExitL)
1975       SE->forgetLoop(OuterExitL);
1976     else
1977       SE->forgetTopmostLoop(&L);
1978   }
1979 
1980   // If the edge from this terminator to a successor dominates that successor,
1981   // store a map from each block in its dominator subtree to it. This lets us
1982   // tell when cloning for a particular successor if a block is dominated by
1983   // some *other* successor with a single data structure. We use this to
1984   // significantly reduce cloning.
1985   SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
1986   for (auto *SuccBB : llvm::concat<BasicBlock *const>(
1987            makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
1988     if (SuccBB->getUniquePredecessor() ||
1989         llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
1990           return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
1991         }))
1992       visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
1993         DominatingSucc[BB] = SuccBB;
1994         return true;
1995       });
1996 
1997   // Split the preheader, so that we know that there is a safe place to insert
1998   // the conditional branch. We will change the preheader to have a conditional
1999   // branch on LoopCond. The original preheader will become the split point
2000   // between the unswitched versions, and we will have a new preheader for the
2001   // original loop.
2002   BasicBlock *SplitBB = L.getLoopPreheader();
2003   BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
2004 
2005   // Keep track of the dominator tree updates needed.
2006   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2007 
2008   // Clone the loop for each unswitched successor.
2009   SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
2010   VMaps.reserve(UnswitchedSuccBBs.size());
2011   SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
2012   for (auto *SuccBB : UnswitchedSuccBBs) {
2013     VMaps.emplace_back(new ValueToValueMapTy());
2014     ClonedPHs[SuccBB] = buildClonedLoopBlocks(
2015         L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2016         DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
2017   }
2018 
2019   // The stitching of the branched code back together depends on whether we're
2020   // doing full unswitching or not with the exception that we always want to
2021   // nuke the initial terminator placed in the split block.
2022   SplitBB->getTerminator()->eraseFromParent();
2023   if (FullUnswitch) {
2024     // Splice the terminator from the original loop and rewrite its
2025     // successors.
2026     SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2027 
2028     // Keep a clone of the terminator for MSSA updates.
2029     Instruction *NewTI = TI.clone();
2030     ParentBB->getInstList().push_back(NewTI);
2031 
2032     // First wire up the moved terminator to the preheaders.
2033     if (BI) {
2034       BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2035       BI->setSuccessor(ClonedSucc, ClonedPH);
2036       BI->setSuccessor(1 - ClonedSucc, LoopPH);
2037       DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2038     } else {
2039       assert(SI && "Must either be a branch or switch!");
2040 
2041       // Walk the cases and directly update their successors.
2042       assert(SI->getDefaultDest() == RetainedSuccBB &&
2043              "Not retaining default successor!");
2044       SI->setDefaultDest(LoopPH);
2045       for (auto &Case : SI->cases())
2046         if (Case.getCaseSuccessor() == RetainedSuccBB)
2047           Case.setSuccessor(LoopPH);
2048         else
2049           Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2050 
2051       // We need to use the set to populate domtree updates as even when there
2052       // are multiple cases pointing at the same successor we only want to
2053       // remove and insert one edge in the domtree.
2054       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2055         DTUpdates.push_back(
2056             {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2057     }
2058 
2059     if (MSSAU) {
2060       DT.applyUpdates(DTUpdates);
2061       DTUpdates.clear();
2062 
2063       // Remove all but one edge to the retained block and all unswitched
2064       // blocks. This is to avoid having duplicate entries in the cloned Phis,
2065       // when we know we only keep a single edge for each case.
2066       MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2067       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2068         MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2069 
2070       for (auto &VMap : VMaps)
2071         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2072                                    /*IgnoreIncomingWithNoClones=*/true);
2073       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2074 
2075       // Remove all edges to unswitched blocks.
2076       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2077         MSSAU->removeEdge(ParentBB, SuccBB);
2078     }
2079 
2080     // Now unhook the successor relationship as we'll be replacing
2081     // the terminator with a direct branch. This is much simpler for branches
2082     // than switches so we handle those first.
2083     if (BI) {
2084       // Remove the parent as a predecessor of the unswitched successor.
2085       assert(UnswitchedSuccBBs.size() == 1 &&
2086              "Only one possible unswitched block for a branch!");
2087       BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2088       UnswitchedSuccBB->removePredecessor(ParentBB,
2089                                           /*KeepOneInputPHIs*/ true);
2090       DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2091     } else {
2092       // Note that we actually want to remove the parent block as a predecessor
2093       // of *every* case successor. The case successor is either unswitched,
2094       // completely eliminating an edge from the parent to that successor, or it
2095       // is a duplicate edge to the retained successor as the retained successor
2096       // is always the default successor and as we'll replace this with a direct
2097       // branch we no longer need the duplicate entries in the PHI nodes.
2098       SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2099       assert(NewSI->getDefaultDest() == RetainedSuccBB &&
2100              "Not retaining default successor!");
2101       for (auto &Case : NewSI->cases())
2102         Case.getCaseSuccessor()->removePredecessor(
2103             ParentBB,
2104             /*KeepOneInputPHIs*/ true);
2105 
2106       // We need to use the set to populate domtree updates as even when there
2107       // are multiple cases pointing at the same successor we only want to
2108       // remove and insert one edge in the domtree.
2109       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2110         DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
2111     }
2112 
2113     // After MSSAU update, remove the cloned terminator instruction NewTI.
2114     ParentBB->getTerminator()->eraseFromParent();
2115 
2116     // Create a new unconditional branch to the continuing block (as opposed to
2117     // the one cloned).
2118     BranchInst::Create(RetainedSuccBB, ParentBB);
2119   } else {
2120     assert(BI && "Only branches have partial unswitching.");
2121     assert(UnswitchedSuccBBs.size() == 1 &&
2122            "Only one possible unswitched block for a branch!");
2123     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2124     // When doing a partial unswitch, we have to do a bit more work to build up
2125     // the branch in the split block.
2126     buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
2127                                           *ClonedPH, *LoopPH);
2128     DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2129   }
2130 
2131   // Apply the updates accumulated above to get an up-to-date dominator tree.
2132   DT.applyUpdates(DTUpdates);
2133   if (!FullUnswitch && MSSAU) {
2134     // Update MSSA for partial unswitch, after DT update.
2135     SmallVector<CFGUpdate, 1> Updates;
2136     Updates.push_back(
2137         {cfg::UpdateKind::Insert, SplitBB, ClonedPHs.begin()->second});
2138     MSSAU->applyInsertUpdates(Updates, DT);
2139   }
2140 
2141   // Now that we have an accurate dominator tree, first delete the dead cloned
2142   // blocks so that we can accurately build any cloned loops. It is important to
2143   // not delete the blocks from the original loop yet because we still want to
2144   // reference the original loop to understand the cloned loop's structure.
2145   deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
2146 
2147   // Build the cloned loop structure itself. This may be substantially
2148   // different from the original structure due to the simplified CFG. This also
2149   // handles inserting all the cloned blocks into the correct loops.
2150   SmallVector<Loop *, 4> NonChildClonedLoops;
2151   for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2152     buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
2153 
2154   // Now that our cloned loops have been built, we can update the original loop.
2155   // First we delete the dead blocks from it and then we rebuild the loop
2156   // structure taking these deletions into account.
2157   deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU);
2158 
2159   if (MSSAU && VerifyMemorySSA)
2160     MSSAU->getMemorySSA()->verifyMemorySSA();
2161 
2162   SmallVector<Loop *, 4> HoistedLoops;
2163   bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2164 
2165   if (MSSAU && VerifyMemorySSA)
2166     MSSAU->getMemorySSA()->verifyMemorySSA();
2167 
2168   // This transformation has a high risk of corrupting the dominator tree, and
2169   // the below steps to rebuild loop structures will result in hard to debug
2170   // errors in that case so verify that the dominator tree is sane first.
2171   // FIXME: Remove this when the bugs stop showing up and rely on existing
2172   // verification steps.
2173   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2174 
2175   if (BI) {
2176     // If we unswitched a branch which collapses the condition to a known
2177     // constant we want to replace all the uses of the invariants within both
2178     // the original and cloned blocks. We do this here so that we can use the
2179     // now updated dominator tree to identify which side the users are on.
2180     assert(UnswitchedSuccBBs.size() == 1 &&
2181            "Only one possible unswitched block for a branch!");
2182     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2183 
2184     // When considering multiple partially-unswitched invariants
2185     // we cant just go replace them with constants in both branches.
2186     //
2187     // For 'AND' we infer that true branch ("continue") means true
2188     // for each invariant operand.
2189     // For 'OR' we can infer that false branch ("continue") means false
2190     // for each invariant operand.
2191     // So it happens that for multiple-partial case we dont replace
2192     // in the unswitched branch.
2193     bool ReplaceUnswitched = FullUnswitch || (Invariants.size() == 1);
2194 
2195     ConstantInt *UnswitchedReplacement =
2196         Direction ? ConstantInt::getTrue(BI->getContext())
2197                   : ConstantInt::getFalse(BI->getContext());
2198     ConstantInt *ContinueReplacement =
2199         Direction ? ConstantInt::getFalse(BI->getContext())
2200                   : ConstantInt::getTrue(BI->getContext());
2201     for (Value *Invariant : Invariants)
2202       for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2203            UI != UE;) {
2204         // Grab the use and walk past it so we can clobber it in the use list.
2205         Use *U = &*UI++;
2206         Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2207         if (!UserI)
2208           continue;
2209 
2210         // Replace it with the 'continue' side if in the main loop body, and the
2211         // unswitched if in the cloned blocks.
2212         if (DT.dominates(LoopPH, UserI->getParent()))
2213           U->set(ContinueReplacement);
2214         else if (ReplaceUnswitched &&
2215                  DT.dominates(ClonedPH, UserI->getParent()))
2216           U->set(UnswitchedReplacement);
2217       }
2218   }
2219 
2220   // We can change which blocks are exit blocks of all the cloned sibling
2221   // loops, the current loop, and any parent loops which shared exit blocks
2222   // with the current loop. As a consequence, we need to re-form LCSSA for
2223   // them. But we shouldn't need to re-form LCSSA for any child loops.
2224   // FIXME: This could be made more efficient by tracking which exit blocks are
2225   // new, and focusing on them, but that isn't likely to be necessary.
2226   //
2227   // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2228   // loop nest and update every loop that could have had its exits changed. We
2229   // also need to cover any intervening loops. We add all of these loops to
2230   // a list and sort them by loop depth to achieve this without updating
2231   // unnecessary loops.
2232   auto UpdateLoop = [&](Loop &UpdateL) {
2233 #ifndef NDEBUG
2234     UpdateL.verifyLoop();
2235     for (Loop *ChildL : UpdateL) {
2236       ChildL->verifyLoop();
2237       assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2238              "Perturbed a child loop's LCSSA form!");
2239     }
2240 #endif
2241     // First build LCSSA for this loop so that we can preserve it when
2242     // forming dedicated exits. We don't want to perturb some other loop's
2243     // LCSSA while doing that CFG edit.
2244     formLCSSA(UpdateL, DT, &LI, nullptr);
2245 
2246     // For loops reached by this loop's original exit blocks we may
2247     // introduced new, non-dedicated exits. At least try to re-form dedicated
2248     // exits for these loops. This may fail if they couldn't have dedicated
2249     // exits to start with.
2250     formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
2251   };
2252 
2253   // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2254   // and we can do it in any order as they don't nest relative to each other.
2255   //
2256   // Also check if any of the loops we have updated have become top-level loops
2257   // as that will necessitate widening the outer loop scope.
2258   for (Loop *UpdatedL :
2259        llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2260     UpdateLoop(*UpdatedL);
2261     if (!UpdatedL->getParentLoop())
2262       OuterExitL = nullptr;
2263   }
2264   if (IsStillLoop) {
2265     UpdateLoop(L);
2266     if (!L.getParentLoop())
2267       OuterExitL = nullptr;
2268   }
2269 
2270   // If the original loop had exit blocks, walk up through the outer most loop
2271   // of those exit blocks to update LCSSA and form updated dedicated exits.
2272   if (OuterExitL != &L)
2273     for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2274          OuterL = OuterL->getParentLoop())
2275       UpdateLoop(*OuterL);
2276 
2277 #ifndef NDEBUG
2278   // Verify the entire loop structure to catch any incorrect updates before we
2279   // progress in the pass pipeline.
2280   LI.verify(DT);
2281 #endif
2282 
2283   // Now that we've unswitched something, make callbacks to report the changes.
2284   // For that we need to merge together the updated loops and the cloned loops
2285   // and check whether the original loop survived.
2286   SmallVector<Loop *, 4> SibLoops;
2287   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2288     if (UpdatedL->getParentLoop() == ParentL)
2289       SibLoops.push_back(UpdatedL);
2290   UnswitchCB(IsStillLoop, SibLoops);
2291 
2292   if (MSSAU && VerifyMemorySSA)
2293     MSSAU->getMemorySSA()->verifyMemorySSA();
2294 
2295   if (BI)
2296     ++NumBranches;
2297   else
2298     ++NumSwitches;
2299 }
2300 
2301 /// Recursively compute the cost of a dominator subtree based on the per-block
2302 /// cost map provided.
2303 ///
2304 /// The recursive computation is memozied into the provided DT-indexed cost map
2305 /// to allow querying it for most nodes in the domtree without it becoming
2306 /// quadratic.
2307 static int
2308 computeDomSubtreeCost(DomTreeNode &N,
2309                       const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2310                       SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2311   // Don't accumulate cost (or recurse through) blocks not in our block cost
2312   // map and thus not part of the duplication cost being considered.
2313   auto BBCostIt = BBCostMap.find(N.getBlock());
2314   if (BBCostIt == BBCostMap.end())
2315     return 0;
2316 
2317   // Lookup this node to see if we already computed its cost.
2318   auto DTCostIt = DTCostMap.find(&N);
2319   if (DTCostIt != DTCostMap.end())
2320     return DTCostIt->second;
2321 
2322   // If not, we have to compute it. We can't use insert above and update
2323   // because computing the cost may insert more things into the map.
2324   int Cost = std::accumulate(
2325       N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2326         return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2327       });
2328   bool Inserted = DTCostMap.insert({&N, Cost}).second;
2329   (void)Inserted;
2330   assert(Inserted && "Should not insert a node while visiting children!");
2331   return Cost;
2332 }
2333 
2334 /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2335 /// making the following replacement:
2336 ///
2337 ///   --code before guard--
2338 ///   call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
2339 ///   --code after guard--
2340 ///
2341 /// into
2342 ///
2343 ///   --code before guard--
2344 ///   br i1 %cond, label %guarded, label %deopt
2345 ///
2346 /// guarded:
2347 ///   --code after guard--
2348 ///
2349 /// deopt:
2350 ///   call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2351 ///   unreachable
2352 ///
2353 /// It also makes all relevant DT and LI updates, so that all structures are in
2354 /// valid state after this transform.
2355 static BranchInst *
2356 turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2357                     SmallVectorImpl<BasicBlock *> &ExitBlocks,
2358                     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
2359   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2360   LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2361   BasicBlock *CheckBB = GI->getParent();
2362 
2363   if (MSSAU && VerifyMemorySSA)
2364      MSSAU->getMemorySSA()->verifyMemorySSA();
2365 
2366   // Remove all CheckBB's successors from DomTree. A block can be seen among
2367   // successors more than once, but for DomTree it should be added only once.
2368   SmallPtrSet<BasicBlock *, 4> Successors;
2369   for (auto *Succ : successors(CheckBB))
2370     if (Successors.insert(Succ).second)
2371       DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2372 
2373   Instruction *DeoptBlockTerm =
2374       SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2375   BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2376   // SplitBlockAndInsertIfThen inserts control flow that branches to
2377   // DeoptBlockTerm if the condition is true.  We want the opposite.
2378   CheckBI->swapSuccessors();
2379 
2380   BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2381   GuardedBlock->setName("guarded");
2382   CheckBI->getSuccessor(1)->setName("deopt");
2383   BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
2384 
2385   // We now have a new exit block.
2386   ExitBlocks.push_back(CheckBI->getSuccessor(1));
2387 
2388   if (MSSAU)
2389     MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2390 
2391   GI->moveBefore(DeoptBlockTerm);
2392   GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2393 
2394   // Add new successors of CheckBB into DomTree.
2395   for (auto *Succ : successors(CheckBB))
2396     DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2397 
2398   // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2399   // successors.
2400   for (auto *Succ : Successors)
2401     DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2402 
2403   // Make proper changes to DT.
2404   DT.applyUpdates(DTUpdates);
2405   // Inform LI of a new loop block.
2406   L.addBasicBlockToLoop(GuardedBlock, LI);
2407 
2408   if (MSSAU) {
2409     MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2410     MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::End);
2411     if (VerifyMemorySSA)
2412       MSSAU->getMemorySSA()->verifyMemorySSA();
2413   }
2414 
2415   ++NumGuards;
2416   return CheckBI;
2417 }
2418 
2419 /// Cost multiplier is a way to limit potentially exponential behavior
2420 /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2421 /// candidates available. Also accounting for the number of "sibling" loops with
2422 /// the idea to account for previous unswitches that already happened on this
2423 /// cluster of loops. There was an attempt to keep this formula simple,
2424 /// just enough to limit the worst case behavior. Even if it is not that simple
2425 /// now it is still not an attempt to provide a detailed heuristic size
2426 /// prediction.
2427 ///
2428 /// TODO: Make a proper accounting of "explosion" effect for all kinds of
2429 /// unswitch candidates, making adequate predictions instead of wild guesses.
2430 /// That requires knowing not just the number of "remaining" candidates but
2431 /// also costs of unswitching for each of these candidates.
2432 static int calculateUnswitchCostMultiplier(
2433     Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
2434     ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
2435         UnswitchCandidates) {
2436 
2437   // Guards and other exiting conditions do not contribute to exponential
2438   // explosion as soon as they dominate the latch (otherwise there might be
2439   // another path to the latch remaining that does not allow to eliminate the
2440   // loop copy on unswitch).
2441   BasicBlock *Latch = L.getLoopLatch();
2442   BasicBlock *CondBlock = TI.getParent();
2443   if (DT.dominates(CondBlock, Latch) &&
2444       (isGuard(&TI) ||
2445        llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
2446          return L.contains(SuccBB);
2447        }) <= 1)) {
2448     NumCostMultiplierSkipped++;
2449     return 1;
2450   }
2451 
2452   auto *ParentL = L.getParentLoop();
2453   int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2454                                : std::distance(LI.begin(), LI.end()));
2455   // Count amount of clones that all the candidates might cause during
2456   // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2457   int UnswitchedClones = 0;
2458   for (auto Candidate : UnswitchCandidates) {
2459     Instruction *CI = Candidate.first;
2460     BasicBlock *CondBlock = CI->getParent();
2461     bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2462     if (isGuard(CI)) {
2463       if (!SkipExitingSuccessors)
2464         UnswitchedClones++;
2465       continue;
2466     }
2467     int NonExitingSuccessors = llvm::count_if(
2468         successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
2469           return !SkipExitingSuccessors || L.contains(SuccBB);
2470         });
2471     UnswitchedClones += Log2_32(NonExitingSuccessors);
2472   }
2473 
2474   // Ignore up to the "unscaled candidates" number of unswitch candidates
2475   // when calculating the power-of-two scaling of the cost. The main idea
2476   // with this control is to allow a small number of unswitches to happen
2477   // and rely more on siblings multiplier (see below) when the number
2478   // of candidates is small.
2479   unsigned ClonesPower =
2480       std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
2481 
2482   // Allowing top-level loops to spread a bit more than nested ones.
2483   int SiblingsMultiplier =
2484       std::max((ParentL ? SiblingsCount
2485                         : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
2486                1);
2487   // Compute the cost multiplier in a way that won't overflow by saturating
2488   // at an upper bound.
2489   int CostMultiplier;
2490   if (ClonesPower > Log2_32(UnswitchThreshold) ||
2491       SiblingsMultiplier > UnswitchThreshold)
2492     CostMultiplier = UnswitchThreshold;
2493   else
2494     CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2495                               (int)UnswitchThreshold);
2496 
2497   LLVM_DEBUG(dbgs() << "  Computed multiplier  " << CostMultiplier
2498                     << " (siblings " << SiblingsMultiplier << " * clones "
2499                     << (1 << ClonesPower) << ")"
2500                     << " for unswitch candidate: " << TI << "\n");
2501   return CostMultiplier;
2502 }
2503 
2504 static bool
2505 unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2506                       AssumptionCache &AC, TargetTransformInfo &TTI,
2507                       function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2508                       ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
2509   // Collect all invariant conditions within this loop (as opposed to an inner
2510   // loop which would be handled when visiting that inner loop).
2511   SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
2512       UnswitchCandidates;
2513 
2514   // Whether or not we should also collect guards in the loop.
2515   bool CollectGuards = false;
2516   if (UnswitchGuards) {
2517     auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2518         Intrinsic::getName(Intrinsic::experimental_guard));
2519     if (GuardDecl && !GuardDecl->use_empty())
2520       CollectGuards = true;
2521   }
2522 
2523   for (auto *BB : L.blocks()) {
2524     if (LI.getLoopFor(BB) != &L)
2525       continue;
2526 
2527     if (CollectGuards)
2528       for (auto &I : *BB)
2529         if (isGuard(&I)) {
2530           auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2531           // TODO: Support AND, OR conditions and partial unswitching.
2532           if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2533             UnswitchCandidates.push_back({&I, {Cond}});
2534         }
2535 
2536     if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2537       // We can only consider fully loop-invariant switch conditions as we need
2538       // to completely eliminate the switch after unswitching.
2539       if (!isa<Constant>(SI->getCondition()) &&
2540           L.isLoopInvariant(SI->getCondition()))
2541         UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2542       continue;
2543     }
2544 
2545     auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2546     if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2547         BI->getSuccessor(0) == BI->getSuccessor(1))
2548       continue;
2549 
2550     if (L.isLoopInvariant(BI->getCondition())) {
2551       UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2552       continue;
2553     }
2554 
2555     Instruction &CondI = *cast<Instruction>(BI->getCondition());
2556     if (CondI.getOpcode() != Instruction::And &&
2557       CondI.getOpcode() != Instruction::Or)
2558       continue;
2559 
2560     TinyPtrVector<Value *> Invariants =
2561         collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2562     if (Invariants.empty())
2563       continue;
2564 
2565     UnswitchCandidates.push_back({BI, std::move(Invariants)});
2566   }
2567 
2568   // If we didn't find any candidates, we're done.
2569   if (UnswitchCandidates.empty())
2570     return false;
2571 
2572   // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2573   // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2574   // irreducible control flow into reducible control flow and introduce new
2575   // loops "out of thin air". If we ever discover important use cases for doing
2576   // this, we can add support to loop unswitch, but it is a lot of complexity
2577   // for what seems little or no real world benefit.
2578   LoopBlocksRPO RPOT(&L);
2579   RPOT.perform(&LI);
2580   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
2581     return false;
2582 
2583   SmallVector<BasicBlock *, 4> ExitBlocks;
2584   L.getUniqueExitBlocks(ExitBlocks);
2585 
2586   // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
2587   // don't know how to split those exit blocks.
2588   // FIXME: We should teach SplitBlock to handle this and remove this
2589   // restriction.
2590   for (auto *ExitBB : ExitBlocks)
2591     if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) {
2592       dbgs() << "Cannot unswitch because of cleanuppad in exit block\n";
2593       return false;
2594     }
2595 
2596   LLVM_DEBUG(
2597       dbgs() << "Considering " << UnswitchCandidates.size()
2598              << " non-trivial loop invariant conditions for unswitching.\n");
2599 
2600   // Given that unswitching these terminators will require duplicating parts of
2601   // the loop, so we need to be able to model that cost. Compute the ephemeral
2602   // values and set up a data structure to hold per-BB costs. We cache each
2603   // block's cost so that we don't recompute this when considering different
2604   // subsets of the loop for duplication during unswitching.
2605   SmallPtrSet<const Value *, 4> EphValues;
2606   CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2607   SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2608 
2609   // Compute the cost of each block, as well as the total loop cost. Also, bail
2610   // out if we see instructions which are incompatible with loop unswitching
2611   // (convergent, noduplicate, or cross-basic-block tokens).
2612   // FIXME: We might be able to safely handle some of these in non-duplicated
2613   // regions.
2614   int LoopCost = 0;
2615   for (auto *BB : L.blocks()) {
2616     int Cost = 0;
2617     for (auto &I : *BB) {
2618       if (EphValues.count(&I))
2619         continue;
2620 
2621       if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
2622         return false;
2623       if (auto CS = CallSite(&I))
2624         if (CS.isConvergent() || CS.cannotDuplicate())
2625           return false;
2626 
2627       Cost += TTI.getUserCost(&I);
2628     }
2629     assert(Cost >= 0 && "Must not have negative costs!");
2630     LoopCost += Cost;
2631     assert(LoopCost >= 0 && "Must not have negative loop costs!");
2632     BBCostMap[BB] = Cost;
2633   }
2634   LLVM_DEBUG(dbgs() << "  Total loop cost: " << LoopCost << "\n");
2635 
2636   // Now we find the best candidate by searching for the one with the following
2637   // properties in order:
2638   //
2639   // 1) An unswitching cost below the threshold
2640   // 2) The smallest number of duplicated unswitch candidates (to avoid
2641   //    creating redundant subsequent unswitching)
2642   // 3) The smallest cost after unswitching.
2643   //
2644   // We prioritize reducing fanout of unswitch candidates provided the cost
2645   // remains below the threshold because this has a multiplicative effect.
2646   //
2647   // This requires memoizing each dominator subtree to avoid redundant work.
2648   //
2649   // FIXME: Need to actually do the number of candidates part above.
2650   SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2651   // Given a terminator which might be unswitched, computes the non-duplicated
2652   // cost for that terminator.
2653   auto ComputeUnswitchedCost = [&](Instruction &TI, bool FullUnswitch) {
2654     BasicBlock &BB = *TI.getParent();
2655     SmallPtrSet<BasicBlock *, 4> Visited;
2656 
2657     int Cost = LoopCost;
2658     for (BasicBlock *SuccBB : successors(&BB)) {
2659       // Don't count successors more than once.
2660       if (!Visited.insert(SuccBB).second)
2661         continue;
2662 
2663       // If this is a partial unswitch candidate, then it must be a conditional
2664       // branch with a condition of either `or` or `and`. In that case, one of
2665       // the successors is necessarily duplicated, so don't even try to remove
2666       // its cost.
2667       if (!FullUnswitch) {
2668         auto &BI = cast<BranchInst>(TI);
2669         if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2670             Instruction::And) {
2671           if (SuccBB == BI.getSuccessor(1))
2672             continue;
2673         } else {
2674           assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2675                      Instruction::Or &&
2676                  "Only `and` and `or` conditions can result in a partial "
2677                  "unswitch!");
2678           if (SuccBB == BI.getSuccessor(0))
2679             continue;
2680         }
2681       }
2682 
2683       // This successor's domtree will not need to be duplicated after
2684       // unswitching if the edge to the successor dominates it (and thus the
2685       // entire tree). This essentially means there is no other path into this
2686       // subtree and so it will end up live in only one clone of the loop.
2687       if (SuccBB->getUniquePredecessor() ||
2688           llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2689             return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2690           })) {
2691         Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2692         assert(Cost >= 0 &&
2693                "Non-duplicated cost should never exceed total loop cost!");
2694       }
2695     }
2696 
2697     // Now scale the cost by the number of unique successors minus one. We
2698     // subtract one because there is already at least one copy of the entire
2699     // loop. This is computing the new cost of unswitching a condition.
2700     // Note that guards always have 2 unique successors that are implicit and
2701     // will be materialized if we decide to unswitch it.
2702     int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2703     assert(SuccessorsCount > 1 &&
2704            "Cannot unswitch a condition without multiple distinct successors!");
2705     return Cost * (SuccessorsCount - 1);
2706   };
2707   Instruction *BestUnswitchTI = nullptr;
2708   int BestUnswitchCost;
2709   ArrayRef<Value *> BestUnswitchInvariants;
2710   for (auto &TerminatorAndInvariants : UnswitchCandidates) {
2711     Instruction &TI = *TerminatorAndInvariants.first;
2712     ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2713     BranchInst *BI = dyn_cast<BranchInst>(&TI);
2714     int CandidateCost = ComputeUnswitchedCost(
2715         TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2716                                      Invariants[0] == BI->getCondition()));
2717     // Calculate cost multiplier which is a tool to limit potentially
2718     // exponential behavior of loop-unswitch.
2719     if (EnableUnswitchCostMultiplier) {
2720       int CostMultiplier =
2721           calculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
2722       assert(
2723           (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
2724           "cost multiplier needs to be in the range of 1..UnswitchThreshold");
2725       CandidateCost *= CostMultiplier;
2726       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
2727                         << " (multiplier: " << CostMultiplier << ")"
2728                         << " for unswitch candidate: " << TI << "\n");
2729     } else {
2730       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
2731                         << " for unswitch candidate: " << TI << "\n");
2732     }
2733 
2734     if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2735       BestUnswitchTI = &TI;
2736       BestUnswitchCost = CandidateCost;
2737       BestUnswitchInvariants = Invariants;
2738     }
2739   }
2740 
2741   if (BestUnswitchCost >= UnswitchThreshold) {
2742     LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2743                       << BestUnswitchCost << "\n");
2744     return false;
2745   }
2746 
2747   // If the best candidate is a guard, turn it into a branch.
2748   if (isGuard(BestUnswitchTI))
2749     BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
2750                                          ExitBlocks, DT, LI, MSSAU);
2751 
2752   LLVM_DEBUG(dbgs() << "  Unswitching non-trivial (cost = "
2753                     << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2754                     << "\n");
2755   unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
2756                                ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU);
2757   return true;
2758 }
2759 
2760 /// Unswitch control flow predicated on loop invariant conditions.
2761 ///
2762 /// This first hoists all branches or switches which are trivial (IE, do not
2763 /// require duplicating any part of the loop) out of the loop body. It then
2764 /// looks at other loop invariant control flows and tries to unswitch those as
2765 /// well by cloning the loop if the result is small enough.
2766 ///
2767 /// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2768 /// updated based on the unswitch.
2769 /// The `MSSA` analysis is also updated if valid (i.e. its use is enabled).
2770 ///
2771 /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2772 /// true, we will attempt to do non-trivial unswitching as well as trivial
2773 /// unswitching.
2774 ///
2775 /// The `UnswitchCB` callback provided will be run after unswitching is
2776 /// complete, with the first parameter set to `true` if the provided loop
2777 /// remains a loop, and a list of new sibling loops created.
2778 ///
2779 /// If `SE` is non-null, we will update that analysis based on the unswitching
2780 /// done.
2781 static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2782                          AssumptionCache &AC, TargetTransformInfo &TTI,
2783                          bool NonTrivial,
2784                          function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2785                          ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
2786   assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2787          "Loops must be in LCSSA form before unswitching.");
2788   bool Changed = false;
2789 
2790   // Must be in loop simplified form: we need a preheader and dedicated exits.
2791   if (!L.isLoopSimplifyForm())
2792     return false;
2793 
2794   // Try trivial unswitch first before loop over other basic blocks in the loop.
2795   if (unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
2796     // If we unswitched successfully we will want to clean up the loop before
2797     // processing it further so just mark it as unswitched and return.
2798     UnswitchCB(/*CurrentLoopValid*/ true, {});
2799     return true;
2800   }
2801 
2802   // If we're not doing non-trivial unswitching, we're done. We both accept
2803   // a parameter but also check a local flag that can be used for testing
2804   // a debugging.
2805   if (!NonTrivial && !EnableNonTrivialUnswitch)
2806     return false;
2807 
2808   // For non-trivial unswitching, because it often creates new loops, we rely on
2809   // the pass manager to iterate on the loops rather than trying to immediately
2810   // reach a fixed point. There is no substantial advantage to iterating
2811   // internally, and if any of the new loops are simplified enough to contain
2812   // trivial unswitching we want to prefer those.
2813 
2814   // Try to unswitch the best invariant condition. We prefer this full unswitch to
2815   // a partial unswitch when possible below the threshold.
2816   if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE, MSSAU))
2817     return true;
2818 
2819   // No other opportunities to unswitch.
2820   return Changed;
2821 }
2822 
2823 PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2824                                               LoopStandardAnalysisResults &AR,
2825                                               LPMUpdater &U) {
2826   Function &F = *L.getHeader()->getParent();
2827   (void)F;
2828 
2829   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2830                     << "\n");
2831 
2832   // Save the current loop name in a variable so that we can report it even
2833   // after it has been deleted.
2834   std::string LoopName = L.getName();
2835 
2836   auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2837                                         ArrayRef<Loop *> NewLoops) {
2838     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2839     if (!NewLoops.empty())
2840       U.addSiblingLoops(NewLoops);
2841 
2842     // If the current loop remains valid, we should revisit it to catch any
2843     // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2844     if (CurrentLoopValid)
2845       U.revisitCurrentLoop();
2846     else
2847       U.markLoopAsDeleted(L, LoopName);
2848   };
2849 
2850   Optional<MemorySSAUpdater> MSSAU;
2851   if (AR.MSSA) {
2852     MSSAU = MemorySSAUpdater(AR.MSSA);
2853     if (VerifyMemorySSA)
2854       AR.MSSA->verifyMemorySSA();
2855   }
2856   if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
2857                     &AR.SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
2858     return PreservedAnalyses::all();
2859 
2860   if (AR.MSSA && VerifyMemorySSA)
2861     AR.MSSA->verifyMemorySSA();
2862 
2863   // Historically this pass has had issues with the dominator tree so verify it
2864   // in asserts builds.
2865   assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
2866   return getLoopPassPreservedAnalyses();
2867 }
2868 
2869 namespace {
2870 
2871 class SimpleLoopUnswitchLegacyPass : public LoopPass {
2872   bool NonTrivial;
2873 
2874 public:
2875   static char ID; // Pass ID, replacement for typeid
2876 
2877   explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2878       : LoopPass(ID), NonTrivial(NonTrivial) {
2879     initializeSimpleLoopUnswitchLegacyPassPass(
2880         *PassRegistry::getPassRegistry());
2881   }
2882 
2883   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2884 
2885   void getAnalysisUsage(AnalysisUsage &AU) const override {
2886     AU.addRequired<AssumptionCacheTracker>();
2887     AU.addRequired<TargetTransformInfoWrapperPass>();
2888     if (EnableMSSALoopDependency) {
2889       AU.addRequired<MemorySSAWrapperPass>();
2890       AU.addPreserved<MemorySSAWrapperPass>();
2891     }
2892     getLoopAnalysisUsage(AU);
2893   }
2894 };
2895 
2896 } // end anonymous namespace
2897 
2898 bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2899   if (skipLoop(L))
2900     return false;
2901 
2902   Function &F = *L->getHeader()->getParent();
2903 
2904   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2905                     << "\n");
2906 
2907   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2908   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2909   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2910   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2911   MemorySSA *MSSA = nullptr;
2912   Optional<MemorySSAUpdater> MSSAU;
2913   if (EnableMSSALoopDependency) {
2914     MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
2915     MSSAU = MemorySSAUpdater(MSSA);
2916   }
2917 
2918   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2919   auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2920 
2921   auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2922                                ArrayRef<Loop *> NewLoops) {
2923     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2924     for (auto *NewL : NewLoops)
2925       LPM.addLoop(*NewL);
2926 
2927     // If the current loop remains valid, re-add it to the queue. This is
2928     // a little wasteful as we'll finish processing the current loop as well,
2929     // but it is the best we can do in the old PM.
2930     if (CurrentLoopValid)
2931       LPM.addLoop(*L);
2932     else
2933       LPM.markLoopAsDeleted(*L);
2934   };
2935 
2936   if (MSSA && VerifyMemorySSA)
2937     MSSA->verifyMemorySSA();
2938 
2939   bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE,
2940                               MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
2941 
2942   if (MSSA && VerifyMemorySSA)
2943     MSSA->verifyMemorySSA();
2944 
2945   // If anything was unswitched, also clear any cached information about this
2946   // loop.
2947   LPM.deleteSimpleAnalysisLoop(L);
2948 
2949   // Historically this pass has had issues with the dominator tree so verify it
2950   // in asserts builds.
2951   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2952 
2953   return Changed;
2954 }
2955 
2956 char SimpleLoopUnswitchLegacyPass::ID = 0;
2957 INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2958                       "Simple unswitch loops", false, false)
2959 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2960 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2961 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2962 INITIALIZE_PASS_DEPENDENCY(LoopPass)
2963 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2964 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2965 INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2966                     "Simple unswitch loops", false, false)
2967 
2968 Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2969   return new SimpleLoopUnswitchLegacyPass(NonTrivial);
2970 }
2971