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