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