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