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