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