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