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