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