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