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