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