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