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