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