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