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