10b57cec5SDimitry Andric ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric
90b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
100b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
110b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
120b57cec5SDimitry Andric #include "llvm/ADT/Sequence.h"
130b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
140b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
150b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
160b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
170b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
19bdd1243dSDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/CodeMetrics.h"
22fe013be4SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/GuardUtils.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/LoopAnalysisManager.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
280b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
29e8d8bef9SDimitry Andric #include "llvm/Analysis/MustExecute.h"
30bdd1243dSDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
31e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
3281ad6265SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
33349cc55cSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
340b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
350b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
360b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
370b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
380b57cec5SDimitry Andric #include "llvm/IR/Function.h"
39e8d8bef9SDimitry Andric #include "llvm/IR/IRBuilder.h"
400b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
410b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
420b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
430b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
44fe6060f1SDimitry Andric #include "llvm/IR/PatternMatch.h"
45fe013be4SDimitry Andric #include "llvm/IR/ProfDataUtils.h"
460b57cec5SDimitry Andric #include "llvm/IR/Use.h"
470b57cec5SDimitry Andric #include "llvm/IR/Value.h"
480b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
49480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
500b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
510b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
520b57cec5SDimitry Andric #include "llvm/Support/GenericDomTree.h"
5381ad6265SDimitry Andric #include "llvm/Support/InstructionCost.h"
540b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
5581ad6265SDimitry Andric #include "llvm/Transforms/Scalar/LoopPassManager.h"
560b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
570b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
58e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
590b57cec5SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
600b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
610b57cec5SDimitry Andric #include <algorithm>
620b57cec5SDimitry Andric #include <cassert>
630b57cec5SDimitry Andric #include <iterator>
640b57cec5SDimitry Andric #include <numeric>
65bdd1243dSDimitry Andric #include <optional>
660b57cec5SDimitry Andric #include <utility>
670b57cec5SDimitry Andric
680b57cec5SDimitry Andric #define DEBUG_TYPE "simple-loop-unswitch"
690b57cec5SDimitry Andric
700b57cec5SDimitry Andric using namespace llvm;
71fe6060f1SDimitry Andric using namespace llvm::PatternMatch;
720b57cec5SDimitry Andric
730b57cec5SDimitry Andric STATISTIC(NumBranches, "Number of branches unswitched");
740b57cec5SDimitry Andric STATISTIC(NumSwitches, "Number of switches unswitched");
75fe013be4SDimitry Andric STATISTIC(NumSelects, "Number of selects turned into branches for unswitching");
760b57cec5SDimitry Andric STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
770b57cec5SDimitry Andric STATISTIC(NumTrivial, "Number of unswitches that are trivial");
780b57cec5SDimitry Andric STATISTIC(
790b57cec5SDimitry Andric NumCostMultiplierSkipped,
800b57cec5SDimitry Andric "Number of unswitch candidates that had their cost multiplier skipped");
81fe013be4SDimitry Andric STATISTIC(NumInvariantConditionsInjected,
82fe013be4SDimitry Andric "Number of invariant conditions injected and unswitched");
830b57cec5SDimitry Andric
840b57cec5SDimitry Andric static cl::opt<bool> EnableNonTrivialUnswitch(
850b57cec5SDimitry Andric "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
860b57cec5SDimitry Andric cl::desc("Forcibly enables non-trivial loop unswitching rather than "
870b57cec5SDimitry Andric "following the configuration passed into the pass."));
880b57cec5SDimitry Andric
890b57cec5SDimitry Andric static cl::opt<int>
900b57cec5SDimitry Andric UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
910b57cec5SDimitry Andric cl::desc("The cost threshold for unswitching a loop."));
920b57cec5SDimitry Andric
930b57cec5SDimitry Andric static cl::opt<bool> EnableUnswitchCostMultiplier(
940b57cec5SDimitry Andric "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
950b57cec5SDimitry Andric cl::desc("Enable unswitch cost multiplier that prohibits exponential "
960b57cec5SDimitry Andric "explosion in nontrivial unswitch."));
970b57cec5SDimitry Andric static cl::opt<int> UnswitchSiblingsToplevelDiv(
980b57cec5SDimitry Andric "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
990b57cec5SDimitry Andric cl::desc("Toplevel siblings divisor for cost multiplier."));
1000b57cec5SDimitry Andric static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
1010b57cec5SDimitry Andric "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
1020b57cec5SDimitry Andric cl::desc("Number of unswitch candidates that are ignored when calculating "
1030b57cec5SDimitry Andric "cost multiplier."));
1040b57cec5SDimitry Andric static cl::opt<bool> UnswitchGuards(
1050b57cec5SDimitry Andric "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
1060b57cec5SDimitry Andric cl::desc("If enabled, simple loop unswitching will also consider "
1070b57cec5SDimitry Andric "llvm.experimental.guard intrinsics as unswitch candidates."));
108e8d8bef9SDimitry Andric static cl::opt<bool> DropNonTrivialImplicitNullChecks(
109e8d8bef9SDimitry Andric "simple-loop-unswitch-drop-non-trivial-implicit-null-checks",
110e8d8bef9SDimitry Andric cl::init(false), cl::Hidden,
111e8d8bef9SDimitry Andric cl::desc("If enabled, drop make.implicit metadata in unswitched implicit "
112e8d8bef9SDimitry Andric "null checks to save time analyzing if we can keep it."));
113fe6060f1SDimitry Andric static cl::opt<unsigned>
114fe6060f1SDimitry Andric MSSAThreshold("simple-loop-unswitch-memoryssa-threshold",
115fe6060f1SDimitry Andric cl::desc("Max number of memory uses to explore during "
116fe6060f1SDimitry Andric "partial unswitching analysis"),
117fe6060f1SDimitry Andric cl::init(100), cl::Hidden);
118349cc55cSDimitry Andric static cl::opt<bool> FreezeLoopUnswitchCond(
11981ad6265SDimitry Andric "freeze-loop-unswitch-cond", cl::init(true), cl::Hidden,
120349cc55cSDimitry Andric cl::desc("If enabled, the freeze instruction will be added to condition "
121349cc55cSDimitry Andric "of loop unswitch to prevent miscompilation."));
1220b57cec5SDimitry Andric
123fe013be4SDimitry Andric static cl::opt<bool> InjectInvariantConditions(
124fe013be4SDimitry Andric "simple-loop-unswitch-inject-invariant-conditions", cl::Hidden,
125fe013be4SDimitry Andric cl::desc("Whether we should inject new invariants and unswitch them to "
126fe013be4SDimitry Andric "eliminate some existing (non-invariant) conditions."),
127fe013be4SDimitry Andric cl::init(true));
128fe013be4SDimitry Andric
129fe013be4SDimitry Andric static cl::opt<unsigned> InjectInvariantConditionHotnesThreshold(
130fe013be4SDimitry Andric "simple-loop-unswitch-inject-invariant-condition-hotness-threshold",
131fe013be4SDimitry Andric cl::Hidden, cl::desc("Only try to inject loop invariant conditions and "
132fe013be4SDimitry Andric "unswitch on them to eliminate branches that are "
133fe013be4SDimitry Andric "not-taken 1/<this option> times or less."),
134fe013be4SDimitry Andric cl::init(16));
135fe013be4SDimitry Andric
136bdd1243dSDimitry Andric namespace {
137fe013be4SDimitry Andric struct CompareDesc {
138fe013be4SDimitry Andric BranchInst *Term;
139fe013be4SDimitry Andric Value *Invariant;
140fe013be4SDimitry Andric BasicBlock *InLoopSucc;
141fe013be4SDimitry Andric
CompareDesc__anonabc101420111::CompareDesc142fe013be4SDimitry Andric CompareDesc(BranchInst *Term, Value *Invariant, BasicBlock *InLoopSucc)
143fe013be4SDimitry Andric : Term(Term), Invariant(Invariant), InLoopSucc(InLoopSucc) {}
144fe013be4SDimitry Andric };
145fe013be4SDimitry Andric
146fe013be4SDimitry Andric struct InjectedInvariant {
147fe013be4SDimitry Andric ICmpInst::Predicate Pred;
148fe013be4SDimitry Andric Value *LHS;
149fe013be4SDimitry Andric Value *RHS;
150fe013be4SDimitry Andric BasicBlock *InLoopSucc;
151fe013be4SDimitry Andric
InjectedInvariant__anonabc101420111::InjectedInvariant152fe013be4SDimitry Andric InjectedInvariant(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
153fe013be4SDimitry Andric BasicBlock *InLoopSucc)
154fe013be4SDimitry Andric : Pred(Pred), LHS(LHS), RHS(RHS), InLoopSucc(InLoopSucc) {}
155fe013be4SDimitry Andric };
156fe013be4SDimitry Andric
157bdd1243dSDimitry Andric struct NonTrivialUnswitchCandidate {
158bdd1243dSDimitry Andric Instruction *TI = nullptr;
159bdd1243dSDimitry Andric TinyPtrVector<Value *> Invariants;
160bdd1243dSDimitry Andric std::optional<InstructionCost> Cost;
161fe013be4SDimitry Andric std::optional<InjectedInvariant> PendingInjection;
NonTrivialUnswitchCandidate__anonabc101420111::NonTrivialUnswitchCandidate162bdd1243dSDimitry Andric NonTrivialUnswitchCandidate(
163bdd1243dSDimitry Andric Instruction *TI, ArrayRef<Value *> Invariants,
164fe013be4SDimitry Andric std::optional<InstructionCost> Cost = std::nullopt,
165fe013be4SDimitry Andric std::optional<InjectedInvariant> PendingInjection = std::nullopt)
166fe013be4SDimitry Andric : TI(TI), Invariants(Invariants), Cost(Cost),
167fe013be4SDimitry Andric PendingInjection(PendingInjection) {};
168fe013be4SDimitry Andric
hasPendingInjection__anonabc101420111::NonTrivialUnswitchCandidate169fe013be4SDimitry Andric bool hasPendingInjection() const { return PendingInjection.has_value(); }
170bdd1243dSDimitry Andric };
171bdd1243dSDimitry Andric } // end anonymous namespace.
172bdd1243dSDimitry Andric
17381ad6265SDimitry Andric // Helper to skip (select x, true, false), which matches both a logical AND and
17481ad6265SDimitry Andric // OR and can confuse code that tries to determine if \p Cond is either a
17581ad6265SDimitry Andric // logical AND or OR but not both.
skipTrivialSelect(Value * Cond)17681ad6265SDimitry Andric static Value *skipTrivialSelect(Value *Cond) {
17781ad6265SDimitry Andric Value *CondNext;
17881ad6265SDimitry Andric while (match(Cond, m_Select(m_Value(CondNext), m_One(), m_Zero())))
17981ad6265SDimitry Andric Cond = CondNext;
18081ad6265SDimitry Andric return Cond;
18181ad6265SDimitry Andric }
18281ad6265SDimitry Andric
1830b57cec5SDimitry Andric /// Collect all of the loop invariant input values transitively used by the
1840b57cec5SDimitry Andric /// homogeneous instruction graph from a given root.
1850b57cec5SDimitry Andric ///
1860b57cec5SDimitry Andric /// This essentially walks from a root recursively through loop variant operands
18781ad6265SDimitry Andric /// which have perform the same logical operation (AND or OR) and finds all
18881ad6265SDimitry Andric /// inputs which are loop invariant. For some operations these can be
18981ad6265SDimitry Andric /// re-associated and unswitched out of the loop entirely.
1900b57cec5SDimitry Andric static TinyPtrVector<Value *>
collectHomogenousInstGraphLoopInvariants(const Loop & L,Instruction & Root,const LoopInfo & LI)191bdd1243dSDimitry Andric collectHomogenousInstGraphLoopInvariants(const Loop &L, Instruction &Root,
192bdd1243dSDimitry Andric const LoopInfo &LI) {
1930b57cec5SDimitry Andric assert(!L.isLoopInvariant(&Root) &&
1940b57cec5SDimitry Andric "Only need to walk the graph if root itself is not invariant.");
1950b57cec5SDimitry Andric TinyPtrVector<Value *> Invariants;
1960b57cec5SDimitry Andric
197fe6060f1SDimitry Andric bool IsRootAnd = match(&Root, m_LogicalAnd());
198fe6060f1SDimitry Andric bool IsRootOr = match(&Root, m_LogicalOr());
199fe6060f1SDimitry Andric
2000b57cec5SDimitry Andric // Build a worklist and recurse through operators collecting invariants.
2010b57cec5SDimitry Andric SmallVector<Instruction *, 4> Worklist;
2020b57cec5SDimitry Andric SmallPtrSet<Instruction *, 8> Visited;
2030b57cec5SDimitry Andric Worklist.push_back(&Root);
2040b57cec5SDimitry Andric Visited.insert(&Root);
2050b57cec5SDimitry Andric do {
2060b57cec5SDimitry Andric Instruction &I = *Worklist.pop_back_val();
2070b57cec5SDimitry Andric for (Value *OpV : I.operand_values()) {
2080b57cec5SDimitry Andric // Skip constants as unswitching isn't interesting for them.
2090b57cec5SDimitry Andric if (isa<Constant>(OpV))
2100b57cec5SDimitry Andric continue;
2110b57cec5SDimitry Andric
2120b57cec5SDimitry Andric // Add it to our result if loop invariant.
2130b57cec5SDimitry Andric if (L.isLoopInvariant(OpV)) {
2140b57cec5SDimitry Andric Invariants.push_back(OpV);
2150b57cec5SDimitry Andric continue;
2160b57cec5SDimitry Andric }
2170b57cec5SDimitry Andric
2180b57cec5SDimitry Andric // If not an instruction with the same opcode, nothing we can do.
21981ad6265SDimitry Andric Instruction *OpI = dyn_cast<Instruction>(skipTrivialSelect(OpV));
2200b57cec5SDimitry Andric
221fe6060f1SDimitry Andric if (OpI && ((IsRootAnd && match(OpI, m_LogicalAnd())) ||
222fe6060f1SDimitry Andric (IsRootOr && match(OpI, m_LogicalOr())))) {
2230b57cec5SDimitry Andric // Visit this operand.
2240b57cec5SDimitry Andric if (Visited.insert(OpI).second)
2250b57cec5SDimitry Andric Worklist.push_back(OpI);
2260b57cec5SDimitry Andric }
227fe6060f1SDimitry Andric }
2280b57cec5SDimitry Andric } while (!Worklist.empty());
2290b57cec5SDimitry Andric
2300b57cec5SDimitry Andric return Invariants;
2310b57cec5SDimitry Andric }
2320b57cec5SDimitry Andric
replaceLoopInvariantUses(const Loop & L,Value * Invariant,Constant & Replacement)233bdd1243dSDimitry Andric static void replaceLoopInvariantUses(const Loop &L, Value *Invariant,
2340b57cec5SDimitry Andric Constant &Replacement) {
2350b57cec5SDimitry Andric assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
2360b57cec5SDimitry Andric
2370b57cec5SDimitry Andric // Replace uses of LIC in the loop with the given constant.
238fe6060f1SDimitry Andric // We use make_early_inc_range as set invalidates the iterator.
239fe6060f1SDimitry Andric for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
240fe6060f1SDimitry Andric Instruction *UserI = dyn_cast<Instruction>(U.getUser());
2410b57cec5SDimitry Andric
2420b57cec5SDimitry Andric // Replace this use within the loop body.
2430b57cec5SDimitry Andric if (UserI && L.contains(UserI))
244fe6060f1SDimitry Andric U.set(&Replacement);
2450b57cec5SDimitry Andric }
2460b57cec5SDimitry Andric }
2470b57cec5SDimitry Andric
2480b57cec5SDimitry Andric /// Check that all the LCSSA PHI nodes in the loop exit block have trivial
2490b57cec5SDimitry Andric /// incoming values along this edge.
areLoopExitPHIsLoopInvariant(const Loop & L,const BasicBlock & ExitingBB,const BasicBlock & ExitBB)250bdd1243dSDimitry Andric static bool areLoopExitPHIsLoopInvariant(const Loop &L,
251bdd1243dSDimitry Andric const BasicBlock &ExitingBB,
252bdd1243dSDimitry Andric const BasicBlock &ExitBB) {
253bdd1243dSDimitry Andric for (const Instruction &I : ExitBB) {
2540b57cec5SDimitry Andric auto *PN = dyn_cast<PHINode>(&I);
2550b57cec5SDimitry Andric if (!PN)
2560b57cec5SDimitry Andric // No more PHIs to check.
2570b57cec5SDimitry Andric return true;
2580b57cec5SDimitry Andric
2590b57cec5SDimitry Andric // If the incoming value for this edge isn't loop invariant the unswitch
2600b57cec5SDimitry Andric // won't be trivial.
2610b57cec5SDimitry Andric if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
2620b57cec5SDimitry Andric return false;
2630b57cec5SDimitry Andric }
2640b57cec5SDimitry Andric llvm_unreachable("Basic blocks should never be empty!");
2650b57cec5SDimitry Andric }
2660b57cec5SDimitry Andric
267fe6060f1SDimitry Andric /// Copy a set of loop invariant values \p ToDuplicate and insert them at the
268fe6060f1SDimitry Andric /// end of \p BB and conditionally branch on the copied condition. We only
269fe6060f1SDimitry Andric /// branch on a single value.
buildPartialUnswitchConditionalBranch(BasicBlock & BB,ArrayRef<Value * > Invariants,bool Direction,BasicBlock & UnswitchedSucc,BasicBlock & NormalSucc,bool InsertFreeze,const Instruction * I,AssumptionCache * AC,const DominatorTree & DT)270349cc55cSDimitry Andric static void buildPartialUnswitchConditionalBranch(
271349cc55cSDimitry Andric BasicBlock &BB, ArrayRef<Value *> Invariants, bool Direction,
27281ad6265SDimitry Andric BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, bool InsertFreeze,
273bdd1243dSDimitry Andric const Instruction *I, AssumptionCache *AC, const DominatorTree &DT) {
2740b57cec5SDimitry Andric IRBuilder<> IRB(&BB);
2750b57cec5SDimitry Andric
27681ad6265SDimitry Andric SmallVector<Value *> FrozenInvariants;
27781ad6265SDimitry Andric for (Value *Inv : Invariants) {
27881ad6265SDimitry Andric if (InsertFreeze && !isGuaranteedNotToBeUndefOrPoison(Inv, AC, I, &DT))
27981ad6265SDimitry Andric Inv = IRB.CreateFreeze(Inv, Inv->getName() + ".fr");
28081ad6265SDimitry Andric FrozenInvariants.push_back(Inv);
28181ad6265SDimitry Andric }
28281ad6265SDimitry Andric
28381ad6265SDimitry Andric Value *Cond = Direction ? IRB.CreateOr(FrozenInvariants)
28481ad6265SDimitry Andric : IRB.CreateAnd(FrozenInvariants);
2850b57cec5SDimitry Andric IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
2860b57cec5SDimitry Andric Direction ? &NormalSucc : &UnswitchedSucc);
2870b57cec5SDimitry Andric }
2880b57cec5SDimitry Andric
289fe6060f1SDimitry Andric /// Copy a set of loop invariant values, and conditionally branch on them.
buildPartialInvariantUnswitchConditionalBranch(BasicBlock & BB,ArrayRef<Value * > ToDuplicate,bool Direction,BasicBlock & UnswitchedSucc,BasicBlock & NormalSucc,Loop & L,MemorySSAUpdater * MSSAU)290fe6060f1SDimitry Andric static void buildPartialInvariantUnswitchConditionalBranch(
291fe6060f1SDimitry Andric BasicBlock &BB, ArrayRef<Value *> ToDuplicate, bool Direction,
292fe6060f1SDimitry Andric BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, Loop &L,
293fe6060f1SDimitry Andric MemorySSAUpdater *MSSAU) {
294fe6060f1SDimitry Andric ValueToValueMapTy VMap;
295fe6060f1SDimitry Andric for (auto *Val : reverse(ToDuplicate)) {
296fe6060f1SDimitry Andric Instruction *Inst = cast<Instruction>(Val);
297fe6060f1SDimitry Andric Instruction *NewInst = Inst->clone();
298bdd1243dSDimitry Andric NewInst->insertInto(&BB, BB.end());
299fe6060f1SDimitry Andric RemapInstruction(NewInst, VMap,
300fe6060f1SDimitry Andric RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
301fe6060f1SDimitry Andric VMap[Val] = NewInst;
302fe6060f1SDimitry Andric
303fe6060f1SDimitry Andric if (!MSSAU)
304fe6060f1SDimitry Andric continue;
305fe6060f1SDimitry Andric
306fe6060f1SDimitry Andric MemorySSA *MSSA = MSSAU->getMemorySSA();
307fe6060f1SDimitry Andric if (auto *MemUse =
308fe6060f1SDimitry Andric dyn_cast_or_null<MemoryUse>(MSSA->getMemoryAccess(Inst))) {
309fe6060f1SDimitry Andric auto *DefiningAccess = MemUse->getDefiningAccess();
310fe6060f1SDimitry Andric // Get the first defining access before the loop.
311fe6060f1SDimitry Andric while (L.contains(DefiningAccess->getBlock())) {
312fe6060f1SDimitry Andric // If the defining access is a MemoryPhi, get the incoming
313fe6060f1SDimitry Andric // value for the pre-header as defining access.
314fe6060f1SDimitry Andric if (auto *MemPhi = dyn_cast<MemoryPhi>(DefiningAccess))
315fe6060f1SDimitry Andric DefiningAccess =
316fe6060f1SDimitry Andric MemPhi->getIncomingValueForBlock(L.getLoopPreheader());
317fe6060f1SDimitry Andric else
318fe6060f1SDimitry Andric DefiningAccess = cast<MemoryDef>(DefiningAccess)->getDefiningAccess();
319fe6060f1SDimitry Andric }
320fe6060f1SDimitry Andric MSSAU->createMemoryAccessInBB(NewInst, DefiningAccess,
321fe6060f1SDimitry Andric NewInst->getParent(),
322fe6060f1SDimitry Andric MemorySSA::BeforeTerminator);
323fe6060f1SDimitry Andric }
324fe6060f1SDimitry Andric }
325fe6060f1SDimitry Andric
326fe6060f1SDimitry Andric IRBuilder<> IRB(&BB);
327fe6060f1SDimitry Andric Value *Cond = VMap[ToDuplicate[0]];
328fe6060f1SDimitry Andric IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
329fe6060f1SDimitry Andric Direction ? &NormalSucc : &UnswitchedSucc);
330fe6060f1SDimitry Andric }
331fe6060f1SDimitry Andric
3320b57cec5SDimitry Andric /// Rewrite the PHI nodes in an unswitched loop exit basic block.
3330b57cec5SDimitry Andric ///
3340b57cec5SDimitry Andric /// Requires that the loop exit and unswitched basic block are the same, and
3350b57cec5SDimitry Andric /// that the exiting block was a unique predecessor of that block. Rewrites the
3360b57cec5SDimitry Andric /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
3370b57cec5SDimitry Andric /// PHI nodes from the old preheader that now contains the unswitched
3380b57cec5SDimitry Andric /// terminator.
rewritePHINodesForUnswitchedExitBlock(BasicBlock & UnswitchedBB,BasicBlock & OldExitingBB,BasicBlock & OldPH)3390b57cec5SDimitry Andric static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
3400b57cec5SDimitry Andric BasicBlock &OldExitingBB,
3410b57cec5SDimitry Andric BasicBlock &OldPH) {
3420b57cec5SDimitry Andric for (PHINode &PN : UnswitchedBB.phis()) {
3430b57cec5SDimitry Andric // When the loop exit is directly unswitched we just need to update the
3440b57cec5SDimitry Andric // incoming basic block. We loop to handle weird cases with repeated
3450b57cec5SDimitry Andric // incoming blocks, but expect to typically only have one operand here.
3460b57cec5SDimitry Andric for (auto i : seq<int>(0, PN.getNumOperands())) {
3470b57cec5SDimitry Andric assert(PN.getIncomingBlock(i) == &OldExitingBB &&
3480b57cec5SDimitry Andric "Found incoming block different from unique predecessor!");
3490b57cec5SDimitry Andric PN.setIncomingBlock(i, &OldPH);
3500b57cec5SDimitry Andric }
3510b57cec5SDimitry Andric }
3520b57cec5SDimitry Andric }
3530b57cec5SDimitry Andric
3540b57cec5SDimitry Andric /// Rewrite the PHI nodes in the loop exit basic block and the split off
3550b57cec5SDimitry Andric /// unswitched block.
3560b57cec5SDimitry Andric ///
3570b57cec5SDimitry Andric /// Because the exit block remains an exit from the loop, this rewrites the
3580b57cec5SDimitry Andric /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
3590b57cec5SDimitry Andric /// nodes into the unswitched basic block to select between the value in the
3600b57cec5SDimitry Andric /// old preheader and the loop exit.
rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock & ExitBB,BasicBlock & UnswitchedBB,BasicBlock & OldExitingBB,BasicBlock & OldPH,bool FullUnswitch)3610b57cec5SDimitry Andric static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
3620b57cec5SDimitry Andric BasicBlock &UnswitchedBB,
3630b57cec5SDimitry Andric BasicBlock &OldExitingBB,
3640b57cec5SDimitry Andric BasicBlock &OldPH,
3650b57cec5SDimitry Andric bool FullUnswitch) {
3660b57cec5SDimitry Andric assert(&ExitBB != &UnswitchedBB &&
3670b57cec5SDimitry Andric "Must have different loop exit and unswitched blocks!");
368*c9157d92SDimitry Andric BasicBlock::iterator InsertPt = UnswitchedBB.begin();
3690b57cec5SDimitry Andric for (PHINode &PN : ExitBB.phis()) {
3700b57cec5SDimitry Andric auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
371*c9157d92SDimitry Andric PN.getName() + ".split");
372*c9157d92SDimitry Andric NewPN->insertBefore(InsertPt);
3730b57cec5SDimitry Andric
3740b57cec5SDimitry Andric // Walk backwards over the old PHI node's inputs to minimize the cost of
3750b57cec5SDimitry Andric // removing each one. We have to do this weird loop manually so that we
3760b57cec5SDimitry Andric // create the same number of new incoming edges in the new PHI as we expect
3770b57cec5SDimitry Andric // each case-based edge to be included in the unswitched switch in some
3780b57cec5SDimitry Andric // cases.
3790b57cec5SDimitry Andric // FIXME: This is really, really gross. It would be much cleaner if LLVM
3800b57cec5SDimitry Andric // allowed us to create a single entry for a predecessor block without
3810b57cec5SDimitry Andric // having separate entries for each "edge" even though these edges are
3820b57cec5SDimitry Andric // required to produce identical results.
3830b57cec5SDimitry Andric for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
3840b57cec5SDimitry Andric if (PN.getIncomingBlock(i) != &OldExitingBB)
3850b57cec5SDimitry Andric continue;
3860b57cec5SDimitry Andric
3870b57cec5SDimitry Andric Value *Incoming = PN.getIncomingValue(i);
3880b57cec5SDimitry Andric if (FullUnswitch)
3890b57cec5SDimitry Andric // No more edge from the old exiting block to the exit block.
3900b57cec5SDimitry Andric PN.removeIncomingValue(i);
3910b57cec5SDimitry Andric
3920b57cec5SDimitry Andric NewPN->addIncoming(Incoming, &OldPH);
3930b57cec5SDimitry Andric }
3940b57cec5SDimitry Andric
3950b57cec5SDimitry Andric // Now replace the old PHI with the new one and wire the old one in as an
3960b57cec5SDimitry Andric // input to the new one.
3970b57cec5SDimitry Andric PN.replaceAllUsesWith(NewPN);
3980b57cec5SDimitry Andric NewPN->addIncoming(&PN, &ExitBB);
3990b57cec5SDimitry Andric }
4000b57cec5SDimitry Andric }
4010b57cec5SDimitry Andric
4020b57cec5SDimitry Andric /// Hoist the current loop up to the innermost loop containing a remaining exit.
4030b57cec5SDimitry Andric ///
4040b57cec5SDimitry Andric /// Because we've removed an exit from the loop, we may have changed the set of
4050b57cec5SDimitry Andric /// loops reachable and need to move the current loop up the loop nest or even
4060b57cec5SDimitry Andric /// to an entirely separate nest.
hoistLoopToNewParent(Loop & L,BasicBlock & Preheader,DominatorTree & DT,LoopInfo & LI,MemorySSAUpdater * MSSAU,ScalarEvolution * SE)4070b57cec5SDimitry Andric static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
4080b57cec5SDimitry Andric DominatorTree &DT, LoopInfo &LI,
409480093f4SDimitry Andric MemorySSAUpdater *MSSAU, ScalarEvolution *SE) {
4100b57cec5SDimitry Andric // If the loop is already at the top level, we can't hoist it anywhere.
4110b57cec5SDimitry Andric Loop *OldParentL = L.getParentLoop();
4120b57cec5SDimitry Andric if (!OldParentL)
4130b57cec5SDimitry Andric return;
4140b57cec5SDimitry Andric
4150b57cec5SDimitry Andric SmallVector<BasicBlock *, 4> Exits;
4160b57cec5SDimitry Andric L.getExitBlocks(Exits);
4170b57cec5SDimitry Andric Loop *NewParentL = nullptr;
4180b57cec5SDimitry Andric for (auto *ExitBB : Exits)
4190b57cec5SDimitry Andric if (Loop *ExitL = LI.getLoopFor(ExitBB))
4200b57cec5SDimitry Andric if (!NewParentL || NewParentL->contains(ExitL))
4210b57cec5SDimitry Andric NewParentL = ExitL;
4220b57cec5SDimitry Andric
4230b57cec5SDimitry Andric if (NewParentL == OldParentL)
4240b57cec5SDimitry Andric return;
4250b57cec5SDimitry Andric
4260b57cec5SDimitry Andric // The new parent loop (if different) should always contain the old one.
4270b57cec5SDimitry Andric if (NewParentL)
4280b57cec5SDimitry Andric assert(NewParentL->contains(OldParentL) &&
4290b57cec5SDimitry Andric "Can only hoist this loop up the nest!");
4300b57cec5SDimitry Andric
4310b57cec5SDimitry Andric // The preheader will need to move with the body of this loop. However,
4320b57cec5SDimitry Andric // because it isn't in this loop we also need to update the primary loop map.
4330b57cec5SDimitry Andric assert(OldParentL == LI.getLoopFor(&Preheader) &&
4340b57cec5SDimitry Andric "Parent loop of this loop should contain this loop's preheader!");
4350b57cec5SDimitry Andric LI.changeLoopFor(&Preheader, NewParentL);
4360b57cec5SDimitry Andric
4370b57cec5SDimitry Andric // Remove this loop from its old parent.
4380b57cec5SDimitry Andric OldParentL->removeChildLoop(&L);
4390b57cec5SDimitry Andric
4400b57cec5SDimitry Andric // Add the loop either to the new parent or as a top-level loop.
4410b57cec5SDimitry Andric if (NewParentL)
4420b57cec5SDimitry Andric NewParentL->addChildLoop(&L);
4430b57cec5SDimitry Andric else
4440b57cec5SDimitry Andric LI.addTopLevelLoop(&L);
4450b57cec5SDimitry Andric
4460b57cec5SDimitry Andric // Remove this loops blocks from the old parent and every other loop up the
4470b57cec5SDimitry Andric // nest until reaching the new parent. Also update all of these
4480b57cec5SDimitry Andric // no-longer-containing loops to reflect the nesting change.
4490b57cec5SDimitry Andric for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
4500b57cec5SDimitry Andric OldContainingL = OldContainingL->getParentLoop()) {
4510b57cec5SDimitry Andric llvm::erase_if(OldContainingL->getBlocksVector(),
4520b57cec5SDimitry Andric [&](const BasicBlock *BB) {
4530b57cec5SDimitry Andric return BB == &Preheader || L.contains(BB);
4540b57cec5SDimitry Andric });
4550b57cec5SDimitry Andric
4560b57cec5SDimitry Andric OldContainingL->getBlocksSet().erase(&Preheader);
4570b57cec5SDimitry Andric for (BasicBlock *BB : L.blocks())
4580b57cec5SDimitry Andric OldContainingL->getBlocksSet().erase(BB);
4590b57cec5SDimitry Andric
4600b57cec5SDimitry Andric // Because we just hoisted a loop out of this one, we have essentially
4610b57cec5SDimitry Andric // created new exit paths from it. That means we need to form LCSSA PHI
4620b57cec5SDimitry Andric // nodes for values used in the no-longer-nested loop.
463480093f4SDimitry Andric formLCSSA(*OldContainingL, DT, &LI, SE);
4640b57cec5SDimitry Andric
4650b57cec5SDimitry Andric // We shouldn't need to form dedicated exits because the exit introduced
4660b57cec5SDimitry Andric // here is the (just split by unswitching) preheader. However, after trivial
4670b57cec5SDimitry Andric // unswitching it is possible to get new non-dedicated exits out of parent
4680b57cec5SDimitry Andric // loop so let's conservatively form dedicated exit blocks and figure out
4690b57cec5SDimitry Andric // if we can optimize later.
4700b57cec5SDimitry Andric formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
4710b57cec5SDimitry Andric /*PreserveLCSSA*/ true);
4720b57cec5SDimitry Andric }
4730b57cec5SDimitry Andric }
4740b57cec5SDimitry Andric
475480093f4SDimitry Andric // Return the top-most loop containing ExitBB and having ExitBB as exiting block
476480093f4SDimitry Andric // or the loop containing ExitBB, if there is no parent loop containing ExitBB
477480093f4SDimitry Andric // as exiting block.
getTopMostExitingLoop(const BasicBlock * ExitBB,const LoopInfo & LI)478fe013be4SDimitry Andric static Loop *getTopMostExitingLoop(const BasicBlock *ExitBB,
479bdd1243dSDimitry Andric const LoopInfo &LI) {
480fe013be4SDimitry Andric Loop *TopMost = LI.getLoopFor(ExitBB);
481fe013be4SDimitry Andric Loop *Current = TopMost;
482480093f4SDimitry Andric while (Current) {
483480093f4SDimitry Andric if (Current->isLoopExiting(ExitBB))
484480093f4SDimitry Andric TopMost = Current;
485480093f4SDimitry Andric Current = Current->getParentLoop();
486480093f4SDimitry Andric }
487480093f4SDimitry Andric return TopMost;
488480093f4SDimitry Andric }
489480093f4SDimitry Andric
4900b57cec5SDimitry Andric /// Unswitch a trivial branch if the condition is loop invariant.
4910b57cec5SDimitry Andric ///
4920b57cec5SDimitry Andric /// This routine should only be called when loop code leading to the branch has
4930b57cec5SDimitry Andric /// been validated as trivial (no side effects). This routine checks if the
4940b57cec5SDimitry Andric /// condition is invariant and one of the successors is a loop exit. This
4950b57cec5SDimitry Andric /// allows us to unswitch without duplicating the loop, making it trivial.
4960b57cec5SDimitry Andric ///
4970b57cec5SDimitry Andric /// If this routine fails to unswitch the branch it returns false.
4980b57cec5SDimitry Andric ///
4990b57cec5SDimitry Andric /// If the branch can be unswitched, this routine splits the preheader and
5000b57cec5SDimitry Andric /// hoists the branch above that split. Preserves loop simplified form
5010b57cec5SDimitry Andric /// (splitting the exit block as necessary). It simplifies the branch within
5020b57cec5SDimitry Andric /// the loop to an unconditional branch but doesn't remove it entirely. Further
503fe6060f1SDimitry Andric /// cleanup can be done with some simplifycfg like pass.
5040b57cec5SDimitry Andric ///
5050b57cec5SDimitry Andric /// If `SE` is not null, it will be updated based on the potential loop SCEVs
5060b57cec5SDimitry Andric /// invalidated by this.
unswitchTrivialBranch(Loop & L,BranchInst & BI,DominatorTree & DT,LoopInfo & LI,ScalarEvolution * SE,MemorySSAUpdater * MSSAU)5070b57cec5SDimitry Andric static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
5080b57cec5SDimitry Andric LoopInfo &LI, ScalarEvolution *SE,
5090b57cec5SDimitry Andric MemorySSAUpdater *MSSAU) {
5100b57cec5SDimitry Andric assert(BI.isConditional() && "Can only unswitch a conditional branch!");
5110b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n");
5120b57cec5SDimitry Andric
5130b57cec5SDimitry Andric // The loop invariant values that we want to unswitch.
5140b57cec5SDimitry Andric TinyPtrVector<Value *> Invariants;
5150b57cec5SDimitry Andric
5160b57cec5SDimitry Andric // When true, we're fully unswitching the branch rather than just unswitching
5170b57cec5SDimitry Andric // some input conditions to the branch.
5180b57cec5SDimitry Andric bool FullUnswitch = false;
5190b57cec5SDimitry Andric
52081ad6265SDimitry Andric Value *Cond = skipTrivialSelect(BI.getCondition());
52181ad6265SDimitry Andric if (L.isLoopInvariant(Cond)) {
52281ad6265SDimitry Andric Invariants.push_back(Cond);
5230b57cec5SDimitry Andric FullUnswitch = true;
5240b57cec5SDimitry Andric } else {
52581ad6265SDimitry Andric if (auto *CondInst = dyn_cast<Instruction>(Cond))
5260b57cec5SDimitry Andric Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
527fe6060f1SDimitry Andric if (Invariants.empty()) {
528fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << " Couldn't find invariant inputs!\n");
5290b57cec5SDimitry Andric return false;
5300b57cec5SDimitry Andric }
531fe6060f1SDimitry Andric }
5320b57cec5SDimitry Andric
5330b57cec5SDimitry Andric // Check that one of the branch's successors exits, and which one.
5340b57cec5SDimitry Andric bool ExitDirection = true;
5350b57cec5SDimitry Andric int LoopExitSuccIdx = 0;
5360b57cec5SDimitry Andric auto *LoopExitBB = BI.getSuccessor(0);
5370b57cec5SDimitry Andric if (L.contains(LoopExitBB)) {
5380b57cec5SDimitry Andric ExitDirection = false;
5390b57cec5SDimitry Andric LoopExitSuccIdx = 1;
5400b57cec5SDimitry Andric LoopExitBB = BI.getSuccessor(1);
541fe6060f1SDimitry Andric if (L.contains(LoopExitBB)) {
542fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << " Branch doesn't exit the loop!\n");
5430b57cec5SDimitry Andric return false;
5440b57cec5SDimitry Andric }
545fe6060f1SDimitry Andric }
5460b57cec5SDimitry Andric auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
5470b57cec5SDimitry Andric auto *ParentBB = BI.getParent();
548fe6060f1SDimitry Andric if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) {
549fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << " Loop exit PHI's aren't loop-invariant!\n");
5500b57cec5SDimitry Andric return false;
551fe6060f1SDimitry Andric }
5520b57cec5SDimitry Andric
5530b57cec5SDimitry Andric // When unswitching only part of the branch's condition, we need the exit
5540b57cec5SDimitry Andric // block to be reached directly from the partially unswitched input. This can
5550b57cec5SDimitry Andric // be done when the exit block is along the true edge and the branch condition
5560b57cec5SDimitry Andric // is a graph of `or` operations, or the exit block is along the false edge
5570b57cec5SDimitry Andric // and the condition is a graph of `and` operations.
5580b57cec5SDimitry Andric if (!FullUnswitch) {
55981ad6265SDimitry Andric if (ExitDirection ? !match(Cond, m_LogicalOr())
56081ad6265SDimitry Andric : !match(Cond, m_LogicalAnd())) {
561fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << " Branch condition is in improper form for "
562fe6060f1SDimitry Andric "non-full unswitch!\n");
5630b57cec5SDimitry Andric return false;
5640b57cec5SDimitry Andric }
5650b57cec5SDimitry Andric }
5660b57cec5SDimitry Andric
5670b57cec5SDimitry Andric LLVM_DEBUG({
5680b57cec5SDimitry Andric dbgs() << " unswitching trivial invariant conditions for: " << BI
5690b57cec5SDimitry Andric << "\n";
5700b57cec5SDimitry Andric for (Value *Invariant : Invariants) {
5710b57cec5SDimitry Andric dbgs() << " " << *Invariant << " == true";
5720b57cec5SDimitry Andric if (Invariant != Invariants.back())
5730b57cec5SDimitry Andric dbgs() << " ||";
5740b57cec5SDimitry Andric dbgs() << "\n";
5750b57cec5SDimitry Andric }
5760b57cec5SDimitry Andric });
5770b57cec5SDimitry Andric
5780b57cec5SDimitry Andric // If we have scalar evolutions, we need to invalidate them including this
579480093f4SDimitry Andric // loop, the loop containing the exit block and the topmost parent loop
580480093f4SDimitry Andric // exiting via LoopExitBB.
5810b57cec5SDimitry Andric if (SE) {
582bdd1243dSDimitry Andric if (const Loop *ExitL = getTopMostExitingLoop(LoopExitBB, LI))
5830b57cec5SDimitry Andric SE->forgetLoop(ExitL);
5840b57cec5SDimitry Andric else
5850b57cec5SDimitry Andric // Forget the entire nest as this exits the entire nest.
5860b57cec5SDimitry Andric SE->forgetTopmostLoop(&L);
587bdd1243dSDimitry Andric SE->forgetBlockAndLoopDispositions();
5880b57cec5SDimitry Andric }
5890b57cec5SDimitry Andric
5900b57cec5SDimitry Andric if (MSSAU && VerifyMemorySSA)
5910b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
5920b57cec5SDimitry Andric
5930b57cec5SDimitry Andric // Split the preheader, so that we know that there is a safe place to insert
5940b57cec5SDimitry Andric // the conditional branch. We will change the preheader to have a conditional
5950b57cec5SDimitry Andric // branch on LoopCond.
5960b57cec5SDimitry Andric BasicBlock *OldPH = L.getLoopPreheader();
5970b57cec5SDimitry Andric BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
5980b57cec5SDimitry Andric
5990b57cec5SDimitry Andric // Now that we have a place to insert the conditional branch, create a place
6000b57cec5SDimitry Andric // to branch to: this is the exit block out of the loop that we are
6010b57cec5SDimitry Andric // unswitching. We need to split this if there are other loop predecessors.
6020b57cec5SDimitry Andric // Because the loop is in simplified form, *any* other predecessor is enough.
6030b57cec5SDimitry Andric BasicBlock *UnswitchedBB;
6040b57cec5SDimitry Andric if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
6050b57cec5SDimitry Andric assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
6060b57cec5SDimitry Andric "A branch's parent isn't a predecessor!");
6070b57cec5SDimitry Andric UnswitchedBB = LoopExitBB;
6080b57cec5SDimitry Andric } else {
6090b57cec5SDimitry Andric UnswitchedBB =
610*c9157d92SDimitry Andric SplitBlock(LoopExitBB, LoopExitBB->begin(), &DT, &LI, MSSAU, "", false);
6110b57cec5SDimitry Andric }
6120b57cec5SDimitry Andric
6130b57cec5SDimitry Andric if (MSSAU && VerifyMemorySSA)
6140b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
6150b57cec5SDimitry Andric
6160b57cec5SDimitry Andric // Actually move the invariant uses into the unswitched position. If possible,
6170b57cec5SDimitry Andric // we do this by moving the instructions, but when doing partial unswitching
6180b57cec5SDimitry Andric // we do it by building a new merge of the values in the unswitched position.
6190b57cec5SDimitry Andric OldPH->getTerminator()->eraseFromParent();
6200b57cec5SDimitry Andric if (FullUnswitch) {
6210b57cec5SDimitry Andric // If fully unswitching, we can use the existing branch instruction.
6220b57cec5SDimitry Andric // Splice it into the old PH to gate reaching the new preheader and re-point
6230b57cec5SDimitry Andric // its successors.
624*c9157d92SDimitry Andric BI.moveBefore(*OldPH, OldPH->end());
62581ad6265SDimitry Andric BI.setCondition(Cond);
6260b57cec5SDimitry Andric if (MSSAU) {
6270b57cec5SDimitry Andric // Temporarily clone the terminator, to make MSSA update cheaper by
6280b57cec5SDimitry Andric // separating "insert edge" updates from "remove edge" ones.
629bdd1243dSDimitry Andric BI.clone()->insertInto(ParentBB, ParentBB->end());
6300b57cec5SDimitry Andric } else {
6310b57cec5SDimitry Andric // Create a new unconditional branch that will continue the loop as a new
6320b57cec5SDimitry Andric // terminator.
6330b57cec5SDimitry Andric BranchInst::Create(ContinueBB, ParentBB);
6340b57cec5SDimitry Andric }
6350b57cec5SDimitry Andric BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
6360b57cec5SDimitry Andric BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
6370b57cec5SDimitry Andric } else {
6380b57cec5SDimitry Andric // Only unswitching a subset of inputs to the condition, so we will need to
6390b57cec5SDimitry Andric // build a new branch that merges the invariant inputs.
6400b57cec5SDimitry Andric if (ExitDirection)
64181ad6265SDimitry Andric assert(match(skipTrivialSelect(BI.getCondition()), m_LogicalOr()) &&
642fe6060f1SDimitry Andric "Must have an `or` of `i1`s or `select i1 X, true, Y`s for the "
643fe6060f1SDimitry Andric "condition!");
6440b57cec5SDimitry Andric else
64581ad6265SDimitry Andric assert(match(skipTrivialSelect(BI.getCondition()), m_LogicalAnd()) &&
646fe6060f1SDimitry Andric "Must have an `and` of `i1`s or `select i1 X, Y, false`s for the"
647fe6060f1SDimitry Andric " condition!");
64881ad6265SDimitry Andric buildPartialUnswitchConditionalBranch(
64981ad6265SDimitry Andric *OldPH, Invariants, ExitDirection, *UnswitchedBB, *NewPH,
65081ad6265SDimitry Andric FreezeLoopUnswitchCond, OldPH->getTerminator(), nullptr, DT);
6510b57cec5SDimitry Andric }
6520b57cec5SDimitry Andric
6530b57cec5SDimitry Andric // Update the dominator tree with the added edge.
6540b57cec5SDimitry Andric DT.insertEdge(OldPH, UnswitchedBB);
6550b57cec5SDimitry Andric
6560b57cec5SDimitry Andric // After the dominator tree was updated with the added edge, update MemorySSA
6570b57cec5SDimitry Andric // if available.
6580b57cec5SDimitry Andric if (MSSAU) {
6590b57cec5SDimitry Andric SmallVector<CFGUpdate, 1> Updates;
6600b57cec5SDimitry Andric Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
6610b57cec5SDimitry Andric MSSAU->applyInsertUpdates(Updates, DT);
6620b57cec5SDimitry Andric }
6630b57cec5SDimitry Andric
6640b57cec5SDimitry Andric // Finish updating dominator tree and memory ssa for full unswitch.
6650b57cec5SDimitry Andric if (FullUnswitch) {
6660b57cec5SDimitry Andric if (MSSAU) {
6670b57cec5SDimitry Andric // Remove the cloned branch instruction.
6680b57cec5SDimitry Andric ParentBB->getTerminator()->eraseFromParent();
6690b57cec5SDimitry Andric // Create unconditional branch now.
6700b57cec5SDimitry Andric BranchInst::Create(ContinueBB, ParentBB);
6710b57cec5SDimitry Andric MSSAU->removeEdge(ParentBB, LoopExitBB);
6720b57cec5SDimitry Andric }
6730b57cec5SDimitry Andric DT.deleteEdge(ParentBB, LoopExitBB);
6740b57cec5SDimitry Andric }
6750b57cec5SDimitry Andric
6760b57cec5SDimitry Andric if (MSSAU && VerifyMemorySSA)
6770b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
6780b57cec5SDimitry Andric
6790b57cec5SDimitry Andric // Rewrite the relevant PHI nodes.
6800b57cec5SDimitry Andric if (UnswitchedBB == LoopExitBB)
6810b57cec5SDimitry Andric rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
6820b57cec5SDimitry Andric else
6830b57cec5SDimitry Andric rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
6840b57cec5SDimitry Andric *ParentBB, *OldPH, FullUnswitch);
6850b57cec5SDimitry Andric
6860b57cec5SDimitry Andric // The constant we can replace all of our invariants with inside the loop
6870b57cec5SDimitry Andric // body. If any of the invariants have a value other than this the loop won't
6880b57cec5SDimitry Andric // be entered.
6890b57cec5SDimitry Andric ConstantInt *Replacement = ExitDirection
6900b57cec5SDimitry Andric ? ConstantInt::getFalse(BI.getContext())
6910b57cec5SDimitry Andric : ConstantInt::getTrue(BI.getContext());
6920b57cec5SDimitry Andric
6930b57cec5SDimitry Andric // Since this is an i1 condition we can also trivially replace uses of it
6940b57cec5SDimitry Andric // within the loop with a constant.
6950b57cec5SDimitry Andric for (Value *Invariant : Invariants)
6960b57cec5SDimitry Andric replaceLoopInvariantUses(L, Invariant, *Replacement);
6970b57cec5SDimitry Andric
6980b57cec5SDimitry Andric // If this was full unswitching, we may have changed the nesting relationship
6990b57cec5SDimitry Andric // for this loop so hoist it to its correct parent if needed.
7000b57cec5SDimitry Andric if (FullUnswitch)
701480093f4SDimitry Andric hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
7020b57cec5SDimitry Andric
7030b57cec5SDimitry Andric if (MSSAU && VerifyMemorySSA)
7040b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
7050b57cec5SDimitry Andric
7060b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n");
7070b57cec5SDimitry Andric ++NumTrivial;
7080b57cec5SDimitry Andric ++NumBranches;
7090b57cec5SDimitry Andric return true;
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric
7120b57cec5SDimitry Andric /// Unswitch a trivial switch if the condition is loop invariant.
7130b57cec5SDimitry Andric ///
7140b57cec5SDimitry Andric /// This routine should only be called when loop code leading to the switch has
7150b57cec5SDimitry Andric /// been validated as trivial (no side effects). This routine checks if the
7160b57cec5SDimitry Andric /// condition is invariant and that at least one of the successors is a loop
7170b57cec5SDimitry Andric /// exit. This allows us to unswitch without duplicating the loop, making it
7180b57cec5SDimitry Andric /// trivial.
7190b57cec5SDimitry Andric ///
7200b57cec5SDimitry Andric /// If this routine fails to unswitch the switch it returns false.
7210b57cec5SDimitry Andric ///
7220b57cec5SDimitry Andric /// If the switch can be unswitched, this routine splits the preheader and
7230b57cec5SDimitry Andric /// copies the switch above that split. If the default case is one of the
7240b57cec5SDimitry Andric /// exiting cases, it copies the non-exiting cases and points them at the new
7250b57cec5SDimitry Andric /// preheader. If the default case is not exiting, it copies the exiting cases
7260b57cec5SDimitry Andric /// and points the default at the preheader. It preserves loop simplified form
7270b57cec5SDimitry Andric /// (splitting the exit blocks as necessary). It simplifies the switch within
7280b57cec5SDimitry Andric /// the loop by removing now-dead cases. If the default case is one of those
7290b57cec5SDimitry Andric /// unswitched, it replaces its destination with a new basic block containing
7300b57cec5SDimitry Andric /// only unreachable. Such basic blocks, while technically loop exits, are not
7310b57cec5SDimitry Andric /// considered for unswitching so this is a stable transform and the same
7320b57cec5SDimitry Andric /// switch will not be revisited. If after unswitching there is only a single
7330b57cec5SDimitry Andric /// in-loop successor, the switch is further simplified to an unconditional
734fe6060f1SDimitry Andric /// branch. Still more cleanup can be done with some simplifycfg like pass.
7350b57cec5SDimitry Andric ///
7360b57cec5SDimitry Andric /// If `SE` is not null, it will be updated based on the potential loop SCEVs
7370b57cec5SDimitry Andric /// invalidated by this.
unswitchTrivialSwitch(Loop & L,SwitchInst & SI,DominatorTree & DT,LoopInfo & LI,ScalarEvolution * SE,MemorySSAUpdater * MSSAU)7380b57cec5SDimitry Andric static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
7390b57cec5SDimitry Andric LoopInfo &LI, ScalarEvolution *SE,
7400b57cec5SDimitry Andric MemorySSAUpdater *MSSAU) {
7410b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n");
7420b57cec5SDimitry Andric Value *LoopCond = SI.getCondition();
7430b57cec5SDimitry Andric
7440b57cec5SDimitry Andric // If this isn't switching on an invariant condition, we can't unswitch it.
7450b57cec5SDimitry Andric if (!L.isLoopInvariant(LoopCond))
7460b57cec5SDimitry Andric return false;
7470b57cec5SDimitry Andric
7480b57cec5SDimitry Andric auto *ParentBB = SI.getParent();
7490b57cec5SDimitry Andric
7505ffd83dbSDimitry Andric // The same check must be used both for the default and the exit cases. We
7515ffd83dbSDimitry Andric // should never leave edges from the switch instruction to a basic block that
7525ffd83dbSDimitry Andric // we are unswitching, hence the condition used to determine the default case
7535ffd83dbSDimitry Andric // needs to also be used to populate ExitCaseIndices, which is then used to
7545ffd83dbSDimitry Andric // remove cases from the switch.
7555ffd83dbSDimitry Andric auto IsTriviallyUnswitchableExitBlock = [&](BasicBlock &BBToCheck) {
7565ffd83dbSDimitry Andric // BBToCheck is not an exit block if it is inside loop L.
7575ffd83dbSDimitry Andric if (L.contains(&BBToCheck))
7585ffd83dbSDimitry Andric return false;
7595ffd83dbSDimitry Andric // BBToCheck is not trivial to unswitch if its phis aren't loop invariant.
7605ffd83dbSDimitry Andric if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, BBToCheck))
7615ffd83dbSDimitry Andric return false;
7625ffd83dbSDimitry Andric // We do not unswitch a block that only has an unreachable statement, as
7635ffd83dbSDimitry Andric // it's possible this is a previously unswitched block. Only unswitch if
7645ffd83dbSDimitry Andric // either the terminator is not unreachable, or, if it is, it's not the only
7655ffd83dbSDimitry Andric // instruction in the block.
7665ffd83dbSDimitry Andric auto *TI = BBToCheck.getTerminator();
7675ffd83dbSDimitry Andric bool isUnreachable = isa<UnreachableInst>(TI);
7685ffd83dbSDimitry Andric return !isUnreachable ||
7695ffd83dbSDimitry Andric (isUnreachable && (BBToCheck.getFirstNonPHIOrDbg() != TI));
7705ffd83dbSDimitry Andric };
7715ffd83dbSDimitry Andric
7720b57cec5SDimitry Andric SmallVector<int, 4> ExitCaseIndices;
7735ffd83dbSDimitry Andric for (auto Case : SI.cases())
7745ffd83dbSDimitry Andric if (IsTriviallyUnswitchableExitBlock(*Case.getCaseSuccessor()))
7750b57cec5SDimitry Andric ExitCaseIndices.push_back(Case.getCaseIndex());
7760b57cec5SDimitry Andric BasicBlock *DefaultExitBB = nullptr;
7770b57cec5SDimitry Andric SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight =
7780b57cec5SDimitry Andric SwitchInstProfUpdateWrapper::getSuccessorWeight(SI, 0);
7795ffd83dbSDimitry Andric if (IsTriviallyUnswitchableExitBlock(*SI.getDefaultDest())) {
7800b57cec5SDimitry Andric DefaultExitBB = SI.getDefaultDest();
7810b57cec5SDimitry Andric } else if (ExitCaseIndices.empty())
7820b57cec5SDimitry Andric return false;
7830b57cec5SDimitry Andric
7840b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n");
7850b57cec5SDimitry Andric
7860b57cec5SDimitry Andric if (MSSAU && VerifyMemorySSA)
7870b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
7880b57cec5SDimitry Andric
7890b57cec5SDimitry Andric // We may need to invalidate SCEVs for the outermost loop reached by any of
7900b57cec5SDimitry Andric // the exits.
7910b57cec5SDimitry Andric Loop *OuterL = &L;
7920b57cec5SDimitry Andric
7930b57cec5SDimitry Andric if (DefaultExitBB) {
794fe013be4SDimitry Andric // Check the loop containing this exit.
795fe013be4SDimitry Andric Loop *ExitL = getTopMostExitingLoop(DefaultExitBB, LI);
796fe013be4SDimitry Andric if (!ExitL || ExitL->contains(OuterL))
797fe013be4SDimitry Andric OuterL = ExitL;
798fe013be4SDimitry Andric }
799fe013be4SDimitry Andric for (unsigned Index : ExitCaseIndices) {
800fe013be4SDimitry Andric auto CaseI = SI.case_begin() + Index;
801fe013be4SDimitry Andric // Compute the outer loop from this exit.
802fe013be4SDimitry Andric Loop *ExitL = getTopMostExitingLoop(CaseI->getCaseSuccessor(), LI);
803fe013be4SDimitry Andric if (!ExitL || ExitL->contains(OuterL))
804fe013be4SDimitry Andric OuterL = ExitL;
805fe013be4SDimitry Andric }
806fe013be4SDimitry Andric
807fe013be4SDimitry Andric if (SE) {
808fe013be4SDimitry Andric if (OuterL)
809fe013be4SDimitry Andric SE->forgetLoop(OuterL);
810fe013be4SDimitry Andric else
811fe013be4SDimitry Andric SE->forgetTopmostLoop(&L);
812fe013be4SDimitry Andric }
813fe013be4SDimitry Andric
814fe013be4SDimitry Andric if (DefaultExitBB) {
8150b57cec5SDimitry Andric // Clear out the default destination temporarily to allow accurate
8160b57cec5SDimitry Andric // predecessor lists to be examined below.
8170b57cec5SDimitry Andric SI.setDefaultDest(nullptr);
8180b57cec5SDimitry Andric }
8190b57cec5SDimitry Andric
8200b57cec5SDimitry Andric // Store the exit cases into a separate data structure and remove them from
8210b57cec5SDimitry Andric // the switch.
8220b57cec5SDimitry Andric SmallVector<std::tuple<ConstantInt *, BasicBlock *,
8230b57cec5SDimitry Andric SwitchInstProfUpdateWrapper::CaseWeightOpt>,
8240b57cec5SDimitry Andric 4> ExitCases;
8250b57cec5SDimitry Andric ExitCases.reserve(ExitCaseIndices.size());
8260b57cec5SDimitry Andric SwitchInstProfUpdateWrapper SIW(SI);
8270b57cec5SDimitry Andric // We walk the case indices backwards so that we remove the last case first
8280b57cec5SDimitry Andric // and don't disrupt the earlier indices.
8290b57cec5SDimitry Andric for (unsigned Index : reverse(ExitCaseIndices)) {
8300b57cec5SDimitry Andric auto CaseI = SI.case_begin() + Index;
8310b57cec5SDimitry Andric // Save the value of this case.
8320b57cec5SDimitry Andric auto W = SIW.getSuccessorWeight(CaseI->getSuccessorIndex());
8330b57cec5SDimitry Andric ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W);
8340b57cec5SDimitry Andric // Delete the unswitched cases.
8350b57cec5SDimitry Andric SIW.removeCase(CaseI);
8360b57cec5SDimitry Andric }
8370b57cec5SDimitry Andric
8380b57cec5SDimitry Andric // Check if after this all of the remaining cases point at the same
8390b57cec5SDimitry Andric // successor.
8400b57cec5SDimitry Andric BasicBlock *CommonSuccBB = nullptr;
8410b57cec5SDimitry Andric if (SI.getNumCases() > 0 &&
842e8d8bef9SDimitry Andric all_of(drop_begin(SI.cases()), [&SI](const SwitchInst::CaseHandle &Case) {
843e8d8bef9SDimitry Andric return Case.getCaseSuccessor() == SI.case_begin()->getCaseSuccessor();
8440b57cec5SDimitry Andric }))
8450b57cec5SDimitry Andric CommonSuccBB = SI.case_begin()->getCaseSuccessor();
8460b57cec5SDimitry Andric if (!DefaultExitBB) {
8470b57cec5SDimitry Andric // If we're not unswitching the default, we need it to match any cases to
8480b57cec5SDimitry Andric // have a common successor or if we have no cases it is the common
8490b57cec5SDimitry Andric // successor.
8500b57cec5SDimitry Andric if (SI.getNumCases() == 0)
8510b57cec5SDimitry Andric CommonSuccBB = SI.getDefaultDest();
8520b57cec5SDimitry Andric else if (SI.getDefaultDest() != CommonSuccBB)
8530b57cec5SDimitry Andric CommonSuccBB = nullptr;
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric
8560b57cec5SDimitry Andric // Split the preheader, so that we know that there is a safe place to insert
8570b57cec5SDimitry Andric // the switch.
8580b57cec5SDimitry Andric BasicBlock *OldPH = L.getLoopPreheader();
8590b57cec5SDimitry Andric BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
8600b57cec5SDimitry Andric OldPH->getTerminator()->eraseFromParent();
8610b57cec5SDimitry Andric
8620b57cec5SDimitry Andric // Now add the unswitched switch.
8630b57cec5SDimitry Andric auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
8640b57cec5SDimitry Andric SwitchInstProfUpdateWrapper NewSIW(*NewSI);
8650b57cec5SDimitry Andric
8660b57cec5SDimitry Andric // Rewrite the IR for the unswitched basic blocks. This requires two steps.
8670b57cec5SDimitry Andric // First, we split any exit blocks with remaining in-loop predecessors. Then
8680b57cec5SDimitry Andric // we update the PHIs in one of two ways depending on if there was a split.
8690b57cec5SDimitry Andric // We walk in reverse so that we split in the same order as the cases
8700b57cec5SDimitry Andric // appeared. This is purely for convenience of reading the resulting IR, but
8710b57cec5SDimitry Andric // it doesn't cost anything really.
8720b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
8730b57cec5SDimitry Andric SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
8740b57cec5SDimitry Andric // Handle the default exit if necessary.
8750b57cec5SDimitry Andric // FIXME: It'd be great if we could merge this with the loop below but LLVM's
8760b57cec5SDimitry Andric // ranges aren't quite powerful enough yet.
8770b57cec5SDimitry Andric if (DefaultExitBB) {
8780b57cec5SDimitry Andric if (pred_empty(DefaultExitBB)) {
8790b57cec5SDimitry Andric UnswitchedExitBBs.insert(DefaultExitBB);
8800b57cec5SDimitry Andric rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
8810b57cec5SDimitry Andric } else {
8820b57cec5SDimitry Andric auto *SplitBB =
883*c9157d92SDimitry Andric SplitBlock(DefaultExitBB, DefaultExitBB->begin(), &DT, &LI, MSSAU);
8840b57cec5SDimitry Andric rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
8850b57cec5SDimitry Andric *ParentBB, *OldPH,
8860b57cec5SDimitry Andric /*FullUnswitch*/ true);
8870b57cec5SDimitry Andric DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
8880b57cec5SDimitry Andric }
8890b57cec5SDimitry Andric }
8900b57cec5SDimitry Andric // Note that we must use a reference in the for loop so that we update the
8910b57cec5SDimitry Andric // container.
8920b57cec5SDimitry Andric for (auto &ExitCase : reverse(ExitCases)) {
8930b57cec5SDimitry Andric // Grab a reference to the exit block in the pair so that we can update it.
8940b57cec5SDimitry Andric BasicBlock *ExitBB = std::get<1>(ExitCase);
8950b57cec5SDimitry Andric
8960b57cec5SDimitry Andric // If this case is the last edge into the exit block, we can simply reuse it
8970b57cec5SDimitry Andric // as it will no longer be a loop exit. No mapping necessary.
8980b57cec5SDimitry Andric if (pred_empty(ExitBB)) {
8990b57cec5SDimitry Andric // Only rewrite once.
9000b57cec5SDimitry Andric if (UnswitchedExitBBs.insert(ExitBB).second)
9010b57cec5SDimitry Andric rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
9020b57cec5SDimitry Andric continue;
9030b57cec5SDimitry Andric }
9040b57cec5SDimitry Andric
9050b57cec5SDimitry Andric // Otherwise we need to split the exit block so that we retain an exit
9060b57cec5SDimitry Andric // block from the loop and a target for the unswitched condition.
9070b57cec5SDimitry Andric BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
9080b57cec5SDimitry Andric if (!SplitExitBB) {
9090b57cec5SDimitry Andric // If this is the first time we see this, do the split and remember it.
910*c9157d92SDimitry Andric SplitExitBB = SplitBlock(ExitBB, ExitBB->begin(), &DT, &LI, MSSAU);
9110b57cec5SDimitry Andric rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
9120b57cec5SDimitry Andric *ParentBB, *OldPH,
9130b57cec5SDimitry Andric /*FullUnswitch*/ true);
9140b57cec5SDimitry Andric }
9150b57cec5SDimitry Andric // Update the case pair to point to the split block.
9160b57cec5SDimitry Andric std::get<1>(ExitCase) = SplitExitBB;
9170b57cec5SDimitry Andric }
9180b57cec5SDimitry Andric
9190b57cec5SDimitry Andric // Now add the unswitched cases. We do this in reverse order as we built them
9200b57cec5SDimitry Andric // in reverse order.
9210b57cec5SDimitry Andric for (auto &ExitCase : reverse(ExitCases)) {
9220b57cec5SDimitry Andric ConstantInt *CaseVal = std::get<0>(ExitCase);
9230b57cec5SDimitry Andric BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
9240b57cec5SDimitry Andric
9250b57cec5SDimitry Andric NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
9260b57cec5SDimitry Andric }
9270b57cec5SDimitry Andric
9280b57cec5SDimitry Andric // If the default was unswitched, re-point it and add explicit cases for
9290b57cec5SDimitry Andric // entering the loop.
9300b57cec5SDimitry Andric if (DefaultExitBB) {
9310b57cec5SDimitry Andric NewSIW->setDefaultDest(DefaultExitBB);
9320b57cec5SDimitry Andric NewSIW.setSuccessorWeight(0, DefaultCaseWeight);
9330b57cec5SDimitry Andric
9340b57cec5SDimitry Andric // We removed all the exit cases, so we just copy the cases to the
9350b57cec5SDimitry Andric // unswitched switch.
9360b57cec5SDimitry Andric for (const auto &Case : SI.cases())
9370b57cec5SDimitry Andric NewSIW.addCase(Case.getCaseValue(), NewPH,
9380b57cec5SDimitry Andric SIW.getSuccessorWeight(Case.getSuccessorIndex()));
9390b57cec5SDimitry Andric } else if (DefaultCaseWeight) {
9400b57cec5SDimitry Andric // We have to set branch weight of the default case.
9410b57cec5SDimitry Andric uint64_t SW = *DefaultCaseWeight;
9420b57cec5SDimitry Andric for (const auto &Case : SI.cases()) {
9430b57cec5SDimitry Andric auto W = SIW.getSuccessorWeight(Case.getSuccessorIndex());
9440b57cec5SDimitry Andric assert(W &&
9450b57cec5SDimitry Andric "case weight must be defined as default case weight is defined");
9460b57cec5SDimitry Andric SW += *W;
9470b57cec5SDimitry Andric }
9480b57cec5SDimitry Andric NewSIW.setSuccessorWeight(0, SW);
9490b57cec5SDimitry Andric }
9500b57cec5SDimitry Andric
9510b57cec5SDimitry Andric // If we ended up with a common successor for every path through the switch
9520b57cec5SDimitry Andric // after unswitching, rewrite it to an unconditional branch to make it easy
9530b57cec5SDimitry Andric // to recognize. Otherwise we potentially have to recognize the default case
9540b57cec5SDimitry Andric // pointing at unreachable and other complexity.
9550b57cec5SDimitry Andric if (CommonSuccBB) {
9560b57cec5SDimitry Andric BasicBlock *BB = SI.getParent();
9570b57cec5SDimitry Andric // We may have had multiple edges to this common successor block, so remove
9580b57cec5SDimitry Andric // them as predecessors. We skip the first one, either the default or the
9590b57cec5SDimitry Andric // actual first case.
9600b57cec5SDimitry Andric bool SkippedFirst = DefaultExitBB == nullptr;
9610b57cec5SDimitry Andric for (auto Case : SI.cases()) {
9620b57cec5SDimitry Andric assert(Case.getCaseSuccessor() == CommonSuccBB &&
9630b57cec5SDimitry Andric "Non-common successor!");
9640b57cec5SDimitry Andric (void)Case;
9650b57cec5SDimitry Andric if (!SkippedFirst) {
9660b57cec5SDimitry Andric SkippedFirst = true;
9670b57cec5SDimitry Andric continue;
9680b57cec5SDimitry Andric }
9690b57cec5SDimitry Andric CommonSuccBB->removePredecessor(BB,
9700b57cec5SDimitry Andric /*KeepOneInputPHIs*/ true);
9710b57cec5SDimitry Andric }
9720b57cec5SDimitry Andric // Now nuke the switch and replace it with a direct branch.
9730b57cec5SDimitry Andric SIW.eraseFromParent();
9740b57cec5SDimitry Andric BranchInst::Create(CommonSuccBB, BB);
9750b57cec5SDimitry Andric } else if (DefaultExitBB) {
9760b57cec5SDimitry Andric assert(SI.getNumCases() > 0 &&
9770b57cec5SDimitry Andric "If we had no cases we'd have a common successor!");
9780b57cec5SDimitry Andric // Move the last case to the default successor. This is valid as if the
9790b57cec5SDimitry Andric // default got unswitched it cannot be reached. This has the advantage of
9800b57cec5SDimitry Andric // being simple and keeping the number of edges from this switch to
9810b57cec5SDimitry Andric // successors the same, and avoiding any PHI update complexity.
9820b57cec5SDimitry Andric auto LastCaseI = std::prev(SI.case_end());
9830b57cec5SDimitry Andric
9840b57cec5SDimitry Andric SI.setDefaultDest(LastCaseI->getCaseSuccessor());
9850b57cec5SDimitry Andric SIW.setSuccessorWeight(
9860b57cec5SDimitry Andric 0, SIW.getSuccessorWeight(LastCaseI->getSuccessorIndex()));
9870b57cec5SDimitry Andric SIW.removeCase(LastCaseI);
9880b57cec5SDimitry Andric }
9890b57cec5SDimitry Andric
9900b57cec5SDimitry Andric // Walk the unswitched exit blocks and the unswitched split blocks and update
9910b57cec5SDimitry Andric // the dominator tree based on the CFG edits. While we are walking unordered
9920b57cec5SDimitry Andric // containers here, the API for applyUpdates takes an unordered list of
9930b57cec5SDimitry Andric // updates and requires them to not contain duplicates.
9940b57cec5SDimitry Andric SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
9950b57cec5SDimitry Andric for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
9960b57cec5SDimitry Andric DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
9970b57cec5SDimitry Andric DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
9980b57cec5SDimitry Andric }
9990b57cec5SDimitry Andric for (auto SplitUnswitchedPair : SplitExitBBMap) {
10000b57cec5SDimitry Andric DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first});
10010b57cec5SDimitry Andric DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second});
10020b57cec5SDimitry Andric }
10030b57cec5SDimitry Andric
10040b57cec5SDimitry Andric if (MSSAU) {
1005e8d8bef9SDimitry Andric MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
10060b57cec5SDimitry Andric if (VerifyMemorySSA)
10070b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
1008e8d8bef9SDimitry Andric } else {
1009e8d8bef9SDimitry Andric DT.applyUpdates(DTUpdates);
10100b57cec5SDimitry Andric }
10110b57cec5SDimitry Andric
10120b57cec5SDimitry Andric assert(DT.verify(DominatorTree::VerificationLevel::Fast));
10130b57cec5SDimitry Andric
10140b57cec5SDimitry Andric // We may have changed the nesting relationship for this loop so hoist it to
10150b57cec5SDimitry Andric // its correct parent if needed.
1016480093f4SDimitry Andric hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
10170b57cec5SDimitry Andric
10180b57cec5SDimitry Andric if (MSSAU && VerifyMemorySSA)
10190b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
10200b57cec5SDimitry Andric
10210b57cec5SDimitry Andric ++NumTrivial;
10220b57cec5SDimitry Andric ++NumSwitches;
10230b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n");
10240b57cec5SDimitry Andric return true;
10250b57cec5SDimitry Andric }
10260b57cec5SDimitry Andric
10270b57cec5SDimitry Andric /// This routine scans the loop to find a branch or switch which occurs before
10280b57cec5SDimitry Andric /// any side effects occur. These can potentially be unswitched without
10290b57cec5SDimitry Andric /// duplicating the loop. If a branch or switch is successfully unswitched the
10300b57cec5SDimitry Andric /// scanning continues to see if subsequent branches or switches have become
10310b57cec5SDimitry Andric /// trivial. Once all trivial candidates have been unswitched, this routine
10320b57cec5SDimitry Andric /// returns.
10330b57cec5SDimitry Andric ///
10340b57cec5SDimitry Andric /// The return value indicates whether anything was unswitched (and therefore
10350b57cec5SDimitry Andric /// changed).
10360b57cec5SDimitry Andric ///
10370b57cec5SDimitry Andric /// If `SE` is not null, it will be updated based on the potential loop SCEVs
10380b57cec5SDimitry Andric /// invalidated by this.
unswitchAllTrivialConditions(Loop & L,DominatorTree & DT,LoopInfo & LI,ScalarEvolution * SE,MemorySSAUpdater * MSSAU)10390b57cec5SDimitry Andric static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
10400b57cec5SDimitry Andric LoopInfo &LI, ScalarEvolution *SE,
10410b57cec5SDimitry Andric MemorySSAUpdater *MSSAU) {
10420b57cec5SDimitry Andric bool Changed = false;
10430b57cec5SDimitry Andric
10440b57cec5SDimitry Andric // If loop header has only one reachable successor we should keep looking for
10450b57cec5SDimitry Andric // trivial condition candidates in the successor as well. An alternative is
10460b57cec5SDimitry Andric // to constant fold conditions and merge successors into loop header (then we
10470b57cec5SDimitry Andric // only need to check header's terminator). The reason for not doing this in
10480b57cec5SDimitry Andric // LoopUnswitch pass is that it could potentially break LoopPassManager's
10490b57cec5SDimitry Andric // invariants. Folding dead branches could either eliminate the current loop
10500b57cec5SDimitry Andric // or make other loops unreachable. LCSSA form might also not be preserved
10510b57cec5SDimitry Andric // after deleting branches. The following code keeps traversing loop header's
10520b57cec5SDimitry Andric // successors until it finds the trivial condition candidate (condition that
10530b57cec5SDimitry Andric // is not a constant). Since unswitching generates branches with constant
10540b57cec5SDimitry Andric // conditions, this scenario could be very common in practice.
10550b57cec5SDimitry Andric BasicBlock *CurrentBB = L.getHeader();
10560b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 8> Visited;
10570b57cec5SDimitry Andric Visited.insert(CurrentBB);
10580b57cec5SDimitry Andric do {
10590b57cec5SDimitry Andric // Check if there are any side-effecting instructions (e.g. stores, calls,
10600b57cec5SDimitry Andric // volatile loads) in the part of the loop that the code *would* execute
10610b57cec5SDimitry Andric // without unswitching.
10620b57cec5SDimitry Andric if (MSSAU) // Possible early exit with MSSA
10630b57cec5SDimitry Andric if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
10640b57cec5SDimitry Andric if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
10650b57cec5SDimitry Andric return Changed;
10660b57cec5SDimitry Andric if (llvm::any_of(*CurrentBB,
10670b57cec5SDimitry Andric [](Instruction &I) { return I.mayHaveSideEffects(); }))
10680b57cec5SDimitry Andric return Changed;
10690b57cec5SDimitry Andric
10700b57cec5SDimitry Andric Instruction *CurrentTerm = CurrentBB->getTerminator();
10710b57cec5SDimitry Andric
10720b57cec5SDimitry Andric if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
10730b57cec5SDimitry Andric // Don't bother trying to unswitch past a switch with a constant
10740b57cec5SDimitry Andric // condition. This should be removed prior to running this pass by
1075fe6060f1SDimitry Andric // simplifycfg.
10760b57cec5SDimitry Andric if (isa<Constant>(SI->getCondition()))
10770b57cec5SDimitry Andric return Changed;
10780b57cec5SDimitry Andric
10790b57cec5SDimitry Andric if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
10800b57cec5SDimitry Andric // Couldn't unswitch this one so we're done.
10810b57cec5SDimitry Andric return Changed;
10820b57cec5SDimitry Andric
10830b57cec5SDimitry Andric // Mark that we managed to unswitch something.
10840b57cec5SDimitry Andric Changed = true;
10850b57cec5SDimitry Andric
10860b57cec5SDimitry Andric // If unswitching turned the terminator into an unconditional branch then
10870b57cec5SDimitry Andric // we can continue. The unswitching logic specifically works to fold any
10880b57cec5SDimitry Andric // cases it can into an unconditional branch to make it easier to
10890b57cec5SDimitry Andric // recognize here.
10900b57cec5SDimitry Andric auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
10910b57cec5SDimitry Andric if (!BI || BI->isConditional())
10920b57cec5SDimitry Andric return Changed;
10930b57cec5SDimitry Andric
10940b57cec5SDimitry Andric CurrentBB = BI->getSuccessor(0);
10950b57cec5SDimitry Andric continue;
10960b57cec5SDimitry Andric }
10970b57cec5SDimitry Andric
10980b57cec5SDimitry Andric auto *BI = dyn_cast<BranchInst>(CurrentTerm);
10990b57cec5SDimitry Andric if (!BI)
11000b57cec5SDimitry Andric // We do not understand other terminator instructions.
11010b57cec5SDimitry Andric return Changed;
11020b57cec5SDimitry Andric
11030b57cec5SDimitry Andric // Don't bother trying to unswitch past an unconditional branch or a branch
1104fe6060f1SDimitry Andric // with a constant value. These should be removed by simplifycfg prior to
11050b57cec5SDimitry Andric // running this pass.
110681ad6265SDimitry Andric if (!BI->isConditional() ||
110781ad6265SDimitry Andric isa<Constant>(skipTrivialSelect(BI->getCondition())))
11080b57cec5SDimitry Andric return Changed;
11090b57cec5SDimitry Andric
11100b57cec5SDimitry Andric // Found a trivial condition candidate: non-foldable conditional branch. If
11110b57cec5SDimitry Andric // we fail to unswitch this, we can't do anything else that is trivial.
11120b57cec5SDimitry Andric if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
11130b57cec5SDimitry Andric return Changed;
11140b57cec5SDimitry Andric
11150b57cec5SDimitry Andric // Mark that we managed to unswitch something.
11160b57cec5SDimitry Andric Changed = true;
11170b57cec5SDimitry Andric
11180b57cec5SDimitry Andric // If we only unswitched some of the conditions feeding the branch, we won't
11190b57cec5SDimitry Andric // have collapsed it to a single successor.
11200b57cec5SDimitry Andric BI = cast<BranchInst>(CurrentBB->getTerminator());
11210b57cec5SDimitry Andric if (BI->isConditional())
11220b57cec5SDimitry Andric return Changed;
11230b57cec5SDimitry Andric
11240b57cec5SDimitry Andric // Follow the newly unconditional branch into its successor.
11250b57cec5SDimitry Andric CurrentBB = BI->getSuccessor(0);
11260b57cec5SDimitry Andric
11270b57cec5SDimitry Andric // When continuing, if we exit the loop or reach a previous visited block,
11280b57cec5SDimitry Andric // then we can not reach any trivial condition candidates (unfoldable
11290b57cec5SDimitry Andric // branch instructions or switch instructions) and no unswitch can happen.
11300b57cec5SDimitry Andric } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
11310b57cec5SDimitry Andric
11320b57cec5SDimitry Andric return Changed;
11330b57cec5SDimitry Andric }
11340b57cec5SDimitry Andric
11350b57cec5SDimitry Andric /// Build the cloned blocks for an unswitched copy of the given loop.
11360b57cec5SDimitry Andric ///
11370b57cec5SDimitry Andric /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
11380b57cec5SDimitry Andric /// after the split block (`SplitBB`) that will be used to select between the
11390b57cec5SDimitry Andric /// cloned and original loop.
11400b57cec5SDimitry Andric ///
11410b57cec5SDimitry Andric /// This routine handles cloning all of the necessary loop blocks and exit
11420b57cec5SDimitry Andric /// blocks including rewriting their instructions and the relevant PHI nodes.
11430b57cec5SDimitry Andric /// Any loop blocks or exit blocks which are dominated by a different successor
11440b57cec5SDimitry Andric /// than the one for this clone of the loop blocks can be trivially skipped. We
11450b57cec5SDimitry Andric /// use the `DominatingSucc` map to determine whether a block satisfies that
11460b57cec5SDimitry Andric /// property with a simple map lookup.
11470b57cec5SDimitry Andric ///
11480b57cec5SDimitry Andric /// It also correctly creates the unconditional branch in the cloned
11490b57cec5SDimitry Andric /// unswitched parent block to only point at the unswitched successor.
11500b57cec5SDimitry Andric ///
11510b57cec5SDimitry Andric /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
11520b57cec5SDimitry Andric /// block splitting is correctly reflected in `LoopInfo`, essentially all of
11530b57cec5SDimitry Andric /// the cloned blocks (and their loops) are left without full `LoopInfo`
11540b57cec5SDimitry Andric /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
11550b57cec5SDimitry Andric /// blocks to them but doesn't create the cloned `DominatorTree` structure and
11560b57cec5SDimitry Andric /// instead the caller must recompute an accurate DT. It *does* correctly
11570b57cec5SDimitry Andric /// update the `AssumptionCache` provided in `AC`.
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)11580b57cec5SDimitry Andric static BasicBlock *buildClonedLoopBlocks(
11590b57cec5SDimitry Andric Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
11600b57cec5SDimitry Andric ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
11610b57cec5SDimitry Andric BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
11620b57cec5SDimitry Andric const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
11630b57cec5SDimitry Andric ValueToValueMapTy &VMap,
11640b57cec5SDimitry Andric SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
1165bdd1243dSDimitry Andric DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU,
1166bdd1243dSDimitry Andric ScalarEvolution *SE) {
11670b57cec5SDimitry Andric SmallVector<BasicBlock *, 4> NewBlocks;
11680b57cec5SDimitry Andric NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
11690b57cec5SDimitry Andric
11700b57cec5SDimitry Andric // We will need to clone a bunch of blocks, wrap up the clone operation in
11710b57cec5SDimitry Andric // a helper.
11720b57cec5SDimitry Andric auto CloneBlock = [&](BasicBlock *OldBB) {
11730b57cec5SDimitry Andric // Clone the basic block and insert it before the new preheader.
11740b57cec5SDimitry Andric BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
11750b57cec5SDimitry Andric NewBB->moveBefore(LoopPH);
11760b57cec5SDimitry Andric
11770b57cec5SDimitry Andric // Record this block and the mapping.
11780b57cec5SDimitry Andric NewBlocks.push_back(NewBB);
11790b57cec5SDimitry Andric VMap[OldBB] = NewBB;
11800b57cec5SDimitry Andric
11810b57cec5SDimitry Andric return NewBB;
11820b57cec5SDimitry Andric };
11830b57cec5SDimitry Andric
11840b57cec5SDimitry Andric // We skip cloning blocks when they have a dominating succ that is not the
11850b57cec5SDimitry Andric // succ we are cloning for.
11860b57cec5SDimitry Andric auto SkipBlock = [&](BasicBlock *BB) {
11870b57cec5SDimitry Andric auto It = DominatingSucc.find(BB);
11880b57cec5SDimitry Andric return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
11890b57cec5SDimitry Andric };
11900b57cec5SDimitry Andric
11910b57cec5SDimitry Andric // First, clone the preheader.
11920b57cec5SDimitry Andric auto *ClonedPH = CloneBlock(LoopPH);
11930b57cec5SDimitry Andric
11940b57cec5SDimitry Andric // Then clone all the loop blocks, skipping the ones that aren't necessary.
11950b57cec5SDimitry Andric for (auto *LoopBB : L.blocks())
11960b57cec5SDimitry Andric if (!SkipBlock(LoopBB))
11970b57cec5SDimitry Andric CloneBlock(LoopBB);
11980b57cec5SDimitry Andric
11990b57cec5SDimitry Andric // Split all the loop exit edges so that when we clone the exit blocks, if
12000b57cec5SDimitry Andric // any of the exit blocks are *also* a preheader for some other loop, we
12010b57cec5SDimitry Andric // don't create multiple predecessors entering the loop header.
12020b57cec5SDimitry Andric for (auto *ExitBB : ExitBlocks) {
12030b57cec5SDimitry Andric if (SkipBlock(ExitBB))
12040b57cec5SDimitry Andric continue;
12050b57cec5SDimitry Andric
12060b57cec5SDimitry Andric // When we are going to clone an exit, we don't need to clone all the
12070b57cec5SDimitry Andric // instructions in the exit block and we want to ensure we have an easy
12080b57cec5SDimitry Andric // place to merge the CFG, so split the exit first. This is always safe to
12090b57cec5SDimitry Andric // do because there cannot be any non-loop predecessors of a loop exit in
12100b57cec5SDimitry Andric // loop simplified form.
1211*c9157d92SDimitry Andric auto *MergeBB = SplitBlock(ExitBB, ExitBB->begin(), &DT, &LI, MSSAU);
12120b57cec5SDimitry Andric
12130b57cec5SDimitry Andric // Rearrange the names to make it easier to write test cases by having the
12140b57cec5SDimitry Andric // exit block carry the suffix rather than the merge block carrying the
12150b57cec5SDimitry Andric // suffix.
12160b57cec5SDimitry Andric MergeBB->takeName(ExitBB);
12170b57cec5SDimitry Andric ExitBB->setName(Twine(MergeBB->getName()) + ".split");
12180b57cec5SDimitry Andric
12190b57cec5SDimitry Andric // Now clone the original exit block.
12200b57cec5SDimitry Andric auto *ClonedExitBB = CloneBlock(ExitBB);
12210b57cec5SDimitry Andric assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
12220b57cec5SDimitry Andric "Exit block should have been split to have one successor!");
12230b57cec5SDimitry Andric assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
12240b57cec5SDimitry Andric "Cloned exit block has the wrong successor!");
12250b57cec5SDimitry Andric
12260b57cec5SDimitry Andric // Remap any cloned instructions and create a merge phi node for them.
12270b57cec5SDimitry Andric for (auto ZippedInsts : llvm::zip_first(
12280b57cec5SDimitry Andric llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
12290b57cec5SDimitry Andric llvm::make_range(ClonedExitBB->begin(),
12300b57cec5SDimitry Andric std::prev(ClonedExitBB->end())))) {
12310b57cec5SDimitry Andric Instruction &I = std::get<0>(ZippedInsts);
12320b57cec5SDimitry Andric Instruction &ClonedI = std::get<1>(ZippedInsts);
12330b57cec5SDimitry Andric
12340b57cec5SDimitry Andric // The only instructions in the exit block should be PHI nodes and
12350b57cec5SDimitry Andric // potentially a landing pad.
12360b57cec5SDimitry Andric assert(
12370b57cec5SDimitry Andric (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
12380b57cec5SDimitry Andric "Bad instruction in exit block!");
12390b57cec5SDimitry Andric // We should have a value map between the instruction and its clone.
12400b57cec5SDimitry Andric assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
12410b57cec5SDimitry Andric
1242bdd1243dSDimitry Andric // Forget SCEVs based on exit phis in case SCEV looked through the phi.
1243bdd1243dSDimitry Andric if (SE && isa<PHINode>(I))
1244bdd1243dSDimitry Andric SE->forgetValue(&I);
1245bdd1243dSDimitry Andric
12460b57cec5SDimitry Andric auto *MergePN =
1247*c9157d92SDimitry Andric PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi");
1248*c9157d92SDimitry Andric MergePN->insertBefore(MergeBB->getFirstInsertionPt());
12490b57cec5SDimitry Andric I.replaceAllUsesWith(MergePN);
12500b57cec5SDimitry Andric MergePN->addIncoming(&I, ExitBB);
12510b57cec5SDimitry Andric MergePN->addIncoming(&ClonedI, ClonedExitBB);
12520b57cec5SDimitry Andric }
12530b57cec5SDimitry Andric }
12540b57cec5SDimitry Andric
12550b57cec5SDimitry Andric // Rewrite the instructions in the cloned blocks to refer to the instructions
12560b57cec5SDimitry Andric // in the cloned blocks. We have to do this as a second pass so that we have
12570b57cec5SDimitry Andric // everything available. Also, we have inserted new instructions which may
12580b57cec5SDimitry Andric // include assume intrinsics, so we update the assumption cache while
12590b57cec5SDimitry Andric // processing this.
1260*c9157d92SDimitry Andric Module *M = ClonedPH->getParent()->getParent();
12610b57cec5SDimitry Andric for (auto *ClonedBB : NewBlocks)
12620b57cec5SDimitry Andric for (Instruction &I : *ClonedBB) {
1263*c9157d92SDimitry Andric RemapDPValueRange(M, I.getDbgValueRange(), VMap,
1264*c9157d92SDimitry Andric RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
12650b57cec5SDimitry Andric RemapInstruction(&I, VMap,
12660b57cec5SDimitry Andric RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1267fe6060f1SDimitry Andric if (auto *II = dyn_cast<AssumeInst>(&I))
12680b57cec5SDimitry Andric AC.registerAssumption(II);
12690b57cec5SDimitry Andric }
12700b57cec5SDimitry Andric
12710b57cec5SDimitry Andric // Update any PHI nodes in the cloned successors of the skipped blocks to not
12720b57cec5SDimitry Andric // have spurious incoming values.
12730b57cec5SDimitry Andric for (auto *LoopBB : L.blocks())
12740b57cec5SDimitry Andric if (SkipBlock(LoopBB))
12750b57cec5SDimitry Andric for (auto *SuccBB : successors(LoopBB))
12760b57cec5SDimitry Andric if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
12770b57cec5SDimitry Andric for (PHINode &PN : ClonedSuccBB->phis())
12780b57cec5SDimitry Andric PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
12790b57cec5SDimitry Andric
12800b57cec5SDimitry Andric // Remove the cloned parent as a predecessor of any successor we ended up
12810b57cec5SDimitry Andric // cloning other than the unswitched one.
12820b57cec5SDimitry Andric auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
12830b57cec5SDimitry Andric for (auto *SuccBB : successors(ParentBB)) {
12840b57cec5SDimitry Andric if (SuccBB == UnswitchedSuccBB)
12850b57cec5SDimitry Andric continue;
12860b57cec5SDimitry Andric
12870b57cec5SDimitry Andric auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
12880b57cec5SDimitry Andric if (!ClonedSuccBB)
12890b57cec5SDimitry Andric continue;
12900b57cec5SDimitry Andric
12910b57cec5SDimitry Andric ClonedSuccBB->removePredecessor(ClonedParentBB,
12920b57cec5SDimitry Andric /*KeepOneInputPHIs*/ true);
12930b57cec5SDimitry Andric }
12940b57cec5SDimitry Andric
12950b57cec5SDimitry Andric // Replace the cloned branch with an unconditional branch to the cloned
12960b57cec5SDimitry Andric // unswitched successor.
12970b57cec5SDimitry Andric auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1298e8d8bef9SDimitry Andric Instruction *ClonedTerminator = ClonedParentBB->getTerminator();
1299e8d8bef9SDimitry Andric // Trivial Simplification. If Terminator is a conditional branch and
1300e8d8bef9SDimitry Andric // condition becomes dead - erase it.
1301e8d8bef9SDimitry Andric Value *ClonedConditionToErase = nullptr;
1302e8d8bef9SDimitry Andric if (auto *BI = dyn_cast<BranchInst>(ClonedTerminator))
1303e8d8bef9SDimitry Andric ClonedConditionToErase = BI->getCondition();
1304e8d8bef9SDimitry Andric else if (auto *SI = dyn_cast<SwitchInst>(ClonedTerminator))
1305e8d8bef9SDimitry Andric ClonedConditionToErase = SI->getCondition();
1306e8d8bef9SDimitry Andric
1307e8d8bef9SDimitry Andric ClonedTerminator->eraseFromParent();
13080b57cec5SDimitry Andric BranchInst::Create(ClonedSuccBB, ClonedParentBB);
13090b57cec5SDimitry Andric
1310e8d8bef9SDimitry Andric if (ClonedConditionToErase)
1311e8d8bef9SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(ClonedConditionToErase, nullptr,
1312e8d8bef9SDimitry Andric MSSAU);
1313e8d8bef9SDimitry Andric
13140b57cec5SDimitry Andric // If there are duplicate entries in the PHI nodes because of multiple edges
13150b57cec5SDimitry Andric // to the unswitched successor, we need to nuke all but one as we replaced it
13160b57cec5SDimitry Andric // with a direct branch.
13170b57cec5SDimitry Andric for (PHINode &PN : ClonedSuccBB->phis()) {
13180b57cec5SDimitry Andric bool Found = false;
13190b57cec5SDimitry Andric // Loop over the incoming operands backwards so we can easily delete as we
13200b57cec5SDimitry Andric // go without invalidating the index.
13210b57cec5SDimitry Andric for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
13220b57cec5SDimitry Andric if (PN.getIncomingBlock(i) != ClonedParentBB)
13230b57cec5SDimitry Andric continue;
13240b57cec5SDimitry Andric if (!Found) {
13250b57cec5SDimitry Andric Found = true;
13260b57cec5SDimitry Andric continue;
13270b57cec5SDimitry Andric }
13280b57cec5SDimitry Andric PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
13290b57cec5SDimitry Andric }
13300b57cec5SDimitry Andric }
13310b57cec5SDimitry Andric
13320b57cec5SDimitry Andric // Record the domtree updates for the new blocks.
13330b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 4> SuccSet;
13340b57cec5SDimitry Andric for (auto *ClonedBB : NewBlocks) {
13350b57cec5SDimitry Andric for (auto *SuccBB : successors(ClonedBB))
13360b57cec5SDimitry Andric if (SuccSet.insert(SuccBB).second)
13370b57cec5SDimitry Andric DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
13380b57cec5SDimitry Andric SuccSet.clear();
13390b57cec5SDimitry Andric }
13400b57cec5SDimitry Andric
13410b57cec5SDimitry Andric return ClonedPH;
13420b57cec5SDimitry Andric }
13430b57cec5SDimitry Andric
13440b57cec5SDimitry Andric /// Recursively clone the specified loop and all of its children.
13450b57cec5SDimitry Andric ///
13460b57cec5SDimitry Andric /// The target parent loop for the clone should be provided, or can be null if
13470b57cec5SDimitry Andric /// the clone is a top-level loop. While cloning, all the blocks are mapped
13480b57cec5SDimitry Andric /// with the provided value map. The entire original loop must be present in
13490b57cec5SDimitry Andric /// the value map. The cloned loop is returned.
cloneLoopNest(Loop & OrigRootL,Loop * RootParentL,const ValueToValueMapTy & VMap,LoopInfo & LI)13500b57cec5SDimitry Andric static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
13510b57cec5SDimitry Andric const ValueToValueMapTy &VMap, LoopInfo &LI) {
13520b57cec5SDimitry Andric auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
13530b57cec5SDimitry Andric assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
13540b57cec5SDimitry Andric ClonedL.reserveBlocks(OrigL.getNumBlocks());
13550b57cec5SDimitry Andric for (auto *BB : OrigL.blocks()) {
13560b57cec5SDimitry Andric auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
13570b57cec5SDimitry Andric ClonedL.addBlockEntry(ClonedBB);
13580b57cec5SDimitry Andric if (LI.getLoopFor(BB) == &OrigL)
13590b57cec5SDimitry Andric LI.changeLoopFor(ClonedBB, &ClonedL);
13600b57cec5SDimitry Andric }
13610b57cec5SDimitry Andric };
13620b57cec5SDimitry Andric
13630b57cec5SDimitry Andric // We specially handle the first loop because it may get cloned into
13640b57cec5SDimitry Andric // a different parent and because we most commonly are cloning leaf loops.
13650b57cec5SDimitry Andric Loop *ClonedRootL = LI.AllocateLoop();
13660b57cec5SDimitry Andric if (RootParentL)
13670b57cec5SDimitry Andric RootParentL->addChildLoop(ClonedRootL);
13680b57cec5SDimitry Andric else
13690b57cec5SDimitry Andric LI.addTopLevelLoop(ClonedRootL);
13700b57cec5SDimitry Andric AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
13710b57cec5SDimitry Andric
1372e8d8bef9SDimitry Andric if (OrigRootL.isInnermost())
13730b57cec5SDimitry Andric return ClonedRootL;
13740b57cec5SDimitry Andric
13750b57cec5SDimitry Andric // If we have a nest, we can quickly clone the entire loop nest using an
13760b57cec5SDimitry Andric // iterative approach because it is a tree. We keep the cloned parent in the
13770b57cec5SDimitry Andric // data structure to avoid repeatedly querying through a map to find it.
13780b57cec5SDimitry Andric SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
13790b57cec5SDimitry Andric // Build up the loops to clone in reverse order as we'll clone them from the
13800b57cec5SDimitry Andric // back.
13810b57cec5SDimitry Andric for (Loop *ChildL : llvm::reverse(OrigRootL))
13820b57cec5SDimitry Andric LoopsToClone.push_back({ClonedRootL, ChildL});
13830b57cec5SDimitry Andric do {
13840b57cec5SDimitry Andric Loop *ClonedParentL, *L;
13850b57cec5SDimitry Andric std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
13860b57cec5SDimitry Andric Loop *ClonedL = LI.AllocateLoop();
13870b57cec5SDimitry Andric ClonedParentL->addChildLoop(ClonedL);
13880b57cec5SDimitry Andric AddClonedBlocksToLoop(*L, *ClonedL);
13890b57cec5SDimitry Andric for (Loop *ChildL : llvm::reverse(*L))
13900b57cec5SDimitry Andric LoopsToClone.push_back({ClonedL, ChildL});
13910b57cec5SDimitry Andric } while (!LoopsToClone.empty());
13920b57cec5SDimitry Andric
13930b57cec5SDimitry Andric return ClonedRootL;
13940b57cec5SDimitry Andric }
13950b57cec5SDimitry Andric
13960b57cec5SDimitry Andric /// Build the cloned loops of an original loop from unswitching.
13970b57cec5SDimitry Andric ///
13980b57cec5SDimitry Andric /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
13990b57cec5SDimitry Andric /// operation. We need to re-verify that there even is a loop (as the backedge
14000b57cec5SDimitry Andric /// may not have been cloned), and even if there are remaining backedges the
14010b57cec5SDimitry Andric /// backedge set may be different. However, we know that each child loop is
14020b57cec5SDimitry Andric /// undisturbed, we only need to find where to place each child loop within
14030b57cec5SDimitry Andric /// either any parent loop or within a cloned version of the original loop.
14040b57cec5SDimitry Andric ///
14050b57cec5SDimitry Andric /// Because child loops may end up cloned outside of any cloned version of the
14060b57cec5SDimitry Andric /// original loop, multiple cloned sibling loops may be created. All of them
14070b57cec5SDimitry Andric /// are returned so that the newly introduced loop nest roots can be
14080b57cec5SDimitry Andric /// identified.
buildClonedLoops(Loop & OrigL,ArrayRef<BasicBlock * > ExitBlocks,const ValueToValueMapTy & VMap,LoopInfo & LI,SmallVectorImpl<Loop * > & NonChildClonedLoops)14090b57cec5SDimitry Andric static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
14100b57cec5SDimitry Andric const ValueToValueMapTy &VMap, LoopInfo &LI,
14110b57cec5SDimitry Andric SmallVectorImpl<Loop *> &NonChildClonedLoops) {
14120b57cec5SDimitry Andric Loop *ClonedL = nullptr;
14130b57cec5SDimitry Andric
14140b57cec5SDimitry Andric auto *OrigPH = OrigL.getLoopPreheader();
14150b57cec5SDimitry Andric auto *OrigHeader = OrigL.getHeader();
14160b57cec5SDimitry Andric
14170b57cec5SDimitry Andric auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
14180b57cec5SDimitry Andric auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
14190b57cec5SDimitry Andric
14200b57cec5SDimitry Andric // We need to know the loops of the cloned exit blocks to even compute the
14210b57cec5SDimitry Andric // accurate parent loop. If we only clone exits to some parent of the
14220b57cec5SDimitry Andric // original parent, we want to clone into that outer loop. We also keep track
14230b57cec5SDimitry Andric // of the loops that our cloned exit blocks participate in.
14240b57cec5SDimitry Andric Loop *ParentL = nullptr;
14250b57cec5SDimitry Andric SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
14260b57cec5SDimitry Andric SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
14270b57cec5SDimitry Andric ClonedExitsInLoops.reserve(ExitBlocks.size());
14280b57cec5SDimitry Andric for (auto *ExitBB : ExitBlocks)
14290b57cec5SDimitry Andric if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
14300b57cec5SDimitry Andric if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
14310b57cec5SDimitry Andric ExitLoopMap[ClonedExitBB] = ExitL;
14320b57cec5SDimitry Andric ClonedExitsInLoops.push_back(ClonedExitBB);
14330b57cec5SDimitry Andric if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
14340b57cec5SDimitry Andric ParentL = ExitL;
14350b57cec5SDimitry Andric }
14360b57cec5SDimitry Andric assert((!ParentL || ParentL == OrigL.getParentLoop() ||
14370b57cec5SDimitry Andric ParentL->contains(OrigL.getParentLoop())) &&
14380b57cec5SDimitry Andric "The computed parent loop should always contain (or be) the parent of "
14390b57cec5SDimitry Andric "the original loop.");
14400b57cec5SDimitry Andric
14410b57cec5SDimitry Andric // We build the set of blocks dominated by the cloned header from the set of
14420b57cec5SDimitry Andric // cloned blocks out of the original loop. While not all of these will
14430b57cec5SDimitry Andric // necessarily be in the cloned loop, it is enough to establish that they
14440b57cec5SDimitry Andric // aren't in unreachable cycles, etc.
14450b57cec5SDimitry Andric SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
14460b57cec5SDimitry Andric for (auto *BB : OrigL.blocks())
14470b57cec5SDimitry Andric if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
14480b57cec5SDimitry Andric ClonedLoopBlocks.insert(ClonedBB);
14490b57cec5SDimitry Andric
14500b57cec5SDimitry Andric // Rebuild the set of blocks that will end up in the cloned loop. We may have
14510b57cec5SDimitry Andric // skipped cloning some region of this loop which can in turn skip some of
14520b57cec5SDimitry Andric // the backedges so we have to rebuild the blocks in the loop based on the
14530b57cec5SDimitry Andric // backedges that remain after cloning.
14540b57cec5SDimitry Andric SmallVector<BasicBlock *, 16> Worklist;
14550b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
14560b57cec5SDimitry Andric for (auto *Pred : predecessors(ClonedHeader)) {
14570b57cec5SDimitry Andric // The only possible non-loop header predecessor is the preheader because
14580b57cec5SDimitry Andric // we know we cloned the loop in simplified form.
14590b57cec5SDimitry Andric if (Pred == ClonedPH)
14600b57cec5SDimitry Andric continue;
14610b57cec5SDimitry Andric
14620b57cec5SDimitry Andric // Because the loop was in simplified form, the only non-loop predecessor
14630b57cec5SDimitry Andric // should be the preheader.
14640b57cec5SDimitry Andric assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
14650b57cec5SDimitry Andric "header other than the preheader "
14660b57cec5SDimitry Andric "that is not part of the loop!");
14670b57cec5SDimitry Andric
14680b57cec5SDimitry Andric // Insert this block into the loop set and on the first visit (and if it
14690b57cec5SDimitry Andric // isn't the header we're currently walking) put it into the worklist to
14700b57cec5SDimitry Andric // recurse through.
14710b57cec5SDimitry Andric if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
14720b57cec5SDimitry Andric Worklist.push_back(Pred);
14730b57cec5SDimitry Andric }
14740b57cec5SDimitry Andric
14750b57cec5SDimitry Andric // If we had any backedges then there *is* a cloned loop. Put the header into
14760b57cec5SDimitry Andric // the loop set and then walk the worklist backwards to find all the blocks
14770b57cec5SDimitry Andric // that remain within the loop after cloning.
14780b57cec5SDimitry Andric if (!BlocksInClonedLoop.empty()) {
14790b57cec5SDimitry Andric BlocksInClonedLoop.insert(ClonedHeader);
14800b57cec5SDimitry Andric
14810b57cec5SDimitry Andric while (!Worklist.empty()) {
14820b57cec5SDimitry Andric BasicBlock *BB = Worklist.pop_back_val();
14830b57cec5SDimitry Andric assert(BlocksInClonedLoop.count(BB) &&
14840b57cec5SDimitry Andric "Didn't put block into the loop set!");
14850b57cec5SDimitry Andric
14860b57cec5SDimitry Andric // Insert any predecessors that are in the possible set into the cloned
14870b57cec5SDimitry Andric // set, and if the insert is successful, add them to the worklist. Note
14880b57cec5SDimitry Andric // that we filter on the blocks that are definitely reachable via the
14890b57cec5SDimitry Andric // backedge to the loop header so we may prune out dead code within the
14900b57cec5SDimitry Andric // cloned loop.
14910b57cec5SDimitry Andric for (auto *Pred : predecessors(BB))
14920b57cec5SDimitry Andric if (ClonedLoopBlocks.count(Pred) &&
14930b57cec5SDimitry Andric BlocksInClonedLoop.insert(Pred).second)
14940b57cec5SDimitry Andric Worklist.push_back(Pred);
14950b57cec5SDimitry Andric }
14960b57cec5SDimitry Andric
14970b57cec5SDimitry Andric ClonedL = LI.AllocateLoop();
14980b57cec5SDimitry Andric if (ParentL) {
14990b57cec5SDimitry Andric ParentL->addBasicBlockToLoop(ClonedPH, LI);
15000b57cec5SDimitry Andric ParentL->addChildLoop(ClonedL);
15010b57cec5SDimitry Andric } else {
15020b57cec5SDimitry Andric LI.addTopLevelLoop(ClonedL);
15030b57cec5SDimitry Andric }
15040b57cec5SDimitry Andric NonChildClonedLoops.push_back(ClonedL);
15050b57cec5SDimitry Andric
15060b57cec5SDimitry Andric ClonedL->reserveBlocks(BlocksInClonedLoop.size());
15070b57cec5SDimitry Andric // We don't want to just add the cloned loop blocks based on how we
15080b57cec5SDimitry Andric // discovered them. The original order of blocks was carefully built in
15090b57cec5SDimitry Andric // a way that doesn't rely on predecessor ordering. Rather than re-invent
15100b57cec5SDimitry Andric // that logic, we just re-walk the original blocks (and those of the child
15110b57cec5SDimitry Andric // loops) and filter them as we add them into the cloned loop.
15120b57cec5SDimitry Andric for (auto *BB : OrigL.blocks()) {
15130b57cec5SDimitry Andric auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
15140b57cec5SDimitry Andric if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
15150b57cec5SDimitry Andric continue;
15160b57cec5SDimitry Andric
15170b57cec5SDimitry Andric // Directly add the blocks that are only in this loop.
15180b57cec5SDimitry Andric if (LI.getLoopFor(BB) == &OrigL) {
15190b57cec5SDimitry Andric ClonedL->addBasicBlockToLoop(ClonedBB, LI);
15200b57cec5SDimitry Andric continue;
15210b57cec5SDimitry Andric }
15220b57cec5SDimitry Andric
15230b57cec5SDimitry Andric // We want to manually add it to this loop and parents.
15240b57cec5SDimitry Andric // Registering it with LoopInfo will happen when we clone the top
15250b57cec5SDimitry Andric // loop for this block.
15260b57cec5SDimitry Andric for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
15270b57cec5SDimitry Andric PL->addBlockEntry(ClonedBB);
15280b57cec5SDimitry Andric }
15290b57cec5SDimitry Andric
15300b57cec5SDimitry Andric // Now add each child loop whose header remains within the cloned loop. All
15310b57cec5SDimitry Andric // of the blocks within the loop must satisfy the same constraints as the
15320b57cec5SDimitry Andric // header so once we pass the header checks we can just clone the entire
15330b57cec5SDimitry Andric // child loop nest.
15340b57cec5SDimitry Andric for (Loop *ChildL : OrigL) {
15350b57cec5SDimitry Andric auto *ClonedChildHeader =
15360b57cec5SDimitry Andric cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
15370b57cec5SDimitry Andric if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
15380b57cec5SDimitry Andric continue;
15390b57cec5SDimitry Andric
15400b57cec5SDimitry Andric #ifndef NDEBUG
15410b57cec5SDimitry Andric // We should never have a cloned child loop header but fail to have
15420b57cec5SDimitry Andric // all of the blocks for that child loop.
15430b57cec5SDimitry Andric for (auto *ChildLoopBB : ChildL->blocks())
15440b57cec5SDimitry Andric assert(BlocksInClonedLoop.count(
15450b57cec5SDimitry Andric cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
15460b57cec5SDimitry Andric "Child cloned loop has a header within the cloned outer "
15470b57cec5SDimitry Andric "loop but not all of its blocks!");
15480b57cec5SDimitry Andric #endif
15490b57cec5SDimitry Andric
15500b57cec5SDimitry Andric cloneLoopNest(*ChildL, ClonedL, VMap, LI);
15510b57cec5SDimitry Andric }
15520b57cec5SDimitry Andric }
15530b57cec5SDimitry Andric
15540b57cec5SDimitry Andric // Now that we've handled all the components of the original loop that were
15550b57cec5SDimitry Andric // cloned into a new loop, we still need to handle anything from the original
15560b57cec5SDimitry Andric // loop that wasn't in a cloned loop.
15570b57cec5SDimitry Andric
15580b57cec5SDimitry Andric // Figure out what blocks are left to place within any loop nest containing
15590b57cec5SDimitry Andric // the unswitched loop. If we never formed a loop, the cloned PH is one of
15600b57cec5SDimitry Andric // them.
15610b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
15620b57cec5SDimitry Andric if (BlocksInClonedLoop.empty())
15630b57cec5SDimitry Andric UnloopedBlockSet.insert(ClonedPH);
15640b57cec5SDimitry Andric for (auto *ClonedBB : ClonedLoopBlocks)
15650b57cec5SDimitry Andric if (!BlocksInClonedLoop.count(ClonedBB))
15660b57cec5SDimitry Andric UnloopedBlockSet.insert(ClonedBB);
15670b57cec5SDimitry Andric
15680b57cec5SDimitry Andric // Copy the cloned exits and sort them in ascending loop depth, we'll work
15690b57cec5SDimitry Andric // backwards across these to process them inside out. The order shouldn't
15700b57cec5SDimitry Andric // matter as we're just trying to build up the map from inside-out; we use
15710b57cec5SDimitry Andric // the map in a more stably ordered way below.
15720b57cec5SDimitry Andric auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
15730b57cec5SDimitry Andric llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
15740b57cec5SDimitry Andric return ExitLoopMap.lookup(LHS)->getLoopDepth() <
15750b57cec5SDimitry Andric ExitLoopMap.lookup(RHS)->getLoopDepth();
15760b57cec5SDimitry Andric });
15770b57cec5SDimitry Andric
15780b57cec5SDimitry Andric // Populate the existing ExitLoopMap with everything reachable from each
15790b57cec5SDimitry Andric // exit, starting from the inner most exit.
15800b57cec5SDimitry Andric while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
15810b57cec5SDimitry Andric assert(Worklist.empty() && "Didn't clear worklist!");
15820b57cec5SDimitry Andric
15830b57cec5SDimitry Andric BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
15840b57cec5SDimitry Andric Loop *ExitL = ExitLoopMap.lookup(ExitBB);
15850b57cec5SDimitry Andric
15860b57cec5SDimitry Andric // Walk the CFG back until we hit the cloned PH adding everything reachable
15870b57cec5SDimitry Andric // and in the unlooped set to this exit block's loop.
15880b57cec5SDimitry Andric Worklist.push_back(ExitBB);
15890b57cec5SDimitry Andric do {
15900b57cec5SDimitry Andric BasicBlock *BB = Worklist.pop_back_val();
15910b57cec5SDimitry Andric // We can stop recursing at the cloned preheader (if we get there).
15920b57cec5SDimitry Andric if (BB == ClonedPH)
15930b57cec5SDimitry Andric continue;
15940b57cec5SDimitry Andric
15950b57cec5SDimitry Andric for (BasicBlock *PredBB : predecessors(BB)) {
15960b57cec5SDimitry Andric // If this pred has already been moved to our set or is part of some
15970b57cec5SDimitry Andric // (inner) loop, no update needed.
15980b57cec5SDimitry Andric if (!UnloopedBlockSet.erase(PredBB)) {
15990b57cec5SDimitry Andric assert(
16000b57cec5SDimitry Andric (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
16010b57cec5SDimitry Andric "Predecessor not mapped to a loop!");
16020b57cec5SDimitry Andric continue;
16030b57cec5SDimitry Andric }
16040b57cec5SDimitry Andric
16050b57cec5SDimitry Andric // We just insert into the loop set here. We'll add these blocks to the
16060b57cec5SDimitry Andric // exit loop after we build up the set in an order that doesn't rely on
16070b57cec5SDimitry Andric // predecessor order (which in turn relies on use list order).
16080b57cec5SDimitry Andric bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
16090b57cec5SDimitry Andric (void)Inserted;
16100b57cec5SDimitry Andric assert(Inserted && "Should only visit an unlooped block once!");
16110b57cec5SDimitry Andric
16120b57cec5SDimitry Andric // And recurse through to its predecessors.
16130b57cec5SDimitry Andric Worklist.push_back(PredBB);
16140b57cec5SDimitry Andric }
16150b57cec5SDimitry Andric } while (!Worklist.empty());
16160b57cec5SDimitry Andric }
16170b57cec5SDimitry Andric
16180b57cec5SDimitry Andric // Now that the ExitLoopMap gives as mapping for all the non-looping cloned
16190b57cec5SDimitry Andric // blocks to their outer loops, walk the cloned blocks and the cloned exits
16200b57cec5SDimitry Andric // in their original order adding them to the correct loop.
16210b57cec5SDimitry Andric
16220b57cec5SDimitry Andric // We need a stable insertion order. We use the order of the original loop
16230b57cec5SDimitry Andric // order and map into the correct parent loop.
16240b57cec5SDimitry Andric for (auto *BB : llvm::concat<BasicBlock *const>(
1625bdd1243dSDimitry Andric ArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
16260b57cec5SDimitry Andric if (Loop *OuterL = ExitLoopMap.lookup(BB))
16270b57cec5SDimitry Andric OuterL->addBasicBlockToLoop(BB, LI);
16280b57cec5SDimitry Andric
16290b57cec5SDimitry Andric #ifndef NDEBUG
16300b57cec5SDimitry Andric for (auto &BBAndL : ExitLoopMap) {
16310b57cec5SDimitry Andric auto *BB = BBAndL.first;
16320b57cec5SDimitry Andric auto *OuterL = BBAndL.second;
16330b57cec5SDimitry Andric assert(LI.getLoopFor(BB) == OuterL &&
16340b57cec5SDimitry Andric "Failed to put all blocks into outer loops!");
16350b57cec5SDimitry Andric }
16360b57cec5SDimitry Andric #endif
16370b57cec5SDimitry Andric
16380b57cec5SDimitry Andric // Now that all the blocks are placed into the correct containing loop in the
16390b57cec5SDimitry Andric // absence of child loops, find all the potentially cloned child loops and
16400b57cec5SDimitry Andric // clone them into whatever outer loop we placed their header into.
16410b57cec5SDimitry Andric for (Loop *ChildL : OrigL) {
16420b57cec5SDimitry Andric auto *ClonedChildHeader =
16430b57cec5SDimitry Andric cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
16440b57cec5SDimitry Andric if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
16450b57cec5SDimitry Andric continue;
16460b57cec5SDimitry Andric
16470b57cec5SDimitry Andric #ifndef NDEBUG
16480b57cec5SDimitry Andric for (auto *ChildLoopBB : ChildL->blocks())
16490b57cec5SDimitry Andric assert(VMap.count(ChildLoopBB) &&
16500b57cec5SDimitry Andric "Cloned a child loop header but not all of that loops blocks!");
16510b57cec5SDimitry Andric #endif
16520b57cec5SDimitry Andric
16530b57cec5SDimitry Andric NonChildClonedLoops.push_back(cloneLoopNest(
16540b57cec5SDimitry Andric *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
16550b57cec5SDimitry Andric }
16560b57cec5SDimitry Andric }
16570b57cec5SDimitry Andric
16580b57cec5SDimitry Andric static void
deleteDeadClonedBlocks(Loop & L,ArrayRef<BasicBlock * > ExitBlocks,ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,DominatorTree & DT,MemorySSAUpdater * MSSAU)16590b57cec5SDimitry Andric deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
16600b57cec5SDimitry Andric ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
16610b57cec5SDimitry Andric DominatorTree &DT, MemorySSAUpdater *MSSAU) {
16620b57cec5SDimitry Andric // Find all the dead clones, and remove them from their successors.
16630b57cec5SDimitry Andric SmallVector<BasicBlock *, 16> DeadBlocks;
16640b57cec5SDimitry Andric for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1665bdd1243dSDimitry Andric for (const auto &VMap : VMaps)
16660b57cec5SDimitry Andric if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
16670b57cec5SDimitry Andric if (!DT.isReachableFromEntry(ClonedBB)) {
16680b57cec5SDimitry Andric for (BasicBlock *SuccBB : successors(ClonedBB))
16690b57cec5SDimitry Andric SuccBB->removePredecessor(ClonedBB);
16700b57cec5SDimitry Andric DeadBlocks.push_back(ClonedBB);
16710b57cec5SDimitry Andric }
16720b57cec5SDimitry Andric
16730b57cec5SDimitry Andric // Remove all MemorySSA in the dead blocks
16740b57cec5SDimitry Andric if (MSSAU) {
16750b57cec5SDimitry Andric SmallSetVector<BasicBlock *, 8> DeadBlockSet(DeadBlocks.begin(),
16760b57cec5SDimitry Andric DeadBlocks.end());
16770b57cec5SDimitry Andric MSSAU->removeBlocks(DeadBlockSet);
16780b57cec5SDimitry Andric }
16790b57cec5SDimitry Andric
16800b57cec5SDimitry Andric // Drop any remaining references to break cycles.
16810b57cec5SDimitry Andric for (BasicBlock *BB : DeadBlocks)
16820b57cec5SDimitry Andric BB->dropAllReferences();
16830b57cec5SDimitry Andric // Erase them from the IR.
16840b57cec5SDimitry Andric for (BasicBlock *BB : DeadBlocks)
16850b57cec5SDimitry Andric BB->eraseFromParent();
16860b57cec5SDimitry Andric }
16870b57cec5SDimitry Andric
deleteDeadBlocksFromLoop(Loop & L,SmallVectorImpl<BasicBlock * > & ExitBlocks,DominatorTree & DT,LoopInfo & LI,MemorySSAUpdater * MSSAU,ScalarEvolution * SE,LPMUpdater & LoopUpdater)1688*c9157d92SDimitry Andric static void deleteDeadBlocksFromLoop(Loop &L,
16890b57cec5SDimitry Andric SmallVectorImpl<BasicBlock *> &ExitBlocks,
16900b57cec5SDimitry Andric DominatorTree &DT, LoopInfo &LI,
16918c6f6c0cSDimitry Andric MemorySSAUpdater *MSSAU,
1692bdd1243dSDimitry Andric ScalarEvolution *SE,
1693*c9157d92SDimitry Andric LPMUpdater &LoopUpdater) {
16940b57cec5SDimitry Andric // Find all the dead blocks tied to this loop, and remove them from their
16950b57cec5SDimitry Andric // successors.
16960b57cec5SDimitry Andric SmallSetVector<BasicBlock *, 8> DeadBlockSet;
16970b57cec5SDimitry Andric
16980b57cec5SDimitry Andric // Start with loop/exit blocks and get a transitive closure of reachable dead
16990b57cec5SDimitry Andric // blocks.
17000b57cec5SDimitry Andric SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
17010b57cec5SDimitry Andric ExitBlocks.end());
17020b57cec5SDimitry Andric DeathCandidates.append(L.blocks().begin(), L.blocks().end());
17030b57cec5SDimitry Andric while (!DeathCandidates.empty()) {
17040b57cec5SDimitry Andric auto *BB = DeathCandidates.pop_back_val();
17050b57cec5SDimitry Andric if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
17060b57cec5SDimitry Andric for (BasicBlock *SuccBB : successors(BB)) {
17070b57cec5SDimitry Andric SuccBB->removePredecessor(BB);
17080b57cec5SDimitry Andric DeathCandidates.push_back(SuccBB);
17090b57cec5SDimitry Andric }
17100b57cec5SDimitry Andric DeadBlockSet.insert(BB);
17110b57cec5SDimitry Andric }
17120b57cec5SDimitry Andric }
17130b57cec5SDimitry Andric
17140b57cec5SDimitry Andric // Remove all MemorySSA in the dead blocks
17150b57cec5SDimitry Andric if (MSSAU)
17160b57cec5SDimitry Andric MSSAU->removeBlocks(DeadBlockSet);
17170b57cec5SDimitry Andric
17180b57cec5SDimitry Andric // Filter out the dead blocks from the exit blocks list so that it can be
17190b57cec5SDimitry Andric // used in the caller.
17200b57cec5SDimitry Andric llvm::erase_if(ExitBlocks,
17210b57cec5SDimitry Andric [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
17220b57cec5SDimitry Andric
17230b57cec5SDimitry Andric // Walk from this loop up through its parents removing all of the dead blocks.
17240b57cec5SDimitry Andric for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
17250b57cec5SDimitry Andric for (auto *BB : DeadBlockSet)
17260b57cec5SDimitry Andric ParentL->getBlocksSet().erase(BB);
17270b57cec5SDimitry Andric llvm::erase_if(ParentL->getBlocksVector(),
17280b57cec5SDimitry Andric [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
17290b57cec5SDimitry Andric }
17300b57cec5SDimitry Andric
17310b57cec5SDimitry Andric // Now delete the dead child loops. This raw delete will clear them
17320b57cec5SDimitry Andric // recursively.
17330b57cec5SDimitry Andric llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
17340b57cec5SDimitry Andric if (!DeadBlockSet.count(ChildL->getHeader()))
17350b57cec5SDimitry Andric return false;
17360b57cec5SDimitry Andric
17370b57cec5SDimitry Andric assert(llvm::all_of(ChildL->blocks(),
17380b57cec5SDimitry Andric [&](BasicBlock *ChildBB) {
17390b57cec5SDimitry Andric return DeadBlockSet.count(ChildBB);
17400b57cec5SDimitry Andric }) &&
17410b57cec5SDimitry Andric "If the child loop header is dead all blocks in the child loop must "
17420b57cec5SDimitry Andric "be dead as well!");
1743*c9157d92SDimitry Andric LoopUpdater.markLoopAsDeleted(*ChildL, ChildL->getName());
1744bdd1243dSDimitry Andric if (SE)
1745bdd1243dSDimitry Andric SE->forgetBlockAndLoopDispositions();
17460b57cec5SDimitry Andric LI.destroy(ChildL);
17470b57cec5SDimitry Andric return true;
17480b57cec5SDimitry Andric });
17490b57cec5SDimitry Andric
17500b57cec5SDimitry Andric // Remove the loop mappings for the dead blocks and drop all the references
17510b57cec5SDimitry Andric // from these blocks to others to handle cyclic references as we start
17520b57cec5SDimitry Andric // deleting the blocks themselves.
17530b57cec5SDimitry Andric for (auto *BB : DeadBlockSet) {
17540b57cec5SDimitry Andric // Check that the dominator tree has already been updated.
17550b57cec5SDimitry Andric assert(!DT.getNode(BB) && "Should already have cleared domtree!");
17560b57cec5SDimitry Andric LI.changeLoopFor(BB, nullptr);
17575ffd83dbSDimitry Andric // Drop all uses of the instructions to make sure we won't have dangling
17585ffd83dbSDimitry Andric // uses in other blocks.
17595ffd83dbSDimitry Andric for (auto &I : *BB)
17605ffd83dbSDimitry Andric if (!I.use_empty())
176181ad6265SDimitry Andric I.replaceAllUsesWith(PoisonValue::get(I.getType()));
17620b57cec5SDimitry Andric BB->dropAllReferences();
17630b57cec5SDimitry Andric }
17640b57cec5SDimitry Andric
17650b57cec5SDimitry Andric // Actually delete the blocks now that they've been fully unhooked from the
17660b57cec5SDimitry Andric // IR.
17670b57cec5SDimitry Andric for (auto *BB : DeadBlockSet)
17680b57cec5SDimitry Andric BB->eraseFromParent();
17690b57cec5SDimitry Andric }
17700b57cec5SDimitry Andric
17710b57cec5SDimitry Andric /// Recompute the set of blocks in a loop after unswitching.
17720b57cec5SDimitry Andric ///
17730b57cec5SDimitry Andric /// This walks from the original headers predecessors to rebuild the loop. We
17740b57cec5SDimitry Andric /// take advantage of the fact that new blocks can't have been added, and so we
17750b57cec5SDimitry Andric /// filter by the original loop's blocks. This also handles potentially
17760b57cec5SDimitry Andric /// unreachable code that we don't want to explore but might be found examining
17770b57cec5SDimitry Andric /// the predecessors of the header.
17780b57cec5SDimitry Andric ///
17790b57cec5SDimitry Andric /// If the original loop is no longer a loop, this will return an empty set. If
17800b57cec5SDimitry Andric /// it remains a loop, all the blocks within it will be added to the set
17810b57cec5SDimitry Andric /// (including those blocks in inner loops).
recomputeLoopBlockSet(Loop & L,LoopInfo & LI)17820b57cec5SDimitry Andric static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
17830b57cec5SDimitry Andric LoopInfo &LI) {
17840b57cec5SDimitry Andric SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
17850b57cec5SDimitry Andric
17860b57cec5SDimitry Andric auto *PH = L.getLoopPreheader();
17870b57cec5SDimitry Andric auto *Header = L.getHeader();
17880b57cec5SDimitry Andric
17890b57cec5SDimitry Andric // A worklist to use while walking backwards from the header.
17900b57cec5SDimitry Andric SmallVector<BasicBlock *, 16> Worklist;
17910b57cec5SDimitry Andric
17920b57cec5SDimitry Andric // First walk the predecessors of the header to find the backedges. This will
17930b57cec5SDimitry Andric // form the basis of our walk.
17940b57cec5SDimitry Andric for (auto *Pred : predecessors(Header)) {
17950b57cec5SDimitry Andric // Skip the preheader.
17960b57cec5SDimitry Andric if (Pred == PH)
17970b57cec5SDimitry Andric continue;
17980b57cec5SDimitry Andric
17990b57cec5SDimitry Andric // Because the loop was in simplified form, the only non-loop predecessor
18000b57cec5SDimitry Andric // is the preheader.
18010b57cec5SDimitry Andric assert(L.contains(Pred) && "Found a predecessor of the loop header other "
18020b57cec5SDimitry Andric "than the preheader that is not part of the "
18030b57cec5SDimitry Andric "loop!");
18040b57cec5SDimitry Andric
18050b57cec5SDimitry Andric // Insert this block into the loop set and on the first visit and, if it
18060b57cec5SDimitry Andric // isn't the header we're currently walking, put it into the worklist to
18070b57cec5SDimitry Andric // recurse through.
18080b57cec5SDimitry Andric if (LoopBlockSet.insert(Pred).second && Pred != Header)
18090b57cec5SDimitry Andric Worklist.push_back(Pred);
18100b57cec5SDimitry Andric }
18110b57cec5SDimitry Andric
18120b57cec5SDimitry Andric // If no backedges were found, we're done.
18130b57cec5SDimitry Andric if (LoopBlockSet.empty())
18140b57cec5SDimitry Andric return LoopBlockSet;
18150b57cec5SDimitry Andric
18160b57cec5SDimitry Andric // We found backedges, recurse through them to identify the loop blocks.
18170b57cec5SDimitry Andric while (!Worklist.empty()) {
18180b57cec5SDimitry Andric BasicBlock *BB = Worklist.pop_back_val();
18190b57cec5SDimitry Andric assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
18200b57cec5SDimitry Andric
18210b57cec5SDimitry Andric // No need to walk past the header.
18220b57cec5SDimitry Andric if (BB == Header)
18230b57cec5SDimitry Andric continue;
18240b57cec5SDimitry Andric
18250b57cec5SDimitry Andric // Because we know the inner loop structure remains valid we can use the
18260b57cec5SDimitry Andric // loop structure to jump immediately across the entire nested loop.
18270b57cec5SDimitry Andric // Further, because it is in loop simplified form, we can directly jump
18280b57cec5SDimitry Andric // to its preheader afterward.
18290b57cec5SDimitry Andric if (Loop *InnerL = LI.getLoopFor(BB))
18300b57cec5SDimitry Andric if (InnerL != &L) {
18310b57cec5SDimitry Andric assert(L.contains(InnerL) &&
18320b57cec5SDimitry Andric "Should not reach a loop *outside* this loop!");
18330b57cec5SDimitry Andric // The preheader is the only possible predecessor of the loop so
18340b57cec5SDimitry Andric // insert it into the set and check whether it was already handled.
18350b57cec5SDimitry Andric auto *InnerPH = InnerL->getLoopPreheader();
18360b57cec5SDimitry Andric assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
18370b57cec5SDimitry Andric "but not contain the inner loop "
18380b57cec5SDimitry Andric "preheader!");
18390b57cec5SDimitry Andric if (!LoopBlockSet.insert(InnerPH).second)
18400b57cec5SDimitry Andric // The only way to reach the preheader is through the loop body
18410b57cec5SDimitry Andric // itself so if it has been visited the loop is already handled.
18420b57cec5SDimitry Andric continue;
18430b57cec5SDimitry Andric
18440b57cec5SDimitry Andric // Insert all of the blocks (other than those already present) into
18450b57cec5SDimitry Andric // the loop set. We expect at least the block that led us to find the
18460b57cec5SDimitry Andric // inner loop to be in the block set, but we may also have other loop
18470b57cec5SDimitry Andric // blocks if they were already enqueued as predecessors of some other
18480b57cec5SDimitry Andric // outer loop block.
18490b57cec5SDimitry Andric for (auto *InnerBB : InnerL->blocks()) {
18500b57cec5SDimitry Andric if (InnerBB == BB) {
18510b57cec5SDimitry Andric assert(LoopBlockSet.count(InnerBB) &&
18520b57cec5SDimitry Andric "Block should already be in the set!");
18530b57cec5SDimitry Andric continue;
18540b57cec5SDimitry Andric }
18550b57cec5SDimitry Andric
18560b57cec5SDimitry Andric LoopBlockSet.insert(InnerBB);
18570b57cec5SDimitry Andric }
18580b57cec5SDimitry Andric
18590b57cec5SDimitry Andric // Add the preheader to the worklist so we will continue past the
18600b57cec5SDimitry Andric // loop body.
18610b57cec5SDimitry Andric Worklist.push_back(InnerPH);
18620b57cec5SDimitry Andric continue;
18630b57cec5SDimitry Andric }
18640b57cec5SDimitry Andric
18650b57cec5SDimitry Andric // Insert any predecessors that were in the original loop into the new
18660b57cec5SDimitry Andric // set, and if the insert is successful, add them to the worklist.
18670b57cec5SDimitry Andric for (auto *Pred : predecessors(BB))
18680b57cec5SDimitry Andric if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
18690b57cec5SDimitry Andric Worklist.push_back(Pred);
18700b57cec5SDimitry Andric }
18710b57cec5SDimitry Andric
18720b57cec5SDimitry Andric assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
18730b57cec5SDimitry Andric
18740b57cec5SDimitry Andric // We've found all the blocks participating in the loop, return our completed
18750b57cec5SDimitry Andric // set.
18760b57cec5SDimitry Andric return LoopBlockSet;
18770b57cec5SDimitry Andric }
18780b57cec5SDimitry Andric
18790b57cec5SDimitry Andric /// Rebuild a loop after unswitching removes some subset of blocks and edges.
18800b57cec5SDimitry Andric ///
18810b57cec5SDimitry Andric /// The removal may have removed some child loops entirely but cannot have
18820b57cec5SDimitry Andric /// disturbed any remaining child loops. However, they may need to be hoisted
18830b57cec5SDimitry Andric /// to the parent loop (or to be top-level loops). The original loop may be
18840b57cec5SDimitry Andric /// completely removed.
18850b57cec5SDimitry Andric ///
18860b57cec5SDimitry Andric /// The sibling loops resulting from this update are returned. If the original
18870b57cec5SDimitry Andric /// loop remains a valid loop, it will be the first entry in this list with all
18880b57cec5SDimitry Andric /// of the newly sibling loops following it.
18890b57cec5SDimitry Andric ///
18900b57cec5SDimitry Andric /// Returns true if the loop remains a loop after unswitching, and false if it
18910b57cec5SDimitry Andric /// is no longer a loop after unswitching (and should not continue to be
18920b57cec5SDimitry Andric /// referenced).
rebuildLoopAfterUnswitch(Loop & L,ArrayRef<BasicBlock * > ExitBlocks,LoopInfo & LI,SmallVectorImpl<Loop * > & HoistedLoops,ScalarEvolution * SE)18930b57cec5SDimitry Andric static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
18940b57cec5SDimitry Andric LoopInfo &LI,
1895bdd1243dSDimitry Andric SmallVectorImpl<Loop *> &HoistedLoops,
1896bdd1243dSDimitry Andric ScalarEvolution *SE) {
18970b57cec5SDimitry Andric auto *PH = L.getLoopPreheader();
18980b57cec5SDimitry Andric
18990b57cec5SDimitry Andric // Compute the actual parent loop from the exit blocks. Because we may have
19000b57cec5SDimitry Andric // pruned some exits the loop may be different from the original parent.
19010b57cec5SDimitry Andric Loop *ParentL = nullptr;
19020b57cec5SDimitry Andric SmallVector<Loop *, 4> ExitLoops;
19030b57cec5SDimitry Andric SmallVector<BasicBlock *, 4> ExitsInLoops;
19040b57cec5SDimitry Andric ExitsInLoops.reserve(ExitBlocks.size());
19050b57cec5SDimitry Andric for (auto *ExitBB : ExitBlocks)
19060b57cec5SDimitry Andric if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
19070b57cec5SDimitry Andric ExitLoops.push_back(ExitL);
19080b57cec5SDimitry Andric ExitsInLoops.push_back(ExitBB);
19090b57cec5SDimitry Andric if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
19100b57cec5SDimitry Andric ParentL = ExitL;
19110b57cec5SDimitry Andric }
19120b57cec5SDimitry Andric
19130b57cec5SDimitry Andric // Recompute the blocks participating in this loop. This may be empty if it
19140b57cec5SDimitry Andric // is no longer a loop.
19150b57cec5SDimitry Andric auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
19160b57cec5SDimitry Andric
19170b57cec5SDimitry Andric // If we still have a loop, we need to re-set the loop's parent as the exit
19180b57cec5SDimitry Andric // block set changing may have moved it within the loop nest. Note that this
19190b57cec5SDimitry Andric // can only happen when this loop has a parent as it can only hoist the loop
19200b57cec5SDimitry Andric // *up* the nest.
19210b57cec5SDimitry Andric if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
19220b57cec5SDimitry Andric // Remove this loop's (original) blocks from all of the intervening loops.
19230b57cec5SDimitry Andric for (Loop *IL = L.getParentLoop(); IL != ParentL;
19240b57cec5SDimitry Andric IL = IL->getParentLoop()) {
19250b57cec5SDimitry Andric IL->getBlocksSet().erase(PH);
19260b57cec5SDimitry Andric for (auto *BB : L.blocks())
19270b57cec5SDimitry Andric IL->getBlocksSet().erase(BB);
19280b57cec5SDimitry Andric llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
19290b57cec5SDimitry Andric return BB == PH || L.contains(BB);
19300b57cec5SDimitry Andric });
19310b57cec5SDimitry Andric }
19320b57cec5SDimitry Andric
19330b57cec5SDimitry Andric LI.changeLoopFor(PH, ParentL);
19340b57cec5SDimitry Andric L.getParentLoop()->removeChildLoop(&L);
19350b57cec5SDimitry Andric if (ParentL)
19360b57cec5SDimitry Andric ParentL->addChildLoop(&L);
19370b57cec5SDimitry Andric else
19380b57cec5SDimitry Andric LI.addTopLevelLoop(&L);
19390b57cec5SDimitry Andric }
19400b57cec5SDimitry Andric
19410b57cec5SDimitry Andric // Now we update all the blocks which are no longer within the loop.
19420b57cec5SDimitry Andric auto &Blocks = L.getBlocksVector();
19430b57cec5SDimitry Andric auto BlocksSplitI =
19440b57cec5SDimitry Andric LoopBlockSet.empty()
19450b57cec5SDimitry Andric ? Blocks.begin()
19460b57cec5SDimitry Andric : std::stable_partition(
19470b57cec5SDimitry Andric Blocks.begin(), Blocks.end(),
19480b57cec5SDimitry Andric [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
19490b57cec5SDimitry Andric
19500b57cec5SDimitry Andric // Before we erase the list of unlooped blocks, build a set of them.
19510b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
19520b57cec5SDimitry Andric if (LoopBlockSet.empty())
19530b57cec5SDimitry Andric UnloopedBlocks.insert(PH);
19540b57cec5SDimitry Andric
19550b57cec5SDimitry Andric // Now erase these blocks from the loop.
19560b57cec5SDimitry Andric for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
19570b57cec5SDimitry Andric L.getBlocksSet().erase(BB);
19580b57cec5SDimitry Andric Blocks.erase(BlocksSplitI, Blocks.end());
19590b57cec5SDimitry Andric
19600b57cec5SDimitry Andric // Sort the exits in ascending loop depth, we'll work backwards across these
19610b57cec5SDimitry Andric // to process them inside out.
19620b57cec5SDimitry Andric llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
19630b57cec5SDimitry Andric return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
19640b57cec5SDimitry Andric });
19650b57cec5SDimitry Andric
19660b57cec5SDimitry Andric // We'll build up a set for each exit loop.
19670b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
19680b57cec5SDimitry Andric Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
19690b57cec5SDimitry Andric
19700b57cec5SDimitry Andric auto RemoveUnloopedBlocksFromLoop =
19710b57cec5SDimitry Andric [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
19720b57cec5SDimitry Andric for (auto *BB : UnloopedBlocks)
19730b57cec5SDimitry Andric L.getBlocksSet().erase(BB);
19740b57cec5SDimitry Andric llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
19750b57cec5SDimitry Andric return UnloopedBlocks.count(BB);
19760b57cec5SDimitry Andric });
19770b57cec5SDimitry Andric };
19780b57cec5SDimitry Andric
19790b57cec5SDimitry Andric SmallVector<BasicBlock *, 16> Worklist;
19800b57cec5SDimitry Andric while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
19810b57cec5SDimitry Andric assert(Worklist.empty() && "Didn't clear worklist!");
19820b57cec5SDimitry Andric assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
19830b57cec5SDimitry Andric
19840b57cec5SDimitry Andric // Grab the next exit block, in decreasing loop depth order.
19850b57cec5SDimitry Andric BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
19860b57cec5SDimitry Andric Loop &ExitL = *LI.getLoopFor(ExitBB);
19870b57cec5SDimitry Andric assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
19880b57cec5SDimitry Andric
19890b57cec5SDimitry Andric // Erase all of the unlooped blocks from the loops between the previous
19900b57cec5SDimitry Andric // exit loop and this exit loop. This works because the ExitInLoops list is
19910b57cec5SDimitry Andric // sorted in increasing order of loop depth and thus we visit loops in
19920b57cec5SDimitry Andric // decreasing order of loop depth.
19930b57cec5SDimitry Andric for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
19940b57cec5SDimitry Andric RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
19950b57cec5SDimitry Andric
19960b57cec5SDimitry Andric // Walk the CFG back until we hit the cloned PH adding everything reachable
19970b57cec5SDimitry Andric // and in the unlooped set to this exit block's loop.
19980b57cec5SDimitry Andric Worklist.push_back(ExitBB);
19990b57cec5SDimitry Andric do {
20000b57cec5SDimitry Andric BasicBlock *BB = Worklist.pop_back_val();
20010b57cec5SDimitry Andric // We can stop recursing at the cloned preheader (if we get there).
20020b57cec5SDimitry Andric if (BB == PH)
20030b57cec5SDimitry Andric continue;
20040b57cec5SDimitry Andric
20050b57cec5SDimitry Andric for (BasicBlock *PredBB : predecessors(BB)) {
20060b57cec5SDimitry Andric // If this pred has already been moved to our set or is part of some
20070b57cec5SDimitry Andric // (inner) loop, no update needed.
20080b57cec5SDimitry Andric if (!UnloopedBlocks.erase(PredBB)) {
20090b57cec5SDimitry Andric assert((NewExitLoopBlocks.count(PredBB) ||
20100b57cec5SDimitry Andric ExitL.contains(LI.getLoopFor(PredBB))) &&
20110b57cec5SDimitry Andric "Predecessor not in a nested loop (or already visited)!");
20120b57cec5SDimitry Andric continue;
20130b57cec5SDimitry Andric }
20140b57cec5SDimitry Andric
20150b57cec5SDimitry Andric // We just insert into the loop set here. We'll add these blocks to the
20160b57cec5SDimitry Andric // exit loop after we build up the set in a deterministic order rather
20170b57cec5SDimitry Andric // than the predecessor-influenced visit order.
20180b57cec5SDimitry Andric bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
20190b57cec5SDimitry Andric (void)Inserted;
20200b57cec5SDimitry Andric assert(Inserted && "Should only visit an unlooped block once!");
20210b57cec5SDimitry Andric
20220b57cec5SDimitry Andric // And recurse through to its predecessors.
20230b57cec5SDimitry Andric Worklist.push_back(PredBB);
20240b57cec5SDimitry Andric }
20250b57cec5SDimitry Andric } while (!Worklist.empty());
20260b57cec5SDimitry Andric
20270b57cec5SDimitry Andric // If blocks in this exit loop were directly part of the original loop (as
20280b57cec5SDimitry Andric // opposed to a child loop) update the map to point to this exit loop. This
20290b57cec5SDimitry Andric // just updates a map and so the fact that the order is unstable is fine.
20300b57cec5SDimitry Andric for (auto *BB : NewExitLoopBlocks)
20310b57cec5SDimitry Andric if (Loop *BBL = LI.getLoopFor(BB))
20320b57cec5SDimitry Andric if (BBL == &L || !L.contains(BBL))
20330b57cec5SDimitry Andric LI.changeLoopFor(BB, &ExitL);
20340b57cec5SDimitry Andric
20350b57cec5SDimitry Andric // We will remove the remaining unlooped blocks from this loop in the next
20360b57cec5SDimitry Andric // iteration or below.
20370b57cec5SDimitry Andric NewExitLoopBlocks.clear();
20380b57cec5SDimitry Andric }
20390b57cec5SDimitry Andric
20400b57cec5SDimitry Andric // Any remaining unlooped blocks are no longer part of any loop unless they
20410b57cec5SDimitry Andric // are part of some child loop.
20420b57cec5SDimitry Andric for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
20430b57cec5SDimitry Andric RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
20440b57cec5SDimitry Andric for (auto *BB : UnloopedBlocks)
20450b57cec5SDimitry Andric if (Loop *BBL = LI.getLoopFor(BB))
20460b57cec5SDimitry Andric if (BBL == &L || !L.contains(BBL))
20470b57cec5SDimitry Andric LI.changeLoopFor(BB, nullptr);
20480b57cec5SDimitry Andric
20490b57cec5SDimitry Andric // Sink all the child loops whose headers are no longer in the loop set to
20500b57cec5SDimitry Andric // the parent (or to be top level loops). We reach into the loop and directly
20510b57cec5SDimitry Andric // update its subloop vector to make this batch update efficient.
20520b57cec5SDimitry Andric auto &SubLoops = L.getSubLoopsVector();
20530b57cec5SDimitry Andric auto SubLoopsSplitI =
20540b57cec5SDimitry Andric LoopBlockSet.empty()
20550b57cec5SDimitry Andric ? SubLoops.begin()
20560b57cec5SDimitry Andric : std::stable_partition(
20570b57cec5SDimitry Andric SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
20580b57cec5SDimitry Andric return LoopBlockSet.count(SubL->getHeader());
20590b57cec5SDimitry Andric });
20600b57cec5SDimitry Andric for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
20610b57cec5SDimitry Andric HoistedLoops.push_back(HoistedL);
20620b57cec5SDimitry Andric HoistedL->setParentLoop(nullptr);
20630b57cec5SDimitry Andric
20640b57cec5SDimitry Andric // To compute the new parent of this hoisted loop we look at where we
20650b57cec5SDimitry Andric // placed the preheader above. We can't lookup the header itself because we
20660b57cec5SDimitry Andric // retained the mapping from the header to the hoisted loop. But the
20670b57cec5SDimitry Andric // preheader and header should have the exact same new parent computed
20680b57cec5SDimitry Andric // based on the set of exit blocks from the original loop as the preheader
20690b57cec5SDimitry Andric // is a predecessor of the header and so reached in the reverse walk. And
20700b57cec5SDimitry Andric // because the loops were all in simplified form the preheader of the
20710b57cec5SDimitry Andric // hoisted loop can't be part of some *other* loop.
20720b57cec5SDimitry Andric if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
20730b57cec5SDimitry Andric NewParentL->addChildLoop(HoistedL);
20740b57cec5SDimitry Andric else
20750b57cec5SDimitry Andric LI.addTopLevelLoop(HoistedL);
20760b57cec5SDimitry Andric }
20770b57cec5SDimitry Andric SubLoops.erase(SubLoopsSplitI, SubLoops.end());
20780b57cec5SDimitry Andric
20790b57cec5SDimitry Andric // Actually delete the loop if nothing remained within it.
20800b57cec5SDimitry Andric if (Blocks.empty()) {
20810b57cec5SDimitry Andric assert(SubLoops.empty() &&
20820b57cec5SDimitry Andric "Failed to remove all subloops from the original loop!");
20830b57cec5SDimitry Andric if (Loop *ParentL = L.getParentLoop())
20840b57cec5SDimitry Andric ParentL->removeChildLoop(llvm::find(*ParentL, &L));
20850b57cec5SDimitry Andric else
20860b57cec5SDimitry Andric LI.removeLoop(llvm::find(LI, &L));
2087*c9157d92SDimitry Andric // markLoopAsDeleted for L should be triggered by the caller (it is
2088*c9157d92SDimitry Andric // typically done within postUnswitch).
2089bdd1243dSDimitry Andric if (SE)
2090bdd1243dSDimitry Andric SE->forgetBlockAndLoopDispositions();
20910b57cec5SDimitry Andric LI.destroy(&L);
20920b57cec5SDimitry Andric return false;
20930b57cec5SDimitry Andric }
20940b57cec5SDimitry Andric
20950b57cec5SDimitry Andric return true;
20960b57cec5SDimitry Andric }
20970b57cec5SDimitry Andric
20980b57cec5SDimitry Andric /// Helper to visit a dominator subtree, invoking a callable on each node.
20990b57cec5SDimitry Andric ///
21000b57cec5SDimitry Andric /// Returning false at any point will stop walking past that node of the tree.
21010b57cec5SDimitry Andric template <typename CallableT>
visitDomSubTree(DominatorTree & DT,BasicBlock * BB,CallableT Callable)21020b57cec5SDimitry Andric void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
21030b57cec5SDimitry Andric SmallVector<DomTreeNode *, 4> DomWorklist;
21040b57cec5SDimitry Andric DomWorklist.push_back(DT[BB]);
21050b57cec5SDimitry Andric #ifndef NDEBUG
21060b57cec5SDimitry Andric SmallPtrSet<DomTreeNode *, 4> Visited;
21070b57cec5SDimitry Andric Visited.insert(DT[BB]);
21080b57cec5SDimitry Andric #endif
21090b57cec5SDimitry Andric do {
21100b57cec5SDimitry Andric DomTreeNode *N = DomWorklist.pop_back_val();
21110b57cec5SDimitry Andric
21120b57cec5SDimitry Andric // Visit this node.
21130b57cec5SDimitry Andric if (!Callable(N->getBlock()))
21140b57cec5SDimitry Andric continue;
21150b57cec5SDimitry Andric
21160b57cec5SDimitry Andric // Accumulate the child nodes.
21170b57cec5SDimitry Andric for (DomTreeNode *ChildN : *N) {
21180b57cec5SDimitry Andric assert(Visited.insert(ChildN).second &&
21190b57cec5SDimitry Andric "Cannot visit a node twice when walking a tree!");
21200b57cec5SDimitry Andric DomWorklist.push_back(ChildN);
21210b57cec5SDimitry Andric }
21220b57cec5SDimitry Andric } while (!DomWorklist.empty());
21230b57cec5SDimitry Andric }
21240b57cec5SDimitry Andric
postUnswitch(Loop & L,LPMUpdater & U,StringRef LoopName,bool CurrentLoopValid,bool PartiallyInvariant,bool InjectedCondition,ArrayRef<Loop * > NewLoops)2125*c9157d92SDimitry Andric void postUnswitch(Loop &L, LPMUpdater &U, StringRef LoopName,
2126*c9157d92SDimitry Andric bool CurrentLoopValid, bool PartiallyInvariant,
2127*c9157d92SDimitry Andric bool InjectedCondition, ArrayRef<Loop *> NewLoops) {
2128*c9157d92SDimitry Andric // If we did a non-trivial unswitch, we have added new (cloned) loops.
2129*c9157d92SDimitry Andric if (!NewLoops.empty())
2130*c9157d92SDimitry Andric U.addSiblingLoops(NewLoops);
2131*c9157d92SDimitry Andric
2132*c9157d92SDimitry Andric // If the current loop remains valid, we should revisit it to catch any
2133*c9157d92SDimitry Andric // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2134*c9157d92SDimitry Andric if (CurrentLoopValid) {
2135*c9157d92SDimitry Andric if (PartiallyInvariant) {
2136*c9157d92SDimitry Andric // Mark the new loop as partially unswitched, to avoid unswitching on
2137*c9157d92SDimitry Andric // the same condition again.
2138*c9157d92SDimitry Andric auto &Context = L.getHeader()->getContext();
2139*c9157d92SDimitry Andric MDNode *DisableUnswitchMD = MDNode::get(
2140*c9157d92SDimitry Andric Context,
2141*c9157d92SDimitry Andric MDString::get(Context, "llvm.loop.unswitch.partial.disable"));
2142*c9157d92SDimitry Andric MDNode *NewLoopID = makePostTransformationMetadata(
2143*c9157d92SDimitry Andric Context, L.getLoopID(), {"llvm.loop.unswitch.partial"},
2144*c9157d92SDimitry Andric {DisableUnswitchMD});
2145*c9157d92SDimitry Andric L.setLoopID(NewLoopID);
2146*c9157d92SDimitry Andric } else if (InjectedCondition) {
2147*c9157d92SDimitry Andric // Do the same for injection of invariant conditions.
2148*c9157d92SDimitry Andric auto &Context = L.getHeader()->getContext();
2149*c9157d92SDimitry Andric MDNode *DisableUnswitchMD = MDNode::get(
2150*c9157d92SDimitry Andric Context,
2151*c9157d92SDimitry Andric MDString::get(Context, "llvm.loop.unswitch.injection.disable"));
2152*c9157d92SDimitry Andric MDNode *NewLoopID = makePostTransformationMetadata(
2153*c9157d92SDimitry Andric Context, L.getLoopID(), {"llvm.loop.unswitch.injection"},
2154*c9157d92SDimitry Andric {DisableUnswitchMD});
2155*c9157d92SDimitry Andric L.setLoopID(NewLoopID);
2156*c9157d92SDimitry Andric } else
2157*c9157d92SDimitry Andric U.revisitCurrentLoop();
2158*c9157d92SDimitry Andric } else
2159*c9157d92SDimitry Andric U.markLoopAsDeleted(L, LoopName);
2160*c9157d92SDimitry Andric }
2161*c9157d92SDimitry Andric
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)21620b57cec5SDimitry Andric static void unswitchNontrivialInvariants(
21630b57cec5SDimitry Andric Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
2164bdd1243dSDimitry Andric IVConditionInfo &PartialIVInfo, DominatorTree &DT, LoopInfo &LI,
2165*c9157d92SDimitry Andric AssumptionCache &AC, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
2166*c9157d92SDimitry Andric LPMUpdater &LoopUpdater, bool InsertFreeze, bool InjectedCondition) {
21670b57cec5SDimitry Andric auto *ParentBB = TI.getParent();
21680b57cec5SDimitry Andric BranchInst *BI = dyn_cast<BranchInst>(&TI);
21690b57cec5SDimitry Andric SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
21700b57cec5SDimitry Andric
2171*c9157d92SDimitry Andric // Save the current loop name in a variable so that we can report it even
2172*c9157d92SDimitry Andric // after it has been deleted.
2173*c9157d92SDimitry Andric std::string LoopName(L.getName());
2174*c9157d92SDimitry Andric
21750b57cec5SDimitry Andric // We can only unswitch switches, conditional branches with an invariant
2176fe6060f1SDimitry Andric // condition, or combining invariant conditions with an instruction or
2177fe6060f1SDimitry Andric // partially invariant instructions.
21788bcb0991SDimitry Andric assert((SI || (BI && BI->isConditional())) &&
21790b57cec5SDimitry Andric "Can only unswitch switches and conditional branch!");
2180fe6060f1SDimitry Andric bool PartiallyInvariant = !PartialIVInfo.InstToDuplicate.empty();
2181fe6060f1SDimitry Andric bool FullUnswitch =
218281ad6265SDimitry Andric SI || (skipTrivialSelect(BI->getCondition()) == Invariants[0] &&
218381ad6265SDimitry Andric !PartiallyInvariant);
21840b57cec5SDimitry Andric if (FullUnswitch)
21850b57cec5SDimitry Andric assert(Invariants.size() == 1 &&
21860b57cec5SDimitry Andric "Cannot have other invariants with full unswitching!");
21870b57cec5SDimitry Andric else
218881ad6265SDimitry Andric assert(isa<Instruction>(skipTrivialSelect(BI->getCondition())) &&
21890b57cec5SDimitry Andric "Partial unswitching requires an instruction as the condition!");
21900b57cec5SDimitry Andric
21910b57cec5SDimitry Andric if (MSSAU && VerifyMemorySSA)
21920b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
21930b57cec5SDimitry Andric
21940b57cec5SDimitry Andric // Constant and BBs tracking the cloned and continuing successor. When we are
21950b57cec5SDimitry Andric // unswitching the entire condition, this can just be trivially chosen to
21960b57cec5SDimitry Andric // unswitch towards `true`. However, when we are unswitching a set of
2197fe6060f1SDimitry Andric // invariants combined with `and` or `or` or partially invariant instructions,
2198fe6060f1SDimitry Andric // the combining operation determines the best direction to unswitch: we want
2199fe6060f1SDimitry Andric // to unswitch the direction that will collapse the branch.
22000b57cec5SDimitry Andric bool Direction = true;
22010b57cec5SDimitry Andric int ClonedSucc = 0;
22020b57cec5SDimitry Andric if (!FullUnswitch) {
220381ad6265SDimitry Andric Value *Cond = skipTrivialSelect(BI->getCondition());
2204fe6060f1SDimitry Andric (void)Cond;
2205fe6060f1SDimitry Andric assert(((match(Cond, m_LogicalAnd()) ^ match(Cond, m_LogicalOr())) ||
2206fe6060f1SDimitry Andric PartiallyInvariant) &&
2207fe6060f1SDimitry Andric "Only `or`, `and`, an `select`, partially invariant instructions "
2208fe6060f1SDimitry Andric "can combine invariants being unswitched.");
220981ad6265SDimitry Andric if (!match(Cond, m_LogicalOr())) {
221081ad6265SDimitry Andric if (match(Cond, m_LogicalAnd()) ||
2211fe6060f1SDimitry Andric (PartiallyInvariant && !PartialIVInfo.KnownValue->isOneValue())) {
22120b57cec5SDimitry Andric Direction = false;
22130b57cec5SDimitry Andric ClonedSucc = 1;
22140b57cec5SDimitry Andric }
22150b57cec5SDimitry Andric }
2216fe6060f1SDimitry Andric }
22170b57cec5SDimitry Andric
22180b57cec5SDimitry Andric BasicBlock *RetainedSuccBB =
22190b57cec5SDimitry Andric BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
22200b57cec5SDimitry Andric SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
22210b57cec5SDimitry Andric if (BI)
22220b57cec5SDimitry Andric UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
22230b57cec5SDimitry Andric else
22240b57cec5SDimitry Andric for (auto Case : SI->cases())
22250b57cec5SDimitry Andric if (Case.getCaseSuccessor() != RetainedSuccBB)
22260b57cec5SDimitry Andric UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
22270b57cec5SDimitry Andric
22280b57cec5SDimitry Andric assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
22290b57cec5SDimitry Andric "Should not unswitch the same successor we are retaining!");
22300b57cec5SDimitry Andric
22310b57cec5SDimitry Andric // The branch should be in this exact loop. Any inner loop's invariant branch
22320b57cec5SDimitry Andric // should be handled by unswitching that inner loop. The caller of this
22330b57cec5SDimitry Andric // routine should filter out any candidates that remain (but were skipped for
22340b57cec5SDimitry Andric // whatever reason).
22350b57cec5SDimitry Andric assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
22360b57cec5SDimitry Andric
22370b57cec5SDimitry Andric // Compute the parent loop now before we start hacking on things.
22380b57cec5SDimitry Andric Loop *ParentL = L.getParentLoop();
22390b57cec5SDimitry Andric // Get blocks in RPO order for MSSA update, before changing the CFG.
22400b57cec5SDimitry Andric LoopBlocksRPO LBRPO(&L);
22410b57cec5SDimitry Andric if (MSSAU)
22420b57cec5SDimitry Andric LBRPO.perform(&LI);
22430b57cec5SDimitry Andric
22440b57cec5SDimitry Andric // Compute the outer-most loop containing one of our exit blocks. This is the
22450b57cec5SDimitry Andric // furthest up our loopnest which can be mutated, which we will use below to
22460b57cec5SDimitry Andric // update things.
22470b57cec5SDimitry Andric Loop *OuterExitL = &L;
2248bdd1243dSDimitry Andric SmallVector<BasicBlock *, 4> ExitBlocks;
2249bdd1243dSDimitry Andric L.getUniqueExitBlocks(ExitBlocks);
22500b57cec5SDimitry Andric for (auto *ExitBB : ExitBlocks) {
2251fe013be4SDimitry Andric // ExitBB can be an exit block for several levels in the loop nest. Make
2252fe013be4SDimitry Andric // sure we find the top most.
2253fe013be4SDimitry Andric Loop *NewOuterExitL = getTopMostExitingLoop(ExitBB, LI);
22540b57cec5SDimitry Andric if (!NewOuterExitL) {
22550b57cec5SDimitry Andric // We exited the entire nest with this block, so we're done.
22560b57cec5SDimitry Andric OuterExitL = nullptr;
22570b57cec5SDimitry Andric break;
22580b57cec5SDimitry Andric }
22590b57cec5SDimitry Andric if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
22600b57cec5SDimitry Andric OuterExitL = NewOuterExitL;
22610b57cec5SDimitry Andric }
22620b57cec5SDimitry Andric
22630b57cec5SDimitry Andric // At this point, we're definitely going to unswitch something so invalidate
22640b57cec5SDimitry Andric // any cached information in ScalarEvolution for the outer most loop
22650b57cec5SDimitry Andric // containing an exit block and all nested loops.
22660b57cec5SDimitry Andric if (SE) {
22670b57cec5SDimitry Andric if (OuterExitL)
22680b57cec5SDimitry Andric SE->forgetLoop(OuterExitL);
22690b57cec5SDimitry Andric else
22700b57cec5SDimitry Andric SE->forgetTopmostLoop(&L);
2271bdd1243dSDimitry Andric SE->forgetBlockAndLoopDispositions();
22720b57cec5SDimitry Andric }
22730b57cec5SDimitry Andric
22740b57cec5SDimitry Andric // If the edge from this terminator to a successor dominates that successor,
22750b57cec5SDimitry Andric // store a map from each block in its dominator subtree to it. This lets us
22760b57cec5SDimitry Andric // tell when cloning for a particular successor if a block is dominated by
22770b57cec5SDimitry Andric // some *other* successor with a single data structure. We use this to
22780b57cec5SDimitry Andric // significantly reduce cloning.
22790b57cec5SDimitry Andric SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
2280bdd1243dSDimitry Andric for (auto *SuccBB : llvm::concat<BasicBlock *const>(ArrayRef(RetainedSuccBB),
2281bdd1243dSDimitry Andric UnswitchedSuccBBs))
22820b57cec5SDimitry Andric if (SuccBB->getUniquePredecessor() ||
22830b57cec5SDimitry Andric llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
22840b57cec5SDimitry Andric return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
22850b57cec5SDimitry Andric }))
22860b57cec5SDimitry Andric visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
22870b57cec5SDimitry Andric DominatingSucc[BB] = SuccBB;
22880b57cec5SDimitry Andric return true;
22890b57cec5SDimitry Andric });
22900b57cec5SDimitry Andric
22910b57cec5SDimitry Andric // Split the preheader, so that we know that there is a safe place to insert
22920b57cec5SDimitry Andric // the conditional branch. We will change the preheader to have a conditional
22930b57cec5SDimitry Andric // branch on LoopCond. The original preheader will become the split point
22940b57cec5SDimitry Andric // between the unswitched versions, and we will have a new preheader for the
22950b57cec5SDimitry Andric // original loop.
22960b57cec5SDimitry Andric BasicBlock *SplitBB = L.getLoopPreheader();
22970b57cec5SDimitry Andric BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
22980b57cec5SDimitry Andric
22990b57cec5SDimitry Andric // Keep track of the dominator tree updates needed.
23000b57cec5SDimitry Andric SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
23010b57cec5SDimitry Andric
23020b57cec5SDimitry Andric // Clone the loop for each unswitched successor.
23030b57cec5SDimitry Andric SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
23040b57cec5SDimitry Andric VMaps.reserve(UnswitchedSuccBBs.size());
23050b57cec5SDimitry Andric SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
23060b57cec5SDimitry Andric for (auto *SuccBB : UnswitchedSuccBBs) {
23070b57cec5SDimitry Andric VMaps.emplace_back(new ValueToValueMapTy());
23080b57cec5SDimitry Andric ClonedPHs[SuccBB] = buildClonedLoopBlocks(
23090b57cec5SDimitry Andric L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2310bdd1243dSDimitry Andric DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU, SE);
23110b57cec5SDimitry Andric }
23120b57cec5SDimitry Andric
2313e8d8bef9SDimitry Andric // Drop metadata if we may break its semantics by moving this instr into the
2314e8d8bef9SDimitry Andric // split block.
2315e8d8bef9SDimitry Andric if (TI.getMetadata(LLVMContext::MD_make_implicit)) {
2316e8d8bef9SDimitry Andric if (DropNonTrivialImplicitNullChecks)
2317e8d8bef9SDimitry Andric // Do not spend time trying to understand if we can keep it, just drop it
2318e8d8bef9SDimitry Andric // to save compile time.
2319e8d8bef9SDimitry Andric TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
2320e8d8bef9SDimitry Andric else {
2321e8d8bef9SDimitry Andric // It is only legal to preserve make.implicit metadata if we are
2322e8d8bef9SDimitry Andric // guaranteed no reach implicit null check after following this branch.
2323e8d8bef9SDimitry Andric ICFLoopSafetyInfo SafetyInfo;
2324e8d8bef9SDimitry Andric SafetyInfo.computeLoopSafetyInfo(&L);
2325e8d8bef9SDimitry Andric if (!SafetyInfo.isGuaranteedToExecute(TI, &DT, &L))
2326e8d8bef9SDimitry Andric TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
2327e8d8bef9SDimitry Andric }
2328e8d8bef9SDimitry Andric }
2329e8d8bef9SDimitry Andric
23300b57cec5SDimitry Andric // The stitching of the branched code back together depends on whether we're
23310b57cec5SDimitry Andric // doing full unswitching or not with the exception that we always want to
23320b57cec5SDimitry Andric // nuke the initial terminator placed in the split block.
23330b57cec5SDimitry Andric SplitBB->getTerminator()->eraseFromParent();
23340b57cec5SDimitry Andric if (FullUnswitch) {
23350b57cec5SDimitry Andric // Splice the terminator from the original loop and rewrite its
23360b57cec5SDimitry Andric // successors.
2337*c9157d92SDimitry Andric TI.moveBefore(*SplitBB, SplitBB->end());
23380b57cec5SDimitry Andric
23390b57cec5SDimitry Andric // Keep a clone of the terminator for MSSA updates.
23400b57cec5SDimitry Andric Instruction *NewTI = TI.clone();
2341bdd1243dSDimitry Andric NewTI->insertInto(ParentBB, ParentBB->end());
23420b57cec5SDimitry Andric
23430b57cec5SDimitry Andric // First wire up the moved terminator to the preheaders.
23440b57cec5SDimitry Andric if (BI) {
23450b57cec5SDimitry Andric BasicBlock *ClonedPH = ClonedPHs.begin()->second;
23460b57cec5SDimitry Andric BI->setSuccessor(ClonedSucc, ClonedPH);
23470b57cec5SDimitry Andric BI->setSuccessor(1 - ClonedSucc, LoopPH);
2348fe013be4SDimitry Andric Value *Cond = skipTrivialSelect(BI->getCondition());
2349bdd1243dSDimitry Andric if (InsertFreeze)
2350fe013be4SDimitry Andric Cond = new FreezeInst(
2351fe013be4SDimitry Andric Cond, Cond->getName() + ".fr", BI);
2352fe013be4SDimitry Andric BI->setCondition(Cond);
23530b57cec5SDimitry Andric DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
23540b57cec5SDimitry Andric } else {
23550b57cec5SDimitry Andric assert(SI && "Must either be a branch or switch!");
23560b57cec5SDimitry Andric
23570b57cec5SDimitry Andric // Walk the cases and directly update their successors.
23580b57cec5SDimitry Andric assert(SI->getDefaultDest() == RetainedSuccBB &&
23590b57cec5SDimitry Andric "Not retaining default successor!");
23600b57cec5SDimitry Andric SI->setDefaultDest(LoopPH);
2361bdd1243dSDimitry Andric for (const auto &Case : SI->cases())
23620b57cec5SDimitry Andric if (Case.getCaseSuccessor() == RetainedSuccBB)
23630b57cec5SDimitry Andric Case.setSuccessor(LoopPH);
23640b57cec5SDimitry Andric else
23650b57cec5SDimitry Andric Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
23660b57cec5SDimitry Andric
2367bdd1243dSDimitry Andric if (InsertFreeze)
2368bdd1243dSDimitry Andric SI->setCondition(new FreezeInst(
2369fe013be4SDimitry Andric SI->getCondition(), SI->getCondition()->getName() + ".fr", SI));
2370bdd1243dSDimitry Andric
23710b57cec5SDimitry Andric // We need to use the set to populate domtree updates as even when there
23720b57cec5SDimitry Andric // are multiple cases pointing at the same successor we only want to
23730b57cec5SDimitry Andric // remove and insert one edge in the domtree.
23740b57cec5SDimitry Andric for (BasicBlock *SuccBB : UnswitchedSuccBBs)
23750b57cec5SDimitry Andric DTUpdates.push_back(
23760b57cec5SDimitry Andric {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
23770b57cec5SDimitry Andric }
23780b57cec5SDimitry Andric
23790b57cec5SDimitry Andric if (MSSAU) {
23800b57cec5SDimitry Andric DT.applyUpdates(DTUpdates);
23810b57cec5SDimitry Andric DTUpdates.clear();
23820b57cec5SDimitry Andric
23830b57cec5SDimitry Andric // Remove all but one edge to the retained block and all unswitched
23840b57cec5SDimitry Andric // blocks. This is to avoid having duplicate entries in the cloned Phis,
23850b57cec5SDimitry Andric // when we know we only keep a single edge for each case.
23860b57cec5SDimitry Andric MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
23870b57cec5SDimitry Andric for (BasicBlock *SuccBB : UnswitchedSuccBBs)
23880b57cec5SDimitry Andric MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
23890b57cec5SDimitry Andric
23900b57cec5SDimitry Andric for (auto &VMap : VMaps)
23910b57cec5SDimitry Andric MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
23920b57cec5SDimitry Andric /*IgnoreIncomingWithNoClones=*/true);
23930b57cec5SDimitry Andric MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
23940b57cec5SDimitry Andric
23950b57cec5SDimitry Andric // Remove all edges to unswitched blocks.
23960b57cec5SDimitry Andric for (BasicBlock *SuccBB : UnswitchedSuccBBs)
23970b57cec5SDimitry Andric MSSAU->removeEdge(ParentBB, SuccBB);
23980b57cec5SDimitry Andric }
23990b57cec5SDimitry Andric
24000b57cec5SDimitry Andric // Now unhook the successor relationship as we'll be replacing
24010b57cec5SDimitry Andric // the terminator with a direct branch. This is much simpler for branches
24020b57cec5SDimitry Andric // than switches so we handle those first.
24030b57cec5SDimitry Andric if (BI) {
24040b57cec5SDimitry Andric // Remove the parent as a predecessor of the unswitched successor.
24050b57cec5SDimitry Andric assert(UnswitchedSuccBBs.size() == 1 &&
24060b57cec5SDimitry Andric "Only one possible unswitched block for a branch!");
24070b57cec5SDimitry Andric BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
24080b57cec5SDimitry Andric UnswitchedSuccBB->removePredecessor(ParentBB,
24090b57cec5SDimitry Andric /*KeepOneInputPHIs*/ true);
24100b57cec5SDimitry Andric DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
24110b57cec5SDimitry Andric } else {
24120b57cec5SDimitry Andric // Note that we actually want to remove the parent block as a predecessor
24130b57cec5SDimitry Andric // of *every* case successor. The case successor is either unswitched,
24140b57cec5SDimitry Andric // completely eliminating an edge from the parent to that successor, or it
24150b57cec5SDimitry Andric // is a duplicate edge to the retained successor as the retained successor
24160b57cec5SDimitry Andric // is always the default successor and as we'll replace this with a direct
24170b57cec5SDimitry Andric // branch we no longer need the duplicate entries in the PHI nodes.
24180b57cec5SDimitry Andric SwitchInst *NewSI = cast<SwitchInst>(NewTI);
24190b57cec5SDimitry Andric assert(NewSI->getDefaultDest() == RetainedSuccBB &&
24200b57cec5SDimitry Andric "Not retaining default successor!");
2421bdd1243dSDimitry Andric for (const auto &Case : NewSI->cases())
24220b57cec5SDimitry Andric Case.getCaseSuccessor()->removePredecessor(
24230b57cec5SDimitry Andric ParentBB,
24240b57cec5SDimitry Andric /*KeepOneInputPHIs*/ true);
24250b57cec5SDimitry Andric
24260b57cec5SDimitry Andric // We need to use the set to populate domtree updates as even when there
24270b57cec5SDimitry Andric // are multiple cases pointing at the same successor we only want to
24280b57cec5SDimitry Andric // remove and insert one edge in the domtree.
24290b57cec5SDimitry Andric for (BasicBlock *SuccBB : UnswitchedSuccBBs)
24300b57cec5SDimitry Andric DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
24310b57cec5SDimitry Andric }
24320b57cec5SDimitry Andric
24330b57cec5SDimitry Andric // After MSSAU update, remove the cloned terminator instruction NewTI.
24340b57cec5SDimitry Andric ParentBB->getTerminator()->eraseFromParent();
24350b57cec5SDimitry Andric
24360b57cec5SDimitry Andric // Create a new unconditional branch to the continuing block (as opposed to
24370b57cec5SDimitry Andric // the one cloned).
24380b57cec5SDimitry Andric BranchInst::Create(RetainedSuccBB, ParentBB);
24390b57cec5SDimitry Andric } else {
24400b57cec5SDimitry Andric assert(BI && "Only branches have partial unswitching.");
24410b57cec5SDimitry Andric assert(UnswitchedSuccBBs.size() == 1 &&
24420b57cec5SDimitry Andric "Only one possible unswitched block for a branch!");
24430b57cec5SDimitry Andric BasicBlock *ClonedPH = ClonedPHs.begin()->second;
24440b57cec5SDimitry Andric // When doing a partial unswitch, we have to do a bit more work to build up
24450b57cec5SDimitry Andric // the branch in the split block.
2446fe6060f1SDimitry Andric if (PartiallyInvariant)
2447fe6060f1SDimitry Andric buildPartialInvariantUnswitchConditionalBranch(
2448fe6060f1SDimitry Andric *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH, L, MSSAU);
244981ad6265SDimitry Andric else {
245081ad6265SDimitry Andric buildPartialUnswitchConditionalBranch(
245181ad6265SDimitry Andric *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH,
245281ad6265SDimitry Andric FreezeLoopUnswitchCond, BI, &AC, DT);
245381ad6265SDimitry Andric }
24540b57cec5SDimitry Andric DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
24558bcb0991SDimitry Andric
24568bcb0991SDimitry Andric if (MSSAU) {
24578bcb0991SDimitry Andric DT.applyUpdates(DTUpdates);
24588bcb0991SDimitry Andric DTUpdates.clear();
24598bcb0991SDimitry Andric
24608bcb0991SDimitry Andric // Perform MSSA cloning updates.
24618bcb0991SDimitry Andric for (auto &VMap : VMaps)
24628bcb0991SDimitry Andric MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
24638bcb0991SDimitry Andric /*IgnoreIncomingWithNoClones=*/true);
24648bcb0991SDimitry Andric MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
24658bcb0991SDimitry Andric }
24660b57cec5SDimitry Andric }
24670b57cec5SDimitry Andric
24680b57cec5SDimitry Andric // Apply the updates accumulated above to get an up-to-date dominator tree.
24690b57cec5SDimitry Andric DT.applyUpdates(DTUpdates);
24700b57cec5SDimitry Andric
24710b57cec5SDimitry Andric // Now that we have an accurate dominator tree, first delete the dead cloned
24720b57cec5SDimitry Andric // blocks so that we can accurately build any cloned loops. It is important to
24730b57cec5SDimitry Andric // not delete the blocks from the original loop yet because we still want to
24740b57cec5SDimitry Andric // reference the original loop to understand the cloned loop's structure.
24750b57cec5SDimitry Andric deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
24760b57cec5SDimitry Andric
24770b57cec5SDimitry Andric // Build the cloned loop structure itself. This may be substantially
24780b57cec5SDimitry Andric // different from the original structure due to the simplified CFG. This also
24790b57cec5SDimitry Andric // handles inserting all the cloned blocks into the correct loops.
24800b57cec5SDimitry Andric SmallVector<Loop *, 4> NonChildClonedLoops;
24810b57cec5SDimitry Andric for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
24820b57cec5SDimitry Andric buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
24830b57cec5SDimitry Andric
24840b57cec5SDimitry Andric // Now that our cloned loops have been built, we can update the original loop.
24850b57cec5SDimitry Andric // First we delete the dead blocks from it and then we rebuild the loop
24860b57cec5SDimitry Andric // structure taking these deletions into account.
2487*c9157d92SDimitry Andric deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU, SE, LoopUpdater);
24880b57cec5SDimitry Andric
24890b57cec5SDimitry Andric if (MSSAU && VerifyMemorySSA)
24900b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
24910b57cec5SDimitry Andric
24920b57cec5SDimitry Andric SmallVector<Loop *, 4> HoistedLoops;
2493bdd1243dSDimitry Andric bool IsStillLoop =
2494bdd1243dSDimitry Andric rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops, SE);
24950b57cec5SDimitry Andric
24960b57cec5SDimitry Andric if (MSSAU && VerifyMemorySSA)
24970b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
24980b57cec5SDimitry Andric
24990b57cec5SDimitry Andric // This transformation has a high risk of corrupting the dominator tree, and
25000b57cec5SDimitry Andric // the below steps to rebuild loop structures will result in hard to debug
25010b57cec5SDimitry Andric // errors in that case so verify that the dominator tree is sane first.
25020b57cec5SDimitry Andric // FIXME: Remove this when the bugs stop showing up and rely on existing
25030b57cec5SDimitry Andric // verification steps.
25040b57cec5SDimitry Andric assert(DT.verify(DominatorTree::VerificationLevel::Fast));
25050b57cec5SDimitry Andric
2506fe6060f1SDimitry Andric if (BI && !PartiallyInvariant) {
25070b57cec5SDimitry Andric // If we unswitched a branch which collapses the condition to a known
25080b57cec5SDimitry Andric // constant we want to replace all the uses of the invariants within both
25090b57cec5SDimitry Andric // the original and cloned blocks. We do this here so that we can use the
25100b57cec5SDimitry Andric // now updated dominator tree to identify which side the users are on.
25110b57cec5SDimitry Andric assert(UnswitchedSuccBBs.size() == 1 &&
25120b57cec5SDimitry Andric "Only one possible unswitched block for a branch!");
25130b57cec5SDimitry Andric BasicBlock *ClonedPH = ClonedPHs.begin()->second;
25140b57cec5SDimitry Andric
25150b57cec5SDimitry Andric // When considering multiple partially-unswitched invariants
25160b57cec5SDimitry Andric // we cant just go replace them with constants in both branches.
25170b57cec5SDimitry Andric //
25180b57cec5SDimitry Andric // For 'AND' we infer that true branch ("continue") means true
25190b57cec5SDimitry Andric // for each invariant operand.
25200b57cec5SDimitry Andric // For 'OR' we can infer that false branch ("continue") means false
25210b57cec5SDimitry Andric // for each invariant operand.
25220b57cec5SDimitry Andric // So it happens that for multiple-partial case we dont replace
25230b57cec5SDimitry Andric // in the unswitched branch.
2524fe6060f1SDimitry Andric bool ReplaceUnswitched =
2525fe6060f1SDimitry Andric FullUnswitch || (Invariants.size() == 1) || PartiallyInvariant;
25260b57cec5SDimitry Andric
25270b57cec5SDimitry Andric ConstantInt *UnswitchedReplacement =
25280b57cec5SDimitry Andric Direction ? ConstantInt::getTrue(BI->getContext())
25290b57cec5SDimitry Andric : ConstantInt::getFalse(BI->getContext());
25300b57cec5SDimitry Andric ConstantInt *ContinueReplacement =
25310b57cec5SDimitry Andric Direction ? ConstantInt::getFalse(BI->getContext())
25320b57cec5SDimitry Andric : ConstantInt::getTrue(BI->getContext());
2533349cc55cSDimitry Andric for (Value *Invariant : Invariants) {
2534349cc55cSDimitry Andric assert(!isa<Constant>(Invariant) &&
2535349cc55cSDimitry Andric "Should not be replacing constant values!");
2536fe6060f1SDimitry Andric // Use make_early_inc_range here as set invalidates the iterator.
2537fe6060f1SDimitry Andric for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
2538fe6060f1SDimitry Andric Instruction *UserI = dyn_cast<Instruction>(U.getUser());
25390b57cec5SDimitry Andric if (!UserI)
25400b57cec5SDimitry Andric continue;
25410b57cec5SDimitry Andric
25420b57cec5SDimitry Andric // Replace it with the 'continue' side if in the main loop body, and the
25430b57cec5SDimitry Andric // unswitched if in the cloned blocks.
25440b57cec5SDimitry Andric if (DT.dominates(LoopPH, UserI->getParent()))
2545fe6060f1SDimitry Andric U.set(ContinueReplacement);
25460b57cec5SDimitry Andric else if (ReplaceUnswitched &&
25470b57cec5SDimitry Andric DT.dominates(ClonedPH, UserI->getParent()))
2548fe6060f1SDimitry Andric U.set(UnswitchedReplacement);
25490b57cec5SDimitry Andric }
25500b57cec5SDimitry Andric }
2551349cc55cSDimitry Andric }
25520b57cec5SDimitry Andric
25530b57cec5SDimitry Andric // We can change which blocks are exit blocks of all the cloned sibling
25540b57cec5SDimitry Andric // loops, the current loop, and any parent loops which shared exit blocks
25550b57cec5SDimitry Andric // with the current loop. As a consequence, we need to re-form LCSSA for
25560b57cec5SDimitry Andric // them. But we shouldn't need to re-form LCSSA for any child loops.
25570b57cec5SDimitry Andric // FIXME: This could be made more efficient by tracking which exit blocks are
25580b57cec5SDimitry Andric // new, and focusing on them, but that isn't likely to be necessary.
25590b57cec5SDimitry Andric //
25600b57cec5SDimitry Andric // In order to reasonably rebuild LCSSA we need to walk inside-out across the
25610b57cec5SDimitry Andric // loop nest and update every loop that could have had its exits changed. We
25620b57cec5SDimitry Andric // also need to cover any intervening loops. We add all of these loops to
25630b57cec5SDimitry Andric // a list and sort them by loop depth to achieve this without updating
25640b57cec5SDimitry Andric // unnecessary loops.
25650b57cec5SDimitry Andric auto UpdateLoop = [&](Loop &UpdateL) {
25660b57cec5SDimitry Andric #ifndef NDEBUG
25670b57cec5SDimitry Andric UpdateL.verifyLoop();
25680b57cec5SDimitry Andric for (Loop *ChildL : UpdateL) {
25690b57cec5SDimitry Andric ChildL->verifyLoop();
25700b57cec5SDimitry Andric assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
25710b57cec5SDimitry Andric "Perturbed a child loop's LCSSA form!");
25720b57cec5SDimitry Andric }
25730b57cec5SDimitry Andric #endif
25740b57cec5SDimitry Andric // First build LCSSA for this loop so that we can preserve it when
25750b57cec5SDimitry Andric // forming dedicated exits. We don't want to perturb some other loop's
25760b57cec5SDimitry Andric // LCSSA while doing that CFG edit.
2577480093f4SDimitry Andric formLCSSA(UpdateL, DT, &LI, SE);
25780b57cec5SDimitry Andric
25790b57cec5SDimitry Andric // For loops reached by this loop's original exit blocks we may
25800b57cec5SDimitry Andric // introduced new, non-dedicated exits. At least try to re-form dedicated
25810b57cec5SDimitry Andric // exits for these loops. This may fail if they couldn't have dedicated
25820b57cec5SDimitry Andric // exits to start with.
25830b57cec5SDimitry Andric formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
25840b57cec5SDimitry Andric };
25850b57cec5SDimitry Andric
25860b57cec5SDimitry Andric // For non-child cloned loops and hoisted loops, we just need to update LCSSA
25870b57cec5SDimitry Andric // and we can do it in any order as they don't nest relative to each other.
25880b57cec5SDimitry Andric //
25890b57cec5SDimitry Andric // Also check if any of the loops we have updated have become top-level loops
25900b57cec5SDimitry Andric // as that will necessitate widening the outer loop scope.
25910b57cec5SDimitry Andric for (Loop *UpdatedL :
25920b57cec5SDimitry Andric llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
25930b57cec5SDimitry Andric UpdateLoop(*UpdatedL);
2594e8d8bef9SDimitry Andric if (UpdatedL->isOutermost())
25950b57cec5SDimitry Andric OuterExitL = nullptr;
25960b57cec5SDimitry Andric }
25970b57cec5SDimitry Andric if (IsStillLoop) {
25980b57cec5SDimitry Andric UpdateLoop(L);
2599e8d8bef9SDimitry Andric if (L.isOutermost())
26000b57cec5SDimitry Andric OuterExitL = nullptr;
26010b57cec5SDimitry Andric }
26020b57cec5SDimitry Andric
26030b57cec5SDimitry Andric // If the original loop had exit blocks, walk up through the outer most loop
26040b57cec5SDimitry Andric // of those exit blocks to update LCSSA and form updated dedicated exits.
26050b57cec5SDimitry Andric if (OuterExitL != &L)
26060b57cec5SDimitry Andric for (Loop *OuterL = ParentL; OuterL != OuterExitL;
26070b57cec5SDimitry Andric OuterL = OuterL->getParentLoop())
26080b57cec5SDimitry Andric UpdateLoop(*OuterL);
26090b57cec5SDimitry Andric
26100b57cec5SDimitry Andric #ifndef NDEBUG
26110b57cec5SDimitry Andric // Verify the entire loop structure to catch any incorrect updates before we
26120b57cec5SDimitry Andric // progress in the pass pipeline.
26130b57cec5SDimitry Andric LI.verify(DT);
26140b57cec5SDimitry Andric #endif
26150b57cec5SDimitry Andric
26160b57cec5SDimitry Andric // Now that we've unswitched something, make callbacks to report the changes.
26170b57cec5SDimitry Andric // For that we need to merge together the updated loops and the cloned loops
26180b57cec5SDimitry Andric // and check whether the original loop survived.
26190b57cec5SDimitry Andric SmallVector<Loop *, 4> SibLoops;
26200b57cec5SDimitry Andric for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
26210b57cec5SDimitry Andric if (UpdatedL->getParentLoop() == ParentL)
26220b57cec5SDimitry Andric SibLoops.push_back(UpdatedL);
2623*c9157d92SDimitry Andric postUnswitch(L, LoopUpdater, LoopName, IsStillLoop, PartiallyInvariant,
2624*c9157d92SDimitry Andric InjectedCondition, SibLoops);
26250b57cec5SDimitry Andric
26260b57cec5SDimitry Andric if (MSSAU && VerifyMemorySSA)
26270b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
26280b57cec5SDimitry Andric
26290b57cec5SDimitry Andric if (BI)
26300b57cec5SDimitry Andric ++NumBranches;
26310b57cec5SDimitry Andric else
26320b57cec5SDimitry Andric ++NumSwitches;
26330b57cec5SDimitry Andric }
26340b57cec5SDimitry Andric
26350b57cec5SDimitry Andric /// Recursively compute the cost of a dominator subtree based on the per-block
26360b57cec5SDimitry Andric /// cost map provided.
26370b57cec5SDimitry Andric ///
26380b57cec5SDimitry Andric /// The recursive computation is memozied into the provided DT-indexed cost map
26390b57cec5SDimitry Andric /// to allow querying it for most nodes in the domtree without it becoming
26400b57cec5SDimitry Andric /// quadratic.
computeDomSubtreeCost(DomTreeNode & N,const SmallDenseMap<BasicBlock *,InstructionCost,4> & BBCostMap,SmallDenseMap<DomTreeNode *,InstructionCost,4> & DTCostMap)2641fe6060f1SDimitry Andric static InstructionCost computeDomSubtreeCost(
2642fe6060f1SDimitry Andric DomTreeNode &N,
2643fe6060f1SDimitry Andric const SmallDenseMap<BasicBlock *, InstructionCost, 4> &BBCostMap,
2644fe6060f1SDimitry Andric SmallDenseMap<DomTreeNode *, InstructionCost, 4> &DTCostMap) {
26450b57cec5SDimitry Andric // Don't accumulate cost (or recurse through) blocks not in our block cost
26460b57cec5SDimitry Andric // map and thus not part of the duplication cost being considered.
26470b57cec5SDimitry Andric auto BBCostIt = BBCostMap.find(N.getBlock());
26480b57cec5SDimitry Andric if (BBCostIt == BBCostMap.end())
26490b57cec5SDimitry Andric return 0;
26500b57cec5SDimitry Andric
26510b57cec5SDimitry Andric // Lookup this node to see if we already computed its cost.
26520b57cec5SDimitry Andric auto DTCostIt = DTCostMap.find(&N);
26530b57cec5SDimitry Andric if (DTCostIt != DTCostMap.end())
26540b57cec5SDimitry Andric return DTCostIt->second;
26550b57cec5SDimitry Andric
26560b57cec5SDimitry Andric // If not, we have to compute it. We can't use insert above and update
26570b57cec5SDimitry Andric // because computing the cost may insert more things into the map.
2658fe6060f1SDimitry Andric InstructionCost Cost = std::accumulate(
2659fe6060f1SDimitry Andric N.begin(), N.end(), BBCostIt->second,
2660fe6060f1SDimitry Andric [&](InstructionCost Sum, DomTreeNode *ChildN) -> InstructionCost {
26610b57cec5SDimitry Andric return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
26620b57cec5SDimitry Andric });
26630b57cec5SDimitry Andric bool Inserted = DTCostMap.insert({&N, Cost}).second;
26640b57cec5SDimitry Andric (void)Inserted;
26650b57cec5SDimitry Andric assert(Inserted && "Should not insert a node while visiting children!");
26660b57cec5SDimitry Andric return Cost;
26670b57cec5SDimitry Andric }
26680b57cec5SDimitry Andric
2669fe013be4SDimitry Andric /// Turns a select instruction into implicit control flow branch,
2670fe013be4SDimitry Andric /// making the following replacement:
2671fe013be4SDimitry Andric ///
2672fe013be4SDimitry Andric /// head:
2673fe013be4SDimitry Andric /// --code before select--
2674fe013be4SDimitry Andric /// select %cond, %trueval, %falseval
2675fe013be4SDimitry Andric /// --code after select--
2676fe013be4SDimitry Andric ///
2677fe013be4SDimitry Andric /// into
2678fe013be4SDimitry Andric ///
2679fe013be4SDimitry Andric /// head:
2680fe013be4SDimitry Andric /// --code before select--
2681fe013be4SDimitry Andric /// br i1 %cond, label %then, label %tail
2682fe013be4SDimitry Andric ///
2683fe013be4SDimitry Andric /// then:
2684fe013be4SDimitry Andric /// br %tail
2685fe013be4SDimitry Andric ///
2686fe013be4SDimitry Andric /// tail:
2687fe013be4SDimitry Andric /// phi [ %trueval, %then ], [ %falseval, %head]
2688fe013be4SDimitry Andric /// unreachable
2689fe013be4SDimitry Andric ///
2690fe013be4SDimitry Andric /// It also makes all relevant DT and LI updates, so that all structures are in
2691fe013be4SDimitry Andric /// valid state after this transform.
turnSelectIntoBranch(SelectInst * SI,DominatorTree & DT,LoopInfo & LI,MemorySSAUpdater * MSSAU,AssumptionCache * AC)2692fe013be4SDimitry Andric static BranchInst *turnSelectIntoBranch(SelectInst *SI, DominatorTree &DT,
2693fe013be4SDimitry Andric LoopInfo &LI, MemorySSAUpdater *MSSAU,
2694fe013be4SDimitry Andric AssumptionCache *AC) {
2695fe013be4SDimitry Andric LLVM_DEBUG(dbgs() << "Turning " << *SI << " into a branch.\n");
2696fe013be4SDimitry Andric BasicBlock *HeadBB = SI->getParent();
2697fe013be4SDimitry Andric
2698fe013be4SDimitry Andric DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
2699fe013be4SDimitry Andric SplitBlockAndInsertIfThen(SI->getCondition(), SI, false,
2700fe013be4SDimitry Andric SI->getMetadata(LLVMContext::MD_prof), &DTU, &LI);
2701fe013be4SDimitry Andric auto *CondBr = cast<BranchInst>(HeadBB->getTerminator());
2702fe013be4SDimitry Andric BasicBlock *ThenBB = CondBr->getSuccessor(0),
2703fe013be4SDimitry Andric *TailBB = CondBr->getSuccessor(1);
2704fe013be4SDimitry Andric if (MSSAU)
2705fe013be4SDimitry Andric MSSAU->moveAllAfterSpliceBlocks(HeadBB, TailBB, SI);
2706fe013be4SDimitry Andric
2707fe013be4SDimitry Andric PHINode *Phi = PHINode::Create(SI->getType(), 2, "unswitched.select", SI);
2708fe013be4SDimitry Andric Phi->addIncoming(SI->getTrueValue(), ThenBB);
2709fe013be4SDimitry Andric Phi->addIncoming(SI->getFalseValue(), HeadBB);
2710fe013be4SDimitry Andric SI->replaceAllUsesWith(Phi);
2711fe013be4SDimitry Andric SI->eraseFromParent();
2712fe013be4SDimitry Andric
2713fe013be4SDimitry Andric if (MSSAU && VerifyMemorySSA)
2714fe013be4SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
2715fe013be4SDimitry Andric
2716fe013be4SDimitry Andric ++NumSelects;
2717fe013be4SDimitry Andric return CondBr;
2718fe013be4SDimitry Andric }
2719fe013be4SDimitry Andric
27200b57cec5SDimitry Andric /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
27210b57cec5SDimitry Andric /// making the following replacement:
27220b57cec5SDimitry Andric ///
27230b57cec5SDimitry Andric /// --code before guard--
27240b57cec5SDimitry Andric /// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
27250b57cec5SDimitry Andric /// --code after guard--
27260b57cec5SDimitry Andric ///
27270b57cec5SDimitry Andric /// into
27280b57cec5SDimitry Andric ///
27290b57cec5SDimitry Andric /// --code before guard--
27300b57cec5SDimitry Andric /// br i1 %cond, label %guarded, label %deopt
27310b57cec5SDimitry Andric ///
27320b57cec5SDimitry Andric /// guarded:
27330b57cec5SDimitry Andric /// --code after guard--
27340b57cec5SDimitry Andric ///
27350b57cec5SDimitry Andric /// deopt:
27360b57cec5SDimitry Andric /// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
27370b57cec5SDimitry Andric /// unreachable
27380b57cec5SDimitry Andric ///
27390b57cec5SDimitry Andric /// It also makes all relevant DT and LI updates, so that all structures are in
27400b57cec5SDimitry Andric /// valid state after this transform.
turnGuardIntoBranch(IntrinsicInst * GI,Loop & L,DominatorTree & DT,LoopInfo & LI,MemorySSAUpdater * MSSAU)2741bdd1243dSDimitry Andric static BranchInst *turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2742bdd1243dSDimitry Andric DominatorTree &DT, LoopInfo &LI,
2743bdd1243dSDimitry Andric MemorySSAUpdater *MSSAU) {
27440b57cec5SDimitry Andric SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
27450b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
27460b57cec5SDimitry Andric BasicBlock *CheckBB = GI->getParent();
27470b57cec5SDimitry Andric
27480b57cec5SDimitry Andric if (MSSAU && VerifyMemorySSA)
27490b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
27500b57cec5SDimitry Andric
2751fe013be4SDimitry Andric DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
27520b57cec5SDimitry Andric Instruction *DeoptBlockTerm =
2753fe013be4SDimitry Andric SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true,
2754fe013be4SDimitry Andric GI->getMetadata(LLVMContext::MD_prof), &DTU, &LI);
27550b57cec5SDimitry Andric BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
27560b57cec5SDimitry Andric // SplitBlockAndInsertIfThen inserts control flow that branches to
27570b57cec5SDimitry Andric // DeoptBlockTerm if the condition is true. We want the opposite.
27580b57cec5SDimitry Andric CheckBI->swapSuccessors();
27590b57cec5SDimitry Andric
27600b57cec5SDimitry Andric BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
27610b57cec5SDimitry Andric GuardedBlock->setName("guarded");
27620b57cec5SDimitry Andric CheckBI->getSuccessor(1)->setName("deopt");
27630b57cec5SDimitry Andric BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
27640b57cec5SDimitry Andric
27650b57cec5SDimitry Andric if (MSSAU)
27660b57cec5SDimitry Andric MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
27670b57cec5SDimitry Andric
27680b57cec5SDimitry Andric GI->moveBefore(DeoptBlockTerm);
27690b57cec5SDimitry Andric GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
27700b57cec5SDimitry Andric
27710b57cec5SDimitry Andric if (MSSAU) {
27720b57cec5SDimitry Andric MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2773480093f4SDimitry Andric MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::BeforeTerminator);
27740b57cec5SDimitry Andric if (VerifyMemorySSA)
27750b57cec5SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
27760b57cec5SDimitry Andric }
27770b57cec5SDimitry Andric
2778fe013be4SDimitry Andric if (VerifyLoopInfo)
2779fe013be4SDimitry Andric LI.verify(DT);
27800b57cec5SDimitry Andric ++NumGuards;
27810b57cec5SDimitry Andric return CheckBI;
27820b57cec5SDimitry Andric }
27830b57cec5SDimitry Andric
27840b57cec5SDimitry Andric /// Cost multiplier is a way to limit potentially exponential behavior
27850b57cec5SDimitry Andric /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
27860b57cec5SDimitry Andric /// candidates available. Also accounting for the number of "sibling" loops with
27870b57cec5SDimitry Andric /// the idea to account for previous unswitches that already happened on this
27880b57cec5SDimitry Andric /// cluster of loops. There was an attempt to keep this formula simple,
27890b57cec5SDimitry Andric /// just enough to limit the worst case behavior. Even if it is not that simple
27900b57cec5SDimitry Andric /// now it is still not an attempt to provide a detailed heuristic size
27910b57cec5SDimitry Andric /// prediction.
27920b57cec5SDimitry Andric ///
27930b57cec5SDimitry Andric /// TODO: Make a proper accounting of "explosion" effect for all kinds of
27940b57cec5SDimitry Andric /// unswitch candidates, making adequate predictions instead of wild guesses.
27950b57cec5SDimitry Andric /// That requires knowing not just the number of "remaining" candidates but
27960b57cec5SDimitry Andric /// also costs of unswitching for each of these candidates.
CalculateUnswitchCostMultiplier(const Instruction & TI,const Loop & L,const LoopInfo & LI,const DominatorTree & DT,ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates)27975ffd83dbSDimitry Andric static int CalculateUnswitchCostMultiplier(
2798bdd1243dSDimitry Andric const Instruction &TI, const Loop &L, const LoopInfo &LI,
2799bdd1243dSDimitry Andric const DominatorTree &DT,
2800bdd1243dSDimitry Andric ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates) {
28010b57cec5SDimitry Andric
28020b57cec5SDimitry Andric // Guards and other exiting conditions do not contribute to exponential
28030b57cec5SDimitry Andric // explosion as soon as they dominate the latch (otherwise there might be
28040b57cec5SDimitry Andric // another path to the latch remaining that does not allow to eliminate the
28050b57cec5SDimitry Andric // loop copy on unswitch).
2806bdd1243dSDimitry Andric const BasicBlock *Latch = L.getLoopLatch();
2807bdd1243dSDimitry Andric const BasicBlock *CondBlock = TI.getParent();
28080b57cec5SDimitry Andric if (DT.dominates(CondBlock, Latch) &&
28090b57cec5SDimitry Andric (isGuard(&TI) ||
2810fe013be4SDimitry Andric (TI.isTerminator() &&
2811bdd1243dSDimitry Andric llvm::count_if(successors(&TI), [&L](const BasicBlock *SuccBB) {
28120b57cec5SDimitry Andric return L.contains(SuccBB);
2813fe013be4SDimitry Andric }) <= 1))) {
28140b57cec5SDimitry Andric NumCostMultiplierSkipped++;
28150b57cec5SDimitry Andric return 1;
28160b57cec5SDimitry Andric }
28170b57cec5SDimitry Andric
28180b57cec5SDimitry Andric auto *ParentL = L.getParentLoop();
28190b57cec5SDimitry Andric int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
28200b57cec5SDimitry Andric : std::distance(LI.begin(), LI.end()));
28210b57cec5SDimitry Andric // Count amount of clones that all the candidates might cause during
2822fe013be4SDimitry Andric // unswitching. Branch/guard/select counts as 1, switch counts as log2 of its
2823fe013be4SDimitry Andric // cases.
28240b57cec5SDimitry Andric int UnswitchedClones = 0;
2825fe013be4SDimitry Andric for (const auto &Candidate : UnswitchCandidates) {
2826bdd1243dSDimitry Andric const Instruction *CI = Candidate.TI;
2827bdd1243dSDimitry Andric const BasicBlock *CondBlock = CI->getParent();
28280b57cec5SDimitry Andric bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2829fe013be4SDimitry Andric if (isa<SelectInst>(CI)) {
2830fe013be4SDimitry Andric UnswitchedClones++;
2831fe013be4SDimitry Andric continue;
2832fe013be4SDimitry Andric }
28330b57cec5SDimitry Andric if (isGuard(CI)) {
28340b57cec5SDimitry Andric if (!SkipExitingSuccessors)
28350b57cec5SDimitry Andric UnswitchedClones++;
28360b57cec5SDimitry Andric continue;
28370b57cec5SDimitry Andric }
2838bdd1243dSDimitry Andric int NonExitingSuccessors =
2839bdd1243dSDimitry Andric llvm::count_if(successors(CondBlock),
2840bdd1243dSDimitry Andric [SkipExitingSuccessors, &L](const BasicBlock *SuccBB) {
28410b57cec5SDimitry Andric return !SkipExitingSuccessors || L.contains(SuccBB);
28420b57cec5SDimitry Andric });
28430b57cec5SDimitry Andric UnswitchedClones += Log2_32(NonExitingSuccessors);
28440b57cec5SDimitry Andric }
28450b57cec5SDimitry Andric
28460b57cec5SDimitry Andric // Ignore up to the "unscaled candidates" number of unswitch candidates
28470b57cec5SDimitry Andric // when calculating the power-of-two scaling of the cost. The main idea
28480b57cec5SDimitry Andric // with this control is to allow a small number of unswitches to happen
28490b57cec5SDimitry Andric // and rely more on siblings multiplier (see below) when the number
28500b57cec5SDimitry Andric // of candidates is small.
28510b57cec5SDimitry Andric unsigned ClonesPower =
28520b57cec5SDimitry Andric std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
28530b57cec5SDimitry Andric
28540b57cec5SDimitry Andric // Allowing top-level loops to spread a bit more than nested ones.
28550b57cec5SDimitry Andric int SiblingsMultiplier =
28560b57cec5SDimitry Andric std::max((ParentL ? SiblingsCount
28570b57cec5SDimitry Andric : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
28580b57cec5SDimitry Andric 1);
28590b57cec5SDimitry Andric // Compute the cost multiplier in a way that won't overflow by saturating
28600b57cec5SDimitry Andric // at an upper bound.
28610b57cec5SDimitry Andric int CostMultiplier;
28620b57cec5SDimitry Andric if (ClonesPower > Log2_32(UnswitchThreshold) ||
28630b57cec5SDimitry Andric SiblingsMultiplier > UnswitchThreshold)
28640b57cec5SDimitry Andric CostMultiplier = UnswitchThreshold;
28650b57cec5SDimitry Andric else
28660b57cec5SDimitry Andric CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
28670b57cec5SDimitry Andric (int)UnswitchThreshold);
28680b57cec5SDimitry Andric
28690b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier
28700b57cec5SDimitry Andric << " (siblings " << SiblingsMultiplier << " * clones "
28710b57cec5SDimitry Andric << (1 << ClonesPower) << ")"
28720b57cec5SDimitry Andric << " for unswitch candidate: " << TI << "\n");
28730b57cec5SDimitry Andric return CostMultiplier;
28740b57cec5SDimitry Andric }
28750b57cec5SDimitry Andric
collectUnswitchCandidates(SmallVectorImpl<NonTrivialUnswitchCandidate> & UnswitchCandidates,IVConditionInfo & PartialIVInfo,Instruction * & PartialIVCondBranch,const Loop & L,const LoopInfo & LI,AAResults & AA,const MemorySSAUpdater * MSSAU)2876bdd1243dSDimitry Andric static bool collectUnswitchCandidates(
2877bdd1243dSDimitry Andric SmallVectorImpl<NonTrivialUnswitchCandidate> &UnswitchCandidates,
2878bdd1243dSDimitry Andric IVConditionInfo &PartialIVInfo, Instruction *&PartialIVCondBranch,
2879bdd1243dSDimitry Andric const Loop &L, const LoopInfo &LI, AAResults &AA,
2880bdd1243dSDimitry Andric const MemorySSAUpdater *MSSAU) {
2881bdd1243dSDimitry Andric assert(UnswitchCandidates.empty() && "Should be!");
2882fe013be4SDimitry Andric
2883fe013be4SDimitry Andric auto AddUnswitchCandidatesForInst = [&](Instruction *I, Value *Cond) {
2884fe013be4SDimitry Andric Cond = skipTrivialSelect(Cond);
2885fe013be4SDimitry Andric if (isa<Constant>(Cond))
2886fe013be4SDimitry Andric return;
2887fe013be4SDimitry Andric if (L.isLoopInvariant(Cond)) {
2888fe013be4SDimitry Andric UnswitchCandidates.push_back({I, {Cond}});
2889fe013be4SDimitry Andric return;
2890fe013be4SDimitry Andric }
2891fe013be4SDimitry Andric if (match(Cond, m_CombineOr(m_LogicalAnd(), m_LogicalOr()))) {
2892fe013be4SDimitry Andric TinyPtrVector<Value *> Invariants =
2893fe013be4SDimitry Andric collectHomogenousInstGraphLoopInvariants(
2894fe013be4SDimitry Andric L, *static_cast<Instruction *>(Cond), LI);
2895fe013be4SDimitry Andric if (!Invariants.empty())
2896fe013be4SDimitry Andric UnswitchCandidates.push_back({I, std::move(Invariants)});
2897fe013be4SDimitry Andric }
2898fe013be4SDimitry Andric };
2899fe013be4SDimitry Andric
29000b57cec5SDimitry Andric // Whether or not we should also collect guards in the loop.
29010b57cec5SDimitry Andric bool CollectGuards = false;
29020b57cec5SDimitry Andric if (UnswitchGuards) {
29030b57cec5SDimitry Andric auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
29040b57cec5SDimitry Andric Intrinsic::getName(Intrinsic::experimental_guard));
29050b57cec5SDimitry Andric if (GuardDecl && !GuardDecl->use_empty())
29060b57cec5SDimitry Andric CollectGuards = true;
29070b57cec5SDimitry Andric }
29080b57cec5SDimitry Andric
29090b57cec5SDimitry Andric for (auto *BB : L.blocks()) {
29100b57cec5SDimitry Andric if (LI.getLoopFor(BB) != &L)
29110b57cec5SDimitry Andric continue;
29120b57cec5SDimitry Andric
2913fe013be4SDimitry Andric for (auto &I : *BB) {
2914fe013be4SDimitry Andric if (auto *SI = dyn_cast<SelectInst>(&I)) {
2915fe013be4SDimitry Andric auto *Cond = SI->getCondition();
2916fe013be4SDimitry Andric // Do not unswitch vector selects and logical and/or selects
2917fe013be4SDimitry Andric if (Cond->getType()->isIntegerTy(1) && !SI->getType()->isIntegerTy(1))
2918fe013be4SDimitry Andric AddUnswitchCandidatesForInst(SI, Cond);
2919fe013be4SDimitry Andric } else if (CollectGuards && isGuard(&I)) {
2920bdd1243dSDimitry Andric auto *Cond =
2921bdd1243dSDimitry Andric skipTrivialSelect(cast<IntrinsicInst>(&I)->getArgOperand(0));
29220b57cec5SDimitry Andric // TODO: Support AND, OR conditions and partial unswitching.
29230b57cec5SDimitry Andric if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
29240b57cec5SDimitry Andric UnswitchCandidates.push_back({&I, {Cond}});
29250b57cec5SDimitry Andric }
2926fe013be4SDimitry Andric }
29270b57cec5SDimitry Andric
29280b57cec5SDimitry Andric if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
29290b57cec5SDimitry Andric // We can only consider fully loop-invariant switch conditions as we need
29300b57cec5SDimitry Andric // to completely eliminate the switch after unswitching.
29310b57cec5SDimitry Andric if (!isa<Constant>(SI->getCondition()) &&
29320b57cec5SDimitry Andric L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor())
29330b57cec5SDimitry Andric UnswitchCandidates.push_back({SI, {SI->getCondition()}});
29340b57cec5SDimitry Andric continue;
29350b57cec5SDimitry Andric }
29360b57cec5SDimitry Andric
29370b57cec5SDimitry Andric auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2938fe013be4SDimitry Andric if (!BI || !BI->isConditional() ||
29390b57cec5SDimitry Andric BI->getSuccessor(0) == BI->getSuccessor(1))
29400b57cec5SDimitry Andric continue;
29410b57cec5SDimitry Andric
2942fe013be4SDimitry Andric AddUnswitchCandidatesForInst(BI, BI->getCondition());
2943fe6060f1SDimitry Andric }
2944fe6060f1SDimitry Andric
2945fe6060f1SDimitry Andric if (MSSAU && !findOptionMDForLoop(&L, "llvm.loop.unswitch.partial.disable") &&
2946fe6060f1SDimitry Andric !any_of(UnswitchCandidates, [&L](auto &TerminatorAndInvariants) {
2947bdd1243dSDimitry Andric return TerminatorAndInvariants.TI == L.getHeader()->getTerminator();
2948fe6060f1SDimitry Andric })) {
2949fe6060f1SDimitry Andric MemorySSA *MSSA = MSSAU->getMemorySSA();
2950fe6060f1SDimitry Andric if (auto Info = hasPartialIVCondition(L, MSSAThreshold, *MSSA, AA)) {
2951fe6060f1SDimitry Andric LLVM_DEBUG(
2952fe6060f1SDimitry Andric dbgs() << "simple-loop-unswitch: Found partially invariant condition "
2953fe6060f1SDimitry Andric << *Info->InstToDuplicate[0] << "\n");
2954fe6060f1SDimitry Andric PartialIVInfo = *Info;
2955fe6060f1SDimitry Andric PartialIVCondBranch = L.getHeader()->getTerminator();
2956fe6060f1SDimitry Andric TinyPtrVector<Value *> ValsToDuplicate;
295781ad6265SDimitry Andric llvm::append_range(ValsToDuplicate, Info->InstToDuplicate);
2958fe6060f1SDimitry Andric UnswitchCandidates.push_back(
2959fe6060f1SDimitry Andric {L.getHeader()->getTerminator(), std::move(ValsToDuplicate)});
2960fe6060f1SDimitry Andric }
29610b57cec5SDimitry Andric }
2962bdd1243dSDimitry Andric return !UnswitchCandidates.empty();
2963bdd1243dSDimitry Andric }
29640b57cec5SDimitry Andric
2965fe013be4SDimitry Andric /// Tries to canonicalize condition described by:
2966fe013be4SDimitry Andric ///
2967fe013be4SDimitry Andric /// br (LHS pred RHS), label IfTrue, label IfFalse
2968fe013be4SDimitry Andric ///
2969fe013be4SDimitry Andric /// into its equivalent where `Pred` is something that we support for injected
2970fe013be4SDimitry Andric /// invariants (so far it is limited to ult), LHS in canonicalized form is
2971fe013be4SDimitry Andric /// non-invariant and RHS is an invariant.
canonicalizeForInvariantConditionInjection(ICmpInst::Predicate & Pred,Value * & LHS,Value * & RHS,BasicBlock * & IfTrue,BasicBlock * & IfFalse,const Loop & L)2972fe013be4SDimitry Andric static void canonicalizeForInvariantConditionInjection(
2973fe013be4SDimitry Andric ICmpInst::Predicate &Pred, Value *&LHS, Value *&RHS, BasicBlock *&IfTrue,
2974fe013be4SDimitry Andric BasicBlock *&IfFalse, const Loop &L) {
2975fe013be4SDimitry Andric if (!L.contains(IfTrue)) {
2976fe013be4SDimitry Andric Pred = ICmpInst::getInversePredicate(Pred);
2977fe013be4SDimitry Andric std::swap(IfTrue, IfFalse);
2978fe013be4SDimitry Andric }
2979fe013be4SDimitry Andric
2980fe013be4SDimitry Andric // Move loop-invariant argument to RHS position.
2981fe013be4SDimitry Andric if (L.isLoopInvariant(LHS)) {
2982fe013be4SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred);
2983fe013be4SDimitry Andric std::swap(LHS, RHS);
2984fe013be4SDimitry Andric }
2985fe013be4SDimitry Andric
2986fe013be4SDimitry Andric if (Pred == ICmpInst::ICMP_SGE && match(RHS, m_Zero())) {
2987fe013be4SDimitry Andric // Turn "x >=s 0" into "x <u UMIN_INT"
2988fe013be4SDimitry Andric Pred = ICmpInst::ICMP_ULT;
2989fe013be4SDimitry Andric RHS = ConstantInt::get(
2990fe013be4SDimitry Andric RHS->getContext(),
2991fe013be4SDimitry Andric APInt::getSignedMinValue(RHS->getType()->getIntegerBitWidth()));
2992fe013be4SDimitry Andric }
2993fe013be4SDimitry Andric }
2994fe013be4SDimitry Andric
2995fe013be4SDimitry Andric /// Returns true, if predicate described by ( \p Pred, \p LHS, \p RHS )
2996fe013be4SDimitry Andric /// succeeding into blocks ( \p IfTrue, \p IfFalse) can be optimized by
2997fe013be4SDimitry Andric /// injecting a loop-invariant condition.
shouldTryInjectInvariantCondition(const ICmpInst::Predicate Pred,const Value * LHS,const Value * RHS,const BasicBlock * IfTrue,const BasicBlock * IfFalse,const Loop & L)2998fe013be4SDimitry Andric static bool shouldTryInjectInvariantCondition(
2999fe013be4SDimitry Andric const ICmpInst::Predicate Pred, const Value *LHS, const Value *RHS,
3000fe013be4SDimitry Andric const BasicBlock *IfTrue, const BasicBlock *IfFalse, const Loop &L) {
3001fe013be4SDimitry Andric if (L.isLoopInvariant(LHS) || !L.isLoopInvariant(RHS))
3002fe013be4SDimitry Andric return false;
3003fe013be4SDimitry Andric // TODO: Support other predicates.
3004fe013be4SDimitry Andric if (Pred != ICmpInst::ICMP_ULT)
3005fe013be4SDimitry Andric return false;
3006fe013be4SDimitry Andric // TODO: Support non-loop-exiting branches?
3007fe013be4SDimitry Andric if (!L.contains(IfTrue) || L.contains(IfFalse))
3008fe013be4SDimitry Andric return false;
3009fe013be4SDimitry Andric // FIXME: For some reason this causes problems with MSSA updates, need to
3010fe013be4SDimitry Andric // investigate why. So far, just don't unswitch latch.
3011fe013be4SDimitry Andric if (L.getHeader() == IfTrue)
3012fe013be4SDimitry Andric return false;
3013fe013be4SDimitry Andric return true;
3014fe013be4SDimitry Andric }
3015fe013be4SDimitry Andric
3016fe013be4SDimitry Andric /// Returns true, if metadata on \p BI allows us to optimize branching into \p
3017fe013be4SDimitry Andric /// TakenSucc via injection of invariant conditions. The branch should be not
3018fe013be4SDimitry Andric /// enough and not previously unswitched, the information about this comes from
3019fe013be4SDimitry Andric /// the metadata.
shouldTryInjectBasingOnMetadata(const BranchInst * BI,const BasicBlock * TakenSucc)3020fe013be4SDimitry Andric bool shouldTryInjectBasingOnMetadata(const BranchInst *BI,
3021fe013be4SDimitry Andric const BasicBlock *TakenSucc) {
3022fe013be4SDimitry Andric SmallVector<uint32_t> Weights;
3023fe013be4SDimitry Andric if (!extractBranchWeights(*BI, Weights))
3024fe013be4SDimitry Andric return false;
3025fe013be4SDimitry Andric unsigned T = InjectInvariantConditionHotnesThreshold;
3026fe013be4SDimitry Andric BranchProbability LikelyTaken(T - 1, T);
3027fe013be4SDimitry Andric
3028fe013be4SDimitry Andric assert(Weights.size() == 2 && "Unexpected profile data!");
3029fe013be4SDimitry Andric size_t Idx = BI->getSuccessor(0) == TakenSucc ? 0 : 1;
3030fe013be4SDimitry Andric auto Num = Weights[Idx];
3031fe013be4SDimitry Andric auto Denom = Weights[0] + Weights[1];
3032fe013be4SDimitry Andric // Degenerate or overflowed metadata.
3033fe013be4SDimitry Andric if (Denom == 0 || Num > Denom)
3034fe013be4SDimitry Andric return false;
3035fe013be4SDimitry Andric BranchProbability ActualTaken(Num, Denom);
3036fe013be4SDimitry Andric if (LikelyTaken > ActualTaken)
3037fe013be4SDimitry Andric return false;
3038fe013be4SDimitry Andric return true;
3039fe013be4SDimitry Andric }
3040fe013be4SDimitry Andric
3041fe013be4SDimitry Andric /// Materialize pending invariant condition of the given candidate into IR. The
3042fe013be4SDimitry Andric /// injected loop-invariant condition implies the original loop-variant branch
3043fe013be4SDimitry Andric /// condition, so the materialization turns
3044fe013be4SDimitry Andric ///
3045fe013be4SDimitry Andric /// loop_block:
3046fe013be4SDimitry Andric /// ...
3047fe013be4SDimitry Andric /// br i1 %variant_cond, label InLoopSucc, label OutOfLoopSucc
3048fe013be4SDimitry Andric ///
3049fe013be4SDimitry Andric /// into
3050fe013be4SDimitry Andric ///
3051fe013be4SDimitry Andric /// preheader:
3052fe013be4SDimitry Andric /// %invariant_cond = LHS pred RHS
3053fe013be4SDimitry Andric /// ...
3054fe013be4SDimitry Andric /// loop_block:
3055fe013be4SDimitry Andric /// br i1 %invariant_cond, label InLoopSucc, label OriginalCheck
3056fe013be4SDimitry Andric /// OriginalCheck:
3057fe013be4SDimitry Andric /// br i1 %variant_cond, label InLoopSucc, label OutOfLoopSucc
3058fe013be4SDimitry Andric /// ...
3059fe013be4SDimitry Andric static NonTrivialUnswitchCandidate
injectPendingInvariantConditions(NonTrivialUnswitchCandidate Candidate,Loop & L,DominatorTree & DT,LoopInfo & LI,AssumptionCache & AC,MemorySSAUpdater * MSSAU)3060fe013be4SDimitry Andric injectPendingInvariantConditions(NonTrivialUnswitchCandidate Candidate, Loop &L,
3061fe013be4SDimitry Andric DominatorTree &DT, LoopInfo &LI,
3062fe013be4SDimitry Andric AssumptionCache &AC, MemorySSAUpdater *MSSAU) {
3063fe013be4SDimitry Andric assert(Candidate.hasPendingInjection() && "Nothing to inject!");
3064fe013be4SDimitry Andric BasicBlock *Preheader = L.getLoopPreheader();
3065fe013be4SDimitry Andric assert(Preheader && "Loop is not in simplified form?");
3066fe013be4SDimitry Andric assert(LI.getLoopFor(Candidate.TI->getParent()) == &L &&
3067fe013be4SDimitry Andric "Unswitching branch of inner loop!");
3068fe013be4SDimitry Andric
3069fe013be4SDimitry Andric auto Pred = Candidate.PendingInjection->Pred;
3070fe013be4SDimitry Andric auto *LHS = Candidate.PendingInjection->LHS;
3071fe013be4SDimitry Andric auto *RHS = Candidate.PendingInjection->RHS;
3072fe013be4SDimitry Andric auto *InLoopSucc = Candidate.PendingInjection->InLoopSucc;
3073fe013be4SDimitry Andric auto *TI = cast<BranchInst>(Candidate.TI);
3074fe013be4SDimitry Andric auto *BB = Candidate.TI->getParent();
3075fe013be4SDimitry Andric auto *OutOfLoopSucc = InLoopSucc == TI->getSuccessor(0) ? TI->getSuccessor(1)
3076fe013be4SDimitry Andric : TI->getSuccessor(0);
3077fe013be4SDimitry Andric // FIXME: Remove this once limitation on successors is lifted.
3078fe013be4SDimitry Andric assert(L.contains(InLoopSucc) && "Not supported yet!");
3079fe013be4SDimitry Andric assert(!L.contains(OutOfLoopSucc) && "Not supported yet!");
3080fe013be4SDimitry Andric auto &Ctx = BB->getContext();
3081fe013be4SDimitry Andric
3082fe013be4SDimitry Andric IRBuilder<> Builder(Preheader->getTerminator());
3083fe013be4SDimitry Andric assert(ICmpInst::isUnsigned(Pred) && "Not supported yet!");
3084fe013be4SDimitry Andric if (LHS->getType() != RHS->getType()) {
3085fe013be4SDimitry Andric if (LHS->getType()->getIntegerBitWidth() <
3086fe013be4SDimitry Andric RHS->getType()->getIntegerBitWidth())
3087fe013be4SDimitry Andric LHS = Builder.CreateZExt(LHS, RHS->getType(), LHS->getName() + ".wide");
3088fe013be4SDimitry Andric else
3089fe013be4SDimitry Andric RHS = Builder.CreateZExt(RHS, LHS->getType(), RHS->getName() + ".wide");
3090fe013be4SDimitry Andric }
3091fe013be4SDimitry Andric // Do not use builder here: CreateICmp may simplify this into a constant and
3092fe013be4SDimitry Andric // unswitching will break. Better optimize it away later.
3093fe013be4SDimitry Andric auto *InjectedCond =
3094fe013be4SDimitry Andric ICmpInst::Create(Instruction::ICmp, Pred, LHS, RHS, "injected.cond",
3095fe013be4SDimitry Andric Preheader->getTerminator());
3096fe013be4SDimitry Andric
3097fe013be4SDimitry Andric BasicBlock *CheckBlock = BasicBlock::Create(Ctx, BB->getName() + ".check",
3098fe013be4SDimitry Andric BB->getParent(), InLoopSucc);
3099fe013be4SDimitry Andric Builder.SetInsertPoint(TI);
3100fe013be4SDimitry Andric auto *InvariantBr =
3101fe013be4SDimitry Andric Builder.CreateCondBr(InjectedCond, InLoopSucc, CheckBlock);
3102fe013be4SDimitry Andric
3103fe013be4SDimitry Andric Builder.SetInsertPoint(CheckBlock);
31047126fb41SDimitry Andric Builder.CreateCondBr(TI->getCondition(), TI->getSuccessor(0),
31057126fb41SDimitry Andric TI->getSuccessor(1));
3106fe013be4SDimitry Andric TI->eraseFromParent();
3107fe013be4SDimitry Andric
3108fe013be4SDimitry Andric // Fixup phis.
3109fe013be4SDimitry Andric for (auto &I : *InLoopSucc) {
3110fe013be4SDimitry Andric auto *PN = dyn_cast<PHINode>(&I);
3111fe013be4SDimitry Andric if (!PN)
3112fe013be4SDimitry Andric break;
3113fe013be4SDimitry Andric auto *Inc = PN->getIncomingValueForBlock(BB);
3114fe013be4SDimitry Andric PN->addIncoming(Inc, CheckBlock);
3115fe013be4SDimitry Andric }
3116fe013be4SDimitry Andric OutOfLoopSucc->replacePhiUsesWith(BB, CheckBlock);
3117fe013be4SDimitry Andric
3118fe013be4SDimitry Andric SmallVector<DominatorTree::UpdateType, 4> DTUpdates = {
3119fe013be4SDimitry Andric { DominatorTree::Insert, BB, CheckBlock },
3120fe013be4SDimitry Andric { DominatorTree::Insert, CheckBlock, InLoopSucc },
3121fe013be4SDimitry Andric { DominatorTree::Insert, CheckBlock, OutOfLoopSucc },
3122fe013be4SDimitry Andric { DominatorTree::Delete, BB, OutOfLoopSucc }
3123fe013be4SDimitry Andric };
3124fe013be4SDimitry Andric
3125fe013be4SDimitry Andric DT.applyUpdates(DTUpdates);
3126fe013be4SDimitry Andric if (MSSAU)
3127fe013be4SDimitry Andric MSSAU->applyUpdates(DTUpdates, DT);
3128fe013be4SDimitry Andric L.addBasicBlockToLoop(CheckBlock, LI);
3129fe013be4SDimitry Andric
3130fe013be4SDimitry Andric #ifndef NDEBUG
3131fe013be4SDimitry Andric DT.verify();
3132fe013be4SDimitry Andric LI.verify(DT);
3133fe013be4SDimitry Andric if (MSSAU && VerifyMemorySSA)
3134fe013be4SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
3135fe013be4SDimitry Andric #endif
3136fe013be4SDimitry Andric
3137fe013be4SDimitry Andric // TODO: In fact, cost of unswitching a new invariant candidate is *slightly*
3138fe013be4SDimitry Andric // higher because we have just inserted a new block. Need to think how to
3139fe013be4SDimitry Andric // adjust the cost of injected candidates when it was first computed.
3140fe013be4SDimitry Andric LLVM_DEBUG(dbgs() << "Injected a new loop-invariant branch " << *InvariantBr
3141fe013be4SDimitry Andric << " and considering it for unswitching.");
3142fe013be4SDimitry Andric ++NumInvariantConditionsInjected;
3143fe013be4SDimitry Andric return NonTrivialUnswitchCandidate(InvariantBr, { InjectedCond },
3144fe013be4SDimitry Andric Candidate.Cost);
3145fe013be4SDimitry Andric }
3146fe013be4SDimitry Andric
3147fe013be4SDimitry Andric /// Given chain of loop branch conditions looking like:
3148fe013be4SDimitry Andric /// br (Variant < Invariant1)
3149fe013be4SDimitry Andric /// br (Variant < Invariant2)
3150fe013be4SDimitry Andric /// br (Variant < Invariant3)
3151fe013be4SDimitry Andric /// ...
3152fe013be4SDimitry Andric /// collect set of invariant conditions on which we want to unswitch, which
3153fe013be4SDimitry Andric /// look like:
3154fe013be4SDimitry Andric /// Invariant1 <= Invariant2
3155fe013be4SDimitry Andric /// Invariant2 <= Invariant3
3156fe013be4SDimitry Andric /// ...
3157fe013be4SDimitry Andric /// Though they might not immediately exist in the IR, we can still inject them.
insertCandidatesWithPendingInjections(SmallVectorImpl<NonTrivialUnswitchCandidate> & UnswitchCandidates,Loop & L,ICmpInst::Predicate Pred,ArrayRef<CompareDesc> Compares,const DominatorTree & DT)3158fe013be4SDimitry Andric static bool insertCandidatesWithPendingInjections(
3159fe013be4SDimitry Andric SmallVectorImpl<NonTrivialUnswitchCandidate> &UnswitchCandidates, Loop &L,
3160fe013be4SDimitry Andric ICmpInst::Predicate Pred, ArrayRef<CompareDesc> Compares,
3161fe013be4SDimitry Andric const DominatorTree &DT) {
3162fe013be4SDimitry Andric
3163fe013be4SDimitry Andric assert(ICmpInst::isRelational(Pred));
3164fe013be4SDimitry Andric assert(ICmpInst::isStrictPredicate(Pred));
3165fe013be4SDimitry Andric if (Compares.size() < 2)
3166fe013be4SDimitry Andric return false;
3167fe013be4SDimitry Andric ICmpInst::Predicate NonStrictPred = ICmpInst::getNonStrictPredicate(Pred);
3168fe013be4SDimitry Andric for (auto Prev = Compares.begin(), Next = Compares.begin() + 1;
3169fe013be4SDimitry Andric Next != Compares.end(); ++Prev, ++Next) {
3170fe013be4SDimitry Andric Value *LHS = Next->Invariant;
3171fe013be4SDimitry Andric Value *RHS = Prev->Invariant;
3172fe013be4SDimitry Andric BasicBlock *InLoopSucc = Prev->InLoopSucc;
3173fe013be4SDimitry Andric InjectedInvariant ToInject(NonStrictPred, LHS, RHS, InLoopSucc);
3174fe013be4SDimitry Andric NonTrivialUnswitchCandidate Candidate(Prev->Term, { LHS, RHS },
3175fe013be4SDimitry Andric std::nullopt, std::move(ToInject));
3176fe013be4SDimitry Andric UnswitchCandidates.push_back(std::move(Candidate));
3177fe013be4SDimitry Andric }
3178fe013be4SDimitry Andric return true;
3179fe013be4SDimitry Andric }
3180fe013be4SDimitry Andric
3181fe013be4SDimitry Andric /// Collect unswitch candidates by invariant conditions that are not immediately
3182fe013be4SDimitry Andric /// present in the loop. However, they can be injected into the code if we
3183fe013be4SDimitry Andric /// decide it's profitable.
3184fe013be4SDimitry Andric /// An example of such conditions is following:
3185fe013be4SDimitry Andric ///
3186fe013be4SDimitry Andric /// for (...) {
3187fe013be4SDimitry Andric /// x = load ...
3188fe013be4SDimitry Andric /// if (! x <u C1) break;
3189fe013be4SDimitry Andric /// if (! x <u C2) break;
3190fe013be4SDimitry Andric /// <do something>
3191fe013be4SDimitry Andric /// }
3192fe013be4SDimitry Andric ///
3193fe013be4SDimitry Andric /// We can unswitch by condition "C1 <=u C2". If that is true, then "x <u C1 <=
3194fe013be4SDimitry Andric /// C2" automatically implies "x <u C2", so we can get rid of one of
3195fe013be4SDimitry Andric /// loop-variant checks in unswitched loop version.
collectUnswitchCandidatesWithInjections(SmallVectorImpl<NonTrivialUnswitchCandidate> & UnswitchCandidates,IVConditionInfo & PartialIVInfo,Instruction * & PartialIVCondBranch,Loop & L,const DominatorTree & DT,const LoopInfo & LI,AAResults & AA,const MemorySSAUpdater * MSSAU)3196fe013be4SDimitry Andric static bool collectUnswitchCandidatesWithInjections(
3197fe013be4SDimitry Andric SmallVectorImpl<NonTrivialUnswitchCandidate> &UnswitchCandidates,
3198fe013be4SDimitry Andric IVConditionInfo &PartialIVInfo, Instruction *&PartialIVCondBranch, Loop &L,
3199fe013be4SDimitry Andric const DominatorTree &DT, const LoopInfo &LI, AAResults &AA,
3200fe013be4SDimitry Andric const MemorySSAUpdater *MSSAU) {
3201fe013be4SDimitry Andric if (!InjectInvariantConditions)
3202fe013be4SDimitry Andric return false;
3203fe013be4SDimitry Andric
3204fe013be4SDimitry Andric if (!DT.isReachableFromEntry(L.getHeader()))
3205fe013be4SDimitry Andric return false;
3206fe013be4SDimitry Andric auto *Latch = L.getLoopLatch();
3207fe013be4SDimitry Andric // Need to have a single latch and a preheader.
3208fe013be4SDimitry Andric if (!Latch)
3209fe013be4SDimitry Andric return false;
3210fe013be4SDimitry Andric assert(L.getLoopPreheader() && "Must have a preheader!");
3211fe013be4SDimitry Andric
3212fe013be4SDimitry Andric DenseMap<Value *, SmallVector<CompareDesc, 4> > CandidatesULT;
3213fe013be4SDimitry Andric // Traverse the conditions that dominate latch (and therefore dominate each
3214fe013be4SDimitry Andric // other).
3215fe013be4SDimitry Andric for (auto *DTN = DT.getNode(Latch); L.contains(DTN->getBlock());
3216fe013be4SDimitry Andric DTN = DTN->getIDom()) {
3217fe013be4SDimitry Andric ICmpInst::Predicate Pred;
3218fe013be4SDimitry Andric Value *LHS = nullptr, *RHS = nullptr;
3219fe013be4SDimitry Andric BasicBlock *IfTrue = nullptr, *IfFalse = nullptr;
3220fe013be4SDimitry Andric auto *BB = DTN->getBlock();
3221fe013be4SDimitry Andric // Ignore inner loops.
3222fe013be4SDimitry Andric if (LI.getLoopFor(BB) != &L)
3223fe013be4SDimitry Andric continue;
3224fe013be4SDimitry Andric auto *Term = BB->getTerminator();
3225fe013be4SDimitry Andric if (!match(Term, m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)),
3226fe013be4SDimitry Andric m_BasicBlock(IfTrue), m_BasicBlock(IfFalse))))
3227fe013be4SDimitry Andric continue;
3228fe013be4SDimitry Andric if (!LHS->getType()->isIntegerTy())
3229fe013be4SDimitry Andric continue;
3230fe013be4SDimitry Andric canonicalizeForInvariantConditionInjection(Pred, LHS, RHS, IfTrue, IfFalse,
3231fe013be4SDimitry Andric L);
3232fe013be4SDimitry Andric if (!shouldTryInjectInvariantCondition(Pred, LHS, RHS, IfTrue, IfFalse, L))
3233fe013be4SDimitry Andric continue;
3234fe013be4SDimitry Andric if (!shouldTryInjectBasingOnMetadata(cast<BranchInst>(Term), IfTrue))
3235fe013be4SDimitry Andric continue;
3236fe013be4SDimitry Andric // Strip ZEXT for unsigned predicate.
3237fe013be4SDimitry Andric // TODO: once signed predicates are supported, also strip SEXT.
3238fe013be4SDimitry Andric CompareDesc Desc(cast<BranchInst>(Term), RHS, IfTrue);
3239fe013be4SDimitry Andric while (auto *Zext = dyn_cast<ZExtInst>(LHS))
3240fe013be4SDimitry Andric LHS = Zext->getOperand(0);
3241fe013be4SDimitry Andric CandidatesULT[LHS].push_back(Desc);
3242fe013be4SDimitry Andric }
3243fe013be4SDimitry Andric
3244fe013be4SDimitry Andric bool Found = false;
3245fe013be4SDimitry Andric for (auto &It : CandidatesULT)
3246fe013be4SDimitry Andric Found |= insertCandidatesWithPendingInjections(
3247fe013be4SDimitry Andric UnswitchCandidates, L, ICmpInst::ICMP_ULT, It.second, DT);
3248fe013be4SDimitry Andric return Found;
3249fe013be4SDimitry Andric }
3250fe013be4SDimitry Andric
isSafeForNoNTrivialUnswitching(Loop & L,LoopInfo & LI)3251bdd1243dSDimitry Andric static bool isSafeForNoNTrivialUnswitching(Loop &L, LoopInfo &LI) {
3252bdd1243dSDimitry Andric if (!L.isSafeToClone())
32530b57cec5SDimitry Andric return false;
3254bdd1243dSDimitry Andric for (auto *BB : L.blocks())
3255bdd1243dSDimitry Andric for (auto &I : *BB) {
3256bdd1243dSDimitry Andric if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
3257bdd1243dSDimitry Andric return false;
3258bdd1243dSDimitry Andric if (auto *CB = dyn_cast<CallBase>(&I)) {
3259bdd1243dSDimitry Andric assert(!CB->cannotDuplicate() && "Checked by L.isSafeToClone().");
3260bdd1243dSDimitry Andric if (CB->isConvergent())
3261bdd1243dSDimitry Andric return false;
3262bdd1243dSDimitry Andric }
3263bdd1243dSDimitry Andric }
32640b57cec5SDimitry Andric
32650b57cec5SDimitry Andric // Check if there are irreducible CFG cycles in this loop. If so, we cannot
32660b57cec5SDimitry Andric // easily unswitch non-trivial edges out of the loop. Doing so might turn the
32670b57cec5SDimitry Andric // irreducible control flow into reducible control flow and introduce new
32680b57cec5SDimitry Andric // loops "out of thin air". If we ever discover important use cases for doing
32690b57cec5SDimitry Andric // this, we can add support to loop unswitch, but it is a lot of complexity
32700b57cec5SDimitry Andric // for what seems little or no real world benefit.
32710b57cec5SDimitry Andric LoopBlocksRPO RPOT(&L);
32720b57cec5SDimitry Andric RPOT.perform(&LI);
32730b57cec5SDimitry Andric if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
32740b57cec5SDimitry Andric return false;
32750b57cec5SDimitry Andric
32760b57cec5SDimitry Andric SmallVector<BasicBlock *, 4> ExitBlocks;
32770b57cec5SDimitry Andric L.getUniqueExitBlocks(ExitBlocks);
3278fe6060f1SDimitry Andric // We cannot unswitch if exit blocks contain a cleanuppad/catchswitch
3279fe6060f1SDimitry Andric // instruction as we don't know how to split those exit blocks.
32800b57cec5SDimitry Andric // FIXME: We should teach SplitBlock to handle this and remove this
32810b57cec5SDimitry Andric // restriction.
3282fe6060f1SDimitry Andric for (auto *ExitBB : ExitBlocks) {
3283fe6060f1SDimitry Andric auto *I = ExitBB->getFirstNonPHI();
3284fe6060f1SDimitry Andric if (isa<CleanupPadInst>(I) || isa<CatchSwitchInst>(I)) {
3285fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Cannot unswitch because of cleanuppad/catchswitch "
3286fe6060f1SDimitry Andric "in exit block\n");
32870b57cec5SDimitry Andric return false;
32880b57cec5SDimitry Andric }
3289fe6060f1SDimitry Andric }
32900b57cec5SDimitry Andric
3291bdd1243dSDimitry Andric return true;
3292bdd1243dSDimitry Andric }
32930b57cec5SDimitry Andric
findBestNonTrivialUnswitchCandidate(ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates,const Loop & L,const DominatorTree & DT,const LoopInfo & LI,AssumptionCache & AC,const TargetTransformInfo & TTI,const IVConditionInfo & PartialIVInfo)3294bdd1243dSDimitry Andric static NonTrivialUnswitchCandidate findBestNonTrivialUnswitchCandidate(
3295bdd1243dSDimitry Andric ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates, const Loop &L,
3296bdd1243dSDimitry Andric const DominatorTree &DT, const LoopInfo &LI, AssumptionCache &AC,
3297bdd1243dSDimitry Andric const TargetTransformInfo &TTI, const IVConditionInfo &PartialIVInfo) {
32980b57cec5SDimitry Andric // Given that unswitching these terminators will require duplicating parts of
32990b57cec5SDimitry Andric // the loop, so we need to be able to model that cost. Compute the ephemeral
33000b57cec5SDimitry Andric // values and set up a data structure to hold per-BB costs. We cache each
33010b57cec5SDimitry Andric // block's cost so that we don't recompute this when considering different
33020b57cec5SDimitry Andric // subsets of the loop for duplication during unswitching.
33030b57cec5SDimitry Andric SmallPtrSet<const Value *, 4> EphValues;
33040b57cec5SDimitry Andric CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
3305fe6060f1SDimitry Andric SmallDenseMap<BasicBlock *, InstructionCost, 4> BBCostMap;
33060b57cec5SDimitry Andric
33070b57cec5SDimitry Andric // Compute the cost of each block, as well as the total loop cost. Also, bail
33080b57cec5SDimitry Andric // out if we see instructions which are incompatible with loop unswitching
33090b57cec5SDimitry Andric // (convergent, noduplicate, or cross-basic-block tokens).
33100b57cec5SDimitry Andric // FIXME: We might be able to safely handle some of these in non-duplicated
33110b57cec5SDimitry Andric // regions.
3312e8d8bef9SDimitry Andric TargetTransformInfo::TargetCostKind CostKind =
3313e8d8bef9SDimitry Andric L.getHeader()->getParent()->hasMinSize()
3314e8d8bef9SDimitry Andric ? TargetTransformInfo::TCK_CodeSize
3315e8d8bef9SDimitry Andric : TargetTransformInfo::TCK_SizeAndLatency;
3316fe6060f1SDimitry Andric InstructionCost LoopCost = 0;
33170b57cec5SDimitry Andric for (auto *BB : L.blocks()) {
3318fe6060f1SDimitry Andric InstructionCost Cost = 0;
33190b57cec5SDimitry Andric for (auto &I : *BB) {
33200b57cec5SDimitry Andric if (EphValues.count(&I))
33210b57cec5SDimitry Andric continue;
3322bdd1243dSDimitry Andric Cost += TTI.getInstructionCost(&I, CostKind);
33230b57cec5SDimitry Andric }
33240b57cec5SDimitry Andric assert(Cost >= 0 && "Must not have negative costs!");
33250b57cec5SDimitry Andric LoopCost += Cost;
33260b57cec5SDimitry Andric assert(LoopCost >= 0 && "Must not have negative loop costs!");
33270b57cec5SDimitry Andric BBCostMap[BB] = Cost;
33280b57cec5SDimitry Andric }
33290b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n");
33300b57cec5SDimitry Andric
33310b57cec5SDimitry Andric // Now we find the best candidate by searching for the one with the following
33320b57cec5SDimitry Andric // properties in order:
33330b57cec5SDimitry Andric //
33340b57cec5SDimitry Andric // 1) An unswitching cost below the threshold
33350b57cec5SDimitry Andric // 2) The smallest number of duplicated unswitch candidates (to avoid
33360b57cec5SDimitry Andric // creating redundant subsequent unswitching)
33370b57cec5SDimitry Andric // 3) The smallest cost after unswitching.
33380b57cec5SDimitry Andric //
33390b57cec5SDimitry Andric // We prioritize reducing fanout of unswitch candidates provided the cost
33400b57cec5SDimitry Andric // remains below the threshold because this has a multiplicative effect.
33410b57cec5SDimitry Andric //
33420b57cec5SDimitry Andric // This requires memoizing each dominator subtree to avoid redundant work.
33430b57cec5SDimitry Andric //
33440b57cec5SDimitry Andric // FIXME: Need to actually do the number of candidates part above.
3345fe6060f1SDimitry Andric SmallDenseMap<DomTreeNode *, InstructionCost, 4> DTCostMap;
33460b57cec5SDimitry Andric // Given a terminator which might be unswitched, computes the non-duplicated
33470b57cec5SDimitry Andric // cost for that terminator.
3348fe6060f1SDimitry Andric auto ComputeUnswitchedCost = [&](Instruction &TI,
3349fe6060f1SDimitry Andric bool FullUnswitch) -> InstructionCost {
3350fe013be4SDimitry Andric // Unswitching selects unswitches the entire loop.
3351fe013be4SDimitry Andric if (isa<SelectInst>(TI))
3352fe013be4SDimitry Andric return LoopCost;
3353fe013be4SDimitry Andric
33540b57cec5SDimitry Andric BasicBlock &BB = *TI.getParent();
33550b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 4> Visited;
33560b57cec5SDimitry Andric
3357fe6060f1SDimitry Andric InstructionCost Cost = 0;
33580b57cec5SDimitry Andric for (BasicBlock *SuccBB : successors(&BB)) {
33590b57cec5SDimitry Andric // Don't count successors more than once.
33600b57cec5SDimitry Andric if (!Visited.insert(SuccBB).second)
33610b57cec5SDimitry Andric continue;
33620b57cec5SDimitry Andric
33630b57cec5SDimitry Andric // If this is a partial unswitch candidate, then it must be a conditional
3364fe6060f1SDimitry Andric // branch with a condition of either `or`, `and`, their corresponding
3365fe6060f1SDimitry Andric // select forms or partially invariant instructions. In that case, one of
33660b57cec5SDimitry Andric // the successors is necessarily duplicated, so don't even try to remove
33670b57cec5SDimitry Andric // its cost.
33680b57cec5SDimitry Andric if (!FullUnswitch) {
33690b57cec5SDimitry Andric auto &BI = cast<BranchInst>(TI);
337081ad6265SDimitry Andric Value *Cond = skipTrivialSelect(BI.getCondition());
337181ad6265SDimitry Andric if (match(Cond, m_LogicalAnd())) {
33720b57cec5SDimitry Andric if (SuccBB == BI.getSuccessor(1))
33730b57cec5SDimitry Andric continue;
337481ad6265SDimitry Andric } else if (match(Cond, m_LogicalOr())) {
33750b57cec5SDimitry Andric if (SuccBB == BI.getSuccessor(0))
33760b57cec5SDimitry Andric continue;
3377fe6060f1SDimitry Andric } else if ((PartialIVInfo.KnownValue->isOneValue() &&
3378fe6060f1SDimitry Andric SuccBB == BI.getSuccessor(0)) ||
3379fe6060f1SDimitry Andric (!PartialIVInfo.KnownValue->isOneValue() &&
3380fe6060f1SDimitry Andric SuccBB == BI.getSuccessor(1)))
3381fe6060f1SDimitry Andric continue;
33820b57cec5SDimitry Andric }
33830b57cec5SDimitry Andric
33840b57cec5SDimitry Andric // This successor's domtree will not need to be duplicated after
33850b57cec5SDimitry Andric // unswitching if the edge to the successor dominates it (and thus the
33860b57cec5SDimitry Andric // entire tree). This essentially means there is no other path into this
33870b57cec5SDimitry Andric // subtree and so it will end up live in only one clone of the loop.
33880b57cec5SDimitry Andric if (SuccBB->getUniquePredecessor() ||
33890b57cec5SDimitry Andric llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
33900b57cec5SDimitry Andric return PredBB == &BB || DT.dominates(SuccBB, PredBB);
33910b57cec5SDimitry Andric })) {
3392fe6060f1SDimitry Andric Cost += computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
3393fe6060f1SDimitry Andric assert(Cost <= LoopCost &&
33940b57cec5SDimitry Andric "Non-duplicated cost should never exceed total loop cost!");
33950b57cec5SDimitry Andric }
33960b57cec5SDimitry Andric }
33970b57cec5SDimitry Andric
33980b57cec5SDimitry Andric // Now scale the cost by the number of unique successors minus one. We
33990b57cec5SDimitry Andric // subtract one because there is already at least one copy of the entire
34000b57cec5SDimitry Andric // loop. This is computing the new cost of unswitching a condition.
34010b57cec5SDimitry Andric // Note that guards always have 2 unique successors that are implicit and
34020b57cec5SDimitry Andric // will be materialized if we decide to unswitch it.
34030b57cec5SDimitry Andric int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
34040b57cec5SDimitry Andric assert(SuccessorsCount > 1 &&
34050b57cec5SDimitry Andric "Cannot unswitch a condition without multiple distinct successors!");
3406fe6060f1SDimitry Andric return (LoopCost - Cost) * (SuccessorsCount - 1);
34070b57cec5SDimitry Andric };
3408bdd1243dSDimitry Andric
3409bdd1243dSDimitry Andric std::optional<NonTrivialUnswitchCandidate> Best;
3410bdd1243dSDimitry Andric for (auto &Candidate : UnswitchCandidates) {
3411bdd1243dSDimitry Andric Instruction &TI = *Candidate.TI;
3412bdd1243dSDimitry Andric ArrayRef<Value *> Invariants = Candidate.Invariants;
34130b57cec5SDimitry Andric BranchInst *BI = dyn_cast<BranchInst>(&TI);
3414fe013be4SDimitry Andric bool FullUnswitch =
3415fe013be4SDimitry Andric !BI || Candidate.hasPendingInjection() ||
341681ad6265SDimitry Andric (Invariants.size() == 1 &&
3417fe013be4SDimitry Andric Invariants[0] == skipTrivialSelect(BI->getCondition()));
3418fe013be4SDimitry Andric InstructionCost CandidateCost = ComputeUnswitchedCost(TI, FullUnswitch);
34190b57cec5SDimitry Andric // Calculate cost multiplier which is a tool to limit potentially
34200b57cec5SDimitry Andric // exponential behavior of loop-unswitch.
34210b57cec5SDimitry Andric if (EnableUnswitchCostMultiplier) {
34220b57cec5SDimitry Andric int CostMultiplier =
34235ffd83dbSDimitry Andric CalculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
34240b57cec5SDimitry Andric assert(
34250b57cec5SDimitry Andric (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
34260b57cec5SDimitry Andric "cost multiplier needs to be in the range of 1..UnswitchThreshold");
34270b57cec5SDimitry Andric CandidateCost *= CostMultiplier;
34280b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
34290b57cec5SDimitry Andric << " (multiplier: " << CostMultiplier << ")"
34300b57cec5SDimitry Andric << " for unswitch candidate: " << TI << "\n");
34310b57cec5SDimitry Andric } else {
34320b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
34330b57cec5SDimitry Andric << " for unswitch candidate: " << TI << "\n");
34340b57cec5SDimitry Andric }
34350b57cec5SDimitry Andric
3436bdd1243dSDimitry Andric if (!Best || CandidateCost < Best->Cost) {
3437bdd1243dSDimitry Andric Best = Candidate;
3438bdd1243dSDimitry Andric Best->Cost = CandidateCost;
34390b57cec5SDimitry Andric }
34400b57cec5SDimitry Andric }
3441bdd1243dSDimitry Andric assert(Best && "Must be!");
3442bdd1243dSDimitry Andric return *Best;
3443bdd1243dSDimitry Andric }
34440b57cec5SDimitry Andric
3445fe013be4SDimitry Andric // Insert a freeze on an unswitched branch if all is true:
3446fe013be4SDimitry Andric // 1. freeze-loop-unswitch-cond option is true
3447fe013be4SDimitry Andric // 2. The branch may not execute in the loop pre-transformation. If a branch may
3448fe013be4SDimitry Andric // not execute and could cause UB, it would always cause UB if it is hoisted outside
3449fe013be4SDimitry Andric // of the loop. Insert a freeze to prevent this case.
3450fe013be4SDimitry Andric // 3. The branch condition may be poison or undef
shouldInsertFreeze(Loop & L,Instruction & TI,DominatorTree & DT,AssumptionCache & AC)3451fe013be4SDimitry Andric static bool shouldInsertFreeze(Loop &L, Instruction &TI, DominatorTree &DT,
3452fe013be4SDimitry Andric AssumptionCache &AC) {
3453fe013be4SDimitry Andric assert(isa<BranchInst>(TI) || isa<SwitchInst>(TI));
3454fe013be4SDimitry Andric if (!FreezeLoopUnswitchCond)
3455fe013be4SDimitry Andric return false;
3456fe013be4SDimitry Andric
3457fe013be4SDimitry Andric ICFLoopSafetyInfo SafetyInfo;
3458fe013be4SDimitry Andric SafetyInfo.computeLoopSafetyInfo(&L);
3459fe013be4SDimitry Andric if (SafetyInfo.isGuaranteedToExecute(TI, &DT, &L))
3460fe013be4SDimitry Andric return false;
3461fe013be4SDimitry Andric
3462fe013be4SDimitry Andric Value *Cond;
3463fe013be4SDimitry Andric if (BranchInst *BI = dyn_cast<BranchInst>(&TI))
3464fe013be4SDimitry Andric Cond = skipTrivialSelect(BI->getCondition());
3465fe013be4SDimitry Andric else
3466fe013be4SDimitry Andric Cond = skipTrivialSelect(cast<SwitchInst>(&TI)->getCondition());
3467fe013be4SDimitry Andric return !isGuaranteedNotToBeUndefOrPoison(
3468fe013be4SDimitry Andric Cond, &AC, L.getLoopPreheader()->getTerminator(), &DT);
3469fe013be4SDimitry Andric }
3470fe013be4SDimitry Andric
unswitchBestCondition(Loop & L,DominatorTree & DT,LoopInfo & LI,AssumptionCache & AC,AAResults & AA,TargetTransformInfo & TTI,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,LPMUpdater & LoopUpdater)3471*c9157d92SDimitry Andric static bool unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
3472*c9157d92SDimitry Andric AssumptionCache &AC, AAResults &AA,
3473*c9157d92SDimitry Andric TargetTransformInfo &TTI, ScalarEvolution *SE,
3474*c9157d92SDimitry Andric MemorySSAUpdater *MSSAU,
3475*c9157d92SDimitry Andric LPMUpdater &LoopUpdater) {
3476bdd1243dSDimitry Andric // Collect all invariant conditions within this loop (as opposed to an inner
3477bdd1243dSDimitry Andric // loop which would be handled when visiting that inner loop).
3478bdd1243dSDimitry Andric SmallVector<NonTrivialUnswitchCandidate, 4> UnswitchCandidates;
3479bdd1243dSDimitry Andric IVConditionInfo PartialIVInfo;
3480bdd1243dSDimitry Andric Instruction *PartialIVCondBranch = nullptr;
3481fe013be4SDimitry Andric collectUnswitchCandidates(UnswitchCandidates, PartialIVInfo,
3482fe013be4SDimitry Andric PartialIVCondBranch, L, LI, AA, MSSAU);
34837126fb41SDimitry Andric if (!findOptionMDForLoop(&L, "llvm.loop.unswitch.injection.disable"))
3484fe013be4SDimitry Andric collectUnswitchCandidatesWithInjections(UnswitchCandidates, PartialIVInfo,
3485fe013be4SDimitry Andric PartialIVCondBranch, L, DT, LI, AA,
3486fe013be4SDimitry Andric MSSAU);
3487bdd1243dSDimitry Andric // If we didn't find any candidates, we're done.
3488fe013be4SDimitry Andric if (UnswitchCandidates.empty())
3489bdd1243dSDimitry Andric return false;
3490bdd1243dSDimitry Andric
3491bdd1243dSDimitry Andric LLVM_DEBUG(
3492bdd1243dSDimitry Andric dbgs() << "Considering " << UnswitchCandidates.size()
3493bdd1243dSDimitry Andric << " non-trivial loop invariant conditions for unswitching.\n");
3494bdd1243dSDimitry Andric
3495bdd1243dSDimitry Andric NonTrivialUnswitchCandidate Best = findBestNonTrivialUnswitchCandidate(
3496bdd1243dSDimitry Andric UnswitchCandidates, L, DT, LI, AC, TTI, PartialIVInfo);
3497bdd1243dSDimitry Andric
3498bdd1243dSDimitry Andric assert(Best.TI && "Failed to find loop unswitch candidate");
3499bdd1243dSDimitry Andric assert(Best.Cost && "Failed to compute cost");
3500bdd1243dSDimitry Andric
3501bdd1243dSDimitry Andric if (*Best.Cost >= UnswitchThreshold) {
3502bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: " << *Best.Cost
3503bdd1243dSDimitry Andric << "\n");
35040b57cec5SDimitry Andric return false;
35050b57cec5SDimitry Andric }
35060b57cec5SDimitry Andric
35077126fb41SDimitry Andric bool InjectedCondition = false;
35087126fb41SDimitry Andric if (Best.hasPendingInjection()) {
3509fe013be4SDimitry Andric Best = injectPendingInvariantConditions(Best, L, DT, LI, AC, MSSAU);
35107126fb41SDimitry Andric InjectedCondition = true;
35117126fb41SDimitry Andric }
3512fe013be4SDimitry Andric assert(!Best.hasPendingInjection() &&
3513fe013be4SDimitry Andric "All injections should have been done by now!");
3514fe013be4SDimitry Andric
3515bdd1243dSDimitry Andric if (Best.TI != PartialIVCondBranch)
3516fe6060f1SDimitry Andric PartialIVInfo.InstToDuplicate.clear();
3517fe6060f1SDimitry Andric
3518fe013be4SDimitry Andric bool InsertFreeze;
3519fe013be4SDimitry Andric if (auto *SI = dyn_cast<SelectInst>(Best.TI)) {
3520fe013be4SDimitry Andric // If the best candidate is a select, turn it into a branch. Select
3521fe013be4SDimitry Andric // instructions with a poison conditional do not propagate poison, but
3522fe013be4SDimitry Andric // branching on poison causes UB. Insert a freeze on the select
3523fe013be4SDimitry Andric // conditional to prevent UB after turning the select into a branch.
3524fe013be4SDimitry Andric InsertFreeze = !isGuaranteedNotToBeUndefOrPoison(
3525fe013be4SDimitry Andric SI->getCondition(), &AC, L.getLoopPreheader()->getTerminator(), &DT);
3526fe013be4SDimitry Andric Best.TI = turnSelectIntoBranch(SI, DT, LI, MSSAU, &AC);
3527fe013be4SDimitry Andric } else {
35280b57cec5SDimitry Andric // If the best candidate is a guard, turn it into a branch.
3529bdd1243dSDimitry Andric if (isGuard(Best.TI))
3530bdd1243dSDimitry Andric Best.TI =
3531bdd1243dSDimitry Andric turnGuardIntoBranch(cast<IntrinsicInst>(Best.TI), L, DT, LI, MSSAU);
3532fe013be4SDimitry Andric InsertFreeze = shouldInsertFreeze(L, *Best.TI, DT, AC);
3533fe013be4SDimitry Andric }
35340b57cec5SDimitry Andric
3535bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = " << Best.Cost
3536bdd1243dSDimitry Andric << ") terminator: " << *Best.TI << "\n");
3537bdd1243dSDimitry Andric unswitchNontrivialInvariants(L, *Best.TI, Best.Invariants, PartialIVInfo, DT,
3538*c9157d92SDimitry Andric LI, AC, SE, MSSAU, LoopUpdater, InsertFreeze,
3539*c9157d92SDimitry Andric InjectedCondition);
35400b57cec5SDimitry Andric return true;
35410b57cec5SDimitry Andric }
35420b57cec5SDimitry Andric
35430b57cec5SDimitry Andric /// Unswitch control flow predicated on loop invariant conditions.
35440b57cec5SDimitry Andric ///
35450b57cec5SDimitry Andric /// This first hoists all branches or switches which are trivial (IE, do not
35460b57cec5SDimitry Andric /// require duplicating any part of the loop) out of the loop body. It then
35470b57cec5SDimitry Andric /// looks at other loop invariant control flows and tries to unswitch those as
35480b57cec5SDimitry Andric /// well by cloning the loop if the result is small enough.
35490b57cec5SDimitry Andric ///
3550fe6060f1SDimitry Andric /// The `DT`, `LI`, `AC`, `AA`, `TTI` parameters are required analyses that are
3551fe6060f1SDimitry Andric /// also updated based on the unswitch. The `MSSA` analysis is also updated if
3552fe6060f1SDimitry Andric /// valid (i.e. its use is enabled).
35530b57cec5SDimitry Andric ///
35540b57cec5SDimitry Andric /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
35550b57cec5SDimitry Andric /// true, we will attempt to do non-trivial unswitching as well as trivial
35560b57cec5SDimitry Andric /// unswitching.
35570b57cec5SDimitry Andric ///
3558*c9157d92SDimitry Andric /// The `postUnswitch` function will be run after unswitching is complete
3559*c9157d92SDimitry Andric /// with information on whether or not the provided loop remains a loop and
3560*c9157d92SDimitry Andric /// a list of new sibling loops created.
35610b57cec5SDimitry Andric ///
35620b57cec5SDimitry Andric /// If `SE` is non-null, we will update that analysis based on the unswitching
35630b57cec5SDimitry Andric /// done.
unswitchLoop(Loop & L,DominatorTree & DT,LoopInfo & LI,AssumptionCache & AC,AAResults & AA,TargetTransformInfo & TTI,bool Trivial,bool NonTrivial,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,ProfileSummaryInfo * PSI,BlockFrequencyInfo * BFI,LPMUpdater & LoopUpdater)3564*c9157d92SDimitry Andric static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
3565*c9157d92SDimitry Andric AssumptionCache &AC, AAResults &AA,
3566*c9157d92SDimitry Andric TargetTransformInfo &TTI, bool Trivial,
3567*c9157d92SDimitry Andric bool NonTrivial, ScalarEvolution *SE,
3568*c9157d92SDimitry Andric MemorySSAUpdater *MSSAU, ProfileSummaryInfo *PSI,
3569*c9157d92SDimitry Andric BlockFrequencyInfo *BFI, LPMUpdater &LoopUpdater) {
35700b57cec5SDimitry Andric assert(L.isRecursivelyLCSSAForm(DT, LI) &&
35710b57cec5SDimitry Andric "Loops must be in LCSSA form before unswitching.");
35720b57cec5SDimitry Andric
35730b57cec5SDimitry Andric // Must be in loop simplified form: we need a preheader and dedicated exits.
35740b57cec5SDimitry Andric if (!L.isLoopSimplifyForm())
35750b57cec5SDimitry Andric return false;
35760b57cec5SDimitry Andric
35770b57cec5SDimitry Andric // Try trivial unswitch first before loop over other basic blocks in the loop.
3578fe6060f1SDimitry Andric if (Trivial && unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
35790b57cec5SDimitry Andric // If we unswitched successfully we will want to clean up the loop before
35800b57cec5SDimitry Andric // processing it further so just mark it as unswitched and return.
3581*c9157d92SDimitry Andric postUnswitch(L, LoopUpdater, L.getName(),
3582*c9157d92SDimitry Andric /*CurrentLoopValid*/ true, /*PartiallyInvariant*/ false,
35837126fb41SDimitry Andric /*InjectedCondition*/ false, {});
35840b57cec5SDimitry Andric return true;
35850b57cec5SDimitry Andric }
35860b57cec5SDimitry Andric
3587fe013be4SDimitry Andric const Function *F = L.getHeader()->getParent();
3588fe013be4SDimitry Andric
3589fe6060f1SDimitry Andric // Check whether we should continue with non-trivial conditions.
3590fe6060f1SDimitry Andric // EnableNonTrivialUnswitch: Global variable that forces non-trivial
3591fe6060f1SDimitry Andric // unswitching for testing and debugging.
3592fe6060f1SDimitry Andric // NonTrivial: Parameter that enables non-trivial unswitching for this
3593fe6060f1SDimitry Andric // invocation of the transform. But this should be allowed only
3594fe6060f1SDimitry Andric // for targets without branch divergence.
3595fe6060f1SDimitry Andric //
3596fe6060f1SDimitry Andric // FIXME: If divergence analysis becomes available to a loop
3597fe6060f1SDimitry Andric // transform, we should allow unswitching for non-trivial uniform
3598fe6060f1SDimitry Andric // branches even on targets that have divergence.
3599fe6060f1SDimitry Andric // https://bugs.llvm.org/show_bug.cgi?id=48819
3600fe6060f1SDimitry Andric bool ContinueWithNonTrivial =
3601fe013be4SDimitry Andric EnableNonTrivialUnswitch || (NonTrivial && !TTI.hasBranchDivergence(F));
3602fe6060f1SDimitry Andric if (!ContinueWithNonTrivial)
36030b57cec5SDimitry Andric return false;
36040b57cec5SDimitry Andric
3605e8d8bef9SDimitry Andric // Skip non-trivial unswitching for optsize functions.
3606fe013be4SDimitry Andric if (F->hasOptSize())
3607e8d8bef9SDimitry Andric return false;
3608e8d8bef9SDimitry Andric
3609fe013be4SDimitry Andric // Returns true if Loop L's loop nest is cold, i.e. if the headers of L,
3610fe013be4SDimitry Andric // of the loops L is nested in, and of the loops nested in L are all cold.
3611fe013be4SDimitry Andric auto IsLoopNestCold = [&](const Loop *L) {
3612fe013be4SDimitry Andric // Check L and all of its parent loops.
3613fe013be4SDimitry Andric auto *Parent = L;
3614fe013be4SDimitry Andric while (Parent) {
3615fe013be4SDimitry Andric if (!PSI->isColdBlock(Parent->getHeader(), BFI))
3616fe013be4SDimitry Andric return false;
3617fe013be4SDimitry Andric Parent = Parent->getParentLoop();
3618fe013be4SDimitry Andric }
3619fe013be4SDimitry Andric // Next check all loops nested within L.
3620fe013be4SDimitry Andric SmallVector<const Loop *, 4> Worklist;
3621fe013be4SDimitry Andric Worklist.insert(Worklist.end(), L->getSubLoops().begin(),
3622fe013be4SDimitry Andric L->getSubLoops().end());
3623fe013be4SDimitry Andric while (!Worklist.empty()) {
3624fe013be4SDimitry Andric auto *CurLoop = Worklist.pop_back_val();
3625fe013be4SDimitry Andric if (!PSI->isColdBlock(CurLoop->getHeader(), BFI))
3626fe013be4SDimitry Andric return false;
3627fe013be4SDimitry Andric Worklist.insert(Worklist.end(), CurLoop->getSubLoops().begin(),
3628fe013be4SDimitry Andric CurLoop->getSubLoops().end());
3629fe013be4SDimitry Andric }
3630fe013be4SDimitry Andric return true;
3631fe013be4SDimitry Andric };
3632fe013be4SDimitry Andric
3633fe013be4SDimitry Andric // Skip cold loops in cold loop nests, as unswitching them brings little
3634fe013be4SDimitry Andric // benefit but increases the code size
3635fe013be4SDimitry Andric if (PSI && PSI->hasProfileSummary() && BFI && IsLoopNestCold(&L)) {
3636bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << " Skip cold loop: " << L << "\n");
3637bdd1243dSDimitry Andric return false;
3638bdd1243dSDimitry Andric }
3639bdd1243dSDimitry Andric
3640bdd1243dSDimitry Andric // Perform legality checks.
3641bdd1243dSDimitry Andric if (!isSafeForNoNTrivialUnswitching(L, LI))
3642fe6060f1SDimitry Andric return false;
3643fe6060f1SDimitry Andric
36440b57cec5SDimitry Andric // For non-trivial unswitching, because it often creates new loops, we rely on
36450b57cec5SDimitry Andric // the pass manager to iterate on the loops rather than trying to immediately
36460b57cec5SDimitry Andric // reach a fixed point. There is no substantial advantage to iterating
36470b57cec5SDimitry Andric // internally, and if any of the new loops are simplified enough to contain
36480b57cec5SDimitry Andric // trivial unswitching we want to prefer those.
36490b57cec5SDimitry Andric
36500b57cec5SDimitry Andric // Try to unswitch the best invariant condition. We prefer this full unswitch to
36510b57cec5SDimitry Andric // a partial unswitch when possible below the threshold.
3652*c9157d92SDimitry Andric if (unswitchBestCondition(L, DT, LI, AC, AA, TTI, SE, MSSAU, LoopUpdater))
36530b57cec5SDimitry Andric return true;
36540b57cec5SDimitry Andric
36550b57cec5SDimitry Andric // No other opportunities to unswitch.
3656e8d8bef9SDimitry Andric return false;
36570b57cec5SDimitry Andric }
36580b57cec5SDimitry Andric
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater & U)36590b57cec5SDimitry Andric PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
36600b57cec5SDimitry Andric LoopStandardAnalysisResults &AR,
36610b57cec5SDimitry Andric LPMUpdater &U) {
36620b57cec5SDimitry Andric Function &F = *L.getHeader()->getParent();
36630b57cec5SDimitry Andric (void)F;
3664bdd1243dSDimitry Andric ProfileSummaryInfo *PSI = nullptr;
3665bdd1243dSDimitry Andric if (auto OuterProxy =
3666bdd1243dSDimitry Andric AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR)
3667bdd1243dSDimitry Andric .getCachedResult<ModuleAnalysisManagerFunctionProxy>(F))
3668bdd1243dSDimitry Andric PSI = OuterProxy->getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
36690b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
36700b57cec5SDimitry Andric << "\n");
36710b57cec5SDimitry Andric
3672bdd1243dSDimitry Andric std::optional<MemorySSAUpdater> MSSAU;
36730b57cec5SDimitry Andric if (AR.MSSA) {
36740b57cec5SDimitry Andric MSSAU = MemorySSAUpdater(AR.MSSA);
36750b57cec5SDimitry Andric if (VerifyMemorySSA)
36760b57cec5SDimitry Andric AR.MSSA->verifyMemorySSA();
36770b57cec5SDimitry Andric }
3678fe6060f1SDimitry Andric if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.AA, AR.TTI, Trivial, NonTrivial,
3679*c9157d92SDimitry Andric &AR.SE, MSSAU ? &*MSSAU : nullptr, PSI, AR.BFI, U))
36800b57cec5SDimitry Andric return PreservedAnalyses::all();
36810b57cec5SDimitry Andric
36820b57cec5SDimitry Andric if (AR.MSSA && VerifyMemorySSA)
36830b57cec5SDimitry Andric AR.MSSA->verifyMemorySSA();
36840b57cec5SDimitry Andric
36850b57cec5SDimitry Andric // Historically this pass has had issues with the dominator tree so verify it
36860b57cec5SDimitry Andric // in asserts builds.
36870b57cec5SDimitry Andric assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
36880b57cec5SDimitry Andric
36890b57cec5SDimitry Andric auto PA = getLoopPassPreservedAnalyses();
36908bcb0991SDimitry Andric if (AR.MSSA)
36910b57cec5SDimitry Andric PA.preserve<MemorySSAAnalysis>();
36920b57cec5SDimitry Andric return PA;
36930b57cec5SDimitry Andric }
36940b57cec5SDimitry Andric
printPipeline(raw_ostream & OS,function_ref<StringRef (StringRef)> MapClassName2PassName)3695349cc55cSDimitry Andric void SimpleLoopUnswitchPass::printPipeline(
3696349cc55cSDimitry Andric raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
3697349cc55cSDimitry Andric static_cast<PassInfoMixin<SimpleLoopUnswitchPass> *>(this)->printPipeline(
3698349cc55cSDimitry Andric OS, MapClassName2PassName);
3699349cc55cSDimitry Andric
3700fe013be4SDimitry Andric OS << '<';
3701349cc55cSDimitry Andric OS << (NonTrivial ? "" : "no-") << "nontrivial;";
3702349cc55cSDimitry Andric OS << (Trivial ? "" : "no-") << "trivial";
3703fe013be4SDimitry Andric OS << '>';
3704349cc55cSDimitry Andric }
3705