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