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