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