xref: /llvm-project/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp (revision d889e17eca8e8c43c6e4a2439fae5a1a40823623)
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     // Drop all uses of the instructions to make sure we won't have dangling
1578     // uses in other blocks.
1579     for (auto &I : *BB)
1580       if (!I.use_empty())
1581         I.replaceAllUsesWith(UndefValue::get(I.getType()));
1582     BB->dropAllReferences();
1583   }
1584 
1585   // Actually delete the blocks now that they've been fully unhooked from the
1586   // IR.
1587   for (auto *BB : DeadBlockSet)
1588     BB->eraseFromParent();
1589 }
1590 
1591 /// Recompute the set of blocks in a loop after unswitching.
1592 ///
1593 /// This walks from the original headers predecessors to rebuild the loop. We
1594 /// take advantage of the fact that new blocks can't have been added, and so we
1595 /// filter by the original loop's blocks. This also handles potentially
1596 /// unreachable code that we don't want to explore but might be found examining
1597 /// the predecessors of the header.
1598 ///
1599 /// If the original loop is no longer a loop, this will return an empty set. If
1600 /// it remains a loop, all the blocks within it will be added to the set
1601 /// (including those blocks in inner loops).
1602 static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1603                                                                  LoopInfo &LI) {
1604   SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1605 
1606   auto *PH = L.getLoopPreheader();
1607   auto *Header = L.getHeader();
1608 
1609   // A worklist to use while walking backwards from the header.
1610   SmallVector<BasicBlock *, 16> Worklist;
1611 
1612   // First walk the predecessors of the header to find the backedges. This will
1613   // form the basis of our walk.
1614   for (auto *Pred : predecessors(Header)) {
1615     // Skip the preheader.
1616     if (Pred == PH)
1617       continue;
1618 
1619     // Because the loop was in simplified form, the only non-loop predecessor
1620     // is the preheader.
1621     assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1622                                "than the preheader that is not part of the "
1623                                "loop!");
1624 
1625     // Insert this block into the loop set and on the first visit and, if it
1626     // isn't the header we're currently walking, put it into the worklist to
1627     // recurse through.
1628     if (LoopBlockSet.insert(Pred).second && Pred != Header)
1629       Worklist.push_back(Pred);
1630   }
1631 
1632   // If no backedges were found, we're done.
1633   if (LoopBlockSet.empty())
1634     return LoopBlockSet;
1635 
1636   // We found backedges, recurse through them to identify the loop blocks.
1637   while (!Worklist.empty()) {
1638     BasicBlock *BB = Worklist.pop_back_val();
1639     assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1640 
1641     // No need to walk past the header.
1642     if (BB == Header)
1643       continue;
1644 
1645     // Because we know the inner loop structure remains valid we can use the
1646     // loop structure to jump immediately across the entire nested loop.
1647     // Further, because it is in loop simplified form, we can directly jump
1648     // to its preheader afterward.
1649     if (Loop *InnerL = LI.getLoopFor(BB))
1650       if (InnerL != &L) {
1651         assert(L.contains(InnerL) &&
1652                "Should not reach a loop *outside* this loop!");
1653         // The preheader is the only possible predecessor of the loop so
1654         // insert it into the set and check whether it was already handled.
1655         auto *InnerPH = InnerL->getLoopPreheader();
1656         assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1657                                       "but not contain the inner loop "
1658                                       "preheader!");
1659         if (!LoopBlockSet.insert(InnerPH).second)
1660           // The only way to reach the preheader is through the loop body
1661           // itself so if it has been visited the loop is already handled.
1662           continue;
1663 
1664         // Insert all of the blocks (other than those already present) into
1665         // the loop set. We expect at least the block that led us to find the
1666         // inner loop to be in the block set, but we may also have other loop
1667         // blocks if they were already enqueued as predecessors of some other
1668         // outer loop block.
1669         for (auto *InnerBB : InnerL->blocks()) {
1670           if (InnerBB == BB) {
1671             assert(LoopBlockSet.count(InnerBB) &&
1672                    "Block should already be in the set!");
1673             continue;
1674           }
1675 
1676           LoopBlockSet.insert(InnerBB);
1677         }
1678 
1679         // Add the preheader to the worklist so we will continue past the
1680         // loop body.
1681         Worklist.push_back(InnerPH);
1682         continue;
1683       }
1684 
1685     // Insert any predecessors that were in the original loop into the new
1686     // set, and if the insert is successful, add them to the worklist.
1687     for (auto *Pred : predecessors(BB))
1688       if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1689         Worklist.push_back(Pred);
1690   }
1691 
1692   assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1693 
1694   // We've found all the blocks participating in the loop, return our completed
1695   // set.
1696   return LoopBlockSet;
1697 }
1698 
1699 /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1700 ///
1701 /// The removal may have removed some child loops entirely but cannot have
1702 /// disturbed any remaining child loops. However, they may need to be hoisted
1703 /// to the parent loop (or to be top-level loops). The original loop may be
1704 /// completely removed.
1705 ///
1706 /// The sibling loops resulting from this update are returned. If the original
1707 /// loop remains a valid loop, it will be the first entry in this list with all
1708 /// of the newly sibling loops following it.
1709 ///
1710 /// Returns true if the loop remains a loop after unswitching, and false if it
1711 /// is no longer a loop after unswitching (and should not continue to be
1712 /// referenced).
1713 static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1714                                      LoopInfo &LI,
1715                                      SmallVectorImpl<Loop *> &HoistedLoops) {
1716   auto *PH = L.getLoopPreheader();
1717 
1718   // Compute the actual parent loop from the exit blocks. Because we may have
1719   // pruned some exits the loop may be different from the original parent.
1720   Loop *ParentL = nullptr;
1721   SmallVector<Loop *, 4> ExitLoops;
1722   SmallVector<BasicBlock *, 4> ExitsInLoops;
1723   ExitsInLoops.reserve(ExitBlocks.size());
1724   for (auto *ExitBB : ExitBlocks)
1725     if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1726       ExitLoops.push_back(ExitL);
1727       ExitsInLoops.push_back(ExitBB);
1728       if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1729         ParentL = ExitL;
1730     }
1731 
1732   // Recompute the blocks participating in this loop. This may be empty if it
1733   // is no longer a loop.
1734   auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1735 
1736   // If we still have a loop, we need to re-set the loop's parent as the exit
1737   // block set changing may have moved it within the loop nest. Note that this
1738   // can only happen when this loop has a parent as it can only hoist the loop
1739   // *up* the nest.
1740   if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1741     // Remove this loop's (original) blocks from all of the intervening loops.
1742     for (Loop *IL = L.getParentLoop(); IL != ParentL;
1743          IL = IL->getParentLoop()) {
1744       IL->getBlocksSet().erase(PH);
1745       for (auto *BB : L.blocks())
1746         IL->getBlocksSet().erase(BB);
1747       llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1748         return BB == PH || L.contains(BB);
1749       });
1750     }
1751 
1752     LI.changeLoopFor(PH, ParentL);
1753     L.getParentLoop()->removeChildLoop(&L);
1754     if (ParentL)
1755       ParentL->addChildLoop(&L);
1756     else
1757       LI.addTopLevelLoop(&L);
1758   }
1759 
1760   // Now we update all the blocks which are no longer within the loop.
1761   auto &Blocks = L.getBlocksVector();
1762   auto BlocksSplitI =
1763       LoopBlockSet.empty()
1764           ? Blocks.begin()
1765           : std::stable_partition(
1766                 Blocks.begin(), Blocks.end(),
1767                 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1768 
1769   // Before we erase the list of unlooped blocks, build a set of them.
1770   SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1771   if (LoopBlockSet.empty())
1772     UnloopedBlocks.insert(PH);
1773 
1774   // Now erase these blocks from the loop.
1775   for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1776     L.getBlocksSet().erase(BB);
1777   Blocks.erase(BlocksSplitI, Blocks.end());
1778 
1779   // Sort the exits in ascending loop depth, we'll work backwards across these
1780   // to process them inside out.
1781   llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1782     return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1783   });
1784 
1785   // We'll build up a set for each exit loop.
1786   SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1787   Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1788 
1789   auto RemoveUnloopedBlocksFromLoop =
1790       [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1791         for (auto *BB : UnloopedBlocks)
1792           L.getBlocksSet().erase(BB);
1793         llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1794           return UnloopedBlocks.count(BB);
1795         });
1796       };
1797 
1798   SmallVector<BasicBlock *, 16> Worklist;
1799   while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1800     assert(Worklist.empty() && "Didn't clear worklist!");
1801     assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1802 
1803     // Grab the next exit block, in decreasing loop depth order.
1804     BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1805     Loop &ExitL = *LI.getLoopFor(ExitBB);
1806     assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1807 
1808     // Erase all of the unlooped blocks from the loops between the previous
1809     // exit loop and this exit loop. This works because the ExitInLoops list is
1810     // sorted in increasing order of loop depth and thus we visit loops in
1811     // decreasing order of loop depth.
1812     for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1813       RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1814 
1815     // Walk the CFG back until we hit the cloned PH adding everything reachable
1816     // and in the unlooped set to this exit block's loop.
1817     Worklist.push_back(ExitBB);
1818     do {
1819       BasicBlock *BB = Worklist.pop_back_val();
1820       // We can stop recursing at the cloned preheader (if we get there).
1821       if (BB == PH)
1822         continue;
1823 
1824       for (BasicBlock *PredBB : predecessors(BB)) {
1825         // If this pred has already been moved to our set or is part of some
1826         // (inner) loop, no update needed.
1827         if (!UnloopedBlocks.erase(PredBB)) {
1828           assert((NewExitLoopBlocks.count(PredBB) ||
1829                   ExitL.contains(LI.getLoopFor(PredBB))) &&
1830                  "Predecessor not in a nested loop (or already visited)!");
1831           continue;
1832         }
1833 
1834         // We just insert into the loop set here. We'll add these blocks to the
1835         // exit loop after we build up the set in a deterministic order rather
1836         // than the predecessor-influenced visit order.
1837         bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1838         (void)Inserted;
1839         assert(Inserted && "Should only visit an unlooped block once!");
1840 
1841         // And recurse through to its predecessors.
1842         Worklist.push_back(PredBB);
1843       }
1844     } while (!Worklist.empty());
1845 
1846     // If blocks in this exit loop were directly part of the original loop (as
1847     // opposed to a child loop) update the map to point to this exit loop. This
1848     // just updates a map and so the fact that the order is unstable is fine.
1849     for (auto *BB : NewExitLoopBlocks)
1850       if (Loop *BBL = LI.getLoopFor(BB))
1851         if (BBL == &L || !L.contains(BBL))
1852           LI.changeLoopFor(BB, &ExitL);
1853 
1854     // We will remove the remaining unlooped blocks from this loop in the next
1855     // iteration or below.
1856     NewExitLoopBlocks.clear();
1857   }
1858 
1859   // Any remaining unlooped blocks are no longer part of any loop unless they
1860   // are part of some child loop.
1861   for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1862     RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1863   for (auto *BB : UnloopedBlocks)
1864     if (Loop *BBL = LI.getLoopFor(BB))
1865       if (BBL == &L || !L.contains(BBL))
1866         LI.changeLoopFor(BB, nullptr);
1867 
1868   // Sink all the child loops whose headers are no longer in the loop set to
1869   // the parent (or to be top level loops). We reach into the loop and directly
1870   // update its subloop vector to make this batch update efficient.
1871   auto &SubLoops = L.getSubLoopsVector();
1872   auto SubLoopsSplitI =
1873       LoopBlockSet.empty()
1874           ? SubLoops.begin()
1875           : std::stable_partition(
1876                 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1877                   return LoopBlockSet.count(SubL->getHeader());
1878                 });
1879   for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1880     HoistedLoops.push_back(HoistedL);
1881     HoistedL->setParentLoop(nullptr);
1882 
1883     // To compute the new parent of this hoisted loop we look at where we
1884     // placed the preheader above. We can't lookup the header itself because we
1885     // retained the mapping from the header to the hoisted loop. But the
1886     // preheader and header should have the exact same new parent computed
1887     // based on the set of exit blocks from the original loop as the preheader
1888     // is a predecessor of the header and so reached in the reverse walk. And
1889     // because the loops were all in simplified form the preheader of the
1890     // hoisted loop can't be part of some *other* loop.
1891     if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1892       NewParentL->addChildLoop(HoistedL);
1893     else
1894       LI.addTopLevelLoop(HoistedL);
1895   }
1896   SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1897 
1898   // Actually delete the loop if nothing remained within it.
1899   if (Blocks.empty()) {
1900     assert(SubLoops.empty() &&
1901            "Failed to remove all subloops from the original loop!");
1902     if (Loop *ParentL = L.getParentLoop())
1903       ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1904     else
1905       LI.removeLoop(llvm::find(LI, &L));
1906     LI.destroy(&L);
1907     return false;
1908   }
1909 
1910   return true;
1911 }
1912 
1913 /// Helper to visit a dominator subtree, invoking a callable on each node.
1914 ///
1915 /// Returning false at any point will stop walking past that node of the tree.
1916 template <typename CallableT>
1917 void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1918   SmallVector<DomTreeNode *, 4> DomWorklist;
1919   DomWorklist.push_back(DT[BB]);
1920 #ifndef NDEBUG
1921   SmallPtrSet<DomTreeNode *, 4> Visited;
1922   Visited.insert(DT[BB]);
1923 #endif
1924   do {
1925     DomTreeNode *N = DomWorklist.pop_back_val();
1926 
1927     // Visit this node.
1928     if (!Callable(N->getBlock()))
1929       continue;
1930 
1931     // Accumulate the child nodes.
1932     for (DomTreeNode *ChildN : *N) {
1933       assert(Visited.insert(ChildN).second &&
1934              "Cannot visit a node twice when walking a tree!");
1935       DomWorklist.push_back(ChildN);
1936     }
1937   } while (!DomWorklist.empty());
1938 }
1939 
1940 static void unswitchNontrivialInvariants(
1941     Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
1942     SmallVectorImpl<BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI,
1943     AssumptionCache &AC, function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
1944     ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
1945   auto *ParentBB = TI.getParent();
1946   BranchInst *BI = dyn_cast<BranchInst>(&TI);
1947   SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
1948 
1949   // We can only unswitch switches, conditional branches with an invariant
1950   // condition, or combining invariant conditions with an instruction.
1951   assert((SI || (BI && BI->isConditional())) &&
1952          "Can only unswitch switches and conditional branch!");
1953   bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
1954   if (FullUnswitch)
1955     assert(Invariants.size() == 1 &&
1956            "Cannot have other invariants with full unswitching!");
1957   else
1958     assert(isa<Instruction>(BI->getCondition()) &&
1959            "Partial unswitching requires an instruction as the condition!");
1960 
1961   if (MSSAU && VerifyMemorySSA)
1962     MSSAU->getMemorySSA()->verifyMemorySSA();
1963 
1964   // Constant and BBs tracking the cloned and continuing successor. When we are
1965   // unswitching the entire condition, this can just be trivially chosen to
1966   // unswitch towards `true`. However, when we are unswitching a set of
1967   // invariants combined with `and` or `or`, the combining operation determines
1968   // the best direction to unswitch: we want to unswitch the direction that will
1969   // collapse the branch.
1970   bool Direction = true;
1971   int ClonedSucc = 0;
1972   if (!FullUnswitch) {
1973     if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1974       assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1975                  Instruction::And &&
1976              "Only `or` and `and` instructions can combine invariants being "
1977              "unswitched.");
1978       Direction = false;
1979       ClonedSucc = 1;
1980     }
1981   }
1982 
1983   BasicBlock *RetainedSuccBB =
1984       BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1985   SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1986   if (BI)
1987     UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1988   else
1989     for (auto Case : SI->cases())
1990       if (Case.getCaseSuccessor() != RetainedSuccBB)
1991         UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
1992 
1993   assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1994          "Should not unswitch the same successor we are retaining!");
1995 
1996   // The branch should be in this exact loop. Any inner loop's invariant branch
1997   // should be handled by unswitching that inner loop. The caller of this
1998   // routine should filter out any candidates that remain (but were skipped for
1999   // whatever reason).
2000   assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
2001 
2002   // Compute the parent loop now before we start hacking on things.
2003   Loop *ParentL = L.getParentLoop();
2004   // Get blocks in RPO order for MSSA update, before changing the CFG.
2005   LoopBlocksRPO LBRPO(&L);
2006   if (MSSAU)
2007     LBRPO.perform(&LI);
2008 
2009   // Compute the outer-most loop containing one of our exit blocks. This is the
2010   // furthest up our loopnest which can be mutated, which we will use below to
2011   // update things.
2012   Loop *OuterExitL = &L;
2013   for (auto *ExitBB : ExitBlocks) {
2014     Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
2015     if (!NewOuterExitL) {
2016       // We exited the entire nest with this block, so we're done.
2017       OuterExitL = nullptr;
2018       break;
2019     }
2020     if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
2021       OuterExitL = NewOuterExitL;
2022   }
2023 
2024   // At this point, we're definitely going to unswitch something so invalidate
2025   // any cached information in ScalarEvolution for the outer most loop
2026   // containing an exit block and all nested loops.
2027   if (SE) {
2028     if (OuterExitL)
2029       SE->forgetLoop(OuterExitL);
2030     else
2031       SE->forgetTopmostLoop(&L);
2032   }
2033 
2034   // If the edge from this terminator to a successor dominates that successor,
2035   // store a map from each block in its dominator subtree to it. This lets us
2036   // tell when cloning for a particular successor if a block is dominated by
2037   // some *other* successor with a single data structure. We use this to
2038   // significantly reduce cloning.
2039   SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
2040   for (auto *SuccBB : llvm::concat<BasicBlock *const>(
2041            makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
2042     if (SuccBB->getUniquePredecessor() ||
2043         llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2044           return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
2045         }))
2046       visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
2047         DominatingSucc[BB] = SuccBB;
2048         return true;
2049       });
2050 
2051   // Split the preheader, so that we know that there is a safe place to insert
2052   // the conditional branch. We will change the preheader to have a conditional
2053   // branch on LoopCond. The original preheader will become the split point
2054   // between the unswitched versions, and we will have a new preheader for the
2055   // original loop.
2056   BasicBlock *SplitBB = L.getLoopPreheader();
2057   BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
2058 
2059   // Keep track of the dominator tree updates needed.
2060   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2061 
2062   // Clone the loop for each unswitched successor.
2063   SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
2064   VMaps.reserve(UnswitchedSuccBBs.size());
2065   SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
2066   for (auto *SuccBB : UnswitchedSuccBBs) {
2067     VMaps.emplace_back(new ValueToValueMapTy());
2068     ClonedPHs[SuccBB] = buildClonedLoopBlocks(
2069         L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2070         DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
2071   }
2072 
2073   // Drop metadata if we may break its semantics by moving this branch into the
2074   // split block.
2075   // TODO: We can keep make.implicit metadata if we prove that TI always
2076   // executes and we cannot leave unswitched loop before getting to null check
2077   // block. See @test_may_keep_make_implicit_non_trivial.
2078   TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
2079 
2080   // The stitching of the branched code back together depends on whether we're
2081   // doing full unswitching or not with the exception that we always want to
2082   // nuke the initial terminator placed in the split block.
2083   SplitBB->getTerminator()->eraseFromParent();
2084   if (FullUnswitch) {
2085     // Splice the terminator from the original loop and rewrite its
2086     // successors.
2087     SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2088 
2089     // Keep a clone of the terminator for MSSA updates.
2090     Instruction *NewTI = TI.clone();
2091     ParentBB->getInstList().push_back(NewTI);
2092 
2093     // First wire up the moved terminator to the preheaders.
2094     if (BI) {
2095       BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2096       BI->setSuccessor(ClonedSucc, ClonedPH);
2097       BI->setSuccessor(1 - ClonedSucc, LoopPH);
2098       DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2099     } else {
2100       assert(SI && "Must either be a branch or switch!");
2101 
2102       // Walk the cases and directly update their successors.
2103       assert(SI->getDefaultDest() == RetainedSuccBB &&
2104              "Not retaining default successor!");
2105       SI->setDefaultDest(LoopPH);
2106       for (auto &Case : SI->cases())
2107         if (Case.getCaseSuccessor() == RetainedSuccBB)
2108           Case.setSuccessor(LoopPH);
2109         else
2110           Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2111 
2112       // We need to use the set to populate domtree updates as even when there
2113       // are multiple cases pointing at the same successor we only want to
2114       // remove and insert one edge in the domtree.
2115       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2116         DTUpdates.push_back(
2117             {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2118     }
2119 
2120     if (MSSAU) {
2121       DT.applyUpdates(DTUpdates);
2122       DTUpdates.clear();
2123 
2124       // Remove all but one edge to the retained block and all unswitched
2125       // blocks. This is to avoid having duplicate entries in the cloned Phis,
2126       // when we know we only keep a single edge for each case.
2127       MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2128       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2129         MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2130 
2131       for (auto &VMap : VMaps)
2132         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2133                                    /*IgnoreIncomingWithNoClones=*/true);
2134       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2135 
2136       // Remove all edges to unswitched blocks.
2137       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2138         MSSAU->removeEdge(ParentBB, SuccBB);
2139     }
2140 
2141     // Now unhook the successor relationship as we'll be replacing
2142     // the terminator with a direct branch. This is much simpler for branches
2143     // than switches so we handle those first.
2144     if (BI) {
2145       // Remove the parent as a predecessor of the unswitched successor.
2146       assert(UnswitchedSuccBBs.size() == 1 &&
2147              "Only one possible unswitched block for a branch!");
2148       BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2149       UnswitchedSuccBB->removePredecessor(ParentBB,
2150                                           /*KeepOneInputPHIs*/ true);
2151       DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2152     } else {
2153       // Note that we actually want to remove the parent block as a predecessor
2154       // of *every* case successor. The case successor is either unswitched,
2155       // completely eliminating an edge from the parent to that successor, or it
2156       // is a duplicate edge to the retained successor as the retained successor
2157       // is always the default successor and as we'll replace this with a direct
2158       // branch we no longer need the duplicate entries in the PHI nodes.
2159       SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2160       assert(NewSI->getDefaultDest() == RetainedSuccBB &&
2161              "Not retaining default successor!");
2162       for (auto &Case : NewSI->cases())
2163         Case.getCaseSuccessor()->removePredecessor(
2164             ParentBB,
2165             /*KeepOneInputPHIs*/ true);
2166 
2167       // We need to use the set to populate domtree updates as even when there
2168       // are multiple cases pointing at the same successor we only want to
2169       // remove and insert one edge in the domtree.
2170       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2171         DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
2172     }
2173 
2174     // After MSSAU update, remove the cloned terminator instruction NewTI.
2175     ParentBB->getTerminator()->eraseFromParent();
2176 
2177     // Create a new unconditional branch to the continuing block (as opposed to
2178     // the one cloned).
2179     BranchInst::Create(RetainedSuccBB, ParentBB);
2180   } else {
2181     assert(BI && "Only branches have partial unswitching.");
2182     assert(UnswitchedSuccBBs.size() == 1 &&
2183            "Only one possible unswitched block for a branch!");
2184     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2185     // When doing a partial unswitch, we have to do a bit more work to build up
2186     // the branch in the split block.
2187     buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
2188                                           *ClonedPH, *LoopPH);
2189     DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2190 
2191     if (MSSAU) {
2192       DT.applyUpdates(DTUpdates);
2193       DTUpdates.clear();
2194 
2195       // Perform MSSA cloning updates.
2196       for (auto &VMap : VMaps)
2197         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2198                                    /*IgnoreIncomingWithNoClones=*/true);
2199       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2200     }
2201   }
2202 
2203   // Apply the updates accumulated above to get an up-to-date dominator tree.
2204   DT.applyUpdates(DTUpdates);
2205 
2206   // Now that we have an accurate dominator tree, first delete the dead cloned
2207   // blocks so that we can accurately build any cloned loops. It is important to
2208   // not delete the blocks from the original loop yet because we still want to
2209   // reference the original loop to understand the cloned loop's structure.
2210   deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
2211 
2212   // Build the cloned loop structure itself. This may be substantially
2213   // different from the original structure due to the simplified CFG. This also
2214   // handles inserting all the cloned blocks into the correct loops.
2215   SmallVector<Loop *, 4> NonChildClonedLoops;
2216   for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2217     buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
2218 
2219   // Now that our cloned loops have been built, we can update the original loop.
2220   // First we delete the dead blocks from it and then we rebuild the loop
2221   // structure taking these deletions into account.
2222   deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU);
2223 
2224   if (MSSAU && VerifyMemorySSA)
2225     MSSAU->getMemorySSA()->verifyMemorySSA();
2226 
2227   SmallVector<Loop *, 4> HoistedLoops;
2228   bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2229 
2230   if (MSSAU && VerifyMemorySSA)
2231     MSSAU->getMemorySSA()->verifyMemorySSA();
2232 
2233   // This transformation has a high risk of corrupting the dominator tree, and
2234   // the below steps to rebuild loop structures will result in hard to debug
2235   // errors in that case so verify that the dominator tree is sane first.
2236   // FIXME: Remove this when the bugs stop showing up and rely on existing
2237   // verification steps.
2238   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2239 
2240   if (BI) {
2241     // If we unswitched a branch which collapses the condition to a known
2242     // constant we want to replace all the uses of the invariants within both
2243     // the original and cloned blocks. We do this here so that we can use the
2244     // now updated dominator tree to identify which side the users are on.
2245     assert(UnswitchedSuccBBs.size() == 1 &&
2246            "Only one possible unswitched block for a branch!");
2247     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2248 
2249     // When considering multiple partially-unswitched invariants
2250     // we cant just go replace them with constants in both branches.
2251     //
2252     // For 'AND' we infer that true branch ("continue") means true
2253     // for each invariant operand.
2254     // For 'OR' we can infer that false branch ("continue") means false
2255     // for each invariant operand.
2256     // So it happens that for multiple-partial case we dont replace
2257     // in the unswitched branch.
2258     bool ReplaceUnswitched = FullUnswitch || (Invariants.size() == 1);
2259 
2260     ConstantInt *UnswitchedReplacement =
2261         Direction ? ConstantInt::getTrue(BI->getContext())
2262                   : ConstantInt::getFalse(BI->getContext());
2263     ConstantInt *ContinueReplacement =
2264         Direction ? ConstantInt::getFalse(BI->getContext())
2265                   : ConstantInt::getTrue(BI->getContext());
2266     for (Value *Invariant : Invariants)
2267       for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2268            UI != UE;) {
2269         // Grab the use and walk past it so we can clobber it in the use list.
2270         Use *U = &*UI++;
2271         Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2272         if (!UserI)
2273           continue;
2274 
2275         // Replace it with the 'continue' side if in the main loop body, and the
2276         // unswitched if in the cloned blocks.
2277         if (DT.dominates(LoopPH, UserI->getParent()))
2278           U->set(ContinueReplacement);
2279         else if (ReplaceUnswitched &&
2280                  DT.dominates(ClonedPH, UserI->getParent()))
2281           U->set(UnswitchedReplacement);
2282       }
2283   }
2284 
2285   // We can change which blocks are exit blocks of all the cloned sibling
2286   // loops, the current loop, and any parent loops which shared exit blocks
2287   // with the current loop. As a consequence, we need to re-form LCSSA for
2288   // them. But we shouldn't need to re-form LCSSA for any child loops.
2289   // FIXME: This could be made more efficient by tracking which exit blocks are
2290   // new, and focusing on them, but that isn't likely to be necessary.
2291   //
2292   // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2293   // loop nest and update every loop that could have had its exits changed. We
2294   // also need to cover any intervening loops. We add all of these loops to
2295   // a list and sort them by loop depth to achieve this without updating
2296   // unnecessary loops.
2297   auto UpdateLoop = [&](Loop &UpdateL) {
2298 #ifndef NDEBUG
2299     UpdateL.verifyLoop();
2300     for (Loop *ChildL : UpdateL) {
2301       ChildL->verifyLoop();
2302       assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2303              "Perturbed a child loop's LCSSA form!");
2304     }
2305 #endif
2306     // First build LCSSA for this loop so that we can preserve it when
2307     // forming dedicated exits. We don't want to perturb some other loop's
2308     // LCSSA while doing that CFG edit.
2309     formLCSSA(UpdateL, DT, &LI, SE);
2310 
2311     // For loops reached by this loop's original exit blocks we may
2312     // introduced new, non-dedicated exits. At least try to re-form dedicated
2313     // exits for these loops. This may fail if they couldn't have dedicated
2314     // exits to start with.
2315     formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
2316   };
2317 
2318   // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2319   // and we can do it in any order as they don't nest relative to each other.
2320   //
2321   // Also check if any of the loops we have updated have become top-level loops
2322   // as that will necessitate widening the outer loop scope.
2323   for (Loop *UpdatedL :
2324        llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2325     UpdateLoop(*UpdatedL);
2326     if (!UpdatedL->getParentLoop())
2327       OuterExitL = nullptr;
2328   }
2329   if (IsStillLoop) {
2330     UpdateLoop(L);
2331     if (!L.getParentLoop())
2332       OuterExitL = nullptr;
2333   }
2334 
2335   // If the original loop had exit blocks, walk up through the outer most loop
2336   // of those exit blocks to update LCSSA and form updated dedicated exits.
2337   if (OuterExitL != &L)
2338     for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2339          OuterL = OuterL->getParentLoop())
2340       UpdateLoop(*OuterL);
2341 
2342 #ifndef NDEBUG
2343   // Verify the entire loop structure to catch any incorrect updates before we
2344   // progress in the pass pipeline.
2345   LI.verify(DT);
2346 #endif
2347 
2348   // Now that we've unswitched something, make callbacks to report the changes.
2349   // For that we need to merge together the updated loops and the cloned loops
2350   // and check whether the original loop survived.
2351   SmallVector<Loop *, 4> SibLoops;
2352   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2353     if (UpdatedL->getParentLoop() == ParentL)
2354       SibLoops.push_back(UpdatedL);
2355   UnswitchCB(IsStillLoop, SibLoops);
2356 
2357   if (MSSAU && VerifyMemorySSA)
2358     MSSAU->getMemorySSA()->verifyMemorySSA();
2359 
2360   if (BI)
2361     ++NumBranches;
2362   else
2363     ++NumSwitches;
2364 }
2365 
2366 /// Recursively compute the cost of a dominator subtree based on the per-block
2367 /// cost map provided.
2368 ///
2369 /// The recursive computation is memozied into the provided DT-indexed cost map
2370 /// to allow querying it for most nodes in the domtree without it becoming
2371 /// quadratic.
2372 static int
2373 computeDomSubtreeCost(DomTreeNode &N,
2374                       const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2375                       SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2376   // Don't accumulate cost (or recurse through) blocks not in our block cost
2377   // map and thus not part of the duplication cost being considered.
2378   auto BBCostIt = BBCostMap.find(N.getBlock());
2379   if (BBCostIt == BBCostMap.end())
2380     return 0;
2381 
2382   // Lookup this node to see if we already computed its cost.
2383   auto DTCostIt = DTCostMap.find(&N);
2384   if (DTCostIt != DTCostMap.end())
2385     return DTCostIt->second;
2386 
2387   // If not, we have to compute it. We can't use insert above and update
2388   // because computing the cost may insert more things into the map.
2389   int Cost = std::accumulate(
2390       N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2391         return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2392       });
2393   bool Inserted = DTCostMap.insert({&N, Cost}).second;
2394   (void)Inserted;
2395   assert(Inserted && "Should not insert a node while visiting children!");
2396   return Cost;
2397 }
2398 
2399 /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2400 /// making the following replacement:
2401 ///
2402 ///   --code before guard--
2403 ///   call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
2404 ///   --code after guard--
2405 ///
2406 /// into
2407 ///
2408 ///   --code before guard--
2409 ///   br i1 %cond, label %guarded, label %deopt
2410 ///
2411 /// guarded:
2412 ///   --code after guard--
2413 ///
2414 /// deopt:
2415 ///   call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2416 ///   unreachable
2417 ///
2418 /// It also makes all relevant DT and LI updates, so that all structures are in
2419 /// valid state after this transform.
2420 static BranchInst *
2421 turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2422                     SmallVectorImpl<BasicBlock *> &ExitBlocks,
2423                     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
2424   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2425   LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2426   BasicBlock *CheckBB = GI->getParent();
2427 
2428   if (MSSAU && VerifyMemorySSA)
2429      MSSAU->getMemorySSA()->verifyMemorySSA();
2430 
2431   // Remove all CheckBB's successors from DomTree. A block can be seen among
2432   // successors more than once, but for DomTree it should be added only once.
2433   SmallPtrSet<BasicBlock *, 4> Successors;
2434   for (auto *Succ : successors(CheckBB))
2435     if (Successors.insert(Succ).second)
2436       DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2437 
2438   Instruction *DeoptBlockTerm =
2439       SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2440   BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2441   // SplitBlockAndInsertIfThen inserts control flow that branches to
2442   // DeoptBlockTerm if the condition is true.  We want the opposite.
2443   CheckBI->swapSuccessors();
2444 
2445   BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2446   GuardedBlock->setName("guarded");
2447   CheckBI->getSuccessor(1)->setName("deopt");
2448   BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
2449 
2450   // We now have a new exit block.
2451   ExitBlocks.push_back(CheckBI->getSuccessor(1));
2452 
2453   if (MSSAU)
2454     MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2455 
2456   GI->moveBefore(DeoptBlockTerm);
2457   GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2458 
2459   // Add new successors of CheckBB into DomTree.
2460   for (auto *Succ : successors(CheckBB))
2461     DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2462 
2463   // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2464   // successors.
2465   for (auto *Succ : Successors)
2466     DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2467 
2468   // Make proper changes to DT.
2469   DT.applyUpdates(DTUpdates);
2470   // Inform LI of a new loop block.
2471   L.addBasicBlockToLoop(GuardedBlock, LI);
2472 
2473   if (MSSAU) {
2474     MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2475     MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::BeforeTerminator);
2476     if (VerifyMemorySSA)
2477       MSSAU->getMemorySSA()->verifyMemorySSA();
2478   }
2479 
2480   ++NumGuards;
2481   return CheckBI;
2482 }
2483 
2484 /// Cost multiplier is a way to limit potentially exponential behavior
2485 /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2486 /// candidates available. Also accounting for the number of "sibling" loops with
2487 /// the idea to account for previous unswitches that already happened on this
2488 /// cluster of loops. There was an attempt to keep this formula simple,
2489 /// just enough to limit the worst case behavior. Even if it is not that simple
2490 /// now it is still not an attempt to provide a detailed heuristic size
2491 /// prediction.
2492 ///
2493 /// TODO: Make a proper accounting of "explosion" effect for all kinds of
2494 /// unswitch candidates, making adequate predictions instead of wild guesses.
2495 /// That requires knowing not just the number of "remaining" candidates but
2496 /// also costs of unswitching for each of these candidates.
2497 static int CalculateUnswitchCostMultiplier(
2498     Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
2499     ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
2500         UnswitchCandidates) {
2501 
2502   // Guards and other exiting conditions do not contribute to exponential
2503   // explosion as soon as they dominate the latch (otherwise there might be
2504   // another path to the latch remaining that does not allow to eliminate the
2505   // loop copy on unswitch).
2506   BasicBlock *Latch = L.getLoopLatch();
2507   BasicBlock *CondBlock = TI.getParent();
2508   if (DT.dominates(CondBlock, Latch) &&
2509       (isGuard(&TI) ||
2510        llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
2511          return L.contains(SuccBB);
2512        }) <= 1)) {
2513     NumCostMultiplierSkipped++;
2514     return 1;
2515   }
2516 
2517   auto *ParentL = L.getParentLoop();
2518   int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2519                                : std::distance(LI.begin(), LI.end()));
2520   // Count amount of clones that all the candidates might cause during
2521   // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2522   int UnswitchedClones = 0;
2523   for (auto Candidate : UnswitchCandidates) {
2524     Instruction *CI = Candidate.first;
2525     BasicBlock *CondBlock = CI->getParent();
2526     bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2527     if (isGuard(CI)) {
2528       if (!SkipExitingSuccessors)
2529         UnswitchedClones++;
2530       continue;
2531     }
2532     int NonExitingSuccessors = llvm::count_if(
2533         successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
2534           return !SkipExitingSuccessors || L.contains(SuccBB);
2535         });
2536     UnswitchedClones += Log2_32(NonExitingSuccessors);
2537   }
2538 
2539   // Ignore up to the "unscaled candidates" number of unswitch candidates
2540   // when calculating the power-of-two scaling of the cost. The main idea
2541   // with this control is to allow a small number of unswitches to happen
2542   // and rely more on siblings multiplier (see below) when the number
2543   // of candidates is small.
2544   unsigned ClonesPower =
2545       std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
2546 
2547   // Allowing top-level loops to spread a bit more than nested ones.
2548   int SiblingsMultiplier =
2549       std::max((ParentL ? SiblingsCount
2550                         : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
2551                1);
2552   // Compute the cost multiplier in a way that won't overflow by saturating
2553   // at an upper bound.
2554   int CostMultiplier;
2555   if (ClonesPower > Log2_32(UnswitchThreshold) ||
2556       SiblingsMultiplier > UnswitchThreshold)
2557     CostMultiplier = UnswitchThreshold;
2558   else
2559     CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2560                               (int)UnswitchThreshold);
2561 
2562   LLVM_DEBUG(dbgs() << "  Computed multiplier  " << CostMultiplier
2563                     << " (siblings " << SiblingsMultiplier << " * clones "
2564                     << (1 << ClonesPower) << ")"
2565                     << " for unswitch candidate: " << TI << "\n");
2566   return CostMultiplier;
2567 }
2568 
2569 static bool
2570 unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2571                       AssumptionCache &AC, TargetTransformInfo &TTI,
2572                       function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2573                       ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
2574   // Collect all invariant conditions within this loop (as opposed to an inner
2575   // loop which would be handled when visiting that inner loop).
2576   SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
2577       UnswitchCandidates;
2578 
2579   // Whether or not we should also collect guards in the loop.
2580   bool CollectGuards = false;
2581   if (UnswitchGuards) {
2582     auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2583         Intrinsic::getName(Intrinsic::experimental_guard));
2584     if (GuardDecl && !GuardDecl->use_empty())
2585       CollectGuards = true;
2586   }
2587 
2588   for (auto *BB : L.blocks()) {
2589     if (LI.getLoopFor(BB) != &L)
2590       continue;
2591 
2592     if (CollectGuards)
2593       for (auto &I : *BB)
2594         if (isGuard(&I)) {
2595           auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2596           // TODO: Support AND, OR conditions and partial unswitching.
2597           if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2598             UnswitchCandidates.push_back({&I, {Cond}});
2599         }
2600 
2601     if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2602       // We can only consider fully loop-invariant switch conditions as we need
2603       // to completely eliminate the switch after unswitching.
2604       if (!isa<Constant>(SI->getCondition()) &&
2605           L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor())
2606         UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2607       continue;
2608     }
2609 
2610     auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2611     if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2612         BI->getSuccessor(0) == BI->getSuccessor(1))
2613       continue;
2614 
2615     if (L.isLoopInvariant(BI->getCondition())) {
2616       UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2617       continue;
2618     }
2619 
2620     Instruction &CondI = *cast<Instruction>(BI->getCondition());
2621     if (CondI.getOpcode() != Instruction::And &&
2622       CondI.getOpcode() != Instruction::Or)
2623       continue;
2624 
2625     TinyPtrVector<Value *> Invariants =
2626         collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2627     if (Invariants.empty())
2628       continue;
2629 
2630     UnswitchCandidates.push_back({BI, std::move(Invariants)});
2631   }
2632 
2633   // If we didn't find any candidates, we're done.
2634   if (UnswitchCandidates.empty())
2635     return false;
2636 
2637   // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2638   // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2639   // irreducible control flow into reducible control flow and introduce new
2640   // loops "out of thin air". If we ever discover important use cases for doing
2641   // this, we can add support to loop unswitch, but it is a lot of complexity
2642   // for what seems little or no real world benefit.
2643   LoopBlocksRPO RPOT(&L);
2644   RPOT.perform(&LI);
2645   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
2646     return false;
2647 
2648   SmallVector<BasicBlock *, 4> ExitBlocks;
2649   L.getUniqueExitBlocks(ExitBlocks);
2650 
2651   // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
2652   // don't know how to split those exit blocks.
2653   // FIXME: We should teach SplitBlock to handle this and remove this
2654   // restriction.
2655   for (auto *ExitBB : ExitBlocks)
2656     if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) {
2657       dbgs() << "Cannot unswitch because of cleanuppad in exit block\n";
2658       return false;
2659     }
2660 
2661   LLVM_DEBUG(
2662       dbgs() << "Considering " << UnswitchCandidates.size()
2663              << " non-trivial loop invariant conditions for unswitching.\n");
2664 
2665   // Given that unswitching these terminators will require duplicating parts of
2666   // the loop, so we need to be able to model that cost. Compute the ephemeral
2667   // values and set up a data structure to hold per-BB costs. We cache each
2668   // block's cost so that we don't recompute this when considering different
2669   // subsets of the loop for duplication during unswitching.
2670   SmallPtrSet<const Value *, 4> EphValues;
2671   CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2672   SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2673 
2674   // Compute the cost of each block, as well as the total loop cost. Also, bail
2675   // out if we see instructions which are incompatible with loop unswitching
2676   // (convergent, noduplicate, or cross-basic-block tokens).
2677   // FIXME: We might be able to safely handle some of these in non-duplicated
2678   // regions.
2679   int LoopCost = 0;
2680   for (auto *BB : L.blocks()) {
2681     int Cost = 0;
2682     for (auto &I : *BB) {
2683       if (EphValues.count(&I))
2684         continue;
2685 
2686       if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
2687         return false;
2688       if (auto *CB = dyn_cast<CallBase>(&I))
2689         if (CB->isConvergent() || CB->cannotDuplicate())
2690           return false;
2691 
2692       Cost += TTI.getUserCost(&I, TargetTransformInfo::TCK_CodeSize);
2693     }
2694     assert(Cost >= 0 && "Must not have negative costs!");
2695     LoopCost += Cost;
2696     assert(LoopCost >= 0 && "Must not have negative loop costs!");
2697     BBCostMap[BB] = Cost;
2698   }
2699   LLVM_DEBUG(dbgs() << "  Total loop cost: " << LoopCost << "\n");
2700 
2701   // Now we find the best candidate by searching for the one with the following
2702   // properties in order:
2703   //
2704   // 1) An unswitching cost below the threshold
2705   // 2) The smallest number of duplicated unswitch candidates (to avoid
2706   //    creating redundant subsequent unswitching)
2707   // 3) The smallest cost after unswitching.
2708   //
2709   // We prioritize reducing fanout of unswitch candidates provided the cost
2710   // remains below the threshold because this has a multiplicative effect.
2711   //
2712   // This requires memoizing each dominator subtree to avoid redundant work.
2713   //
2714   // FIXME: Need to actually do the number of candidates part above.
2715   SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2716   // Given a terminator which might be unswitched, computes the non-duplicated
2717   // cost for that terminator.
2718   auto ComputeUnswitchedCost = [&](Instruction &TI, bool FullUnswitch) {
2719     BasicBlock &BB = *TI.getParent();
2720     SmallPtrSet<BasicBlock *, 4> Visited;
2721 
2722     int Cost = LoopCost;
2723     for (BasicBlock *SuccBB : successors(&BB)) {
2724       // Don't count successors more than once.
2725       if (!Visited.insert(SuccBB).second)
2726         continue;
2727 
2728       // If this is a partial unswitch candidate, then it must be a conditional
2729       // branch with a condition of either `or` or `and`. In that case, one of
2730       // the successors is necessarily duplicated, so don't even try to remove
2731       // its cost.
2732       if (!FullUnswitch) {
2733         auto &BI = cast<BranchInst>(TI);
2734         if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2735             Instruction::And) {
2736           if (SuccBB == BI.getSuccessor(1))
2737             continue;
2738         } else {
2739           assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2740                      Instruction::Or &&
2741                  "Only `and` and `or` conditions can result in a partial "
2742                  "unswitch!");
2743           if (SuccBB == BI.getSuccessor(0))
2744             continue;
2745         }
2746       }
2747 
2748       // This successor's domtree will not need to be duplicated after
2749       // unswitching if the edge to the successor dominates it (and thus the
2750       // entire tree). This essentially means there is no other path into this
2751       // subtree and so it will end up live in only one clone of the loop.
2752       if (SuccBB->getUniquePredecessor() ||
2753           llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2754             return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2755           })) {
2756         Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2757         assert(Cost >= 0 &&
2758                "Non-duplicated cost should never exceed total loop cost!");
2759       }
2760     }
2761 
2762     // Now scale the cost by the number of unique successors minus one. We
2763     // subtract one because there is already at least one copy of the entire
2764     // loop. This is computing the new cost of unswitching a condition.
2765     // Note that guards always have 2 unique successors that are implicit and
2766     // will be materialized if we decide to unswitch it.
2767     int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2768     assert(SuccessorsCount > 1 &&
2769            "Cannot unswitch a condition without multiple distinct successors!");
2770     return Cost * (SuccessorsCount - 1);
2771   };
2772   Instruction *BestUnswitchTI = nullptr;
2773   int BestUnswitchCost = 0;
2774   ArrayRef<Value *> BestUnswitchInvariants;
2775   for (auto &TerminatorAndInvariants : UnswitchCandidates) {
2776     Instruction &TI = *TerminatorAndInvariants.first;
2777     ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2778     BranchInst *BI = dyn_cast<BranchInst>(&TI);
2779     int CandidateCost = ComputeUnswitchedCost(
2780         TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2781                                      Invariants[0] == BI->getCondition()));
2782     // Calculate cost multiplier which is a tool to limit potentially
2783     // exponential behavior of loop-unswitch.
2784     if (EnableUnswitchCostMultiplier) {
2785       int CostMultiplier =
2786           CalculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
2787       assert(
2788           (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
2789           "cost multiplier needs to be in the range of 1..UnswitchThreshold");
2790       CandidateCost *= CostMultiplier;
2791       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
2792                         << " (multiplier: " << CostMultiplier << ")"
2793                         << " for unswitch candidate: " << TI << "\n");
2794     } else {
2795       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
2796                         << " for unswitch candidate: " << TI << "\n");
2797     }
2798 
2799     if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2800       BestUnswitchTI = &TI;
2801       BestUnswitchCost = CandidateCost;
2802       BestUnswitchInvariants = Invariants;
2803     }
2804   }
2805   assert(BestUnswitchTI && "Failed to find loop unswitch candidate");
2806 
2807   if (BestUnswitchCost >= UnswitchThreshold) {
2808     LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2809                       << BestUnswitchCost << "\n");
2810     return false;
2811   }
2812 
2813   // If the best candidate is a guard, turn it into a branch.
2814   if (isGuard(BestUnswitchTI))
2815     BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
2816                                          ExitBlocks, DT, LI, MSSAU);
2817 
2818   LLVM_DEBUG(dbgs() << "  Unswitching non-trivial (cost = "
2819                     << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2820                     << "\n");
2821   unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
2822                                ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU);
2823   return true;
2824 }
2825 
2826 /// Unswitch control flow predicated on loop invariant conditions.
2827 ///
2828 /// This first hoists all branches or switches which are trivial (IE, do not
2829 /// require duplicating any part of the loop) out of the loop body. It then
2830 /// looks at other loop invariant control flows and tries to unswitch those as
2831 /// well by cloning the loop if the result is small enough.
2832 ///
2833 /// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2834 /// updated based on the unswitch.
2835 /// The `MSSA` analysis is also updated if valid (i.e. its use is enabled).
2836 ///
2837 /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2838 /// true, we will attempt to do non-trivial unswitching as well as trivial
2839 /// unswitching.
2840 ///
2841 /// The `UnswitchCB` callback provided will be run after unswitching is
2842 /// complete, with the first parameter set to `true` if the provided loop
2843 /// remains a loop, and a list of new sibling loops created.
2844 ///
2845 /// If `SE` is non-null, we will update that analysis based on the unswitching
2846 /// done.
2847 static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2848                          AssumptionCache &AC, TargetTransformInfo &TTI,
2849                          bool NonTrivial,
2850                          function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2851                          ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
2852   assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2853          "Loops must be in LCSSA form before unswitching.");
2854 
2855   // Must be in loop simplified form: we need a preheader and dedicated exits.
2856   if (!L.isLoopSimplifyForm())
2857     return false;
2858 
2859   // Try trivial unswitch first before loop over other basic blocks in the loop.
2860   if (unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
2861     // If we unswitched successfully we will want to clean up the loop before
2862     // processing it further so just mark it as unswitched and return.
2863     UnswitchCB(/*CurrentLoopValid*/ true, {});
2864     return true;
2865   }
2866 
2867   // If we're not doing non-trivial unswitching, we're done. We both accept
2868   // a parameter but also check a local flag that can be used for testing
2869   // a debugging.
2870   if (!NonTrivial && !EnableNonTrivialUnswitch)
2871     return false;
2872 
2873   // For non-trivial unswitching, because it often creates new loops, we rely on
2874   // the pass manager to iterate on the loops rather than trying to immediately
2875   // reach a fixed point. There is no substantial advantage to iterating
2876   // internally, and if any of the new loops are simplified enough to contain
2877   // trivial unswitching we want to prefer those.
2878 
2879   // Try to unswitch the best invariant condition. We prefer this full unswitch to
2880   // a partial unswitch when possible below the threshold.
2881   if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE, MSSAU))
2882     return true;
2883 
2884   // No other opportunities to unswitch.
2885   return false;
2886 }
2887 
2888 PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2889                                               LoopStandardAnalysisResults &AR,
2890                                               LPMUpdater &U) {
2891   Function &F = *L.getHeader()->getParent();
2892   (void)F;
2893 
2894   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2895                     << "\n");
2896 
2897   // Save the current loop name in a variable so that we can report it even
2898   // after it has been deleted.
2899   std::string LoopName = std::string(L.getName());
2900 
2901   auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2902                                         ArrayRef<Loop *> NewLoops) {
2903     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2904     if (!NewLoops.empty())
2905       U.addSiblingLoops(NewLoops);
2906 
2907     // If the current loop remains valid, we should revisit it to catch any
2908     // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2909     if (CurrentLoopValid)
2910       U.revisitCurrentLoop();
2911     else
2912       U.markLoopAsDeleted(L, LoopName);
2913   };
2914 
2915   Optional<MemorySSAUpdater> MSSAU;
2916   if (AR.MSSA) {
2917     MSSAU = MemorySSAUpdater(AR.MSSA);
2918     if (VerifyMemorySSA)
2919       AR.MSSA->verifyMemorySSA();
2920   }
2921   if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
2922                     &AR.SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
2923     return PreservedAnalyses::all();
2924 
2925   if (AR.MSSA && VerifyMemorySSA)
2926     AR.MSSA->verifyMemorySSA();
2927 
2928   // Historically this pass has had issues with the dominator tree so verify it
2929   // in asserts builds.
2930   assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
2931 
2932   auto PA = getLoopPassPreservedAnalyses();
2933   if (AR.MSSA)
2934     PA.preserve<MemorySSAAnalysis>();
2935   return PA;
2936 }
2937 
2938 namespace {
2939 
2940 class SimpleLoopUnswitchLegacyPass : public LoopPass {
2941   bool NonTrivial;
2942 
2943 public:
2944   static char ID; // Pass ID, replacement for typeid
2945 
2946   explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2947       : LoopPass(ID), NonTrivial(NonTrivial) {
2948     initializeSimpleLoopUnswitchLegacyPassPass(
2949         *PassRegistry::getPassRegistry());
2950   }
2951 
2952   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2953 
2954   void getAnalysisUsage(AnalysisUsage &AU) const override {
2955     AU.addRequired<AssumptionCacheTracker>();
2956     AU.addRequired<TargetTransformInfoWrapperPass>();
2957     if (EnableMSSALoopDependency) {
2958       AU.addRequired<MemorySSAWrapperPass>();
2959       AU.addPreserved<MemorySSAWrapperPass>();
2960     }
2961     getLoopAnalysisUsage(AU);
2962   }
2963 };
2964 
2965 } // end anonymous namespace
2966 
2967 bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2968   if (skipLoop(L))
2969     return false;
2970 
2971   Function &F = *L->getHeader()->getParent();
2972 
2973   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2974                     << "\n");
2975 
2976   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2977   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2978   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2979   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2980   MemorySSA *MSSA = nullptr;
2981   Optional<MemorySSAUpdater> MSSAU;
2982   if (EnableMSSALoopDependency) {
2983     MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
2984     MSSAU = MemorySSAUpdater(MSSA);
2985   }
2986 
2987   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2988   auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2989 
2990   auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2991                                ArrayRef<Loop *> NewLoops) {
2992     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2993     for (auto *NewL : NewLoops)
2994       LPM.addLoop(*NewL);
2995 
2996     // If the current loop remains valid, re-add it to the queue. This is
2997     // a little wasteful as we'll finish processing the current loop as well,
2998     // but it is the best we can do in the old PM.
2999     if (CurrentLoopValid)
3000       LPM.addLoop(*L);
3001     else
3002       LPM.markLoopAsDeleted(*L);
3003   };
3004 
3005   if (MSSA && VerifyMemorySSA)
3006     MSSA->verifyMemorySSA();
3007 
3008   bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE,
3009                               MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
3010 
3011   if (MSSA && VerifyMemorySSA)
3012     MSSA->verifyMemorySSA();
3013 
3014   // Historically this pass has had issues with the dominator tree so verify it
3015   // in asserts builds.
3016   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
3017 
3018   return Changed;
3019 }
3020 
3021 char SimpleLoopUnswitchLegacyPass::ID = 0;
3022 INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
3023                       "Simple unswitch loops", false, false)
3024 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3025 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3026 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
3027 INITIALIZE_PASS_DEPENDENCY(LoopPass)
3028 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3029 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
3030 INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
3031                     "Simple unswitch loops", false, false)
3032 
3033 Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
3034   return new SimpleLoopUnswitchLegacyPass(NonTrivial);
3035 }
3036