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