1d8b0c8ceSChandler Carruth ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
21353f9a4SChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61353f9a4SChandler Carruth //
71353f9a4SChandler Carruth //===----------------------------------------------------------------------===//
81353f9a4SChandler Carruth
96bda14b3SChandler Carruth #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
10a369a457SEugene Zelenko #include "llvm/ADT/DenseMap.h"
116bda14b3SChandler Carruth #include "llvm/ADT/STLExtras.h"
12a369a457SEugene Zelenko #include "llvm/ADT/Sequence.h"
13a369a457SEugene Zelenko #include "llvm/ADT/SetVector.h"
141353f9a4SChandler Carruth #include "llvm/ADT/SmallPtrSet.h"
15a369a457SEugene Zelenko #include "llvm/ADT/SmallVector.h"
161353f9a4SChandler Carruth #include "llvm/ADT/Statistic.h"
17a369a457SEugene Zelenko #include "llvm/ADT/Twine.h"
181353f9a4SChandler Carruth #include "llvm/Analysis/AssumptionCache.h"
1932e62f9cSChandler Carruth #include "llvm/Analysis/CFG.h"
20693eedb1SChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
21619a8346SMax Kazantsev #include "llvm/Analysis/GuardUtils.h"
22a369a457SEugene Zelenko #include "llvm/Analysis/LoopAnalysisManager.h"
231353f9a4SChandler Carruth #include "llvm/Analysis/LoopInfo.h"
2432e62f9cSChandler Carruth #include "llvm/Analysis/LoopIterator.h"
251353f9a4SChandler Carruth #include "llvm/Analysis/LoopPass.h"
26a2eebb82SAlina Sbirlea #include "llvm/Analysis/MemorySSA.h"
27a2eebb82SAlina Sbirlea #include "llvm/Analysis/MemorySSAUpdater.h"
288aaeee5fSMax Kazantsev #include "llvm/Analysis/MustExecute.h"
299ed8e0caSdfukalov #include "llvm/Analysis/ScalarEvolution.h"
30a494ae43Sserge-sans-paille #include "llvm/Analysis/TargetTransformInfo.h"
310aeb3732Shyeongyu kim #include "llvm/Analysis/ValueTracking.h"
32a369a457SEugene Zelenko #include "llvm/IR/BasicBlock.h"
33a369a457SEugene Zelenko #include "llvm/IR/Constant.h"
341353f9a4SChandler Carruth #include "llvm/IR/Constants.h"
351353f9a4SChandler Carruth #include "llvm/IR/Dominators.h"
361353f9a4SChandler Carruth #include "llvm/IR/Function.h"
379ed8e0caSdfukalov #include "llvm/IR/IRBuilder.h"
38a369a457SEugene Zelenko #include "llvm/IR/InstrTypes.h"
39a369a457SEugene Zelenko #include "llvm/IR/Instruction.h"
401353f9a4SChandler Carruth #include "llvm/IR/Instructions.h"
41693eedb1SChandler Carruth #include "llvm/IR/IntrinsicInst.h"
425bb38e84SJuneyoung Lee #include "llvm/IR/PatternMatch.h"
43a369a457SEugene Zelenko #include "llvm/IR/Use.h"
44a369a457SEugene Zelenko #include "llvm/IR/Value.h"
4505da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
46a369a457SEugene Zelenko #include "llvm/Pass.h"
47a369a457SEugene Zelenko #include "llvm/Support/Casting.h"
484c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
491353f9a4SChandler Carruth #include "llvm/Support/Debug.h"
50a369a457SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
51a369a457SEugene Zelenko #include "llvm/Support/GenericDomTree.h"
52a494ae43Sserge-sans-paille #include "llvm/Support/InstructionCost.h"
531353f9a4SChandler Carruth #include "llvm/Support/raw_ostream.h"
5459630917Sserge-sans-paille #include "llvm/Transforms/Scalar/LoopPassManager.h"
551353f9a4SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
56693eedb1SChandler Carruth #include "llvm/Transforms/Utils/Cloning.h"
575502cfa0SSerguei Katkov #include "llvm/Transforms/Utils/Local.h"
581353f9a4SChandler Carruth #include "llvm/Transforms/Utils/LoopUtils.h"
59693eedb1SChandler Carruth #include "llvm/Transforms/Utils/ValueMapper.h"
60a369a457SEugene Zelenko #include <algorithm>
61a369a457SEugene Zelenko #include <cassert>
62a369a457SEugene Zelenko #include <iterator>
63693eedb1SChandler Carruth #include <numeric>
64a369a457SEugene Zelenko #include <utility>
651353f9a4SChandler Carruth
661353f9a4SChandler Carruth #define DEBUG_TYPE "simple-loop-unswitch"
671353f9a4SChandler Carruth
681353f9a4SChandler Carruth using namespace llvm;
695bb38e84SJuneyoung Lee using namespace llvm::PatternMatch;
701353f9a4SChandler Carruth
711353f9a4SChandler Carruth STATISTIC(NumBranches, "Number of branches unswitched");
721353f9a4SChandler Carruth STATISTIC(NumSwitches, "Number of switches unswitched");
73619a8346SMax Kazantsev STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
741353f9a4SChandler Carruth STATISTIC(NumTrivial, "Number of unswitches that are trivial");
752e3e224eSFedor Sergeev STATISTIC(
762e3e224eSFedor Sergeev NumCostMultiplierSkipped,
772e3e224eSFedor Sergeev "Number of unswitch candidates that had their cost multiplier skipped");
781353f9a4SChandler Carruth
79693eedb1SChandler Carruth static cl::opt<bool> EnableNonTrivialUnswitch(
80693eedb1SChandler Carruth "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
81693eedb1SChandler Carruth cl::desc("Forcibly enables non-trivial loop unswitching rather than "
82693eedb1SChandler Carruth "following the configuration passed into the pass."));
83693eedb1SChandler Carruth
84693eedb1SChandler Carruth static cl::opt<int>
85693eedb1SChandler Carruth UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
86693eedb1SChandler Carruth cl::desc("The cost threshold for unswitching a loop."));
87693eedb1SChandler Carruth
882e3e224eSFedor Sergeev static cl::opt<bool> EnableUnswitchCostMultiplier(
892e3e224eSFedor Sergeev "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
902e3e224eSFedor Sergeev cl::desc("Enable unswitch cost multiplier that prohibits exponential "
912e3e224eSFedor Sergeev "explosion in nontrivial unswitch."));
922e3e224eSFedor Sergeev static cl::opt<int> UnswitchSiblingsToplevelDiv(
932e3e224eSFedor Sergeev "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
942e3e224eSFedor Sergeev cl::desc("Toplevel siblings divisor for cost multiplier."));
952e3e224eSFedor Sergeev static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
962e3e224eSFedor Sergeev "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
972e3e224eSFedor Sergeev cl::desc("Number of unswitch candidates that are ignored when calculating "
982e3e224eSFedor Sergeev "cost multiplier."));
99619a8346SMax Kazantsev static cl::opt<bool> UnswitchGuards(
100619a8346SMax Kazantsev "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
101619a8346SMax Kazantsev cl::desc("If enabled, simple loop unswitching will also consider "
102619a8346SMax Kazantsev "llvm.experimental.guard intrinsics as unswitch candidates."));
1037647c271SMax Kazantsev static cl::opt<bool> DropNonTrivialImplicitNullChecks(
1047647c271SMax Kazantsev "simple-loop-unswitch-drop-non-trivial-implicit-null-checks",
1057647c271SMax Kazantsev cl::init(false), cl::Hidden,
1067647c271SMax Kazantsev cl::desc("If enabled, drop make.implicit metadata in unswitched implicit "
1077647c271SMax Kazantsev "null checks to save time analyzing if we can keep it."));
108f3a27511SJingu Kang static cl::opt<unsigned>
109f3a27511SJingu Kang MSSAThreshold("simple-loop-unswitch-memoryssa-threshold",
110f3a27511SJingu Kang cl::desc("Max number of memory uses to explore during "
111f3a27511SJingu Kang "partial unswitching analysis"),
112f3a27511SJingu Kang cl::init(100), cl::Hidden);
1130aeb3732Shyeongyu kim static cl::opt<bool> FreezeLoopUnswitchCond(
1146a6cc554SFlorian Hahn "freeze-loop-unswitch-cond", cl::init(true), cl::Hidden,
1150aeb3732Shyeongyu kim cl::desc("If enabled, the freeze instruction will be added to condition "
1160aeb3732Shyeongyu kim "of loop unswitch to prevent miscompilation."));
117619a8346SMax Kazantsev
11841e142fdSFlorian Hahn // Helper to skip (select x, true, false), which matches both a logical AND and
11941e142fdSFlorian Hahn // OR and can confuse code that tries to determine if \p Cond is either a
12041e142fdSFlorian Hahn // logical AND or OR but not both.
skipTrivialSelect(Value * Cond)12141e142fdSFlorian Hahn static Value *skipTrivialSelect(Value *Cond) {
12241e142fdSFlorian Hahn Value *CondNext;
12341e142fdSFlorian Hahn while (match(Cond, m_Select(m_Value(CondNext), m_One(), m_Zero())))
12441e142fdSFlorian Hahn Cond = CondNext;
12541e142fdSFlorian Hahn return Cond;
12641e142fdSFlorian Hahn }
12741e142fdSFlorian Hahn
1284da3331dSChandler Carruth /// Collect all of the loop invariant input values transitively used by the
1294da3331dSChandler Carruth /// homogeneous instruction graph from a given root.
1304da3331dSChandler Carruth ///
1314da3331dSChandler Carruth /// This essentially walks from a root recursively through loop variant operands
13241e142fdSFlorian Hahn /// which have perform the same logical operation (AND or OR) and finds all
13341e142fdSFlorian Hahn /// inputs which are loop invariant. For some operations these can be
13441e142fdSFlorian Hahn /// re-associated and unswitched out of the loop entirely.
135d1dab0c3SChandler Carruth static TinyPtrVector<Value *>
collectHomogenousInstGraphLoopInvariants(Loop & L,Instruction & Root,LoopInfo & LI)1364da3331dSChandler Carruth collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
1374da3331dSChandler Carruth LoopInfo &LI) {
1384da3331dSChandler Carruth assert(!L.isLoopInvariant(&Root) &&
1394da3331dSChandler Carruth "Only need to walk the graph if root itself is not invariant.");
140d1dab0c3SChandler Carruth TinyPtrVector<Value *> Invariants;
1414da3331dSChandler Carruth
1425bb38e84SJuneyoung Lee bool IsRootAnd = match(&Root, m_LogicalAnd());
1435bb38e84SJuneyoung Lee bool IsRootOr = match(&Root, m_LogicalOr());
1445bb38e84SJuneyoung Lee
1454da3331dSChandler Carruth // Build a worklist and recurse through operators collecting invariants.
1464da3331dSChandler Carruth SmallVector<Instruction *, 4> Worklist;
1474da3331dSChandler Carruth SmallPtrSet<Instruction *, 8> Visited;
1484da3331dSChandler Carruth Worklist.push_back(&Root);
1494da3331dSChandler Carruth Visited.insert(&Root);
1504da3331dSChandler Carruth do {
1514da3331dSChandler Carruth Instruction &I = *Worklist.pop_back_val();
1524da3331dSChandler Carruth for (Value *OpV : I.operand_values()) {
1534da3331dSChandler Carruth // Skip constants as unswitching isn't interesting for them.
1544da3331dSChandler Carruth if (isa<Constant>(OpV))
1554da3331dSChandler Carruth continue;
1564da3331dSChandler Carruth
1574da3331dSChandler Carruth // Add it to our result if loop invariant.
1584da3331dSChandler Carruth if (L.isLoopInvariant(OpV)) {
1594da3331dSChandler Carruth Invariants.push_back(OpV);
1604da3331dSChandler Carruth continue;
1614da3331dSChandler Carruth }
1624da3331dSChandler Carruth
1634da3331dSChandler Carruth // If not an instruction with the same opcode, nothing we can do.
16441e142fdSFlorian Hahn Instruction *OpI = dyn_cast<Instruction>(skipTrivialSelect(OpV));
1654da3331dSChandler Carruth
1665bb38e84SJuneyoung Lee if (OpI && ((IsRootAnd && match(OpI, m_LogicalAnd())) ||
1675bb38e84SJuneyoung Lee (IsRootOr && match(OpI, m_LogicalOr())))) {
1684da3331dSChandler Carruth // Visit this operand.
1694da3331dSChandler Carruth if (Visited.insert(OpI).second)
1704da3331dSChandler Carruth Worklist.push_back(OpI);
1714da3331dSChandler Carruth }
1725bb38e84SJuneyoung Lee }
1734da3331dSChandler Carruth } while (!Worklist.empty());
1744da3331dSChandler Carruth
1754da3331dSChandler Carruth return Invariants;
1764da3331dSChandler Carruth }
1774da3331dSChandler Carruth
replaceLoopInvariantUses(Loop & L,Value * Invariant,Constant & Replacement)1784da3331dSChandler Carruth static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
1791353f9a4SChandler Carruth Constant &Replacement) {
1804da3331dSChandler Carruth assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
1811353f9a4SChandler Carruth
1821353f9a4SChandler Carruth // Replace uses of LIC in the loop with the given constant.
1835fc9e309SKazu Hirata // We use make_early_inc_range as set invalidates the iterator.
1845fc9e309SKazu Hirata for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
1855fc9e309SKazu Hirata Instruction *UserI = dyn_cast<Instruction>(U.getUser());
1861353f9a4SChandler Carruth
1871353f9a4SChandler Carruth // Replace this use within the loop body.
1884da3331dSChandler Carruth if (UserI && L.contains(UserI))
1895fc9e309SKazu Hirata U.set(&Replacement);
1901353f9a4SChandler Carruth }
1911353f9a4SChandler Carruth }
1921353f9a4SChandler Carruth
193d869b188SChandler Carruth /// Check that all the LCSSA PHI nodes in the loop exit block have trivial
194d869b188SChandler Carruth /// incoming values along this edge.
areLoopExitPHIsLoopInvariant(Loop & L,BasicBlock & ExitingBB,BasicBlock & ExitBB)195d869b188SChandler Carruth static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
196d869b188SChandler Carruth BasicBlock &ExitBB) {
197d869b188SChandler Carruth for (Instruction &I : ExitBB) {
198d869b188SChandler Carruth auto *PN = dyn_cast<PHINode>(&I);
199d869b188SChandler Carruth if (!PN)
200d869b188SChandler Carruth // No more PHIs to check.
201d869b188SChandler Carruth return true;
202d869b188SChandler Carruth
203d869b188SChandler Carruth // If the incoming value for this edge isn't loop invariant the unswitch
204d869b188SChandler Carruth // won't be trivial.
205d869b188SChandler Carruth if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
206d869b188SChandler Carruth return false;
207d869b188SChandler Carruth }
208d869b188SChandler Carruth llvm_unreachable("Basic blocks should never be empty!");
209d869b188SChandler Carruth }
210d869b188SChandler Carruth
211f3a27511SJingu Kang /// Copy a set of loop invariant values \p ToDuplicate and insert them at the
212f3a27511SJingu Kang /// end of \p BB and conditionally branch on the copied condition. We only
213f3a27511SJingu Kang /// branch on a single value.
buildPartialUnswitchConditionalBranch(BasicBlock & BB,ArrayRef<Value * > Invariants,bool Direction,BasicBlock & UnswitchedSucc,BasicBlock & NormalSucc,bool InsertFreeze,Instruction * I,AssumptionCache * AC,DominatorTree & DT)2140aeb3732Shyeongyu kim static void buildPartialUnswitchConditionalBranch(
2150aeb3732Shyeongyu kim BasicBlock &BB, ArrayRef<Value *> Invariants, bool Direction,
2165387a38cSFlorian Hahn BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, bool InsertFreeze,
2175387a38cSFlorian Hahn Instruction *I, AssumptionCache *AC, DominatorTree &DT) {
218d1dab0c3SChandler Carruth IRBuilder<> IRB(&BB);
219d1dab0c3SChandler Carruth
2205387a38cSFlorian Hahn SmallVector<Value *> FrozenInvariants;
2215387a38cSFlorian Hahn for (Value *Inv : Invariants) {
2225387a38cSFlorian Hahn if (InsertFreeze && !isGuaranteedNotToBeUndefOrPoison(Inv, AC, I, &DT))
2235387a38cSFlorian Hahn Inv = IRB.CreateFreeze(Inv, Inv->getName() + ".fr");
2245387a38cSFlorian Hahn FrozenInvariants.push_back(Inv);
2255387a38cSFlorian Hahn }
2265387a38cSFlorian Hahn
2275387a38cSFlorian Hahn Value *Cond = Direction ? IRB.CreateOr(FrozenInvariants)
2285387a38cSFlorian Hahn : IRB.CreateAnd(FrozenInvariants);
229d1dab0c3SChandler Carruth IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
230d1dab0c3SChandler Carruth Direction ? &NormalSucc : &UnswitchedSucc);
231d1dab0c3SChandler Carruth }
232d1dab0c3SChandler Carruth
233f3a27511SJingu Kang /// 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)234f3a27511SJingu Kang static void buildPartialInvariantUnswitchConditionalBranch(
235f3a27511SJingu Kang BasicBlock &BB, ArrayRef<Value *> ToDuplicate, bool Direction,
236f3a27511SJingu Kang BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, Loop &L,
237f3a27511SJingu Kang MemorySSAUpdater *MSSAU) {
238f3a27511SJingu Kang ValueToValueMapTy VMap;
239f3a27511SJingu Kang for (auto *Val : reverse(ToDuplicate)) {
240f3a27511SJingu Kang Instruction *Inst = cast<Instruction>(Val);
241f3a27511SJingu Kang Instruction *NewInst = Inst->clone();
242f3a27511SJingu Kang BB.getInstList().insert(BB.end(), NewInst);
243f3a27511SJingu Kang RemapInstruction(NewInst, VMap,
244f3a27511SJingu Kang RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
245f3a27511SJingu Kang VMap[Val] = NewInst;
246f3a27511SJingu Kang
247f3a27511SJingu Kang if (!MSSAU)
248f3a27511SJingu Kang continue;
249f3a27511SJingu Kang
250f3a27511SJingu Kang MemorySSA *MSSA = MSSAU->getMemorySSA();
251f3a27511SJingu Kang if (auto *MemUse =
252f3a27511SJingu Kang dyn_cast_or_null<MemoryUse>(MSSA->getMemoryAccess(Inst))) {
253f3a27511SJingu Kang auto *DefiningAccess = MemUse->getDefiningAccess();
254f3a27511SJingu Kang // Get the first defining access before the loop.
255f3a27511SJingu Kang while (L.contains(DefiningAccess->getBlock())) {
256f3a27511SJingu Kang // If the defining access is a MemoryPhi, get the incoming
257f3a27511SJingu Kang // value for the pre-header as defining access.
258f3a27511SJingu Kang if (auto *MemPhi = dyn_cast<MemoryPhi>(DefiningAccess))
259f3a27511SJingu Kang DefiningAccess =
260f3a27511SJingu Kang MemPhi->getIncomingValueForBlock(L.getLoopPreheader());
261f3a27511SJingu Kang else
262f3a27511SJingu Kang DefiningAccess = cast<MemoryDef>(DefiningAccess)->getDefiningAccess();
263f3a27511SJingu Kang }
264f3a27511SJingu Kang MSSAU->createMemoryAccessInBB(NewInst, DefiningAccess,
265f3a27511SJingu Kang NewInst->getParent(),
266f3a27511SJingu Kang MemorySSA::BeforeTerminator);
267f3a27511SJingu Kang }
268f3a27511SJingu Kang }
269f3a27511SJingu Kang
270f3a27511SJingu Kang IRBuilder<> IRB(&BB);
271f3a27511SJingu Kang Value *Cond = VMap[ToDuplicate[0]];
272f3a27511SJingu Kang IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
273f3a27511SJingu Kang Direction ? &NormalSucc : &UnswitchedSucc);
274f3a27511SJingu Kang }
275f3a27511SJingu Kang
276d869b188SChandler Carruth /// Rewrite the PHI nodes in an unswitched loop exit basic block.
277d869b188SChandler Carruth ///
278d869b188SChandler Carruth /// Requires that the loop exit and unswitched basic block are the same, and
279d869b188SChandler Carruth /// that the exiting block was a unique predecessor of that block. Rewrites the
280d869b188SChandler Carruth /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
281d869b188SChandler Carruth /// PHI nodes from the old preheader that now contains the unswitched
282d869b188SChandler Carruth /// terminator.
rewritePHINodesForUnswitchedExitBlock(BasicBlock & UnswitchedBB,BasicBlock & OldExitingBB,BasicBlock & OldPH)283d869b188SChandler Carruth static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
284d869b188SChandler Carruth BasicBlock &OldExitingBB,
285d869b188SChandler Carruth BasicBlock &OldPH) {
286c7fc81e6SBenjamin Kramer for (PHINode &PN : UnswitchedBB.phis()) {
287d869b188SChandler Carruth // When the loop exit is directly unswitched we just need to update the
288d869b188SChandler Carruth // incoming basic block. We loop to handle weird cases with repeated
289d869b188SChandler Carruth // incoming blocks, but expect to typically only have one operand here.
290c7fc81e6SBenjamin Kramer for (auto i : seq<int>(0, PN.getNumOperands())) {
291c7fc81e6SBenjamin Kramer assert(PN.getIncomingBlock(i) == &OldExitingBB &&
292d869b188SChandler Carruth "Found incoming block different from unique predecessor!");
293c7fc81e6SBenjamin Kramer PN.setIncomingBlock(i, &OldPH);
294d869b188SChandler Carruth }
295d869b188SChandler Carruth }
296d869b188SChandler Carruth }
297d869b188SChandler Carruth
298d869b188SChandler Carruth /// Rewrite the PHI nodes in the loop exit basic block and the split off
299d869b188SChandler Carruth /// unswitched block.
300d869b188SChandler Carruth ///
301d869b188SChandler Carruth /// Because the exit block remains an exit from the loop, this rewrites the
302d869b188SChandler Carruth /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
303d869b188SChandler Carruth /// nodes into the unswitched basic block to select between the value in the
304d869b188SChandler Carruth /// old preheader and the loop exit.
rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock & ExitBB,BasicBlock & UnswitchedBB,BasicBlock & OldExitingBB,BasicBlock & OldPH,bool FullUnswitch)305d869b188SChandler Carruth static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
306d869b188SChandler Carruth BasicBlock &UnswitchedBB,
307d869b188SChandler Carruth BasicBlock &OldExitingBB,
3084da3331dSChandler Carruth BasicBlock &OldPH,
3094da3331dSChandler Carruth bool FullUnswitch) {
310d869b188SChandler Carruth assert(&ExitBB != &UnswitchedBB &&
311d869b188SChandler Carruth "Must have different loop exit and unswitched blocks!");
312d869b188SChandler Carruth Instruction *InsertPt = &*UnswitchedBB.begin();
313c7fc81e6SBenjamin Kramer for (PHINode &PN : ExitBB.phis()) {
314c7fc81e6SBenjamin Kramer auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
315c7fc81e6SBenjamin Kramer PN.getName() + ".split", InsertPt);
316d869b188SChandler Carruth
317d869b188SChandler Carruth // Walk backwards over the old PHI node's inputs to minimize the cost of
318d869b188SChandler Carruth // removing each one. We have to do this weird loop manually so that we
319d869b188SChandler Carruth // create the same number of new incoming edges in the new PHI as we expect
320d869b188SChandler Carruth // each case-based edge to be included in the unswitched switch in some
321d869b188SChandler Carruth // cases.
322d869b188SChandler Carruth // FIXME: This is really, really gross. It would be much cleaner if LLVM
323d869b188SChandler Carruth // allowed us to create a single entry for a predecessor block without
324d869b188SChandler Carruth // having separate entries for each "edge" even though these edges are
325d869b188SChandler Carruth // required to produce identical results.
326c7fc81e6SBenjamin Kramer for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
327c7fc81e6SBenjamin Kramer if (PN.getIncomingBlock(i) != &OldExitingBB)
328d869b188SChandler Carruth continue;
329d869b188SChandler Carruth
3304da3331dSChandler Carruth Value *Incoming = PN.getIncomingValue(i);
3314da3331dSChandler Carruth if (FullUnswitch)
3324da3331dSChandler Carruth // No more edge from the old exiting block to the exit block.
3334da3331dSChandler Carruth PN.removeIncomingValue(i);
3344da3331dSChandler Carruth
335d869b188SChandler Carruth NewPN->addIncoming(Incoming, &OldPH);
336d869b188SChandler Carruth }
337d869b188SChandler Carruth
338d869b188SChandler Carruth // Now replace the old PHI with the new one and wire the old one in as an
339d869b188SChandler Carruth // input to the new one.
340c7fc81e6SBenjamin Kramer PN.replaceAllUsesWith(NewPN);
341c7fc81e6SBenjamin Kramer NewPN->addIncoming(&PN, &ExitBB);
342d869b188SChandler Carruth }
343d869b188SChandler Carruth }
344d869b188SChandler Carruth
345d8b0c8ceSChandler Carruth /// Hoist the current loop up to the innermost loop containing a remaining exit.
346d8b0c8ceSChandler Carruth ///
347d8b0c8ceSChandler Carruth /// Because we've removed an exit from the loop, we may have changed the set of
348d8b0c8ceSChandler Carruth /// loops reachable and need to move the current loop up the loop nest or even
349d8b0c8ceSChandler Carruth /// to an entirely separate nest.
hoistLoopToNewParent(Loop & L,BasicBlock & Preheader,DominatorTree & DT,LoopInfo & LI,MemorySSAUpdater * MSSAU,ScalarEvolution * SE)350d8b0c8ceSChandler Carruth static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
35197468e92SAlina Sbirlea DominatorTree &DT, LoopInfo &LI,
352c4d8c631SDaniil Suchkov MemorySSAUpdater *MSSAU, ScalarEvolution *SE) {
353d8b0c8ceSChandler Carruth // If the loop is already at the top level, we can't hoist it anywhere.
354d8b0c8ceSChandler Carruth Loop *OldParentL = L.getParentLoop();
355d8b0c8ceSChandler Carruth if (!OldParentL)
356d8b0c8ceSChandler Carruth return;
357d8b0c8ceSChandler Carruth
358d8b0c8ceSChandler Carruth SmallVector<BasicBlock *, 4> Exits;
359d8b0c8ceSChandler Carruth L.getExitBlocks(Exits);
360d8b0c8ceSChandler Carruth Loop *NewParentL = nullptr;
361d8b0c8ceSChandler Carruth for (auto *ExitBB : Exits)
362d8b0c8ceSChandler Carruth if (Loop *ExitL = LI.getLoopFor(ExitBB))
363d8b0c8ceSChandler Carruth if (!NewParentL || NewParentL->contains(ExitL))
364d8b0c8ceSChandler Carruth NewParentL = ExitL;
365d8b0c8ceSChandler Carruth
366d8b0c8ceSChandler Carruth if (NewParentL == OldParentL)
367d8b0c8ceSChandler Carruth return;
368d8b0c8ceSChandler Carruth
369d8b0c8ceSChandler Carruth // The new parent loop (if different) should always contain the old one.
370d8b0c8ceSChandler Carruth if (NewParentL)
371d8b0c8ceSChandler Carruth assert(NewParentL->contains(OldParentL) &&
372d8b0c8ceSChandler Carruth "Can only hoist this loop up the nest!");
373d8b0c8ceSChandler Carruth
374d8b0c8ceSChandler Carruth // The preheader will need to move with the body of this loop. However,
375d8b0c8ceSChandler Carruth // because it isn't in this loop we also need to update the primary loop map.
376d8b0c8ceSChandler Carruth assert(OldParentL == LI.getLoopFor(&Preheader) &&
377d8b0c8ceSChandler Carruth "Parent loop of this loop should contain this loop's preheader!");
378d8b0c8ceSChandler Carruth LI.changeLoopFor(&Preheader, NewParentL);
379d8b0c8ceSChandler Carruth
380d8b0c8ceSChandler Carruth // Remove this loop from its old parent.
381d8b0c8ceSChandler Carruth OldParentL->removeChildLoop(&L);
382d8b0c8ceSChandler Carruth
383d8b0c8ceSChandler Carruth // Add the loop either to the new parent or as a top-level loop.
384d8b0c8ceSChandler Carruth if (NewParentL)
385d8b0c8ceSChandler Carruth NewParentL->addChildLoop(&L);
386d8b0c8ceSChandler Carruth else
387d8b0c8ceSChandler Carruth LI.addTopLevelLoop(&L);
388d8b0c8ceSChandler Carruth
389d8b0c8ceSChandler Carruth // Remove this loops blocks from the old parent and every other loop up the
390d8b0c8ceSChandler Carruth // nest until reaching the new parent. Also update all of these
391d8b0c8ceSChandler Carruth // no-longer-containing loops to reflect the nesting change.
392d8b0c8ceSChandler Carruth for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
393d8b0c8ceSChandler Carruth OldContainingL = OldContainingL->getParentLoop()) {
394d8b0c8ceSChandler Carruth llvm::erase_if(OldContainingL->getBlocksVector(),
395d8b0c8ceSChandler Carruth [&](const BasicBlock *BB) {
396d8b0c8ceSChandler Carruth return BB == &Preheader || L.contains(BB);
397d8b0c8ceSChandler Carruth });
398d8b0c8ceSChandler Carruth
399d8b0c8ceSChandler Carruth OldContainingL->getBlocksSet().erase(&Preheader);
400d8b0c8ceSChandler Carruth for (BasicBlock *BB : L.blocks())
401d8b0c8ceSChandler Carruth OldContainingL->getBlocksSet().erase(BB);
402d8b0c8ceSChandler Carruth
403d8b0c8ceSChandler Carruth // Because we just hoisted a loop out of this one, we have essentially
404d8b0c8ceSChandler Carruth // created new exit paths from it. That means we need to form LCSSA PHI
405d8b0c8ceSChandler Carruth // nodes for values used in the no-longer-nested loop.
406c4d8c631SDaniil Suchkov formLCSSA(*OldContainingL, DT, &LI, SE);
407d8b0c8ceSChandler Carruth
408d8b0c8ceSChandler Carruth // We shouldn't need to form dedicated exits because the exit introduced
40952e97a28SAlina Sbirlea // here is the (just split by unswitching) preheader. However, after trivial
41052e97a28SAlina Sbirlea // unswitching it is possible to get new non-dedicated exits out of parent
41152e97a28SAlina Sbirlea // loop so let's conservatively form dedicated exit blocks and figure out
41252e97a28SAlina Sbirlea // if we can optimize later.
41397468e92SAlina Sbirlea formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
41497468e92SAlina Sbirlea /*PreserveLCSSA*/ true);
415d8b0c8ceSChandler Carruth }
416d8b0c8ceSChandler Carruth }
417d8b0c8ceSChandler Carruth
4184a9cde5aSFlorian Hahn // Return the top-most loop containing ExitBB and having ExitBB as exiting block
4194a9cde5aSFlorian Hahn // or the loop containing ExitBB, if there is no parent loop containing ExitBB
4204a9cde5aSFlorian Hahn // as exiting block.
getTopMostExitingLoop(BasicBlock * ExitBB,LoopInfo & LI)4214a9cde5aSFlorian Hahn static Loop *getTopMostExitingLoop(BasicBlock *ExitBB, LoopInfo &LI) {
4224a9cde5aSFlorian Hahn Loop *TopMost = LI.getLoopFor(ExitBB);
4234a9cde5aSFlorian Hahn Loop *Current = TopMost;
4244a9cde5aSFlorian Hahn while (Current) {
4254a9cde5aSFlorian Hahn if (Current->isLoopExiting(ExitBB))
4264a9cde5aSFlorian Hahn TopMost = Current;
4274a9cde5aSFlorian Hahn Current = Current->getParentLoop();
4284a9cde5aSFlorian Hahn }
4294a9cde5aSFlorian Hahn return TopMost;
4304a9cde5aSFlorian Hahn }
4314a9cde5aSFlorian Hahn
4321353f9a4SChandler Carruth /// Unswitch a trivial branch if the condition is loop invariant.
4331353f9a4SChandler Carruth ///
4341353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the branch has
4351353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the
4361353f9a4SChandler Carruth /// condition is invariant and one of the successors is a loop exit. This
4371353f9a4SChandler Carruth /// allows us to unswitch without duplicating the loop, making it trivial.
4381353f9a4SChandler Carruth ///
4391353f9a4SChandler Carruth /// If this routine fails to unswitch the branch it returns false.
4401353f9a4SChandler Carruth ///
4411353f9a4SChandler Carruth /// If the branch can be unswitched, this routine splits the preheader and
4421353f9a4SChandler Carruth /// hoists the branch above that split. Preserves loop simplified form
4431353f9a4SChandler Carruth /// (splitting the exit block as necessary). It simplifies the branch within
4441353f9a4SChandler Carruth /// the loop to an unconditional branch but doesn't remove it entirely. Further
445472462c4SBjorn Pettersson /// cleanup can be done with some simplifycfg like pass.
4463897ded6SChandler Carruth ///
4473897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
4483897ded6SChandler Carruth /// invalidated by this.
unswitchTrivialBranch(Loop & L,BranchInst & BI,DominatorTree & DT,LoopInfo & LI,ScalarEvolution * SE,MemorySSAUpdater * MSSAU)4491353f9a4SChandler Carruth static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
450a2eebb82SAlina Sbirlea LoopInfo &LI, ScalarEvolution *SE,
451a2eebb82SAlina Sbirlea MemorySSAUpdater *MSSAU) {
4521353f9a4SChandler Carruth assert(BI.isConditional() && "Can only unswitch a conditional branch!");
453d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n");
4541353f9a4SChandler Carruth
4554da3331dSChandler Carruth // The loop invariant values that we want to unswitch.
456d1dab0c3SChandler Carruth TinyPtrVector<Value *> Invariants;
4571353f9a4SChandler Carruth
4584da3331dSChandler Carruth // When true, we're fully unswitching the branch rather than just unswitching
4594da3331dSChandler Carruth // some input conditions to the branch.
4604da3331dSChandler Carruth bool FullUnswitch = false;
4614da3331dSChandler Carruth
46232d6ef36SFlorian Hahn Value *Cond = skipTrivialSelect(BI.getCondition());
46332d6ef36SFlorian Hahn if (L.isLoopInvariant(Cond)) {
46432d6ef36SFlorian Hahn Invariants.push_back(Cond);
4654da3331dSChandler Carruth FullUnswitch = true;
4664da3331dSChandler Carruth } else {
46732d6ef36SFlorian Hahn if (auto *CondInst = dyn_cast<Instruction>(Cond))
4684da3331dSChandler Carruth Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
46984eeb828SRoman Lebedev if (Invariants.empty()) {
47084eeb828SRoman Lebedev LLVM_DEBUG(dbgs() << " Couldn't find invariant inputs!\n");
4711353f9a4SChandler Carruth return false;
4724da3331dSChandler Carruth }
47384eeb828SRoman Lebedev }
4741353f9a4SChandler Carruth
4754da3331dSChandler Carruth // Check that one of the branch's successors exits, and which one.
4764da3331dSChandler Carruth bool ExitDirection = true;
4771353f9a4SChandler Carruth int LoopExitSuccIdx = 0;
4781353f9a4SChandler Carruth auto *LoopExitBB = BI.getSuccessor(0);
479baf045fbSChandler Carruth if (L.contains(LoopExitBB)) {
4804da3331dSChandler Carruth ExitDirection = false;
4811353f9a4SChandler Carruth LoopExitSuccIdx = 1;
4821353f9a4SChandler Carruth LoopExitBB = BI.getSuccessor(1);
48384eeb828SRoman Lebedev if (L.contains(LoopExitBB)) {
48484eeb828SRoman Lebedev LLVM_DEBUG(dbgs() << " Branch doesn't exit the loop!\n");
4851353f9a4SChandler Carruth return false;
4861353f9a4SChandler Carruth }
48784eeb828SRoman Lebedev }
4881353f9a4SChandler Carruth auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
489d869b188SChandler Carruth auto *ParentBB = BI.getParent();
49084eeb828SRoman Lebedev if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) {
49184eeb828SRoman Lebedev LLVM_DEBUG(dbgs() << " Loop exit PHI's aren't loop-invariant!\n");
4921353f9a4SChandler Carruth return false;
49384eeb828SRoman Lebedev }
4941353f9a4SChandler Carruth
4954da3331dSChandler Carruth // When unswitching only part of the branch's condition, we need the exit
4964da3331dSChandler Carruth // block to be reached directly from the partially unswitched input. This can
4974da3331dSChandler Carruth // be done when the exit block is along the true edge and the branch condition
4984da3331dSChandler Carruth // is a graph of `or` operations, or the exit block is along the false edge
4994da3331dSChandler Carruth // and the condition is a graph of `and` operations.
5004da3331dSChandler Carruth if (!FullUnswitch) {
50141e142fdSFlorian Hahn if (ExitDirection ? !match(Cond, m_LogicalOr())
50241e142fdSFlorian Hahn : !match(Cond, m_LogicalAnd())) {
50384eeb828SRoman Lebedev LLVM_DEBUG(dbgs() << " Branch condition is in improper form for "
50484eeb828SRoman Lebedev "non-full unswitch!\n");
5054da3331dSChandler Carruth return false;
5064da3331dSChandler Carruth }
5074da3331dSChandler Carruth }
5084da3331dSChandler Carruth
5094da3331dSChandler Carruth LLVM_DEBUG({
5104da3331dSChandler Carruth dbgs() << " unswitching trivial invariant conditions for: " << BI
5114da3331dSChandler Carruth << "\n";
5124da3331dSChandler Carruth for (Value *Invariant : Invariants) {
5134da3331dSChandler Carruth dbgs() << " " << *Invariant << " == true";
5144da3331dSChandler Carruth if (Invariant != Invariants.back())
5154da3331dSChandler Carruth dbgs() << " ||";
5164da3331dSChandler Carruth dbgs() << "\n";
5174da3331dSChandler Carruth }
5184da3331dSChandler Carruth });
5191353f9a4SChandler Carruth
5203897ded6SChandler Carruth // If we have scalar evolutions, we need to invalidate them including this
5214a9cde5aSFlorian Hahn // loop, the loop containing the exit block and the topmost parent loop
5224a9cde5aSFlorian Hahn // exiting via LoopExitBB.
5233897ded6SChandler Carruth if (SE) {
5244a9cde5aSFlorian Hahn if (Loop *ExitL = getTopMostExitingLoop(LoopExitBB, LI))
5253897ded6SChandler Carruth SE->forgetLoop(ExitL);
5263897ded6SChandler Carruth else
5273897ded6SChandler Carruth // Forget the entire nest as this exits the entire nest.
5283897ded6SChandler Carruth SE->forgetTopmostLoop(&L);
5293897ded6SChandler Carruth }
5303897ded6SChandler Carruth
531a2eebb82SAlina Sbirlea if (MSSAU && VerifyMemorySSA)
532a2eebb82SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
533a2eebb82SAlina Sbirlea
5341353f9a4SChandler Carruth // Split the preheader, so that we know that there is a safe place to insert
5351353f9a4SChandler Carruth // the conditional branch. We will change the preheader to have a conditional
5361353f9a4SChandler Carruth // branch on LoopCond.
5371353f9a4SChandler Carruth BasicBlock *OldPH = L.getLoopPreheader();
538a2eebb82SAlina Sbirlea BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
5391353f9a4SChandler Carruth
5401353f9a4SChandler Carruth // Now that we have a place to insert the conditional branch, create a place
5411353f9a4SChandler Carruth // to branch to: this is the exit block out of the loop that we are
5421353f9a4SChandler Carruth // unswitching. We need to split this if there are other loop predecessors.
5431353f9a4SChandler Carruth // Because the loop is in simplified form, *any* other predecessor is enough.
5441353f9a4SChandler Carruth BasicBlock *UnswitchedBB;
5454da3331dSChandler Carruth if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
5464da3331dSChandler Carruth assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
547d869b188SChandler Carruth "A branch's parent isn't a predecessor!");
5481353f9a4SChandler Carruth UnswitchedBB = LoopExitBB;
5491353f9a4SChandler Carruth } else {
550a2eebb82SAlina Sbirlea UnswitchedBB =
551a2eebb82SAlina Sbirlea SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
5521353f9a4SChandler Carruth }
5531353f9a4SChandler Carruth
554a2eebb82SAlina Sbirlea if (MSSAU && VerifyMemorySSA)
555a2eebb82SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
556a2eebb82SAlina Sbirlea
5574da3331dSChandler Carruth // Actually move the invariant uses into the unswitched position. If possible,
5584da3331dSChandler Carruth // we do this by moving the instructions, but when doing partial unswitching
5594da3331dSChandler Carruth // we do it by building a new merge of the values in the unswitched position.
5601353f9a4SChandler Carruth OldPH->getTerminator()->eraseFromParent();
5614da3331dSChandler Carruth if (FullUnswitch) {
5624da3331dSChandler Carruth // If fully unswitching, we can use the existing branch instruction.
5634da3331dSChandler Carruth // Splice it into the old PH to gate reaching the new preheader and re-point
5644da3331dSChandler Carruth // its successors.
5654da3331dSChandler Carruth OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
5664da3331dSChandler Carruth BI);
56732d6ef36SFlorian Hahn BI.setCondition(Cond);
568a2eebb82SAlina Sbirlea if (MSSAU) {
569a2eebb82SAlina Sbirlea // Temporarily clone the terminator, to make MSSA update cheaper by
570a2eebb82SAlina Sbirlea // separating "insert edge" updates from "remove edge" ones.
571a2eebb82SAlina Sbirlea ParentBB->getInstList().push_back(BI.clone());
572a2eebb82SAlina Sbirlea } else {
5731353f9a4SChandler Carruth // Create a new unconditional branch that will continue the loop as a new
5741353f9a4SChandler Carruth // terminator.
5751353f9a4SChandler Carruth BranchInst::Create(ContinueBB, ParentBB);
576a2eebb82SAlina Sbirlea }
577a2eebb82SAlina Sbirlea BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
578a2eebb82SAlina Sbirlea BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
5794da3331dSChandler Carruth } else {
5804da3331dSChandler Carruth // Only unswitching a subset of inputs to the condition, so we will need to
5814da3331dSChandler Carruth // build a new branch that merges the invariant inputs.
5824da3331dSChandler Carruth if (ExitDirection)
58341e142fdSFlorian Hahn assert(match(skipTrivialSelect(BI.getCondition()), m_LogicalOr()) &&
5845bb38e84SJuneyoung Lee "Must have an `or` of `i1`s or `select i1 X, true, Y`s for the "
5855bb38e84SJuneyoung Lee "condition!");
5864da3331dSChandler Carruth else
58741e142fdSFlorian Hahn assert(match(skipTrivialSelect(BI.getCondition()), m_LogicalAnd()) &&
5885bb38e84SJuneyoung Lee "Must have an `and` of `i1`s or `select i1 X, Y, false`s for the"
5895bb38e84SJuneyoung Lee " condition!");
5908b022f87SFlorian Hahn buildPartialUnswitchConditionalBranch(
5918b022f87SFlorian Hahn *OldPH, Invariants, ExitDirection, *UnswitchedBB, *NewPH,
5925387a38cSFlorian Hahn FreezeLoopUnswitchCond, OldPH->getTerminator(), nullptr, DT);
5934da3331dSChandler Carruth }
5941353f9a4SChandler Carruth
595a2eebb82SAlina Sbirlea // Update the dominator tree with the added edge.
596a2eebb82SAlina Sbirlea DT.insertEdge(OldPH, UnswitchedBB);
597a2eebb82SAlina Sbirlea
598a2eebb82SAlina Sbirlea // After the dominator tree was updated with the added edge, update MemorySSA
599a2eebb82SAlina Sbirlea // if available.
600a2eebb82SAlina Sbirlea if (MSSAU) {
601a2eebb82SAlina Sbirlea SmallVector<CFGUpdate, 1> Updates;
602a2eebb82SAlina Sbirlea Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
603a2eebb82SAlina Sbirlea MSSAU->applyInsertUpdates(Updates, DT);
604a2eebb82SAlina Sbirlea }
605a2eebb82SAlina Sbirlea
606a2eebb82SAlina Sbirlea // Finish updating dominator tree and memory ssa for full unswitch.
607a2eebb82SAlina Sbirlea if (FullUnswitch) {
608a2eebb82SAlina Sbirlea if (MSSAU) {
609a2eebb82SAlina Sbirlea // Remove the cloned branch instruction.
610a2eebb82SAlina Sbirlea ParentBB->getTerminator()->eraseFromParent();
611a2eebb82SAlina Sbirlea // Create unconditional branch now.
612a2eebb82SAlina Sbirlea BranchInst::Create(ContinueBB, ParentBB);
613a2eebb82SAlina Sbirlea MSSAU->removeEdge(ParentBB, LoopExitBB);
614a2eebb82SAlina Sbirlea }
615a2eebb82SAlina Sbirlea DT.deleteEdge(ParentBB, LoopExitBB);
616a2eebb82SAlina Sbirlea }
617a2eebb82SAlina Sbirlea
618a2eebb82SAlina Sbirlea if (MSSAU && VerifyMemorySSA)
619a2eebb82SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
620a2eebb82SAlina Sbirlea
621d869b188SChandler Carruth // Rewrite the relevant PHI nodes.
622d869b188SChandler Carruth if (UnswitchedBB == LoopExitBB)
623d869b188SChandler Carruth rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
624d869b188SChandler Carruth else
625d869b188SChandler Carruth rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
6264da3331dSChandler Carruth *ParentBB, *OldPH, FullUnswitch);
627d869b188SChandler Carruth
6284da3331dSChandler Carruth // The constant we can replace all of our invariants with inside the loop
6294da3331dSChandler Carruth // body. If any of the invariants have a value other than this the loop won't
6304da3331dSChandler Carruth // be entered.
6314da3331dSChandler Carruth ConstantInt *Replacement = ExitDirection
6324da3331dSChandler Carruth ? ConstantInt::getFalse(BI.getContext())
6334da3331dSChandler Carruth : ConstantInt::getTrue(BI.getContext());
6341353f9a4SChandler Carruth
6351353f9a4SChandler Carruth // Since this is an i1 condition we can also trivially replace uses of it
6361353f9a4SChandler Carruth // within the loop with a constant.
6374da3331dSChandler Carruth for (Value *Invariant : Invariants)
6384da3331dSChandler Carruth replaceLoopInvariantUses(L, Invariant, *Replacement);
6391353f9a4SChandler Carruth
640d8b0c8ceSChandler Carruth // If this was full unswitching, we may have changed the nesting relationship
641d8b0c8ceSChandler Carruth // for this loop so hoist it to its correct parent if needed.
642d8b0c8ceSChandler Carruth if (FullUnswitch)
643c4d8c631SDaniil Suchkov hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
64497468e92SAlina Sbirlea
64597468e92SAlina Sbirlea if (MSSAU && VerifyMemorySSA)
64697468e92SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
647d8b0c8ceSChandler Carruth
64852e97a28SAlina Sbirlea LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n");
6491353f9a4SChandler Carruth ++NumTrivial;
6501353f9a4SChandler Carruth ++NumBranches;
6511353f9a4SChandler Carruth return true;
6521353f9a4SChandler Carruth }
6531353f9a4SChandler Carruth
6541353f9a4SChandler Carruth /// Unswitch a trivial switch if the condition is loop invariant.
6551353f9a4SChandler Carruth ///
6561353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the switch has
6571353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the
6581353f9a4SChandler Carruth /// condition is invariant and that at least one of the successors is a loop
6591353f9a4SChandler Carruth /// exit. This allows us to unswitch without duplicating the loop, making it
6601353f9a4SChandler Carruth /// trivial.
6611353f9a4SChandler Carruth ///
6621353f9a4SChandler Carruth /// If this routine fails to unswitch the switch it returns false.
6631353f9a4SChandler Carruth ///
6641353f9a4SChandler Carruth /// If the switch can be unswitched, this routine splits the preheader and
6651353f9a4SChandler Carruth /// copies the switch above that split. If the default case is one of the
6661353f9a4SChandler Carruth /// exiting cases, it copies the non-exiting cases and points them at the new
6671353f9a4SChandler Carruth /// preheader. If the default case is not exiting, it copies the exiting cases
6681353f9a4SChandler Carruth /// and points the default at the preheader. It preserves loop simplified form
6691353f9a4SChandler Carruth /// (splitting the exit blocks as necessary). It simplifies the switch within
6701353f9a4SChandler Carruth /// the loop by removing now-dead cases. If the default case is one of those
6711353f9a4SChandler Carruth /// unswitched, it replaces its destination with a new basic block containing
6721353f9a4SChandler Carruth /// only unreachable. Such basic blocks, while technically loop exits, are not
6731353f9a4SChandler Carruth /// considered for unswitching so this is a stable transform and the same
6741353f9a4SChandler Carruth /// switch will not be revisited. If after unswitching there is only a single
6751353f9a4SChandler Carruth /// in-loop successor, the switch is further simplified to an unconditional
676472462c4SBjorn Pettersson /// branch. Still more cleanup can be done with some simplifycfg like pass.
6773897ded6SChandler Carruth ///
6783897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
6793897ded6SChandler Carruth /// invalidated by this.
unswitchTrivialSwitch(Loop & L,SwitchInst & SI,DominatorTree & DT,LoopInfo & LI,ScalarEvolution * SE,MemorySSAUpdater * MSSAU)6801353f9a4SChandler Carruth static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
681a2eebb82SAlina Sbirlea LoopInfo &LI, ScalarEvolution *SE,
682a2eebb82SAlina Sbirlea MemorySSAUpdater *MSSAU) {
683d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n");
6841353f9a4SChandler Carruth Value *LoopCond = SI.getCondition();
6851353f9a4SChandler Carruth
6861353f9a4SChandler Carruth // If this isn't switching on an invariant condition, we can't unswitch it.
6871353f9a4SChandler Carruth if (!L.isLoopInvariant(LoopCond))
6881353f9a4SChandler Carruth return false;
6891353f9a4SChandler Carruth
690d869b188SChandler Carruth auto *ParentBB = SI.getParent();
691d869b188SChandler Carruth
692db04ff4bSAlina Sbirlea // The same check must be used both for the default and the exit cases. We
693db04ff4bSAlina Sbirlea // should never leave edges from the switch instruction to a basic block that
694db04ff4bSAlina Sbirlea // we are unswitching, hence the condition used to determine the default case
695db04ff4bSAlina Sbirlea // needs to also be used to populate ExitCaseIndices, which is then used to
696db04ff4bSAlina Sbirlea // remove cases from the switch.
6976227f021SAlina Sbirlea auto IsTriviallyUnswitchableExitBlock = [&](BasicBlock &BBToCheck) {
6986227f021SAlina Sbirlea // BBToCheck is not an exit block if it is inside loop L.
6996227f021SAlina Sbirlea if (L.contains(&BBToCheck))
7006227f021SAlina Sbirlea return false;
7016227f021SAlina Sbirlea // BBToCheck is not trivial to unswitch if its phis aren't loop invariant.
7026227f021SAlina Sbirlea if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, BBToCheck))
7036227f021SAlina Sbirlea return false;
7046227f021SAlina Sbirlea // We do not unswitch a block that only has an unreachable statement, as
7056227f021SAlina Sbirlea // it's possible this is a previously unswitched block. Only unswitch if
7066227f021SAlina Sbirlea // either the terminator is not unreachable, or, if it is, it's not the only
7076227f021SAlina Sbirlea // instruction in the block.
7086227f021SAlina Sbirlea auto *TI = BBToCheck.getTerminator();
7096227f021SAlina Sbirlea bool isUnreachable = isa<UnreachableInst>(TI);
7106227f021SAlina Sbirlea return !isUnreachable ||
7116227f021SAlina Sbirlea (isUnreachable && (BBToCheck.getFirstNonPHIOrDbg() != TI));
7126227f021SAlina Sbirlea };
7136227f021SAlina Sbirlea
7141353f9a4SChandler Carruth SmallVector<int, 4> ExitCaseIndices;
715db04ff4bSAlina Sbirlea for (auto Case : SI.cases())
716db04ff4bSAlina Sbirlea if (IsTriviallyUnswitchableExitBlock(*Case.getCaseSuccessor()))
7171353f9a4SChandler Carruth ExitCaseIndices.push_back(Case.getCaseIndex());
7181353f9a4SChandler Carruth BasicBlock *DefaultExitBB = nullptr;
719d4097b4aSYevgeny Rouban SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight =
720d4097b4aSYevgeny Rouban SwitchInstProfUpdateWrapper::getSuccessorWeight(SI, 0);
7216227f021SAlina Sbirlea if (IsTriviallyUnswitchableExitBlock(*SI.getDefaultDest())) {
7221353f9a4SChandler Carruth DefaultExitBB = SI.getDefaultDest();
723d4097b4aSYevgeny Rouban } else if (ExitCaseIndices.empty())
7241353f9a4SChandler Carruth return false;
7251353f9a4SChandler Carruth
72652e97a28SAlina Sbirlea LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n");
7271353f9a4SChandler Carruth
728a2eebb82SAlina Sbirlea if (MSSAU && VerifyMemorySSA)
729a2eebb82SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
730a2eebb82SAlina Sbirlea
7313897ded6SChandler Carruth // We may need to invalidate SCEVs for the outermost loop reached by any of
7323897ded6SChandler Carruth // the exits.
7333897ded6SChandler Carruth Loop *OuterL = &L;
7343897ded6SChandler Carruth
73547dc3a34SChandler Carruth if (DefaultExitBB) {
73647dc3a34SChandler Carruth // Clear out the default destination temporarily to allow accurate
73747dc3a34SChandler Carruth // predecessor lists to be examined below.
73847dc3a34SChandler Carruth SI.setDefaultDest(nullptr);
73947dc3a34SChandler Carruth // Check the loop containing this exit.
74047dc3a34SChandler Carruth Loop *ExitL = LI.getLoopFor(DefaultExitBB);
74147dc3a34SChandler Carruth if (!ExitL || ExitL->contains(OuterL))
74247dc3a34SChandler Carruth OuterL = ExitL;
74347dc3a34SChandler Carruth }
74447dc3a34SChandler Carruth
74547dc3a34SChandler Carruth // Store the exit cases into a separate data structure and remove them from
74647dc3a34SChandler Carruth // the switch.
747d4097b4aSYevgeny Rouban SmallVector<std::tuple<ConstantInt *, BasicBlock *,
748d4097b4aSYevgeny Rouban SwitchInstProfUpdateWrapper::CaseWeightOpt>,
749d4097b4aSYevgeny Rouban 4> ExitCases;
7501353f9a4SChandler Carruth ExitCases.reserve(ExitCaseIndices.size());
751d4097b4aSYevgeny Rouban SwitchInstProfUpdateWrapper SIW(SI);
7521353f9a4SChandler Carruth // We walk the case indices backwards so that we remove the last case first
7531353f9a4SChandler Carruth // and don't disrupt the earlier indices.
7541353f9a4SChandler Carruth for (unsigned Index : reverse(ExitCaseIndices)) {
7551353f9a4SChandler Carruth auto CaseI = SI.case_begin() + Index;
7563897ded6SChandler Carruth // Compute the outer loop from this exit.
7573897ded6SChandler Carruth Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
7583897ded6SChandler Carruth if (!ExitL || ExitL->contains(OuterL))
7593897ded6SChandler Carruth OuterL = ExitL;
7601353f9a4SChandler Carruth // Save the value of this case.
761d4097b4aSYevgeny Rouban auto W = SIW.getSuccessorWeight(CaseI->getSuccessorIndex());
762d4097b4aSYevgeny Rouban ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W);
7631353f9a4SChandler Carruth // Delete the unswitched cases.
764d4097b4aSYevgeny Rouban SIW.removeCase(CaseI);
7651353f9a4SChandler Carruth }
7661353f9a4SChandler Carruth
7673897ded6SChandler Carruth if (SE) {
7683897ded6SChandler Carruth if (OuterL)
7693897ded6SChandler Carruth SE->forgetLoop(OuterL);
7703897ded6SChandler Carruth else
7713897ded6SChandler Carruth SE->forgetTopmostLoop(&L);
7723897ded6SChandler Carruth }
7733897ded6SChandler Carruth
7741353f9a4SChandler Carruth // Check if after this all of the remaining cases point at the same
7751353f9a4SChandler Carruth // successor.
7761353f9a4SChandler Carruth BasicBlock *CommonSuccBB = nullptr;
7771353f9a4SChandler Carruth if (SI.getNumCases() > 0 &&
778b023cdeaSKazu Hirata all_of(drop_begin(SI.cases()), [&SI](const SwitchInst::CaseHandle &Case) {
779b023cdeaSKazu Hirata return Case.getCaseSuccessor() == SI.case_begin()->getCaseSuccessor();
7801353f9a4SChandler Carruth }))
7811353f9a4SChandler Carruth CommonSuccBB = SI.case_begin()->getCaseSuccessor();
78247dc3a34SChandler Carruth if (!DefaultExitBB) {
7831353f9a4SChandler Carruth // If we're not unswitching the default, we need it to match any cases to
7841353f9a4SChandler Carruth // have a common successor or if we have no cases it is the common
7851353f9a4SChandler Carruth // successor.
7861353f9a4SChandler Carruth if (SI.getNumCases() == 0)
7871353f9a4SChandler Carruth CommonSuccBB = SI.getDefaultDest();
7881353f9a4SChandler Carruth else if (SI.getDefaultDest() != CommonSuccBB)
7891353f9a4SChandler Carruth CommonSuccBB = nullptr;
7901353f9a4SChandler Carruth }
7911353f9a4SChandler Carruth
7921353f9a4SChandler Carruth // Split the preheader, so that we know that there is a safe place to insert
7931353f9a4SChandler Carruth // the switch.
7941353f9a4SChandler Carruth BasicBlock *OldPH = L.getLoopPreheader();
795a2eebb82SAlina Sbirlea BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
7961353f9a4SChandler Carruth OldPH->getTerminator()->eraseFromParent();
7971353f9a4SChandler Carruth
7981353f9a4SChandler Carruth // Now add the unswitched switch.
7991353f9a4SChandler Carruth auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
800d4097b4aSYevgeny Rouban SwitchInstProfUpdateWrapper NewSIW(*NewSI);
8011353f9a4SChandler Carruth
802d869b188SChandler Carruth // Rewrite the IR for the unswitched basic blocks. This requires two steps.
803d869b188SChandler Carruth // First, we split any exit blocks with remaining in-loop predecessors. Then
804d869b188SChandler Carruth // we update the PHIs in one of two ways depending on if there was a split.
805d869b188SChandler Carruth // We walk in reverse so that we split in the same order as the cases
806d869b188SChandler Carruth // appeared. This is purely for convenience of reading the resulting IR, but
807d869b188SChandler Carruth // it doesn't cost anything really.
808d869b188SChandler Carruth SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
8091353f9a4SChandler Carruth SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
8101353f9a4SChandler Carruth // Handle the default exit if necessary.
8111353f9a4SChandler Carruth // FIXME: It'd be great if we could merge this with the loop below but LLVM's
8121353f9a4SChandler Carruth // ranges aren't quite powerful enough yet.
813d869b188SChandler Carruth if (DefaultExitBB) {
814d869b188SChandler Carruth if (pred_empty(DefaultExitBB)) {
815d869b188SChandler Carruth UnswitchedExitBBs.insert(DefaultExitBB);
816d869b188SChandler Carruth rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
817d869b188SChandler Carruth } else {
8181353f9a4SChandler Carruth auto *SplitBB =
819a2eebb82SAlina Sbirlea SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
820a2eebb82SAlina Sbirlea rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
821a2eebb82SAlina Sbirlea *ParentBB, *OldPH,
822a2eebb82SAlina Sbirlea /*FullUnswitch*/ true);
8231353f9a4SChandler Carruth DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
8241353f9a4SChandler Carruth }
825d869b188SChandler Carruth }
8261353f9a4SChandler Carruth // Note that we must use a reference in the for loop so that we update the
8271353f9a4SChandler Carruth // container.
828d4097b4aSYevgeny Rouban for (auto &ExitCase : reverse(ExitCases)) {
8291353f9a4SChandler Carruth // Grab a reference to the exit block in the pair so that we can update it.
830d4097b4aSYevgeny Rouban BasicBlock *ExitBB = std::get<1>(ExitCase);
8311353f9a4SChandler Carruth
8321353f9a4SChandler Carruth // If this case is the last edge into the exit block, we can simply reuse it
8331353f9a4SChandler Carruth // as it will no longer be a loop exit. No mapping necessary.
834d869b188SChandler Carruth if (pred_empty(ExitBB)) {
835d869b188SChandler Carruth // Only rewrite once.
836d869b188SChandler Carruth if (UnswitchedExitBBs.insert(ExitBB).second)
837d869b188SChandler Carruth rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
8381353f9a4SChandler Carruth continue;
839d869b188SChandler Carruth }
8401353f9a4SChandler Carruth
8411353f9a4SChandler Carruth // Otherwise we need to split the exit block so that we retain an exit
8421353f9a4SChandler Carruth // block from the loop and a target for the unswitched condition.
8431353f9a4SChandler Carruth BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
8441353f9a4SChandler Carruth if (!SplitExitBB) {
8451353f9a4SChandler Carruth // If this is the first time we see this, do the split and remember it.
846a2eebb82SAlina Sbirlea SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
847a2eebb82SAlina Sbirlea rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
848a2eebb82SAlina Sbirlea *ParentBB, *OldPH,
849a2eebb82SAlina Sbirlea /*FullUnswitch*/ true);
8501353f9a4SChandler Carruth }
851d869b188SChandler Carruth // Update the case pair to point to the split block.
852d4097b4aSYevgeny Rouban std::get<1>(ExitCase) = SplitExitBB;
8531353f9a4SChandler Carruth }
8541353f9a4SChandler Carruth
8551353f9a4SChandler Carruth // Now add the unswitched cases. We do this in reverse order as we built them
8561353f9a4SChandler Carruth // in reverse order.
857d4097b4aSYevgeny Rouban for (auto &ExitCase : reverse(ExitCases)) {
858d4097b4aSYevgeny Rouban ConstantInt *CaseVal = std::get<0>(ExitCase);
859d4097b4aSYevgeny Rouban BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
8601353f9a4SChandler Carruth
861d4097b4aSYevgeny Rouban NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
8621353f9a4SChandler Carruth }
8631353f9a4SChandler Carruth
8641353f9a4SChandler Carruth // If the default was unswitched, re-point it and add explicit cases for
8651353f9a4SChandler Carruth // entering the loop.
8661353f9a4SChandler Carruth if (DefaultExitBB) {
867d4097b4aSYevgeny Rouban NewSIW->setDefaultDest(DefaultExitBB);
868d4097b4aSYevgeny Rouban NewSIW.setSuccessorWeight(0, DefaultCaseWeight);
8691353f9a4SChandler Carruth
8701353f9a4SChandler Carruth // We removed all the exit cases, so we just copy the cases to the
8711353f9a4SChandler Carruth // unswitched switch.
872d4097b4aSYevgeny Rouban for (const auto &Case : SI.cases())
873d4097b4aSYevgeny Rouban NewSIW.addCase(Case.getCaseValue(), NewPH,
874d4097b4aSYevgeny Rouban SIW.getSuccessorWeight(Case.getSuccessorIndex()));
875d4097b4aSYevgeny Rouban } else if (DefaultCaseWeight) {
876d4097b4aSYevgeny Rouban // We have to set branch weight of the default case.
877d4097b4aSYevgeny Rouban uint64_t SW = *DefaultCaseWeight;
878d4097b4aSYevgeny Rouban for (const auto &Case : SI.cases()) {
879d4097b4aSYevgeny Rouban auto W = SIW.getSuccessorWeight(Case.getSuccessorIndex());
880d4097b4aSYevgeny Rouban assert(W &&
881d4097b4aSYevgeny Rouban "case weight must be defined as default case weight is defined");
882d4097b4aSYevgeny Rouban SW += *W;
883d4097b4aSYevgeny Rouban }
884d4097b4aSYevgeny Rouban NewSIW.setSuccessorWeight(0, SW);
8851353f9a4SChandler Carruth }
8861353f9a4SChandler Carruth
8871353f9a4SChandler Carruth // If we ended up with a common successor for every path through the switch
8881353f9a4SChandler Carruth // after unswitching, rewrite it to an unconditional branch to make it easy
8891353f9a4SChandler Carruth // to recognize. Otherwise we potentially have to recognize the default case
8901353f9a4SChandler Carruth // pointing at unreachable and other complexity.
8911353f9a4SChandler Carruth if (CommonSuccBB) {
8921353f9a4SChandler Carruth BasicBlock *BB = SI.getParent();
89347dc3a34SChandler Carruth // We may have had multiple edges to this common successor block, so remove
89447dc3a34SChandler Carruth // them as predecessors. We skip the first one, either the default or the
89547dc3a34SChandler Carruth // actual first case.
89647dc3a34SChandler Carruth bool SkippedFirst = DefaultExitBB == nullptr;
89747dc3a34SChandler Carruth for (auto Case : SI.cases()) {
89847dc3a34SChandler Carruth assert(Case.getCaseSuccessor() == CommonSuccBB &&
89947dc3a34SChandler Carruth "Non-common successor!");
900148861f5SChandler Carruth (void)Case;
90147dc3a34SChandler Carruth if (!SkippedFirst) {
90247dc3a34SChandler Carruth SkippedFirst = true;
90347dc3a34SChandler Carruth continue;
90447dc3a34SChandler Carruth }
90547dc3a34SChandler Carruth CommonSuccBB->removePredecessor(BB,
90620b91899SMax Kazantsev /*KeepOneInputPHIs*/ true);
90747dc3a34SChandler Carruth }
90847dc3a34SChandler Carruth // Now nuke the switch and replace it with a direct branch.
909d4097b4aSYevgeny Rouban SIW.eraseFromParent();
9101353f9a4SChandler Carruth BranchInst::Create(CommonSuccBB, BB);
91147dc3a34SChandler Carruth } else if (DefaultExitBB) {
91247dc3a34SChandler Carruth assert(SI.getNumCases() > 0 &&
91347dc3a34SChandler Carruth "If we had no cases we'd have a common successor!");
91447dc3a34SChandler Carruth // Move the last case to the default successor. This is valid as if the
91547dc3a34SChandler Carruth // default got unswitched it cannot be reached. This has the advantage of
91647dc3a34SChandler Carruth // being simple and keeping the number of edges from this switch to
91747dc3a34SChandler Carruth // successors the same, and avoiding any PHI update complexity.
91847dc3a34SChandler Carruth auto LastCaseI = std::prev(SI.case_end());
919d4097b4aSYevgeny Rouban
92047dc3a34SChandler Carruth SI.setDefaultDest(LastCaseI->getCaseSuccessor());
921d4097b4aSYevgeny Rouban SIW.setSuccessorWeight(
922d4097b4aSYevgeny Rouban 0, SIW.getSuccessorWeight(LastCaseI->getSuccessorIndex()));
923d4097b4aSYevgeny Rouban SIW.removeCase(LastCaseI);
9241353f9a4SChandler Carruth }
9251353f9a4SChandler Carruth
9262c85a231SChandler Carruth // Walk the unswitched exit blocks and the unswitched split blocks and update
9272c85a231SChandler Carruth // the dominator tree based on the CFG edits. While we are walking unordered
9282c85a231SChandler Carruth // containers here, the API for applyUpdates takes an unordered list of
9292c85a231SChandler Carruth // updates and requires them to not contain duplicates.
9302c85a231SChandler Carruth SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
9312c85a231SChandler Carruth for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
9322c85a231SChandler Carruth DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
9332c85a231SChandler Carruth DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
9342c85a231SChandler Carruth }
9352c85a231SChandler Carruth for (auto SplitUnswitchedPair : SplitExitBBMap) {
93690d2e3a1SAlina Sbirlea DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first});
93790d2e3a1SAlina Sbirlea DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second});
9382c85a231SChandler Carruth }
939a2eebb82SAlina Sbirlea
940a2eebb82SAlina Sbirlea if (MSSAU) {
94163aeaf75SAlina Sbirlea MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
942a2eebb82SAlina Sbirlea if (VerifyMemorySSA)
943a2eebb82SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
94463aeaf75SAlina Sbirlea } else {
94563aeaf75SAlina Sbirlea DT.applyUpdates(DTUpdates);
946a2eebb82SAlina Sbirlea }
947a2eebb82SAlina Sbirlea
9487c35de12SDavid Green assert(DT.verify(DominatorTree::VerificationLevel::Fast));
949d8b0c8ceSChandler Carruth
950d8b0c8ceSChandler Carruth // We may have changed the nesting relationship for this loop so hoist it to
951d8b0c8ceSChandler Carruth // its correct parent if needed.
952c4d8c631SDaniil Suchkov hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
95397468e92SAlina Sbirlea
95497468e92SAlina Sbirlea if (MSSAU && VerifyMemorySSA)
95597468e92SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
956d8b0c8ceSChandler Carruth
9571353f9a4SChandler Carruth ++NumTrivial;
9581353f9a4SChandler Carruth ++NumSwitches;
95952e97a28SAlina Sbirlea LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n");
9601353f9a4SChandler Carruth return true;
9611353f9a4SChandler Carruth }
9621353f9a4SChandler Carruth
9631353f9a4SChandler Carruth /// This routine scans the loop to find a branch or switch which occurs before
9641353f9a4SChandler Carruth /// any side effects occur. These can potentially be unswitched without
9651353f9a4SChandler Carruth /// duplicating the loop. If a branch or switch is successfully unswitched the
9661353f9a4SChandler Carruth /// scanning continues to see if subsequent branches or switches have become
9671353f9a4SChandler Carruth /// trivial. Once all trivial candidates have been unswitched, this routine
9681353f9a4SChandler Carruth /// returns.
9691353f9a4SChandler Carruth ///
9701353f9a4SChandler Carruth /// The return value indicates whether anything was unswitched (and therefore
9711353f9a4SChandler Carruth /// changed).
9723897ded6SChandler Carruth ///
9733897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
9743897ded6SChandler Carruth /// invalidated by this.
unswitchAllTrivialConditions(Loop & L,DominatorTree & DT,LoopInfo & LI,ScalarEvolution * SE,MemorySSAUpdater * MSSAU)9751353f9a4SChandler Carruth static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
976a2eebb82SAlina Sbirlea LoopInfo &LI, ScalarEvolution *SE,
977a2eebb82SAlina Sbirlea MemorySSAUpdater *MSSAU) {
9781353f9a4SChandler Carruth bool Changed = false;
9791353f9a4SChandler Carruth
9801353f9a4SChandler Carruth // If loop header has only one reachable successor we should keep looking for
9811353f9a4SChandler Carruth // trivial condition candidates in the successor as well. An alternative is
9821353f9a4SChandler Carruth // to constant fold conditions and merge successors into loop header (then we
9831353f9a4SChandler Carruth // only need to check header's terminator). The reason for not doing this in
9841353f9a4SChandler Carruth // LoopUnswitch pass is that it could potentially break LoopPassManager's
9851353f9a4SChandler Carruth // invariants. Folding dead branches could either eliminate the current loop
9861353f9a4SChandler Carruth // or make other loops unreachable. LCSSA form might also not be preserved
9871353f9a4SChandler Carruth // after deleting branches. The following code keeps traversing loop header's
9881353f9a4SChandler Carruth // successors until it finds the trivial condition candidate (condition that
9891353f9a4SChandler Carruth // is not a constant). Since unswitching generates branches with constant
9901353f9a4SChandler Carruth // conditions, this scenario could be very common in practice.
9911353f9a4SChandler Carruth BasicBlock *CurrentBB = L.getHeader();
9921353f9a4SChandler Carruth SmallPtrSet<BasicBlock *, 8> Visited;
9931353f9a4SChandler Carruth Visited.insert(CurrentBB);
9941353f9a4SChandler Carruth do {
9951353f9a4SChandler Carruth // Check if there are any side-effecting instructions (e.g. stores, calls,
9961353f9a4SChandler Carruth // volatile loads) in the part of the loop that the code *would* execute
9971353f9a4SChandler Carruth // without unswitching.
99893210870SAlina Sbirlea if (MSSAU) // Possible early exit with MSSA
99993210870SAlina Sbirlea if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
100093210870SAlina Sbirlea if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
100193210870SAlina Sbirlea return Changed;
10021353f9a4SChandler Carruth if (llvm::any_of(*CurrentBB,
10031353f9a4SChandler Carruth [](Instruction &I) { return I.mayHaveSideEffects(); }))
10041353f9a4SChandler Carruth return Changed;
10051353f9a4SChandler Carruth
1006edb12a83SChandler Carruth Instruction *CurrentTerm = CurrentBB->getTerminator();
10071353f9a4SChandler Carruth
10081353f9a4SChandler Carruth if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
10091353f9a4SChandler Carruth // Don't bother trying to unswitch past a switch with a constant
10101353f9a4SChandler Carruth // condition. This should be removed prior to running this pass by
1011472462c4SBjorn Pettersson // simplifycfg.
10121353f9a4SChandler Carruth if (isa<Constant>(SI->getCondition()))
10131353f9a4SChandler Carruth return Changed;
10141353f9a4SChandler Carruth
1015a2eebb82SAlina Sbirlea if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
1016f209649dSHiroshi Inoue // Couldn't unswitch this one so we're done.
10171353f9a4SChandler Carruth return Changed;
10181353f9a4SChandler Carruth
10191353f9a4SChandler Carruth // Mark that we managed to unswitch something.
10201353f9a4SChandler Carruth Changed = true;
10211353f9a4SChandler Carruth
10221353f9a4SChandler Carruth // If unswitching turned the terminator into an unconditional branch then
10231353f9a4SChandler Carruth // we can continue. The unswitching logic specifically works to fold any
10241353f9a4SChandler Carruth // cases it can into an unconditional branch to make it easier to
10251353f9a4SChandler Carruth // recognize here.
10261353f9a4SChandler Carruth auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
10271353f9a4SChandler Carruth if (!BI || BI->isConditional())
10281353f9a4SChandler Carruth return Changed;
10291353f9a4SChandler Carruth
10301353f9a4SChandler Carruth CurrentBB = BI->getSuccessor(0);
10311353f9a4SChandler Carruth continue;
10321353f9a4SChandler Carruth }
10331353f9a4SChandler Carruth
10341353f9a4SChandler Carruth auto *BI = dyn_cast<BranchInst>(CurrentTerm);
10351353f9a4SChandler Carruth if (!BI)
10361353f9a4SChandler Carruth // We do not understand other terminator instructions.
10371353f9a4SChandler Carruth return Changed;
10381353f9a4SChandler Carruth
10391353f9a4SChandler Carruth // Don't bother trying to unswitch past an unconditional branch or a branch
1040472462c4SBjorn Pettersson // with a constant value. These should be removed by simplifycfg prior to
10411353f9a4SChandler Carruth // running this pass.
104232d6ef36SFlorian Hahn if (!BI->isConditional() ||
104332d6ef36SFlorian Hahn isa<Constant>(skipTrivialSelect(BI->getCondition())))
10441353f9a4SChandler Carruth return Changed;
10451353f9a4SChandler Carruth
10461353f9a4SChandler Carruth // Found a trivial condition candidate: non-foldable conditional branch. If
10471353f9a4SChandler Carruth // we fail to unswitch this, we can't do anything else that is trivial.
1048a2eebb82SAlina Sbirlea if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
10491353f9a4SChandler Carruth return Changed;
10501353f9a4SChandler Carruth
10511353f9a4SChandler Carruth // Mark that we managed to unswitch something.
10521353f9a4SChandler Carruth Changed = true;
10531353f9a4SChandler Carruth
10544da3331dSChandler Carruth // If we only unswitched some of the conditions feeding the branch, we won't
10554da3331dSChandler Carruth // have collapsed it to a single successor.
10561353f9a4SChandler Carruth BI = cast<BranchInst>(CurrentBB->getTerminator());
10574da3331dSChandler Carruth if (BI->isConditional())
10584da3331dSChandler Carruth return Changed;
10594da3331dSChandler Carruth
10604da3331dSChandler Carruth // Follow the newly unconditional branch into its successor.
10611353f9a4SChandler Carruth CurrentBB = BI->getSuccessor(0);
10621353f9a4SChandler Carruth
10631353f9a4SChandler Carruth // When continuing, if we exit the loop or reach a previous visited block,
10641353f9a4SChandler Carruth // then we can not reach any trivial condition candidates (unfoldable
10651353f9a4SChandler Carruth // branch instructions or switch instructions) and no unswitch can happen.
10661353f9a4SChandler Carruth } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
10671353f9a4SChandler Carruth
10681353f9a4SChandler Carruth return Changed;
10691353f9a4SChandler Carruth }
10701353f9a4SChandler Carruth
1071693eedb1SChandler Carruth /// Build the cloned blocks for an unswitched copy of the given loop.
1072693eedb1SChandler Carruth ///
1073693eedb1SChandler Carruth /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
1074693eedb1SChandler Carruth /// after the split block (`SplitBB`) that will be used to select between the
1075693eedb1SChandler Carruth /// cloned and original loop.
1076693eedb1SChandler Carruth ///
1077693eedb1SChandler Carruth /// This routine handles cloning all of the necessary loop blocks and exit
1078693eedb1SChandler Carruth /// blocks including rewriting their instructions and the relevant PHI nodes.
10791652996fSChandler Carruth /// Any loop blocks or exit blocks which are dominated by a different successor
10801652996fSChandler Carruth /// than the one for this clone of the loop blocks can be trivially skipped. We
10811652996fSChandler Carruth /// use the `DominatingSucc` map to determine whether a block satisfies that
10821652996fSChandler Carruth /// property with a simple map lookup.
10831652996fSChandler Carruth ///
10841652996fSChandler Carruth /// It also correctly creates the unconditional branch in the cloned
1085693eedb1SChandler Carruth /// unswitched parent block to only point at the unswitched successor.
1086693eedb1SChandler Carruth ///
1087693eedb1SChandler Carruth /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
1088693eedb1SChandler Carruth /// block splitting is correctly reflected in `LoopInfo`, essentially all of
1089693eedb1SChandler Carruth /// the cloned blocks (and their loops) are left without full `LoopInfo`
1090693eedb1SChandler Carruth /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
1091693eedb1SChandler Carruth /// blocks to them but doesn't create the cloned `DominatorTree` structure and
1092693eedb1SChandler Carruth /// instead the caller must recompute an accurate DT. It *does* correctly
1093693eedb1SChandler Carruth /// 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)1094693eedb1SChandler Carruth static BasicBlock *buildClonedLoopBlocks(
1095693eedb1SChandler Carruth Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
1096693eedb1SChandler Carruth ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
1097693eedb1SChandler Carruth BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
10981652996fSChandler Carruth const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
109969e68f84SChandler Carruth ValueToValueMapTy &VMap,
110069e68f84SChandler Carruth SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
1101a2eebb82SAlina Sbirlea DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
1102693eedb1SChandler Carruth SmallVector<BasicBlock *, 4> NewBlocks;
1103693eedb1SChandler Carruth NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
1104693eedb1SChandler Carruth
1105693eedb1SChandler Carruth // We will need to clone a bunch of blocks, wrap up the clone operation in
1106693eedb1SChandler Carruth // a helper.
1107693eedb1SChandler Carruth auto CloneBlock = [&](BasicBlock *OldBB) {
1108693eedb1SChandler Carruth // Clone the basic block and insert it before the new preheader.
1109693eedb1SChandler Carruth BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
1110693eedb1SChandler Carruth NewBB->moveBefore(LoopPH);
1111693eedb1SChandler Carruth
1112693eedb1SChandler Carruth // Record this block and the mapping.
1113693eedb1SChandler Carruth NewBlocks.push_back(NewBB);
1114693eedb1SChandler Carruth VMap[OldBB] = NewBB;
1115693eedb1SChandler Carruth
1116693eedb1SChandler Carruth return NewBB;
1117693eedb1SChandler Carruth };
1118693eedb1SChandler Carruth
11191652996fSChandler Carruth // We skip cloning blocks when they have a dominating succ that is not the
11201652996fSChandler Carruth // succ we are cloning for.
11211652996fSChandler Carruth auto SkipBlock = [&](BasicBlock *BB) {
11221652996fSChandler Carruth auto It = DominatingSucc.find(BB);
11231652996fSChandler Carruth return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
11241652996fSChandler Carruth };
11251652996fSChandler Carruth
1126693eedb1SChandler Carruth // First, clone the preheader.
1127693eedb1SChandler Carruth auto *ClonedPH = CloneBlock(LoopPH);
1128693eedb1SChandler Carruth
1129693eedb1SChandler Carruth // Then clone all the loop blocks, skipping the ones that aren't necessary.
1130693eedb1SChandler Carruth for (auto *LoopBB : L.blocks())
11311652996fSChandler Carruth if (!SkipBlock(LoopBB))
1132693eedb1SChandler Carruth CloneBlock(LoopBB);
1133693eedb1SChandler Carruth
1134693eedb1SChandler Carruth // Split all the loop exit edges so that when we clone the exit blocks, if
1135693eedb1SChandler Carruth // any of the exit blocks are *also* a preheader for some other loop, we
1136693eedb1SChandler Carruth // don't create multiple predecessors entering the loop header.
1137693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) {
11381652996fSChandler Carruth if (SkipBlock(ExitBB))
1139693eedb1SChandler Carruth continue;
1140693eedb1SChandler Carruth
1141693eedb1SChandler Carruth // When we are going to clone an exit, we don't need to clone all the
1142693eedb1SChandler Carruth // instructions in the exit block and we want to ensure we have an easy
1143693eedb1SChandler Carruth // place to merge the CFG, so split the exit first. This is always safe to
1144693eedb1SChandler Carruth // do because there cannot be any non-loop predecessors of a loop exit in
1145693eedb1SChandler Carruth // loop simplified form.
1146a2eebb82SAlina Sbirlea auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
1147693eedb1SChandler Carruth
1148693eedb1SChandler Carruth // Rearrange the names to make it easier to write test cases by having the
1149693eedb1SChandler Carruth // exit block carry the suffix rather than the merge block carrying the
1150693eedb1SChandler Carruth // suffix.
1151693eedb1SChandler Carruth MergeBB->takeName(ExitBB);
1152693eedb1SChandler Carruth ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1153693eedb1SChandler Carruth
1154693eedb1SChandler Carruth // Now clone the original exit block.
1155693eedb1SChandler Carruth auto *ClonedExitBB = CloneBlock(ExitBB);
1156693eedb1SChandler Carruth assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1157693eedb1SChandler Carruth "Exit block should have been split to have one successor!");
1158693eedb1SChandler Carruth assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1159693eedb1SChandler Carruth "Cloned exit block has the wrong successor!");
1160693eedb1SChandler Carruth
1161693eedb1SChandler Carruth // Remap any cloned instructions and create a merge phi node for them.
1162693eedb1SChandler Carruth for (auto ZippedInsts : llvm::zip_first(
1163693eedb1SChandler Carruth llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1164693eedb1SChandler Carruth llvm::make_range(ClonedExitBB->begin(),
1165693eedb1SChandler Carruth std::prev(ClonedExitBB->end())))) {
1166693eedb1SChandler Carruth Instruction &I = std::get<0>(ZippedInsts);
1167693eedb1SChandler Carruth Instruction &ClonedI = std::get<1>(ZippedInsts);
1168693eedb1SChandler Carruth
1169693eedb1SChandler Carruth // The only instructions in the exit block should be PHI nodes and
1170693eedb1SChandler Carruth // potentially a landing pad.
1171693eedb1SChandler Carruth assert(
1172693eedb1SChandler Carruth (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1173693eedb1SChandler Carruth "Bad instruction in exit block!");
1174693eedb1SChandler Carruth // We should have a value map between the instruction and its clone.
1175693eedb1SChandler Carruth assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1176693eedb1SChandler Carruth
1177693eedb1SChandler Carruth auto *MergePN =
1178693eedb1SChandler Carruth PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1179693eedb1SChandler Carruth &*MergeBB->getFirstInsertionPt());
1180693eedb1SChandler Carruth I.replaceAllUsesWith(MergePN);
1181693eedb1SChandler Carruth MergePN->addIncoming(&I, ExitBB);
1182693eedb1SChandler Carruth MergePN->addIncoming(&ClonedI, ClonedExitBB);
1183693eedb1SChandler Carruth }
1184693eedb1SChandler Carruth }
1185693eedb1SChandler Carruth
1186693eedb1SChandler Carruth // Rewrite the instructions in the cloned blocks to refer to the instructions
1187693eedb1SChandler Carruth // in the cloned blocks. We have to do this as a second pass so that we have
1188693eedb1SChandler Carruth // everything available. Also, we have inserted new instructions which may
1189693eedb1SChandler Carruth // include assume intrinsics, so we update the assumption cache while
1190693eedb1SChandler Carruth // processing this.
1191693eedb1SChandler Carruth for (auto *ClonedBB : NewBlocks)
1192693eedb1SChandler Carruth for (Instruction &I : *ClonedBB) {
1193693eedb1SChandler Carruth RemapInstruction(&I, VMap,
1194693eedb1SChandler Carruth RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1195a6d2a8d6SPhilip Reames if (auto *II = dyn_cast<AssumeInst>(&I))
1196693eedb1SChandler Carruth AC.registerAssumption(II);
1197693eedb1SChandler Carruth }
1198693eedb1SChandler Carruth
1199693eedb1SChandler Carruth // Update any PHI nodes in the cloned successors of the skipped blocks to not
1200693eedb1SChandler Carruth // have spurious incoming values.
1201693eedb1SChandler Carruth for (auto *LoopBB : L.blocks())
12021652996fSChandler Carruth if (SkipBlock(LoopBB))
1203693eedb1SChandler Carruth for (auto *SuccBB : successors(LoopBB))
1204693eedb1SChandler Carruth if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1205693eedb1SChandler Carruth for (PHINode &PN : ClonedSuccBB->phis())
1206693eedb1SChandler Carruth PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1207693eedb1SChandler Carruth
1208ed296543SChandler Carruth // Remove the cloned parent as a predecessor of any successor we ended up
1209ed296543SChandler Carruth // cloning other than the unswitched one.
1210ed296543SChandler Carruth auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1211ed296543SChandler Carruth for (auto *SuccBB : successors(ParentBB)) {
1212ed296543SChandler Carruth if (SuccBB == UnswitchedSuccBB)
1213ed296543SChandler Carruth continue;
1214ed296543SChandler Carruth
1215ed296543SChandler Carruth auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1216ed296543SChandler Carruth if (!ClonedSuccBB)
1217ed296543SChandler Carruth continue;
1218ed296543SChandler Carruth
1219ed296543SChandler Carruth ClonedSuccBB->removePredecessor(ClonedParentBB,
122020b91899SMax Kazantsev /*KeepOneInputPHIs*/ true);
1221ed296543SChandler Carruth }
1222ed296543SChandler Carruth
1223ed296543SChandler Carruth // Replace the cloned branch with an unconditional branch to the cloned
1224ed296543SChandler Carruth // unswitched successor.
1225ed296543SChandler Carruth auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
12265502cfa0SSerguei Katkov Instruction *ClonedTerminator = ClonedParentBB->getTerminator();
12275502cfa0SSerguei Katkov // Trivial Simplification. If Terminator is a conditional branch and
12285502cfa0SSerguei Katkov // condition becomes dead - erase it.
12295502cfa0SSerguei Katkov Value *ClonedConditionToErase = nullptr;
12305502cfa0SSerguei Katkov if (auto *BI = dyn_cast<BranchInst>(ClonedTerminator))
12315502cfa0SSerguei Katkov ClonedConditionToErase = BI->getCondition();
12325502cfa0SSerguei Katkov else if (auto *SI = dyn_cast<SwitchInst>(ClonedTerminator))
12335502cfa0SSerguei Katkov ClonedConditionToErase = SI->getCondition();
12345502cfa0SSerguei Katkov
12355502cfa0SSerguei Katkov ClonedTerminator->eraseFromParent();
1236ed296543SChandler Carruth BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1237ed296543SChandler Carruth
12385502cfa0SSerguei Katkov if (ClonedConditionToErase)
12395502cfa0SSerguei Katkov RecursivelyDeleteTriviallyDeadInstructions(ClonedConditionToErase, nullptr,
12405502cfa0SSerguei Katkov MSSAU);
12415502cfa0SSerguei Katkov
1242ed296543SChandler Carruth // If there are duplicate entries in the PHI nodes because of multiple edges
1243ed296543SChandler Carruth // to the unswitched successor, we need to nuke all but one as we replaced it
1244ed296543SChandler Carruth // with a direct branch.
1245ed296543SChandler Carruth for (PHINode &PN : ClonedSuccBB->phis()) {
1246ed296543SChandler Carruth bool Found = false;
1247ed296543SChandler Carruth // Loop over the incoming operands backwards so we can easily delete as we
1248ed296543SChandler Carruth // go without invalidating the index.
1249ed296543SChandler Carruth for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1250ed296543SChandler Carruth if (PN.getIncomingBlock(i) != ClonedParentBB)
1251ed296543SChandler Carruth continue;
1252ed296543SChandler Carruth if (!Found) {
1253ed296543SChandler Carruth Found = true;
1254ed296543SChandler Carruth continue;
1255ed296543SChandler Carruth }
1256ed296543SChandler Carruth PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1257ed296543SChandler Carruth }
1258ed296543SChandler Carruth }
1259ed296543SChandler Carruth
126069e68f84SChandler Carruth // Record the domtree updates for the new blocks.
126144aab925SChandler Carruth SmallPtrSet<BasicBlock *, 4> SuccSet;
126244aab925SChandler Carruth for (auto *ClonedBB : NewBlocks) {
126369e68f84SChandler Carruth for (auto *SuccBB : successors(ClonedBB))
126444aab925SChandler Carruth if (SuccSet.insert(SuccBB).second)
126569e68f84SChandler Carruth DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
126644aab925SChandler Carruth SuccSet.clear();
126744aab925SChandler Carruth }
126869e68f84SChandler Carruth
1269693eedb1SChandler Carruth return ClonedPH;
1270693eedb1SChandler Carruth }
1271693eedb1SChandler Carruth
1272693eedb1SChandler Carruth /// Recursively clone the specified loop and all of its children.
1273693eedb1SChandler Carruth ///
1274693eedb1SChandler Carruth /// The target parent loop for the clone should be provided, or can be null if
1275693eedb1SChandler Carruth /// the clone is a top-level loop. While cloning, all the blocks are mapped
1276693eedb1SChandler Carruth /// with the provided value map. The entire original loop must be present in
1277693eedb1SChandler Carruth /// the value map. The cloned loop is returned.
cloneLoopNest(Loop & OrigRootL,Loop * RootParentL,const ValueToValueMapTy & VMap,LoopInfo & LI)1278693eedb1SChandler Carruth static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1279693eedb1SChandler Carruth const ValueToValueMapTy &VMap, LoopInfo &LI) {
1280693eedb1SChandler Carruth auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1281693eedb1SChandler Carruth assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1282693eedb1SChandler Carruth ClonedL.reserveBlocks(OrigL.getNumBlocks());
1283693eedb1SChandler Carruth for (auto *BB : OrigL.blocks()) {
1284693eedb1SChandler Carruth auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1285693eedb1SChandler Carruth ClonedL.addBlockEntry(ClonedBB);
12860ace148cSChandler Carruth if (LI.getLoopFor(BB) == &OrigL)
1287693eedb1SChandler Carruth LI.changeLoopFor(ClonedBB, &ClonedL);
1288693eedb1SChandler Carruth }
1289693eedb1SChandler Carruth };
1290693eedb1SChandler Carruth
1291693eedb1SChandler Carruth // We specially handle the first loop because it may get cloned into
1292693eedb1SChandler Carruth // a different parent and because we most commonly are cloning leaf loops.
1293693eedb1SChandler Carruth Loop *ClonedRootL = LI.AllocateLoop();
1294693eedb1SChandler Carruth if (RootParentL)
1295693eedb1SChandler Carruth RootParentL->addChildLoop(ClonedRootL);
1296693eedb1SChandler Carruth else
1297693eedb1SChandler Carruth LI.addTopLevelLoop(ClonedRootL);
1298693eedb1SChandler Carruth AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1299693eedb1SChandler Carruth
130089c1e35fSStefanos Baziotis if (OrigRootL.isInnermost())
1301693eedb1SChandler Carruth return ClonedRootL;
1302693eedb1SChandler Carruth
1303693eedb1SChandler Carruth // If we have a nest, we can quickly clone the entire loop nest using an
1304693eedb1SChandler Carruth // iterative approach because it is a tree. We keep the cloned parent in the
1305693eedb1SChandler Carruth // data structure to avoid repeatedly querying through a map to find it.
1306693eedb1SChandler Carruth SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1307693eedb1SChandler Carruth // Build up the loops to clone in reverse order as we'll clone them from the
1308693eedb1SChandler Carruth // back.
1309693eedb1SChandler Carruth for (Loop *ChildL : llvm::reverse(OrigRootL))
1310693eedb1SChandler Carruth LoopsToClone.push_back({ClonedRootL, ChildL});
1311693eedb1SChandler Carruth do {
1312693eedb1SChandler Carruth Loop *ClonedParentL, *L;
1313693eedb1SChandler Carruth std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1314693eedb1SChandler Carruth Loop *ClonedL = LI.AllocateLoop();
1315693eedb1SChandler Carruth ClonedParentL->addChildLoop(ClonedL);
1316693eedb1SChandler Carruth AddClonedBlocksToLoop(*L, *ClonedL);
1317693eedb1SChandler Carruth for (Loop *ChildL : llvm::reverse(*L))
1318693eedb1SChandler Carruth LoopsToClone.push_back({ClonedL, ChildL});
1319693eedb1SChandler Carruth } while (!LoopsToClone.empty());
1320693eedb1SChandler Carruth
1321693eedb1SChandler Carruth return ClonedRootL;
1322693eedb1SChandler Carruth }
1323693eedb1SChandler Carruth
1324693eedb1SChandler Carruth /// Build the cloned loops of an original loop from unswitching.
1325693eedb1SChandler Carruth ///
1326693eedb1SChandler Carruth /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1327693eedb1SChandler Carruth /// operation. We need to re-verify that there even is a loop (as the backedge
1328693eedb1SChandler Carruth /// may not have been cloned), and even if there are remaining backedges the
1329693eedb1SChandler Carruth /// backedge set may be different. However, we know that each child loop is
1330693eedb1SChandler Carruth /// undisturbed, we only need to find where to place each child loop within
1331693eedb1SChandler Carruth /// either any parent loop or within a cloned version of the original loop.
1332693eedb1SChandler Carruth ///
1333693eedb1SChandler Carruth /// Because child loops may end up cloned outside of any cloned version of the
1334693eedb1SChandler Carruth /// original loop, multiple cloned sibling loops may be created. All of them
1335693eedb1SChandler Carruth /// are returned so that the newly introduced loop nest roots can be
1336693eedb1SChandler Carruth /// identified.
buildClonedLoops(Loop & OrigL,ArrayRef<BasicBlock * > ExitBlocks,const ValueToValueMapTy & VMap,LoopInfo & LI,SmallVectorImpl<Loop * > & NonChildClonedLoops)13379281503eSChandler Carruth static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1338693eedb1SChandler Carruth const ValueToValueMapTy &VMap, LoopInfo &LI,
1339693eedb1SChandler Carruth SmallVectorImpl<Loop *> &NonChildClonedLoops) {
1340693eedb1SChandler Carruth Loop *ClonedL = nullptr;
1341693eedb1SChandler Carruth
1342693eedb1SChandler Carruth auto *OrigPH = OrigL.getLoopPreheader();
1343693eedb1SChandler Carruth auto *OrigHeader = OrigL.getHeader();
1344693eedb1SChandler Carruth
1345693eedb1SChandler Carruth auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1346693eedb1SChandler Carruth auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1347693eedb1SChandler Carruth
1348693eedb1SChandler Carruth // We need to know the loops of the cloned exit blocks to even compute the
1349693eedb1SChandler Carruth // accurate parent loop. If we only clone exits to some parent of the
1350693eedb1SChandler Carruth // original parent, we want to clone into that outer loop. We also keep track
1351693eedb1SChandler Carruth // of the loops that our cloned exit blocks participate in.
1352693eedb1SChandler Carruth Loop *ParentL = nullptr;
1353693eedb1SChandler Carruth SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1354693eedb1SChandler Carruth SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1355693eedb1SChandler Carruth ClonedExitsInLoops.reserve(ExitBlocks.size());
1356693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks)
1357693eedb1SChandler Carruth if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1358693eedb1SChandler Carruth if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1359693eedb1SChandler Carruth ExitLoopMap[ClonedExitBB] = ExitL;
1360693eedb1SChandler Carruth ClonedExitsInLoops.push_back(ClonedExitBB);
1361693eedb1SChandler Carruth if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1362693eedb1SChandler Carruth ParentL = ExitL;
1363693eedb1SChandler Carruth }
1364693eedb1SChandler Carruth assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1365693eedb1SChandler Carruth ParentL->contains(OrigL.getParentLoop())) &&
1366693eedb1SChandler Carruth "The computed parent loop should always contain (or be) the parent of "
1367693eedb1SChandler Carruth "the original loop.");
1368693eedb1SChandler Carruth
1369693eedb1SChandler Carruth // We build the set of blocks dominated by the cloned header from the set of
1370693eedb1SChandler Carruth // cloned blocks out of the original loop. While not all of these will
1371693eedb1SChandler Carruth // necessarily be in the cloned loop, it is enough to establish that they
1372693eedb1SChandler Carruth // aren't in unreachable cycles, etc.
1373693eedb1SChandler Carruth SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1374693eedb1SChandler Carruth for (auto *BB : OrigL.blocks())
1375693eedb1SChandler Carruth if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1376693eedb1SChandler Carruth ClonedLoopBlocks.insert(ClonedBB);
1377693eedb1SChandler Carruth
1378693eedb1SChandler Carruth // Rebuild the set of blocks that will end up in the cloned loop. We may have
1379693eedb1SChandler Carruth // skipped cloning some region of this loop which can in turn skip some of
1380693eedb1SChandler Carruth // the backedges so we have to rebuild the blocks in the loop based on the
1381693eedb1SChandler Carruth // backedges that remain after cloning.
1382693eedb1SChandler Carruth SmallVector<BasicBlock *, 16> Worklist;
1383693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1384693eedb1SChandler Carruth for (auto *Pred : predecessors(ClonedHeader)) {
1385693eedb1SChandler Carruth // The only possible non-loop header predecessor is the preheader because
1386693eedb1SChandler Carruth // we know we cloned the loop in simplified form.
1387693eedb1SChandler Carruth if (Pred == ClonedPH)
1388693eedb1SChandler Carruth continue;
1389693eedb1SChandler Carruth
1390693eedb1SChandler Carruth // Because the loop was in simplified form, the only non-loop predecessor
1391693eedb1SChandler Carruth // should be the preheader.
1392693eedb1SChandler Carruth assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1393693eedb1SChandler Carruth "header other than the preheader "
1394693eedb1SChandler Carruth "that is not part of the loop!");
1395693eedb1SChandler Carruth
1396693eedb1SChandler Carruth // Insert this block into the loop set and on the first visit (and if it
1397693eedb1SChandler Carruth // isn't the header we're currently walking) put it into the worklist to
1398693eedb1SChandler Carruth // recurse through.
1399693eedb1SChandler Carruth if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1400693eedb1SChandler Carruth Worklist.push_back(Pred);
1401693eedb1SChandler Carruth }
1402693eedb1SChandler Carruth
1403693eedb1SChandler Carruth // If we had any backedges then there *is* a cloned loop. Put the header into
1404693eedb1SChandler Carruth // the loop set and then walk the worklist backwards to find all the blocks
1405693eedb1SChandler Carruth // that remain within the loop after cloning.
1406693eedb1SChandler Carruth if (!BlocksInClonedLoop.empty()) {
1407693eedb1SChandler Carruth BlocksInClonedLoop.insert(ClonedHeader);
1408693eedb1SChandler Carruth
1409693eedb1SChandler Carruth while (!Worklist.empty()) {
1410693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val();
1411693eedb1SChandler Carruth assert(BlocksInClonedLoop.count(BB) &&
1412693eedb1SChandler Carruth "Didn't put block into the loop set!");
1413693eedb1SChandler Carruth
1414693eedb1SChandler Carruth // Insert any predecessors that are in the possible set into the cloned
1415693eedb1SChandler Carruth // set, and if the insert is successful, add them to the worklist. Note
1416693eedb1SChandler Carruth // that we filter on the blocks that are definitely reachable via the
1417693eedb1SChandler Carruth // backedge to the loop header so we may prune out dead code within the
1418693eedb1SChandler Carruth // cloned loop.
1419693eedb1SChandler Carruth for (auto *Pred : predecessors(BB))
1420693eedb1SChandler Carruth if (ClonedLoopBlocks.count(Pred) &&
1421693eedb1SChandler Carruth BlocksInClonedLoop.insert(Pred).second)
1422693eedb1SChandler Carruth Worklist.push_back(Pred);
1423693eedb1SChandler Carruth }
1424693eedb1SChandler Carruth
1425693eedb1SChandler Carruth ClonedL = LI.AllocateLoop();
1426693eedb1SChandler Carruth if (ParentL) {
1427693eedb1SChandler Carruth ParentL->addBasicBlockToLoop(ClonedPH, LI);
1428693eedb1SChandler Carruth ParentL->addChildLoop(ClonedL);
1429693eedb1SChandler Carruth } else {
1430693eedb1SChandler Carruth LI.addTopLevelLoop(ClonedL);
1431693eedb1SChandler Carruth }
14329281503eSChandler Carruth NonChildClonedLoops.push_back(ClonedL);
1433693eedb1SChandler Carruth
1434693eedb1SChandler Carruth ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1435693eedb1SChandler Carruth // We don't want to just add the cloned loop blocks based on how we
1436693eedb1SChandler Carruth // discovered them. The original order of blocks was carefully built in
1437693eedb1SChandler Carruth // a way that doesn't rely on predecessor ordering. Rather than re-invent
1438693eedb1SChandler Carruth // that logic, we just re-walk the original blocks (and those of the child
1439693eedb1SChandler Carruth // loops) and filter them as we add them into the cloned loop.
1440693eedb1SChandler Carruth for (auto *BB : OrigL.blocks()) {
1441693eedb1SChandler Carruth auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1442693eedb1SChandler Carruth if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1443693eedb1SChandler Carruth continue;
1444693eedb1SChandler Carruth
1445693eedb1SChandler Carruth // Directly add the blocks that are only in this loop.
1446693eedb1SChandler Carruth if (LI.getLoopFor(BB) == &OrigL) {
1447693eedb1SChandler Carruth ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1448693eedb1SChandler Carruth continue;
1449693eedb1SChandler Carruth }
1450693eedb1SChandler Carruth
1451693eedb1SChandler Carruth // We want to manually add it to this loop and parents.
1452693eedb1SChandler Carruth // Registering it with LoopInfo will happen when we clone the top
1453693eedb1SChandler Carruth // loop for this block.
1454693eedb1SChandler Carruth for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1455693eedb1SChandler Carruth PL->addBlockEntry(ClonedBB);
1456693eedb1SChandler Carruth }
1457693eedb1SChandler Carruth
1458693eedb1SChandler Carruth // Now add each child loop whose header remains within the cloned loop. All
1459693eedb1SChandler Carruth // of the blocks within the loop must satisfy the same constraints as the
1460693eedb1SChandler Carruth // header so once we pass the header checks we can just clone the entire
1461693eedb1SChandler Carruth // child loop nest.
1462693eedb1SChandler Carruth for (Loop *ChildL : OrigL) {
1463693eedb1SChandler Carruth auto *ClonedChildHeader =
1464693eedb1SChandler Carruth cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1465693eedb1SChandler Carruth if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1466693eedb1SChandler Carruth continue;
1467693eedb1SChandler Carruth
1468693eedb1SChandler Carruth #ifndef NDEBUG
1469693eedb1SChandler Carruth // We should never have a cloned child loop header but fail to have
1470693eedb1SChandler Carruth // all of the blocks for that child loop.
1471693eedb1SChandler Carruth for (auto *ChildLoopBB : ChildL->blocks())
1472693eedb1SChandler Carruth assert(BlocksInClonedLoop.count(
1473693eedb1SChandler Carruth cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1474693eedb1SChandler Carruth "Child cloned loop has a header within the cloned outer "
1475693eedb1SChandler Carruth "loop but not all of its blocks!");
1476693eedb1SChandler Carruth #endif
1477693eedb1SChandler Carruth
1478693eedb1SChandler Carruth cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1479693eedb1SChandler Carruth }
1480693eedb1SChandler Carruth }
1481693eedb1SChandler Carruth
1482693eedb1SChandler Carruth // Now that we've handled all the components of the original loop that were
1483693eedb1SChandler Carruth // cloned into a new loop, we still need to handle anything from the original
1484693eedb1SChandler Carruth // loop that wasn't in a cloned loop.
1485693eedb1SChandler Carruth
1486693eedb1SChandler Carruth // Figure out what blocks are left to place within any loop nest containing
1487693eedb1SChandler Carruth // the unswitched loop. If we never formed a loop, the cloned PH is one of
1488693eedb1SChandler Carruth // them.
1489693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1490693eedb1SChandler Carruth if (BlocksInClonedLoop.empty())
1491693eedb1SChandler Carruth UnloopedBlockSet.insert(ClonedPH);
1492693eedb1SChandler Carruth for (auto *ClonedBB : ClonedLoopBlocks)
1493693eedb1SChandler Carruth if (!BlocksInClonedLoop.count(ClonedBB))
1494693eedb1SChandler Carruth UnloopedBlockSet.insert(ClonedBB);
1495693eedb1SChandler Carruth
1496693eedb1SChandler Carruth // Copy the cloned exits and sort them in ascending loop depth, we'll work
1497693eedb1SChandler Carruth // backwards across these to process them inside out. The order shouldn't
1498693eedb1SChandler Carruth // matter as we're just trying to build up the map from inside-out; we use
1499693eedb1SChandler Carruth // the map in a more stably ordered way below.
1500693eedb1SChandler Carruth auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
15010cac726aSFangrui Song llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1502693eedb1SChandler Carruth return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1503693eedb1SChandler Carruth ExitLoopMap.lookup(RHS)->getLoopDepth();
1504693eedb1SChandler Carruth });
1505693eedb1SChandler Carruth
1506693eedb1SChandler Carruth // Populate the existing ExitLoopMap with everything reachable from each
1507693eedb1SChandler Carruth // exit, starting from the inner most exit.
1508693eedb1SChandler Carruth while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1509693eedb1SChandler Carruth assert(Worklist.empty() && "Didn't clear worklist!");
1510693eedb1SChandler Carruth
1511693eedb1SChandler Carruth BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1512693eedb1SChandler Carruth Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1513693eedb1SChandler Carruth
1514693eedb1SChandler Carruth // Walk the CFG back until we hit the cloned PH adding everything reachable
1515693eedb1SChandler Carruth // and in the unlooped set to this exit block's loop.
1516693eedb1SChandler Carruth Worklist.push_back(ExitBB);
1517693eedb1SChandler Carruth do {
1518693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val();
1519693eedb1SChandler Carruth // We can stop recursing at the cloned preheader (if we get there).
1520693eedb1SChandler Carruth if (BB == ClonedPH)
1521693eedb1SChandler Carruth continue;
1522693eedb1SChandler Carruth
1523693eedb1SChandler Carruth for (BasicBlock *PredBB : predecessors(BB)) {
1524693eedb1SChandler Carruth // If this pred has already been moved to our set or is part of some
1525693eedb1SChandler Carruth // (inner) loop, no update needed.
1526693eedb1SChandler Carruth if (!UnloopedBlockSet.erase(PredBB)) {
1527693eedb1SChandler Carruth assert(
1528693eedb1SChandler Carruth (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1529693eedb1SChandler Carruth "Predecessor not mapped to a loop!");
1530693eedb1SChandler Carruth continue;
1531693eedb1SChandler Carruth }
1532693eedb1SChandler Carruth
1533693eedb1SChandler Carruth // We just insert into the loop set here. We'll add these blocks to the
1534693eedb1SChandler Carruth // exit loop after we build up the set in an order that doesn't rely on
1535693eedb1SChandler Carruth // predecessor order (which in turn relies on use list order).
1536693eedb1SChandler Carruth bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1537693eedb1SChandler Carruth (void)Inserted;
1538693eedb1SChandler Carruth assert(Inserted && "Should only visit an unlooped block once!");
1539693eedb1SChandler Carruth
1540693eedb1SChandler Carruth // And recurse through to its predecessors.
1541693eedb1SChandler Carruth Worklist.push_back(PredBB);
1542693eedb1SChandler Carruth }
1543693eedb1SChandler Carruth } while (!Worklist.empty());
1544693eedb1SChandler Carruth }
1545693eedb1SChandler Carruth
1546693eedb1SChandler Carruth // Now that the ExitLoopMap gives as mapping for all the non-looping cloned
1547693eedb1SChandler Carruth // blocks to their outer loops, walk the cloned blocks and the cloned exits
1548693eedb1SChandler Carruth // in their original order adding them to the correct loop.
1549693eedb1SChandler Carruth
1550693eedb1SChandler Carruth // We need a stable insertion order. We use the order of the original loop
1551693eedb1SChandler Carruth // order and map into the correct parent loop.
1552693eedb1SChandler Carruth for (auto *BB : llvm::concat<BasicBlock *const>(
1553693eedb1SChandler Carruth makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1554693eedb1SChandler Carruth if (Loop *OuterL = ExitLoopMap.lookup(BB))
1555693eedb1SChandler Carruth OuterL->addBasicBlockToLoop(BB, LI);
1556693eedb1SChandler Carruth
1557693eedb1SChandler Carruth #ifndef NDEBUG
1558693eedb1SChandler Carruth for (auto &BBAndL : ExitLoopMap) {
1559693eedb1SChandler Carruth auto *BB = BBAndL.first;
1560693eedb1SChandler Carruth auto *OuterL = BBAndL.second;
1561693eedb1SChandler Carruth assert(LI.getLoopFor(BB) == OuterL &&
1562693eedb1SChandler Carruth "Failed to put all blocks into outer loops!");
1563693eedb1SChandler Carruth }
1564693eedb1SChandler Carruth #endif
1565693eedb1SChandler Carruth
1566693eedb1SChandler Carruth // Now that all the blocks are placed into the correct containing loop in the
1567693eedb1SChandler Carruth // absence of child loops, find all the potentially cloned child loops and
1568693eedb1SChandler Carruth // clone them into whatever outer loop we placed their header into.
1569693eedb1SChandler Carruth for (Loop *ChildL : OrigL) {
1570693eedb1SChandler Carruth auto *ClonedChildHeader =
1571693eedb1SChandler Carruth cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1572693eedb1SChandler Carruth if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1573693eedb1SChandler Carruth continue;
1574693eedb1SChandler Carruth
1575693eedb1SChandler Carruth #ifndef NDEBUG
1576693eedb1SChandler Carruth for (auto *ChildLoopBB : ChildL->blocks())
1577693eedb1SChandler Carruth assert(VMap.count(ChildLoopBB) &&
1578693eedb1SChandler Carruth "Cloned a child loop header but not all of that loops blocks!");
1579693eedb1SChandler Carruth #endif
1580693eedb1SChandler Carruth
1581693eedb1SChandler Carruth NonChildClonedLoops.push_back(cloneLoopNest(
1582693eedb1SChandler Carruth *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1583693eedb1SChandler Carruth }
1584693eedb1SChandler Carruth }
1585693eedb1SChandler Carruth
158669e68f84SChandler Carruth static void
deleteDeadClonedBlocks(Loop & L,ArrayRef<BasicBlock * > ExitBlocks,ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,DominatorTree & DT,MemorySSAUpdater * MSSAU)15871652996fSChandler Carruth deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
15881652996fSChandler Carruth ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1589a2eebb82SAlina Sbirlea DominatorTree &DT, MemorySSAUpdater *MSSAU) {
15901652996fSChandler Carruth // Find all the dead clones, and remove them from their successors.
15911652996fSChandler Carruth SmallVector<BasicBlock *, 16> DeadBlocks;
15921652996fSChandler Carruth for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
15931652996fSChandler Carruth for (auto &VMap : VMaps)
15941652996fSChandler Carruth if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
15951652996fSChandler Carruth if (!DT.isReachableFromEntry(ClonedBB)) {
15961652996fSChandler Carruth for (BasicBlock *SuccBB : successors(ClonedBB))
15971652996fSChandler Carruth SuccBB->removePredecessor(ClonedBB);
15981652996fSChandler Carruth DeadBlocks.push_back(ClonedBB);
15991652996fSChandler Carruth }
16001652996fSChandler Carruth
1601a2eebb82SAlina Sbirlea // Remove all MemorySSA in the dead blocks
1602a2eebb82SAlina Sbirlea if (MSSAU) {
1603db101864SAlina Sbirlea SmallSetVector<BasicBlock *, 8> DeadBlockSet(DeadBlocks.begin(),
1604a2eebb82SAlina Sbirlea DeadBlocks.end());
1605a2eebb82SAlina Sbirlea MSSAU->removeBlocks(DeadBlockSet);
1606a2eebb82SAlina Sbirlea }
1607a2eebb82SAlina Sbirlea
16081652996fSChandler Carruth // Drop any remaining references to break cycles.
16091652996fSChandler Carruth for (BasicBlock *BB : DeadBlocks)
16101652996fSChandler Carruth BB->dropAllReferences();
16111652996fSChandler Carruth // Erase them from the IR.
16121652996fSChandler Carruth for (BasicBlock *BB : DeadBlocks)
16131652996fSChandler Carruth BB->eraseFromParent();
16141652996fSChandler Carruth }
16151652996fSChandler Carruth
16160f0344ddSBjorn Pettersson static void
deleteDeadBlocksFromLoop(Loop & L,SmallVectorImpl<BasicBlock * > & ExitBlocks,DominatorTree & DT,LoopInfo & LI,MemorySSAUpdater * MSSAU,function_ref<void (Loop &,StringRef)> DestroyLoopCB)16170f0344ddSBjorn Pettersson deleteDeadBlocksFromLoop(Loop &L,
1618693eedb1SChandler Carruth SmallVectorImpl<BasicBlock *> &ExitBlocks,
1619a2eebb82SAlina Sbirlea DominatorTree &DT, LoopInfo &LI,
16200f0344ddSBjorn Pettersson MemorySSAUpdater *MSSAU,
16210f0344ddSBjorn Pettersson function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
16228b6effd9SFedor Sergeev // Find all the dead blocks tied to this loop, and remove them from their
16238b6effd9SFedor Sergeev // successors.
1624db101864SAlina Sbirlea SmallSetVector<BasicBlock *, 8> DeadBlockSet;
16257b49aa03SFedor Sergeev
16268b6effd9SFedor Sergeev // Start with loop/exit blocks and get a transitive closure of reachable dead
16278b6effd9SFedor Sergeev // blocks.
16288b6effd9SFedor Sergeev SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
16298b6effd9SFedor Sergeev ExitBlocks.end());
16308b6effd9SFedor Sergeev DeathCandidates.append(L.blocks().begin(), L.blocks().end());
16318b6effd9SFedor Sergeev while (!DeathCandidates.empty()) {
16328b6effd9SFedor Sergeev auto *BB = DeathCandidates.pop_back_val();
16338b6effd9SFedor Sergeev if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
16348b6effd9SFedor Sergeev for (BasicBlock *SuccBB : successors(BB)) {
16351652996fSChandler Carruth SuccBB->removePredecessor(BB);
16368b6effd9SFedor Sergeev DeathCandidates.push_back(SuccBB);
16371652996fSChandler Carruth }
16388b6effd9SFedor Sergeev DeadBlockSet.insert(BB);
16398b6effd9SFedor Sergeev }
16408b6effd9SFedor Sergeev }
1641693eedb1SChandler Carruth
1642a2eebb82SAlina Sbirlea // Remove all MemorySSA in the dead blocks
1643a2eebb82SAlina Sbirlea if (MSSAU)
1644a2eebb82SAlina Sbirlea MSSAU->removeBlocks(DeadBlockSet);
1645a2eebb82SAlina Sbirlea
1646693eedb1SChandler Carruth // Filter out the dead blocks from the exit blocks list so that it can be
1647693eedb1SChandler Carruth // used in the caller.
1648693eedb1SChandler Carruth llvm::erase_if(ExitBlocks,
164969e68f84SChandler Carruth [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1650693eedb1SChandler Carruth
1651693eedb1SChandler Carruth // Walk from this loop up through its parents removing all of the dead blocks.
1652693eedb1SChandler Carruth for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
16538b6effd9SFedor Sergeev for (auto *BB : DeadBlockSet)
1654693eedb1SChandler Carruth ParentL->getBlocksSet().erase(BB);
1655693eedb1SChandler Carruth llvm::erase_if(ParentL->getBlocksVector(),
165669e68f84SChandler Carruth [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1657693eedb1SChandler Carruth }
1658693eedb1SChandler Carruth
1659693eedb1SChandler Carruth // Now delete the dead child loops. This raw delete will clear them
1660693eedb1SChandler Carruth // recursively.
1661693eedb1SChandler Carruth llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
166269e68f84SChandler Carruth if (!DeadBlockSet.count(ChildL->getHeader()))
1663693eedb1SChandler Carruth return false;
1664693eedb1SChandler Carruth
1665693eedb1SChandler Carruth assert(llvm::all_of(ChildL->blocks(),
1666693eedb1SChandler Carruth [&](BasicBlock *ChildBB) {
166769e68f84SChandler Carruth return DeadBlockSet.count(ChildBB);
1668693eedb1SChandler Carruth }) &&
1669693eedb1SChandler Carruth "If the child loop header is dead all blocks in the child loop must "
1670693eedb1SChandler Carruth "be dead as well!");
16710f0344ddSBjorn Pettersson DestroyLoopCB(*ChildL, ChildL->getName());
1672693eedb1SChandler Carruth LI.destroy(ChildL);
1673693eedb1SChandler Carruth return true;
1674693eedb1SChandler Carruth });
1675693eedb1SChandler Carruth
167669e68f84SChandler Carruth // Remove the loop mappings for the dead blocks and drop all the references
167769e68f84SChandler Carruth // from these blocks to others to handle cyclic references as we start
167869e68f84SChandler Carruth // deleting the blocks themselves.
16798b6effd9SFedor Sergeev for (auto *BB : DeadBlockSet) {
168069e68f84SChandler Carruth // Check that the dominator tree has already been updated.
168169e68f84SChandler Carruth assert(!DT.getNode(BB) && "Should already have cleared domtree!");
1682693eedb1SChandler Carruth LI.changeLoopFor(BB, nullptr);
1683706b22e3SDaniil Suchkov // Drop all uses of the instructions to make sure we won't have dangling
1684706b22e3SDaniil Suchkov // uses in other blocks.
1685706b22e3SDaniil Suchkov for (auto &I : *BB)
1686706b22e3SDaniil Suchkov if (!I.use_empty())
1687*0586d1caSNuno Lopes I.replaceAllUsesWith(PoisonValue::get(I.getType()));
1688693eedb1SChandler Carruth BB->dropAllReferences();
1689693eedb1SChandler Carruth }
169069e68f84SChandler Carruth
169169e68f84SChandler Carruth // Actually delete the blocks now that they've been fully unhooked from the
169269e68f84SChandler Carruth // IR.
16937b49aa03SFedor Sergeev for (auto *BB : DeadBlockSet)
169469e68f84SChandler Carruth BB->eraseFromParent();
1695693eedb1SChandler Carruth }
1696693eedb1SChandler Carruth
1697693eedb1SChandler Carruth /// Recompute the set of blocks in a loop after unswitching.
1698693eedb1SChandler Carruth ///
1699693eedb1SChandler Carruth /// This walks from the original headers predecessors to rebuild the loop. We
1700693eedb1SChandler Carruth /// take advantage of the fact that new blocks can't have been added, and so we
1701693eedb1SChandler Carruth /// filter by the original loop's blocks. This also handles potentially
1702693eedb1SChandler Carruth /// unreachable code that we don't want to explore but might be found examining
1703693eedb1SChandler Carruth /// the predecessors of the header.
1704693eedb1SChandler Carruth ///
1705693eedb1SChandler Carruth /// If the original loop is no longer a loop, this will return an empty set. If
1706693eedb1SChandler Carruth /// it remains a loop, all the blocks within it will be added to the set
1707693eedb1SChandler Carruth /// (including those blocks in inner loops).
recomputeLoopBlockSet(Loop & L,LoopInfo & LI)1708693eedb1SChandler Carruth static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1709693eedb1SChandler Carruth LoopInfo &LI) {
1710693eedb1SChandler Carruth SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1711693eedb1SChandler Carruth
1712693eedb1SChandler Carruth auto *PH = L.getLoopPreheader();
1713693eedb1SChandler Carruth auto *Header = L.getHeader();
1714693eedb1SChandler Carruth
1715693eedb1SChandler Carruth // A worklist to use while walking backwards from the header.
1716693eedb1SChandler Carruth SmallVector<BasicBlock *, 16> Worklist;
1717693eedb1SChandler Carruth
1718693eedb1SChandler Carruth // First walk the predecessors of the header to find the backedges. This will
1719693eedb1SChandler Carruth // form the basis of our walk.
1720693eedb1SChandler Carruth for (auto *Pred : predecessors(Header)) {
1721693eedb1SChandler Carruth // Skip the preheader.
1722693eedb1SChandler Carruth if (Pred == PH)
1723693eedb1SChandler Carruth continue;
1724693eedb1SChandler Carruth
1725693eedb1SChandler Carruth // Because the loop was in simplified form, the only non-loop predecessor
1726693eedb1SChandler Carruth // is the preheader.
1727693eedb1SChandler Carruth assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1728693eedb1SChandler Carruth "than the preheader that is not part of the "
1729693eedb1SChandler Carruth "loop!");
1730693eedb1SChandler Carruth
1731693eedb1SChandler Carruth // Insert this block into the loop set and on the first visit and, if it
1732693eedb1SChandler Carruth // isn't the header we're currently walking, put it into the worklist to
1733693eedb1SChandler Carruth // recurse through.
1734693eedb1SChandler Carruth if (LoopBlockSet.insert(Pred).second && Pred != Header)
1735693eedb1SChandler Carruth Worklist.push_back(Pred);
1736693eedb1SChandler Carruth }
1737693eedb1SChandler Carruth
1738693eedb1SChandler Carruth // If no backedges were found, we're done.
1739693eedb1SChandler Carruth if (LoopBlockSet.empty())
1740693eedb1SChandler Carruth return LoopBlockSet;
1741693eedb1SChandler Carruth
1742693eedb1SChandler Carruth // We found backedges, recurse through them to identify the loop blocks.
1743693eedb1SChandler Carruth while (!Worklist.empty()) {
1744693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val();
1745693eedb1SChandler Carruth assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1746693eedb1SChandler Carruth
174743acdb35SChandler Carruth // No need to walk past the header.
174843acdb35SChandler Carruth if (BB == Header)
174943acdb35SChandler Carruth continue;
175043acdb35SChandler Carruth
1751693eedb1SChandler Carruth // Because we know the inner loop structure remains valid we can use the
1752693eedb1SChandler Carruth // loop structure to jump immediately across the entire nested loop.
1753693eedb1SChandler Carruth // Further, because it is in loop simplified form, we can directly jump
1754693eedb1SChandler Carruth // to its preheader afterward.
1755693eedb1SChandler Carruth if (Loop *InnerL = LI.getLoopFor(BB))
1756693eedb1SChandler Carruth if (InnerL != &L) {
1757693eedb1SChandler Carruth assert(L.contains(InnerL) &&
1758693eedb1SChandler Carruth "Should not reach a loop *outside* this loop!");
1759693eedb1SChandler Carruth // The preheader is the only possible predecessor of the loop so
1760693eedb1SChandler Carruth // insert it into the set and check whether it was already handled.
1761693eedb1SChandler Carruth auto *InnerPH = InnerL->getLoopPreheader();
1762693eedb1SChandler Carruth assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1763693eedb1SChandler Carruth "but not contain the inner loop "
1764693eedb1SChandler Carruth "preheader!");
1765693eedb1SChandler Carruth if (!LoopBlockSet.insert(InnerPH).second)
1766693eedb1SChandler Carruth // The only way to reach the preheader is through the loop body
1767693eedb1SChandler Carruth // itself so if it has been visited the loop is already handled.
1768693eedb1SChandler Carruth continue;
1769693eedb1SChandler Carruth
1770693eedb1SChandler Carruth // Insert all of the blocks (other than those already present) into
1771bf7190a1SChandler Carruth // the loop set. We expect at least the block that led us to find the
1772bf7190a1SChandler Carruth // inner loop to be in the block set, but we may also have other loop
1773bf7190a1SChandler Carruth // blocks if they were already enqueued as predecessors of some other
1774bf7190a1SChandler Carruth // outer loop block.
1775693eedb1SChandler Carruth for (auto *InnerBB : InnerL->blocks()) {
1776693eedb1SChandler Carruth if (InnerBB == BB) {
1777693eedb1SChandler Carruth assert(LoopBlockSet.count(InnerBB) &&
1778693eedb1SChandler Carruth "Block should already be in the set!");
1779693eedb1SChandler Carruth continue;
1780693eedb1SChandler Carruth }
1781693eedb1SChandler Carruth
1782bf7190a1SChandler Carruth LoopBlockSet.insert(InnerBB);
1783693eedb1SChandler Carruth }
1784693eedb1SChandler Carruth
1785693eedb1SChandler Carruth // Add the preheader to the worklist so we will continue past the
1786693eedb1SChandler Carruth // loop body.
1787693eedb1SChandler Carruth Worklist.push_back(InnerPH);
1788693eedb1SChandler Carruth continue;
1789693eedb1SChandler Carruth }
1790693eedb1SChandler Carruth
1791693eedb1SChandler Carruth // Insert any predecessors that were in the original loop into the new
1792693eedb1SChandler Carruth // set, and if the insert is successful, add them to the worklist.
1793693eedb1SChandler Carruth for (auto *Pred : predecessors(BB))
1794693eedb1SChandler Carruth if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1795693eedb1SChandler Carruth Worklist.push_back(Pred);
1796693eedb1SChandler Carruth }
1797693eedb1SChandler Carruth
179843acdb35SChandler Carruth assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
179943acdb35SChandler Carruth
1800693eedb1SChandler Carruth // We've found all the blocks participating in the loop, return our completed
1801693eedb1SChandler Carruth // set.
1802693eedb1SChandler Carruth return LoopBlockSet;
1803693eedb1SChandler Carruth }
1804693eedb1SChandler Carruth
1805693eedb1SChandler Carruth /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1806693eedb1SChandler Carruth ///
1807693eedb1SChandler Carruth /// The removal may have removed some child loops entirely but cannot have
1808693eedb1SChandler Carruth /// disturbed any remaining child loops. However, they may need to be hoisted
1809693eedb1SChandler Carruth /// to the parent loop (or to be top-level loops). The original loop may be
1810693eedb1SChandler Carruth /// completely removed.
1811693eedb1SChandler Carruth ///
1812693eedb1SChandler Carruth /// The sibling loops resulting from this update are returned. If the original
1813693eedb1SChandler Carruth /// loop remains a valid loop, it will be the first entry in this list with all
1814693eedb1SChandler Carruth /// of the newly sibling loops following it.
1815693eedb1SChandler Carruth ///
1816693eedb1SChandler Carruth /// Returns true if the loop remains a loop after unswitching, and false if it
1817693eedb1SChandler Carruth /// is no longer a loop after unswitching (and should not continue to be
1818693eedb1SChandler Carruth /// referenced).
rebuildLoopAfterUnswitch(Loop & L,ArrayRef<BasicBlock * > ExitBlocks,LoopInfo & LI,SmallVectorImpl<Loop * > & HoistedLoops)1819693eedb1SChandler Carruth static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1820693eedb1SChandler Carruth LoopInfo &LI,
1821693eedb1SChandler Carruth SmallVectorImpl<Loop *> &HoistedLoops) {
1822693eedb1SChandler Carruth auto *PH = L.getLoopPreheader();
1823693eedb1SChandler Carruth
1824693eedb1SChandler Carruth // Compute the actual parent loop from the exit blocks. Because we may have
1825693eedb1SChandler Carruth // pruned some exits the loop may be different from the original parent.
1826693eedb1SChandler Carruth Loop *ParentL = nullptr;
1827693eedb1SChandler Carruth SmallVector<Loop *, 4> ExitLoops;
1828693eedb1SChandler Carruth SmallVector<BasicBlock *, 4> ExitsInLoops;
1829693eedb1SChandler Carruth ExitsInLoops.reserve(ExitBlocks.size());
1830693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks)
1831693eedb1SChandler Carruth if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1832693eedb1SChandler Carruth ExitLoops.push_back(ExitL);
1833693eedb1SChandler Carruth ExitsInLoops.push_back(ExitBB);
1834693eedb1SChandler Carruth if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1835693eedb1SChandler Carruth ParentL = ExitL;
1836693eedb1SChandler Carruth }
1837693eedb1SChandler Carruth
1838693eedb1SChandler Carruth // Recompute the blocks participating in this loop. This may be empty if it
1839693eedb1SChandler Carruth // is no longer a loop.
1840693eedb1SChandler Carruth auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1841693eedb1SChandler Carruth
1842693eedb1SChandler Carruth // If we still have a loop, we need to re-set the loop's parent as the exit
1843693eedb1SChandler Carruth // block set changing may have moved it within the loop nest. Note that this
1844693eedb1SChandler Carruth // can only happen when this loop has a parent as it can only hoist the loop
1845693eedb1SChandler Carruth // *up* the nest.
1846693eedb1SChandler Carruth if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1847693eedb1SChandler Carruth // Remove this loop's (original) blocks from all of the intervening loops.
1848693eedb1SChandler Carruth for (Loop *IL = L.getParentLoop(); IL != ParentL;
1849693eedb1SChandler Carruth IL = IL->getParentLoop()) {
1850693eedb1SChandler Carruth IL->getBlocksSet().erase(PH);
1851693eedb1SChandler Carruth for (auto *BB : L.blocks())
1852693eedb1SChandler Carruth IL->getBlocksSet().erase(BB);
1853693eedb1SChandler Carruth llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1854693eedb1SChandler Carruth return BB == PH || L.contains(BB);
1855693eedb1SChandler Carruth });
1856693eedb1SChandler Carruth }
1857693eedb1SChandler Carruth
1858693eedb1SChandler Carruth LI.changeLoopFor(PH, ParentL);
1859693eedb1SChandler Carruth L.getParentLoop()->removeChildLoop(&L);
1860693eedb1SChandler Carruth if (ParentL)
1861693eedb1SChandler Carruth ParentL->addChildLoop(&L);
1862693eedb1SChandler Carruth else
1863693eedb1SChandler Carruth LI.addTopLevelLoop(&L);
1864693eedb1SChandler Carruth }
1865693eedb1SChandler Carruth
1866693eedb1SChandler Carruth // Now we update all the blocks which are no longer within the loop.
1867693eedb1SChandler Carruth auto &Blocks = L.getBlocksVector();
1868693eedb1SChandler Carruth auto BlocksSplitI =
1869693eedb1SChandler Carruth LoopBlockSet.empty()
1870693eedb1SChandler Carruth ? Blocks.begin()
1871693eedb1SChandler Carruth : std::stable_partition(
1872693eedb1SChandler Carruth Blocks.begin(), Blocks.end(),
1873693eedb1SChandler Carruth [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1874693eedb1SChandler Carruth
1875693eedb1SChandler Carruth // Before we erase the list of unlooped blocks, build a set of them.
1876693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1877693eedb1SChandler Carruth if (LoopBlockSet.empty())
1878693eedb1SChandler Carruth UnloopedBlocks.insert(PH);
1879693eedb1SChandler Carruth
1880693eedb1SChandler Carruth // Now erase these blocks from the loop.
1881693eedb1SChandler Carruth for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1882693eedb1SChandler Carruth L.getBlocksSet().erase(BB);
1883693eedb1SChandler Carruth Blocks.erase(BlocksSplitI, Blocks.end());
1884693eedb1SChandler Carruth
1885693eedb1SChandler Carruth // Sort the exits in ascending loop depth, we'll work backwards across these
1886693eedb1SChandler Carruth // to process them inside out.
1887efd94c56SFangrui Song llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1888693eedb1SChandler Carruth return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1889693eedb1SChandler Carruth });
1890693eedb1SChandler Carruth
1891693eedb1SChandler Carruth // We'll build up a set for each exit loop.
1892693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1893693eedb1SChandler Carruth Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1894693eedb1SChandler Carruth
1895693eedb1SChandler Carruth auto RemoveUnloopedBlocksFromLoop =
1896693eedb1SChandler Carruth [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1897693eedb1SChandler Carruth for (auto *BB : UnloopedBlocks)
1898693eedb1SChandler Carruth L.getBlocksSet().erase(BB);
1899693eedb1SChandler Carruth llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1900693eedb1SChandler Carruth return UnloopedBlocks.count(BB);
1901693eedb1SChandler Carruth });
1902693eedb1SChandler Carruth };
1903693eedb1SChandler Carruth
1904693eedb1SChandler Carruth SmallVector<BasicBlock *, 16> Worklist;
1905693eedb1SChandler Carruth while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1906693eedb1SChandler Carruth assert(Worklist.empty() && "Didn't clear worklist!");
1907693eedb1SChandler Carruth assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1908693eedb1SChandler Carruth
1909693eedb1SChandler Carruth // Grab the next exit block, in decreasing loop depth order.
1910693eedb1SChandler Carruth BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1911693eedb1SChandler Carruth Loop &ExitL = *LI.getLoopFor(ExitBB);
1912693eedb1SChandler Carruth assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1913693eedb1SChandler Carruth
1914693eedb1SChandler Carruth // Erase all of the unlooped blocks from the loops between the previous
1915693eedb1SChandler Carruth // exit loop and this exit loop. This works because the ExitInLoops list is
1916693eedb1SChandler Carruth // sorted in increasing order of loop depth and thus we visit loops in
1917693eedb1SChandler Carruth // decreasing order of loop depth.
1918693eedb1SChandler Carruth for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1919693eedb1SChandler Carruth RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1920693eedb1SChandler Carruth
1921693eedb1SChandler Carruth // Walk the CFG back until we hit the cloned PH adding everything reachable
1922693eedb1SChandler Carruth // and in the unlooped set to this exit block's loop.
1923693eedb1SChandler Carruth Worklist.push_back(ExitBB);
1924693eedb1SChandler Carruth do {
1925693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val();
1926693eedb1SChandler Carruth // We can stop recursing at the cloned preheader (if we get there).
1927693eedb1SChandler Carruth if (BB == PH)
1928693eedb1SChandler Carruth continue;
1929693eedb1SChandler Carruth
1930693eedb1SChandler Carruth for (BasicBlock *PredBB : predecessors(BB)) {
1931693eedb1SChandler Carruth // If this pred has already been moved to our set or is part of some
1932693eedb1SChandler Carruth // (inner) loop, no update needed.
1933693eedb1SChandler Carruth if (!UnloopedBlocks.erase(PredBB)) {
1934693eedb1SChandler Carruth assert((NewExitLoopBlocks.count(PredBB) ||
1935693eedb1SChandler Carruth ExitL.contains(LI.getLoopFor(PredBB))) &&
1936693eedb1SChandler Carruth "Predecessor not in a nested loop (or already visited)!");
1937693eedb1SChandler Carruth continue;
1938693eedb1SChandler Carruth }
1939693eedb1SChandler Carruth
1940693eedb1SChandler Carruth // We just insert into the loop set here. We'll add these blocks to the
1941693eedb1SChandler Carruth // exit loop after we build up the set in a deterministic order rather
1942693eedb1SChandler Carruth // than the predecessor-influenced visit order.
1943693eedb1SChandler Carruth bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1944693eedb1SChandler Carruth (void)Inserted;
1945693eedb1SChandler Carruth assert(Inserted && "Should only visit an unlooped block once!");
1946693eedb1SChandler Carruth
1947693eedb1SChandler Carruth // And recurse through to its predecessors.
1948693eedb1SChandler Carruth Worklist.push_back(PredBB);
1949693eedb1SChandler Carruth }
1950693eedb1SChandler Carruth } while (!Worklist.empty());
1951693eedb1SChandler Carruth
1952693eedb1SChandler Carruth // If blocks in this exit loop were directly part of the original loop (as
1953693eedb1SChandler Carruth // opposed to a child loop) update the map to point to this exit loop. This
1954693eedb1SChandler Carruth // just updates a map and so the fact that the order is unstable is fine.
1955693eedb1SChandler Carruth for (auto *BB : NewExitLoopBlocks)
1956693eedb1SChandler Carruth if (Loop *BBL = LI.getLoopFor(BB))
1957693eedb1SChandler Carruth if (BBL == &L || !L.contains(BBL))
1958693eedb1SChandler Carruth LI.changeLoopFor(BB, &ExitL);
1959693eedb1SChandler Carruth
1960693eedb1SChandler Carruth // We will remove the remaining unlooped blocks from this loop in the next
1961693eedb1SChandler Carruth // iteration or below.
1962693eedb1SChandler Carruth NewExitLoopBlocks.clear();
1963693eedb1SChandler Carruth }
1964693eedb1SChandler Carruth
1965693eedb1SChandler Carruth // Any remaining unlooped blocks are no longer part of any loop unless they
1966693eedb1SChandler Carruth // are part of some child loop.
1967693eedb1SChandler Carruth for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1968693eedb1SChandler Carruth RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1969693eedb1SChandler Carruth for (auto *BB : UnloopedBlocks)
1970693eedb1SChandler Carruth if (Loop *BBL = LI.getLoopFor(BB))
1971693eedb1SChandler Carruth if (BBL == &L || !L.contains(BBL))
1972693eedb1SChandler Carruth LI.changeLoopFor(BB, nullptr);
1973693eedb1SChandler Carruth
1974693eedb1SChandler Carruth // Sink all the child loops whose headers are no longer in the loop set to
1975693eedb1SChandler Carruth // the parent (or to be top level loops). We reach into the loop and directly
1976693eedb1SChandler Carruth // update its subloop vector to make this batch update efficient.
1977693eedb1SChandler Carruth auto &SubLoops = L.getSubLoopsVector();
1978693eedb1SChandler Carruth auto SubLoopsSplitI =
1979693eedb1SChandler Carruth LoopBlockSet.empty()
1980693eedb1SChandler Carruth ? SubLoops.begin()
1981693eedb1SChandler Carruth : std::stable_partition(
1982693eedb1SChandler Carruth SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1983693eedb1SChandler Carruth return LoopBlockSet.count(SubL->getHeader());
1984693eedb1SChandler Carruth });
1985693eedb1SChandler Carruth for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1986693eedb1SChandler Carruth HoistedLoops.push_back(HoistedL);
1987693eedb1SChandler Carruth HoistedL->setParentLoop(nullptr);
1988693eedb1SChandler Carruth
1989693eedb1SChandler Carruth // To compute the new parent of this hoisted loop we look at where we
1990693eedb1SChandler Carruth // placed the preheader above. We can't lookup the header itself because we
1991693eedb1SChandler Carruth // retained the mapping from the header to the hoisted loop. But the
1992693eedb1SChandler Carruth // preheader and header should have the exact same new parent computed
1993693eedb1SChandler Carruth // based on the set of exit blocks from the original loop as the preheader
1994693eedb1SChandler Carruth // is a predecessor of the header and so reached in the reverse walk. And
1995693eedb1SChandler Carruth // because the loops were all in simplified form the preheader of the
1996693eedb1SChandler Carruth // hoisted loop can't be part of some *other* loop.
1997693eedb1SChandler Carruth if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1998693eedb1SChandler Carruth NewParentL->addChildLoop(HoistedL);
1999693eedb1SChandler Carruth else
2000693eedb1SChandler Carruth LI.addTopLevelLoop(HoistedL);
2001693eedb1SChandler Carruth }
2002693eedb1SChandler Carruth SubLoops.erase(SubLoopsSplitI, SubLoops.end());
2003693eedb1SChandler Carruth
2004693eedb1SChandler Carruth // Actually delete the loop if nothing remained within it.
2005693eedb1SChandler Carruth if (Blocks.empty()) {
2006693eedb1SChandler Carruth assert(SubLoops.empty() &&
2007693eedb1SChandler Carruth "Failed to remove all subloops from the original loop!");
2008693eedb1SChandler Carruth if (Loop *ParentL = L.getParentLoop())
2009693eedb1SChandler Carruth ParentL->removeChildLoop(llvm::find(*ParentL, &L));
2010693eedb1SChandler Carruth else
2011693eedb1SChandler Carruth LI.removeLoop(llvm::find(LI, &L));
20120f0344ddSBjorn Pettersson // markLoopAsDeleted for L should be triggered by the caller (it is typically
20130f0344ddSBjorn Pettersson // done by using the UnswitchCB callback).
2014693eedb1SChandler Carruth LI.destroy(&L);
2015693eedb1SChandler Carruth return false;
2016693eedb1SChandler Carruth }
2017693eedb1SChandler Carruth
2018693eedb1SChandler Carruth return true;
2019693eedb1SChandler Carruth }
2020693eedb1SChandler Carruth
2021693eedb1SChandler Carruth /// Helper to visit a dominator subtree, invoking a callable on each node.
2022693eedb1SChandler Carruth ///
2023693eedb1SChandler Carruth /// Returning false at any point will stop walking past that node of the tree.
2024693eedb1SChandler Carruth template <typename CallableT>
visitDomSubTree(DominatorTree & DT,BasicBlock * BB,CallableT Callable)2025693eedb1SChandler Carruth void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
2026693eedb1SChandler Carruth SmallVector<DomTreeNode *, 4> DomWorklist;
2027693eedb1SChandler Carruth DomWorklist.push_back(DT[BB]);
2028693eedb1SChandler Carruth #ifndef NDEBUG
2029693eedb1SChandler Carruth SmallPtrSet<DomTreeNode *, 4> Visited;
2030693eedb1SChandler Carruth Visited.insert(DT[BB]);
2031693eedb1SChandler Carruth #endif
2032693eedb1SChandler Carruth do {
2033693eedb1SChandler Carruth DomTreeNode *N = DomWorklist.pop_back_val();
2034693eedb1SChandler Carruth
2035693eedb1SChandler Carruth // Visit this node.
2036693eedb1SChandler Carruth if (!Callable(N->getBlock()))
2037693eedb1SChandler Carruth continue;
2038693eedb1SChandler Carruth
2039693eedb1SChandler Carruth // Accumulate the child nodes.
2040693eedb1SChandler Carruth for (DomTreeNode *ChildN : *N) {
2041693eedb1SChandler Carruth assert(Visited.insert(ChildN).second &&
2042693eedb1SChandler Carruth "Cannot visit a node twice when walking a tree!");
2043693eedb1SChandler Carruth DomWorklist.push_back(ChildN);
2044693eedb1SChandler Carruth }
2045693eedb1SChandler Carruth } while (!DomWorklist.empty());
2046693eedb1SChandler Carruth }
2047693eedb1SChandler Carruth
unswitchNontrivialInvariants(Loop & L,Instruction & TI,ArrayRef<Value * > Invariants,SmallVectorImpl<BasicBlock * > & ExitBlocks,IVConditionInfo & PartialIVInfo,DominatorTree & DT,LoopInfo & LI,AssumptionCache & AC,function_ref<void (bool,bool,ArrayRef<Loop * >)> UnswitchCB,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,function_ref<void (Loop &,StringRef)> DestroyLoopCB)2048bde31000SMax Kazantsev static void unswitchNontrivialInvariants(
204960b2e054SChandler Carruth Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
2050f3a27511SJingu Kang SmallVectorImpl<BasicBlock *> &ExitBlocks, IVConditionInfo &PartialIVInfo,
2051f3a27511SJingu Kang DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
2052f3a27511SJingu Kang function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
20530f0344ddSBjorn Pettersson ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
20540f0344ddSBjorn Pettersson function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
20551652996fSChandler Carruth auto *ParentBB = TI.getParent();
20561652996fSChandler Carruth BranchInst *BI = dyn_cast<BranchInst>(&TI);
20571652996fSChandler Carruth SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
2058d1dab0c3SChandler Carruth
20591652996fSChandler Carruth // We can only unswitch switches, conditional branches with an invariant
2060f3a27511SJingu Kang // condition, or combining invariant conditions with an instruction or
2061f3a27511SJingu Kang // partially invariant instructions.
2062c598ef7fSSimon Pilgrim assert((SI || (BI && BI->isConditional())) &&
20631652996fSChandler Carruth "Can only unswitch switches and conditional branch!");
2064f3a27511SJingu Kang bool PartiallyInvariant = !PartialIVInfo.InstToDuplicate.empty();
2065f3a27511SJingu Kang bool FullUnswitch =
206641e142fdSFlorian Hahn SI || (skipTrivialSelect(BI->getCondition()) == Invariants[0] &&
206741e142fdSFlorian Hahn !PartiallyInvariant);
2068d1dab0c3SChandler Carruth if (FullUnswitch)
2069d1dab0c3SChandler Carruth assert(Invariants.size() == 1 &&
2070d1dab0c3SChandler Carruth "Cannot have other invariants with full unswitching!");
2071d1dab0c3SChandler Carruth else
207241e142fdSFlorian Hahn assert(isa<Instruction>(skipTrivialSelect(BI->getCondition())) &&
2073d1dab0c3SChandler Carruth "Partial unswitching requires an instruction as the condition!");
2074d1dab0c3SChandler Carruth
2075a2eebb82SAlina Sbirlea if (MSSAU && VerifyMemorySSA)
2076a2eebb82SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
2077a2eebb82SAlina Sbirlea
2078d1dab0c3SChandler Carruth // Constant and BBs tracking the cloned and continuing successor. When we are
2079d1dab0c3SChandler Carruth // unswitching the entire condition, this can just be trivially chosen to
2080d1dab0c3SChandler Carruth // unswitch towards `true`. However, when we are unswitching a set of
2081f3a27511SJingu Kang // invariants combined with `and` or `or` or partially invariant instructions,
2082f3a27511SJingu Kang // the combining operation determines the best direction to unswitch: we want
2083f3a27511SJingu Kang // to unswitch the direction that will collapse the branch.
2084d1dab0c3SChandler Carruth bool Direction = true;
2085d1dab0c3SChandler Carruth int ClonedSucc = 0;
2086d1dab0c3SChandler Carruth if (!FullUnswitch) {
208741e142fdSFlorian Hahn Value *Cond = skipTrivialSelect(BI->getCondition());
20883e5ee194SFangrui Song (void)Cond;
2089f3a27511SJingu Kang assert(((match(Cond, m_LogicalAnd()) ^ match(Cond, m_LogicalOr())) ||
2090f3a27511SJingu Kang PartiallyInvariant) &&
2091f3a27511SJingu Kang "Only `or`, `and`, an `select`, partially invariant instructions "
2092f3a27511SJingu Kang "can combine invariants being unswitched.");
209341e142fdSFlorian Hahn if (!match(Cond, m_LogicalOr())) {
209441e142fdSFlorian Hahn if (match(Cond, m_LogicalAnd()) ||
2095f3a27511SJingu Kang (PartiallyInvariant && !PartialIVInfo.KnownValue->isOneValue())) {
2096d1dab0c3SChandler Carruth Direction = false;
2097d1dab0c3SChandler Carruth ClonedSucc = 1;
2098d1dab0c3SChandler Carruth }
2099d1dab0c3SChandler Carruth }
2100f3a27511SJingu Kang }
2101693eedb1SChandler Carruth
21021652996fSChandler Carruth BasicBlock *RetainedSuccBB =
21031652996fSChandler Carruth BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
21041652996fSChandler Carruth SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
21051652996fSChandler Carruth if (BI)
21061652996fSChandler Carruth UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
21071652996fSChandler Carruth else
21081652996fSChandler Carruth for (auto Case : SI->cases())
2109ed296543SChandler Carruth if (Case.getCaseSuccessor() != RetainedSuccBB)
21101652996fSChandler Carruth UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
21111652996fSChandler Carruth
21121652996fSChandler Carruth assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
21131652996fSChandler Carruth "Should not unswitch the same successor we are retaining!");
2114693eedb1SChandler Carruth
2115693eedb1SChandler Carruth // The branch should be in this exact loop. Any inner loop's invariant branch
2116693eedb1SChandler Carruth // should be handled by unswitching that inner loop. The caller of this
2117693eedb1SChandler Carruth // routine should filter out any candidates that remain (but were skipped for
2118693eedb1SChandler Carruth // whatever reason).
2119693eedb1SChandler Carruth assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
2120693eedb1SChandler Carruth
2121693eedb1SChandler Carruth // Compute the parent loop now before we start hacking on things.
2122693eedb1SChandler Carruth Loop *ParentL = L.getParentLoop();
2123a2eebb82SAlina Sbirlea // Get blocks in RPO order for MSSA update, before changing the CFG.
2124a2eebb82SAlina Sbirlea LoopBlocksRPO LBRPO(&L);
2125a2eebb82SAlina Sbirlea if (MSSAU)
2126a2eebb82SAlina Sbirlea LBRPO.perform(&LI);
2127693eedb1SChandler Carruth
2128693eedb1SChandler Carruth // Compute the outer-most loop containing one of our exit blocks. This is the
2129693eedb1SChandler Carruth // furthest up our loopnest which can be mutated, which we will use below to
2130693eedb1SChandler Carruth // update things.
2131693eedb1SChandler Carruth Loop *OuterExitL = &L;
2132693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) {
2133693eedb1SChandler Carruth Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
2134693eedb1SChandler Carruth if (!NewOuterExitL) {
2135693eedb1SChandler Carruth // We exited the entire nest with this block, so we're done.
2136693eedb1SChandler Carruth OuterExitL = nullptr;
2137693eedb1SChandler Carruth break;
2138693eedb1SChandler Carruth }
2139693eedb1SChandler Carruth if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
2140693eedb1SChandler Carruth OuterExitL = NewOuterExitL;
2141693eedb1SChandler Carruth }
2142693eedb1SChandler Carruth
21433897ded6SChandler Carruth // At this point, we're definitely going to unswitch something so invalidate
21443897ded6SChandler Carruth // any cached information in ScalarEvolution for the outer most loop
21453897ded6SChandler Carruth // containing an exit block and all nested loops.
21463897ded6SChandler Carruth if (SE) {
21473897ded6SChandler Carruth if (OuterExitL)
21483897ded6SChandler Carruth SE->forgetLoop(OuterExitL);
21493897ded6SChandler Carruth else
21503897ded6SChandler Carruth SE->forgetTopmostLoop(&L);
21513897ded6SChandler Carruth }
21523897ded6SChandler Carruth
21530aeb3732Shyeongyu kim bool InsertFreeze = false;
21540aeb3732Shyeongyu kim if (FreezeLoopUnswitchCond) {
21550aeb3732Shyeongyu kim ICFLoopSafetyInfo SafetyInfo;
21560aeb3732Shyeongyu kim SafetyInfo.computeLoopSafetyInfo(&L);
21570aeb3732Shyeongyu kim InsertFreeze = !SafetyInfo.isGuaranteedToExecute(TI, &DT, &L);
21580aeb3732Shyeongyu kim }
21590aeb3732Shyeongyu kim
21601652996fSChandler Carruth // If the edge from this terminator to a successor dominates that successor,
21611652996fSChandler Carruth // store a map from each block in its dominator subtree to it. This lets us
21621652996fSChandler Carruth // tell when cloning for a particular successor if a block is dominated by
21631652996fSChandler Carruth // some *other* successor with a single data structure. We use this to
21641652996fSChandler Carruth // significantly reduce cloning.
21651652996fSChandler Carruth SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
21661652996fSChandler Carruth for (auto *SuccBB : llvm::concat<BasicBlock *const>(
21671652996fSChandler Carruth makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
21681652996fSChandler Carruth if (SuccBB->getUniquePredecessor() ||
21691652996fSChandler Carruth llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
21701652996fSChandler Carruth return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
21711652996fSChandler Carruth }))
21721652996fSChandler Carruth visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
21731652996fSChandler Carruth DominatingSucc[BB] = SuccBB;
2174693eedb1SChandler Carruth return true;
2175693eedb1SChandler Carruth });
2176693eedb1SChandler Carruth
2177693eedb1SChandler Carruth // Split the preheader, so that we know that there is a safe place to insert
2178693eedb1SChandler Carruth // the conditional branch. We will change the preheader to have a conditional
2179693eedb1SChandler Carruth // branch on LoopCond. The original preheader will become the split point
2180693eedb1SChandler Carruth // between the unswitched versions, and we will have a new preheader for the
2181693eedb1SChandler Carruth // original loop.
2182693eedb1SChandler Carruth BasicBlock *SplitBB = L.getLoopPreheader();
2183a2eebb82SAlina Sbirlea BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
2184693eedb1SChandler Carruth
218569e68f84SChandler Carruth // Keep track of the dominator tree updates needed.
218669e68f84SChandler Carruth SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
218769e68f84SChandler Carruth
21881652996fSChandler Carruth // Clone the loop for each unswitched successor.
21891652996fSChandler Carruth SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
21901652996fSChandler Carruth VMaps.reserve(UnswitchedSuccBBs.size());
21911652996fSChandler Carruth SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
21921652996fSChandler Carruth for (auto *SuccBB : UnswitchedSuccBBs) {
21931652996fSChandler Carruth VMaps.emplace_back(new ValueToValueMapTy());
21941652996fSChandler Carruth ClonedPHs[SuccBB] = buildClonedLoopBlocks(
21951652996fSChandler Carruth L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2196a2eebb82SAlina Sbirlea DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
21971652996fSChandler Carruth }
2198693eedb1SChandler Carruth
21998aaeee5fSMax Kazantsev // Drop metadata if we may break its semantics by moving this instr into the
2200d889e17eSMax Kazantsev // split block.
22018aaeee5fSMax Kazantsev if (TI.getMetadata(LLVMContext::MD_make_implicit)) {
22027647c271SMax Kazantsev if (DropNonTrivialImplicitNullChecks)
22037647c271SMax Kazantsev // Do not spend time trying to understand if we can keep it, just drop it
22047647c271SMax Kazantsev // to save compile time.
22057647c271SMax Kazantsev TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
22067647c271SMax Kazantsev else {
22077647c271SMax Kazantsev // It is only legal to preserve make.implicit metadata if we are
22087647c271SMax Kazantsev // guaranteed no reach implicit null check after following this branch.
22098aaeee5fSMax Kazantsev ICFLoopSafetyInfo SafetyInfo;
22108aaeee5fSMax Kazantsev SafetyInfo.computeLoopSafetyInfo(&L);
22118aaeee5fSMax Kazantsev if (!SafetyInfo.isGuaranteedToExecute(TI, &DT, &L))
2212d889e17eSMax Kazantsev TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
22138aaeee5fSMax Kazantsev }
22147647c271SMax Kazantsev }
2215d889e17eSMax Kazantsev
2216d1dab0c3SChandler Carruth // The stitching of the branched code back together depends on whether we're
2217d1dab0c3SChandler Carruth // doing full unswitching or not with the exception that we always want to
2218d1dab0c3SChandler Carruth // nuke the initial terminator placed in the split block.
2219d1dab0c3SChandler Carruth SplitBB->getTerminator()->eraseFromParent();
2220d1dab0c3SChandler Carruth if (FullUnswitch) {
2221a2eebb82SAlina Sbirlea // Splice the terminator from the original loop and rewrite its
2222a2eebb82SAlina Sbirlea // successors.
2223a2eebb82SAlina Sbirlea SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2224a2eebb82SAlina Sbirlea
2225a2eebb82SAlina Sbirlea // Keep a clone of the terminator for MSSA updates.
2226a2eebb82SAlina Sbirlea Instruction *NewTI = TI.clone();
2227a2eebb82SAlina Sbirlea ParentBB->getInstList().push_back(NewTI);
2228a2eebb82SAlina Sbirlea
2229a2eebb82SAlina Sbirlea // First wire up the moved terminator to the preheaders.
2230a2eebb82SAlina Sbirlea if (BI) {
2231a2eebb82SAlina Sbirlea BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2232a2eebb82SAlina Sbirlea BI->setSuccessor(ClonedSucc, ClonedPH);
2233a2eebb82SAlina Sbirlea BI->setSuccessor(1 - ClonedSucc, LoopPH);
2234f96aa493SFlorian Hahn Value *Cond = skipTrivialSelect(BI->getCondition());
22350aeb3732Shyeongyu kim if (InsertFreeze) {
22360aeb3732Shyeongyu kim if (!isGuaranteedNotToBeUndefOrPoison(Cond, &AC, BI, &DT))
2237f96aa493SFlorian Hahn Cond = new FreezeInst(Cond, Cond->getName() + ".fr", BI);
22380aeb3732Shyeongyu kim }
2239f96aa493SFlorian Hahn BI->setCondition(Cond);
2240a2eebb82SAlina Sbirlea DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2241a2eebb82SAlina Sbirlea } else {
2242a2eebb82SAlina Sbirlea assert(SI && "Must either be a branch or switch!");
2243a2eebb82SAlina Sbirlea
2244a2eebb82SAlina Sbirlea // Walk the cases and directly update their successors.
2245a2eebb82SAlina Sbirlea assert(SI->getDefaultDest() == RetainedSuccBB &&
2246a2eebb82SAlina Sbirlea "Not retaining default successor!");
2247a2eebb82SAlina Sbirlea SI->setDefaultDest(LoopPH);
2248a2eebb82SAlina Sbirlea for (auto &Case : SI->cases())
2249a2eebb82SAlina Sbirlea if (Case.getCaseSuccessor() == RetainedSuccBB)
2250a2eebb82SAlina Sbirlea Case.setSuccessor(LoopPH);
2251a2eebb82SAlina Sbirlea else
2252a2eebb82SAlina Sbirlea Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2253a2eebb82SAlina Sbirlea
22540aeb3732Shyeongyu kim if (InsertFreeze) {
22550aeb3732Shyeongyu kim auto Cond = SI->getCondition();
22560aeb3732Shyeongyu kim if (!isGuaranteedNotToBeUndefOrPoison(Cond, &AC, SI, &DT))
22570aeb3732Shyeongyu kim SI->setCondition(new FreezeInst(Cond, Cond->getName() + ".fr", SI));
22580aeb3732Shyeongyu kim }
2259a2eebb82SAlina Sbirlea // We need to use the set to populate domtree updates as even when there
2260a2eebb82SAlina Sbirlea // are multiple cases pointing at the same successor we only want to
2261a2eebb82SAlina Sbirlea // remove and insert one edge in the domtree.
2262a2eebb82SAlina Sbirlea for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2263a2eebb82SAlina Sbirlea DTUpdates.push_back(
2264a2eebb82SAlina Sbirlea {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2265a2eebb82SAlina Sbirlea }
2266a2eebb82SAlina Sbirlea
2267a2eebb82SAlina Sbirlea if (MSSAU) {
2268a2eebb82SAlina Sbirlea DT.applyUpdates(DTUpdates);
2269a2eebb82SAlina Sbirlea DTUpdates.clear();
2270a2eebb82SAlina Sbirlea
2271a2eebb82SAlina Sbirlea // Remove all but one edge to the retained block and all unswitched
2272a2eebb82SAlina Sbirlea // blocks. This is to avoid having duplicate entries in the cloned Phis,
2273a2eebb82SAlina Sbirlea // when we know we only keep a single edge for each case.
2274a2eebb82SAlina Sbirlea MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2275a2eebb82SAlina Sbirlea for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2276a2eebb82SAlina Sbirlea MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2277a2eebb82SAlina Sbirlea
2278a2eebb82SAlina Sbirlea for (auto &VMap : VMaps)
2279a2eebb82SAlina Sbirlea MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2280a2eebb82SAlina Sbirlea /*IgnoreIncomingWithNoClones=*/true);
2281a2eebb82SAlina Sbirlea MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2282a2eebb82SAlina Sbirlea
2283a2eebb82SAlina Sbirlea // Remove all edges to unswitched blocks.
2284a2eebb82SAlina Sbirlea for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2285a2eebb82SAlina Sbirlea MSSAU->removeEdge(ParentBB, SuccBB);
2286a2eebb82SAlina Sbirlea }
2287a2eebb82SAlina Sbirlea
2288a2eebb82SAlina Sbirlea // Now unhook the successor relationship as we'll be replacing
2289ed296543SChandler Carruth // the terminator with a direct branch. This is much simpler for branches
2290ed296543SChandler Carruth // than switches so we handle those first.
2291ed296543SChandler Carruth if (BI) {
22921652996fSChandler Carruth // Remove the parent as a predecessor of the unswitched successor.
2293ed296543SChandler Carruth assert(UnswitchedSuccBBs.size() == 1 &&
2294ed296543SChandler Carruth "Only one possible unswitched block for a branch!");
2295ed296543SChandler Carruth BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2296ed296543SChandler Carruth UnswitchedSuccBB->removePredecessor(ParentBB,
229720b91899SMax Kazantsev /*KeepOneInputPHIs*/ true);
2298ed296543SChandler Carruth DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2299ed296543SChandler Carruth } else {
2300ed296543SChandler Carruth // Note that we actually want to remove the parent block as a predecessor
2301ed296543SChandler Carruth // of *every* case successor. The case successor is either unswitched,
2302ed296543SChandler Carruth // completely eliminating an edge from the parent to that successor, or it
2303ed296543SChandler Carruth // is a duplicate edge to the retained successor as the retained successor
2304ed296543SChandler Carruth // is always the default successor and as we'll replace this with a direct
2305ed296543SChandler Carruth // branch we no longer need the duplicate entries in the PHI nodes.
2306a2eebb82SAlina Sbirlea SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2307a2eebb82SAlina Sbirlea assert(NewSI->getDefaultDest() == RetainedSuccBB &&
2308ed296543SChandler Carruth "Not retaining default successor!");
2309a2eebb82SAlina Sbirlea for (auto &Case : NewSI->cases())
2310ed296543SChandler Carruth Case.getCaseSuccessor()->removePredecessor(
2311ed296543SChandler Carruth ParentBB,
231220b91899SMax Kazantsev /*KeepOneInputPHIs*/ true);
2313ed296543SChandler Carruth
2314ed296543SChandler Carruth // We need to use the set to populate domtree updates as even when there
2315ed296543SChandler Carruth // are multiple cases pointing at the same successor we only want to
2316ed296543SChandler Carruth // remove and insert one edge in the domtree.
2317ed296543SChandler Carruth for (BasicBlock *SuccBB : UnswitchedSuccBBs)
23181652996fSChandler Carruth DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
23191652996fSChandler Carruth }
2320693eedb1SChandler Carruth
2321a2eebb82SAlina Sbirlea // After MSSAU update, remove the cloned terminator instruction NewTI.
2322a2eebb82SAlina Sbirlea ParentBB->getTerminator()->eraseFromParent();
2323693eedb1SChandler Carruth
2324693eedb1SChandler Carruth // Create a new unconditional branch to the continuing block (as opposed to
2325693eedb1SChandler Carruth // the one cloned).
23261652996fSChandler Carruth BranchInst::Create(RetainedSuccBB, ParentBB);
2327d1dab0c3SChandler Carruth } else {
23281652996fSChandler Carruth assert(BI && "Only branches have partial unswitching.");
23291652996fSChandler Carruth assert(UnswitchedSuccBBs.size() == 1 &&
23301652996fSChandler Carruth "Only one possible unswitched block for a branch!");
23311652996fSChandler Carruth BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2332d1dab0c3SChandler Carruth // When doing a partial unswitch, we have to do a bit more work to build up
2333d1dab0c3SChandler Carruth // the branch in the split block.
2334f3a27511SJingu Kang if (PartiallyInvariant)
2335f3a27511SJingu Kang buildPartialInvariantUnswitchConditionalBranch(
2336f3a27511SJingu Kang *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH, L, MSSAU);
2337b341c440SFlorian Hahn else {
23386bd2b708SFlorian Hahn buildPartialUnswitchConditionalBranch(
23396bd2b708SFlorian Hahn *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH,
23406bd2b708SFlorian Hahn FreezeLoopUnswitchCond, BI, &AC, DT);
2341b341c440SFlorian Hahn }
234235c8af18SAlina Sbirlea DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
234335c8af18SAlina Sbirlea
2344b7a33530SAlina Sbirlea if (MSSAU) {
234535c8af18SAlina Sbirlea DT.applyUpdates(DTUpdates);
234635c8af18SAlina Sbirlea DTUpdates.clear();
234735c8af18SAlina Sbirlea
2348b7a33530SAlina Sbirlea // Perform MSSA cloning updates.
2349b7a33530SAlina Sbirlea for (auto &VMap : VMaps)
2350b7a33530SAlina Sbirlea MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2351b7a33530SAlina Sbirlea /*IgnoreIncomingWithNoClones=*/true);
2352b7a33530SAlina Sbirlea MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2353b7a33530SAlina Sbirlea }
23541652996fSChandler Carruth }
23551652996fSChandler Carruth
23561652996fSChandler Carruth // Apply the updates accumulated above to get an up-to-date dominator tree.
235769e68f84SChandler Carruth DT.applyUpdates(DTUpdates);
235869e68f84SChandler Carruth
23591652996fSChandler Carruth // Now that we have an accurate dominator tree, first delete the dead cloned
23601652996fSChandler Carruth // blocks so that we can accurately build any cloned loops. It is important to
23611652996fSChandler Carruth // not delete the blocks from the original loop yet because we still want to
23621652996fSChandler Carruth // reference the original loop to understand the cloned loop's structure.
2363a2eebb82SAlina Sbirlea deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
23641652996fSChandler Carruth
236569e68f84SChandler Carruth // Build the cloned loop structure itself. This may be substantially
236669e68f84SChandler Carruth // different from the original structure due to the simplified CFG. This also
236769e68f84SChandler Carruth // handles inserting all the cloned blocks into the correct loops.
236869e68f84SChandler Carruth SmallVector<Loop *, 4> NonChildClonedLoops;
23691652996fSChandler Carruth for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
23701652996fSChandler Carruth buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
237169e68f84SChandler Carruth
23721652996fSChandler Carruth // Now that our cloned loops have been built, we can update the original loop.
23731652996fSChandler Carruth // First we delete the dead blocks from it and then we rebuild the loop
23741652996fSChandler Carruth // structure taking these deletions into account.
23750f0344ddSBjorn Pettersson deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU, DestroyLoopCB);
2376a2eebb82SAlina Sbirlea
2377a2eebb82SAlina Sbirlea if (MSSAU && VerifyMemorySSA)
2378a2eebb82SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
2379a2eebb82SAlina Sbirlea
2380693eedb1SChandler Carruth SmallVector<Loop *, 4> HoistedLoops;
2381693eedb1SChandler Carruth bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2382693eedb1SChandler Carruth
2383a2eebb82SAlina Sbirlea if (MSSAU && VerifyMemorySSA)
2384a2eebb82SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
2385a2eebb82SAlina Sbirlea
238669e68f84SChandler Carruth // This transformation has a high risk of corrupting the dominator tree, and
238769e68f84SChandler Carruth // the below steps to rebuild loop structures will result in hard to debug
238869e68f84SChandler Carruth // errors in that case so verify that the dominator tree is sane first.
238969e68f84SChandler Carruth // FIXME: Remove this when the bugs stop showing up and rely on existing
239069e68f84SChandler Carruth // verification steps.
239169e68f84SChandler Carruth assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2392693eedb1SChandler Carruth
2393f3a27511SJingu Kang if (BI && !PartiallyInvariant) {
23941652996fSChandler Carruth // If we unswitched a branch which collapses the condition to a known
23951652996fSChandler Carruth // constant we want to replace all the uses of the invariants within both
23961652996fSChandler Carruth // the original and cloned blocks. We do this here so that we can use the
23971652996fSChandler Carruth // now updated dominator tree to identify which side the users are on.
23981652996fSChandler Carruth assert(UnswitchedSuccBBs.size() == 1 &&
23991652996fSChandler Carruth "Only one possible unswitched block for a branch!");
24001652996fSChandler Carruth BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2401f9a02a70SFedor Sergeev
2402f9a02a70SFedor Sergeev // When considering multiple partially-unswitched invariants
2403f9a02a70SFedor Sergeev // we cant just go replace them with constants in both branches.
2404f9a02a70SFedor Sergeev //
2405f9a02a70SFedor Sergeev // For 'AND' we infer that true branch ("continue") means true
2406f9a02a70SFedor Sergeev // for each invariant operand.
2407f9a02a70SFedor Sergeev // For 'OR' we can infer that false branch ("continue") means false
2408f9a02a70SFedor Sergeev // for each invariant operand.
2409f9a02a70SFedor Sergeev // So it happens that for multiple-partial case we dont replace
2410f9a02a70SFedor Sergeev // in the unswitched branch.
2411f3a27511SJingu Kang bool ReplaceUnswitched =
2412f3a27511SJingu Kang FullUnswitch || (Invariants.size() == 1) || PartiallyInvariant;
2413f9a02a70SFedor Sergeev
2414d1dab0c3SChandler Carruth ConstantInt *UnswitchedReplacement =
24151652996fSChandler Carruth Direction ? ConstantInt::getTrue(BI->getContext())
24161652996fSChandler Carruth : ConstantInt::getFalse(BI->getContext());
2417d1dab0c3SChandler Carruth ConstantInt *ContinueReplacement =
24181652996fSChandler Carruth Direction ? ConstantInt::getFalse(BI->getContext())
24191652996fSChandler Carruth : ConstantInt::getTrue(BI->getContext());
242045bd8d94SDaniil Suchkov for (Value *Invariant : Invariants) {
242145bd8d94SDaniil Suchkov assert(!isa<Constant>(Invariant) &&
242245bd8d94SDaniil Suchkov "Should not be replacing constant values!");
24235fc9e309SKazu Hirata // Use make_early_inc_range here as set invalidates the iterator.
24245fc9e309SKazu Hirata for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
24255fc9e309SKazu Hirata Instruction *UserI = dyn_cast<Instruction>(U.getUser());
2426d1dab0c3SChandler Carruth if (!UserI)
2427d1dab0c3SChandler Carruth continue;
2428d1dab0c3SChandler Carruth
2429d1dab0c3SChandler Carruth // Replace it with the 'continue' side if in the main loop body, and the
2430d1dab0c3SChandler Carruth // unswitched if in the cloned blocks.
2431d1dab0c3SChandler Carruth if (DT.dominates(LoopPH, UserI->getParent()))
24325fc9e309SKazu Hirata U.set(ContinueReplacement);
2433f9a02a70SFedor Sergeev else if (ReplaceUnswitched &&
2434f9a02a70SFedor Sergeev DT.dominates(ClonedPH, UserI->getParent()))
24355fc9e309SKazu Hirata U.set(UnswitchedReplacement);
2436d1dab0c3SChandler Carruth }
24371652996fSChandler Carruth }
243845bd8d94SDaniil Suchkov }
2439d1dab0c3SChandler Carruth
2440693eedb1SChandler Carruth // We can change which blocks are exit blocks of all the cloned sibling
2441693eedb1SChandler Carruth // loops, the current loop, and any parent loops which shared exit blocks
2442693eedb1SChandler Carruth // with the current loop. As a consequence, we need to re-form LCSSA for
2443693eedb1SChandler Carruth // them. But we shouldn't need to re-form LCSSA for any child loops.
2444693eedb1SChandler Carruth // FIXME: This could be made more efficient by tracking which exit blocks are
2445693eedb1SChandler Carruth // new, and focusing on them, but that isn't likely to be necessary.
2446693eedb1SChandler Carruth //
2447693eedb1SChandler Carruth // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2448693eedb1SChandler Carruth // loop nest and update every loop that could have had its exits changed. We
2449693eedb1SChandler Carruth // also need to cover any intervening loops. We add all of these loops to
2450693eedb1SChandler Carruth // a list and sort them by loop depth to achieve this without updating
2451693eedb1SChandler Carruth // unnecessary loops.
24529281503eSChandler Carruth auto UpdateLoop = [&](Loop &UpdateL) {
2453693eedb1SChandler Carruth #ifndef NDEBUG
245443acdb35SChandler Carruth UpdateL.verifyLoop();
245543acdb35SChandler Carruth for (Loop *ChildL : UpdateL) {
245643acdb35SChandler Carruth ChildL->verifyLoop();
2457693eedb1SChandler Carruth assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2458693eedb1SChandler Carruth "Perturbed a child loop's LCSSA form!");
245943acdb35SChandler Carruth }
2460693eedb1SChandler Carruth #endif
2461693eedb1SChandler Carruth // First build LCSSA for this loop so that we can preserve it when
2462693eedb1SChandler Carruth // forming dedicated exits. We don't want to perturb some other loop's
2463693eedb1SChandler Carruth // LCSSA while doing that CFG edit.
2464c4d8c631SDaniil Suchkov formLCSSA(UpdateL, DT, &LI, SE);
2465693eedb1SChandler Carruth
2466693eedb1SChandler Carruth // For loops reached by this loop's original exit blocks we may
2467693eedb1SChandler Carruth // introduced new, non-dedicated exits. At least try to re-form dedicated
2468693eedb1SChandler Carruth // exits for these loops. This may fail if they couldn't have dedicated
2469693eedb1SChandler Carruth // exits to start with.
247097468e92SAlina Sbirlea formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
24719281503eSChandler Carruth };
24729281503eSChandler Carruth
24739281503eSChandler Carruth // For non-child cloned loops and hoisted loops, we just need to update LCSSA
24749281503eSChandler Carruth // and we can do it in any order as they don't nest relative to each other.
24759281503eSChandler Carruth //
24769281503eSChandler Carruth // Also check if any of the loops we have updated have become top-level loops
24779281503eSChandler Carruth // as that will necessitate widening the outer loop scope.
24789281503eSChandler Carruth for (Loop *UpdatedL :
24799281503eSChandler Carruth llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
24809281503eSChandler Carruth UpdateLoop(*UpdatedL);
248189c1e35fSStefanos Baziotis if (UpdatedL->isOutermost())
24829281503eSChandler Carruth OuterExitL = nullptr;
2483693eedb1SChandler Carruth }
24849281503eSChandler Carruth if (IsStillLoop) {
24859281503eSChandler Carruth UpdateLoop(L);
248689c1e35fSStefanos Baziotis if (L.isOutermost())
24879281503eSChandler Carruth OuterExitL = nullptr;
2488693eedb1SChandler Carruth }
2489693eedb1SChandler Carruth
24909281503eSChandler Carruth // If the original loop had exit blocks, walk up through the outer most loop
24919281503eSChandler Carruth // of those exit blocks to update LCSSA and form updated dedicated exits.
24929281503eSChandler Carruth if (OuterExitL != &L)
24939281503eSChandler Carruth for (Loop *OuterL = ParentL; OuterL != OuterExitL;
24949281503eSChandler Carruth OuterL = OuterL->getParentLoop())
24959281503eSChandler Carruth UpdateLoop(*OuterL);
24969281503eSChandler Carruth
2497693eedb1SChandler Carruth #ifndef NDEBUG
2498693eedb1SChandler Carruth // Verify the entire loop structure to catch any incorrect updates before we
2499693eedb1SChandler Carruth // progress in the pass pipeline.
2500693eedb1SChandler Carruth LI.verify(DT);
2501693eedb1SChandler Carruth #endif
2502693eedb1SChandler Carruth
2503693eedb1SChandler Carruth // Now that we've unswitched something, make callbacks to report the changes.
2504693eedb1SChandler Carruth // For that we need to merge together the updated loops and the cloned loops
2505693eedb1SChandler Carruth // and check whether the original loop survived.
2506693eedb1SChandler Carruth SmallVector<Loop *, 4> SibLoops;
2507693eedb1SChandler Carruth for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2508693eedb1SChandler Carruth if (UpdatedL->getParentLoop() == ParentL)
2509693eedb1SChandler Carruth SibLoops.push_back(UpdatedL);
2510f3a27511SJingu Kang UnswitchCB(IsStillLoop, PartiallyInvariant, SibLoops);
2511693eedb1SChandler Carruth
2512a2eebb82SAlina Sbirlea if (MSSAU && VerifyMemorySSA)
2513a2eebb82SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
2514a2eebb82SAlina Sbirlea
2515b7dff9c9SZaara Syeda if (BI)
2516693eedb1SChandler Carruth ++NumBranches;
2517b7dff9c9SZaara Syeda else
2518b7dff9c9SZaara Syeda ++NumSwitches;
2519693eedb1SChandler Carruth }
2520693eedb1SChandler Carruth
2521693eedb1SChandler Carruth /// Recursively compute the cost of a dominator subtree based on the per-block
2522693eedb1SChandler Carruth /// cost map provided.
2523693eedb1SChandler Carruth ///
2524693eedb1SChandler Carruth /// The recursive computation is memozied into the provided DT-indexed cost map
2525693eedb1SChandler Carruth /// to allow querying it for most nodes in the domtree without it becoming
2526693eedb1SChandler Carruth /// quadratic.
computeDomSubtreeCost(DomTreeNode & N,const SmallDenseMap<BasicBlock *,InstructionCost,4> & BBCostMap,SmallDenseMap<DomTreeNode *,InstructionCost,4> & DTCostMap)252700da3227SSander de Smalen static InstructionCost computeDomSubtreeCost(
252800da3227SSander de Smalen DomTreeNode &N,
252900da3227SSander de Smalen const SmallDenseMap<BasicBlock *, InstructionCost, 4> &BBCostMap,
253000da3227SSander de Smalen SmallDenseMap<DomTreeNode *, InstructionCost, 4> &DTCostMap) {
2531693eedb1SChandler Carruth // Don't accumulate cost (or recurse through) blocks not in our block cost
2532693eedb1SChandler Carruth // map and thus not part of the duplication cost being considered.
2533693eedb1SChandler Carruth auto BBCostIt = BBCostMap.find(N.getBlock());
2534693eedb1SChandler Carruth if (BBCostIt == BBCostMap.end())
2535693eedb1SChandler Carruth return 0;
2536693eedb1SChandler Carruth
2537693eedb1SChandler Carruth // Lookup this node to see if we already computed its cost.
2538693eedb1SChandler Carruth auto DTCostIt = DTCostMap.find(&N);
2539693eedb1SChandler Carruth if (DTCostIt != DTCostMap.end())
2540693eedb1SChandler Carruth return DTCostIt->second;
2541693eedb1SChandler Carruth
2542693eedb1SChandler Carruth // If not, we have to compute it. We can't use insert above and update
2543693eedb1SChandler Carruth // because computing the cost may insert more things into the map.
254400da3227SSander de Smalen InstructionCost Cost = std::accumulate(
254500da3227SSander de Smalen N.begin(), N.end(), BBCostIt->second,
254600da3227SSander de Smalen [&](InstructionCost Sum, DomTreeNode *ChildN) -> InstructionCost {
2547693eedb1SChandler Carruth return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2548693eedb1SChandler Carruth });
2549693eedb1SChandler Carruth bool Inserted = DTCostMap.insert({&N, Cost}).second;
2550693eedb1SChandler Carruth (void)Inserted;
2551693eedb1SChandler Carruth assert(Inserted && "Should not insert a node while visiting children!");
2552693eedb1SChandler Carruth return Cost;
2553693eedb1SChandler Carruth }
2554693eedb1SChandler Carruth
2555619a8346SMax Kazantsev /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2556619a8346SMax Kazantsev /// making the following replacement:
2557619a8346SMax Kazantsev ///
2558a132016dSSimon Pilgrim /// --code before guard--
2559619a8346SMax Kazantsev /// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
2560a132016dSSimon Pilgrim /// --code after guard--
2561619a8346SMax Kazantsev ///
2562619a8346SMax Kazantsev /// into
2563619a8346SMax Kazantsev ///
2564a132016dSSimon Pilgrim /// --code before guard--
2565619a8346SMax Kazantsev /// br i1 %cond, label %guarded, label %deopt
2566619a8346SMax Kazantsev ///
2567619a8346SMax Kazantsev /// guarded:
2568a132016dSSimon Pilgrim /// --code after guard--
2569619a8346SMax Kazantsev ///
2570619a8346SMax Kazantsev /// deopt:
2571619a8346SMax Kazantsev /// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2572619a8346SMax Kazantsev /// unreachable
2573619a8346SMax Kazantsev ///
2574619a8346SMax Kazantsev /// It also makes all relevant DT and LI updates, so that all structures are in
2575619a8346SMax Kazantsev /// valid state after this transform.
2576619a8346SMax Kazantsev static BranchInst *
turnGuardIntoBranch(IntrinsicInst * GI,Loop & L,SmallVectorImpl<BasicBlock * > & ExitBlocks,DominatorTree & DT,LoopInfo & LI,MemorySSAUpdater * MSSAU)2577619a8346SMax Kazantsev turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2578619a8346SMax Kazantsev SmallVectorImpl<BasicBlock *> &ExitBlocks,
2579a2eebb82SAlina Sbirlea DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
2580619a8346SMax Kazantsev SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2581619a8346SMax Kazantsev LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2582619a8346SMax Kazantsev BasicBlock *CheckBB = GI->getParent();
2583619a8346SMax Kazantsev
2584797935f4SAlina Sbirlea if (MSSAU && VerifyMemorySSA)
2585a2eebb82SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
2586a2eebb82SAlina Sbirlea
2587619a8346SMax Kazantsev // Remove all CheckBB's successors from DomTree. A block can be seen among
2588619a8346SMax Kazantsev // successors more than once, but for DomTree it should be added only once.
2589619a8346SMax Kazantsev SmallPtrSet<BasicBlock *, 4> Successors;
2590619a8346SMax Kazantsev for (auto *Succ : successors(CheckBB))
2591619a8346SMax Kazantsev if (Successors.insert(Succ).second)
2592619a8346SMax Kazantsev DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2593619a8346SMax Kazantsev
2594619a8346SMax Kazantsev Instruction *DeoptBlockTerm =
2595619a8346SMax Kazantsev SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2596619a8346SMax Kazantsev BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2597619a8346SMax Kazantsev // SplitBlockAndInsertIfThen inserts control flow that branches to
2598619a8346SMax Kazantsev // DeoptBlockTerm if the condition is true. We want the opposite.
2599619a8346SMax Kazantsev CheckBI->swapSuccessors();
2600619a8346SMax Kazantsev
2601619a8346SMax Kazantsev BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2602619a8346SMax Kazantsev GuardedBlock->setName("guarded");
2603619a8346SMax Kazantsev CheckBI->getSuccessor(1)->setName("deopt");
2604a2eebb82SAlina Sbirlea BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
2605619a8346SMax Kazantsev
2606619a8346SMax Kazantsev // We now have a new exit block.
2607619a8346SMax Kazantsev ExitBlocks.push_back(CheckBI->getSuccessor(1));
2608619a8346SMax Kazantsev
2609a2eebb82SAlina Sbirlea if (MSSAU)
2610a2eebb82SAlina Sbirlea MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2611a2eebb82SAlina Sbirlea
2612619a8346SMax Kazantsev GI->moveBefore(DeoptBlockTerm);
2613619a8346SMax Kazantsev GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2614619a8346SMax Kazantsev
2615619a8346SMax Kazantsev // Add new successors of CheckBB into DomTree.
2616619a8346SMax Kazantsev for (auto *Succ : successors(CheckBB))
2617619a8346SMax Kazantsev DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2618619a8346SMax Kazantsev
2619619a8346SMax Kazantsev // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2620619a8346SMax Kazantsev // successors.
2621619a8346SMax Kazantsev for (auto *Succ : Successors)
2622619a8346SMax Kazantsev DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2623619a8346SMax Kazantsev
2624619a8346SMax Kazantsev // Make proper changes to DT.
2625619a8346SMax Kazantsev DT.applyUpdates(DTUpdates);
2626619a8346SMax Kazantsev // Inform LI of a new loop block.
2627619a8346SMax Kazantsev L.addBasicBlockToLoop(GuardedBlock, LI);
2628619a8346SMax Kazantsev
2629a2eebb82SAlina Sbirlea if (MSSAU) {
2630a2eebb82SAlina Sbirlea MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
26315c5cf899SAlina Sbirlea MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::BeforeTerminator);
2632a2eebb82SAlina Sbirlea if (VerifyMemorySSA)
2633a2eebb82SAlina Sbirlea MSSAU->getMemorySSA()->verifyMemorySSA();
2634a2eebb82SAlina Sbirlea }
2635a2eebb82SAlina Sbirlea
2636619a8346SMax Kazantsev ++NumGuards;
2637619a8346SMax Kazantsev return CheckBI;
2638619a8346SMax Kazantsev }
2639619a8346SMax Kazantsev
26402e3e224eSFedor Sergeev /// Cost multiplier is a way to limit potentially exponential behavior
26412e3e224eSFedor Sergeev /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
26422e3e224eSFedor Sergeev /// candidates available. Also accounting for the number of "sibling" loops with
26432e3e224eSFedor Sergeev /// the idea to account for previous unswitches that already happened on this
26442e3e224eSFedor Sergeev /// cluster of loops. There was an attempt to keep this formula simple,
26452e3e224eSFedor Sergeev /// just enough to limit the worst case behavior. Even if it is not that simple
26462e3e224eSFedor Sergeev /// now it is still not an attempt to provide a detailed heuristic size
26472e3e224eSFedor Sergeev /// prediction.
26482e3e224eSFedor Sergeev ///
26492e3e224eSFedor Sergeev /// TODO: Make a proper accounting of "explosion" effect for all kinds of
26502e3e224eSFedor Sergeev /// unswitch candidates, making adequate predictions instead of wild guesses.
26512e3e224eSFedor Sergeev /// That requires knowing not just the number of "remaining" candidates but
26522e3e224eSFedor Sergeev /// also costs of unswitching for each of these candidates.
CalculateUnswitchCostMultiplier(Instruction & TI,Loop & L,LoopInfo & LI,DominatorTree & DT,ArrayRef<std::pair<Instruction *,TinyPtrVector<Value * >>> UnswitchCandidates)26531c03cc5aSAlina Sbirlea static int CalculateUnswitchCostMultiplier(
26542e3e224eSFedor Sergeev Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
26552e3e224eSFedor Sergeev ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
26562e3e224eSFedor Sergeev UnswitchCandidates) {
26572e3e224eSFedor Sergeev
26582e3e224eSFedor Sergeev // Guards and other exiting conditions do not contribute to exponential
26592e3e224eSFedor Sergeev // explosion as soon as they dominate the latch (otherwise there might be
26602e3e224eSFedor Sergeev // another path to the latch remaining that does not allow to eliminate the
26612e3e224eSFedor Sergeev // loop copy on unswitch).
26622e3e224eSFedor Sergeev BasicBlock *Latch = L.getLoopLatch();
26632e3e224eSFedor Sergeev BasicBlock *CondBlock = TI.getParent();
26642e3e224eSFedor Sergeev if (DT.dominates(CondBlock, Latch) &&
26652e3e224eSFedor Sergeev (isGuard(&TI) ||
26662e3e224eSFedor Sergeev llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
26672e3e224eSFedor Sergeev return L.contains(SuccBB);
26682e3e224eSFedor Sergeev }) <= 1)) {
26692e3e224eSFedor Sergeev NumCostMultiplierSkipped++;
26702e3e224eSFedor Sergeev return 1;
26712e3e224eSFedor Sergeev }
26722e3e224eSFedor Sergeev
26732e3e224eSFedor Sergeev auto *ParentL = L.getParentLoop();
26742e3e224eSFedor Sergeev int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
26752e3e224eSFedor Sergeev : std::distance(LI.begin(), LI.end()));
26762e3e224eSFedor Sergeev // Count amount of clones that all the candidates might cause during
26772e3e224eSFedor Sergeev // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
26782e3e224eSFedor Sergeev int UnswitchedClones = 0;
26792e3e224eSFedor Sergeev for (auto Candidate : UnswitchCandidates) {
26802e3e224eSFedor Sergeev Instruction *CI = Candidate.first;
26812e3e224eSFedor Sergeev BasicBlock *CondBlock = CI->getParent();
26822e3e224eSFedor Sergeev bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
26832e3e224eSFedor Sergeev if (isGuard(CI)) {
26842e3e224eSFedor Sergeev if (!SkipExitingSuccessors)
26852e3e224eSFedor Sergeev UnswitchedClones++;
26862e3e224eSFedor Sergeev continue;
26872e3e224eSFedor Sergeev }
26882e3e224eSFedor Sergeev int NonExitingSuccessors = llvm::count_if(
26892e3e224eSFedor Sergeev successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
26902e3e224eSFedor Sergeev return !SkipExitingSuccessors || L.contains(SuccBB);
26912e3e224eSFedor Sergeev });
26922e3e224eSFedor Sergeev UnswitchedClones += Log2_32(NonExitingSuccessors);
26932e3e224eSFedor Sergeev }
26942e3e224eSFedor Sergeev
26952e3e224eSFedor Sergeev // Ignore up to the "unscaled candidates" number of unswitch candidates
26962e3e224eSFedor Sergeev // when calculating the power-of-two scaling of the cost. The main idea
26972e3e224eSFedor Sergeev // with this control is to allow a small number of unswitches to happen
26982e3e224eSFedor Sergeev // and rely more on siblings multiplier (see below) when the number
26992e3e224eSFedor Sergeev // of candidates is small.
27002e3e224eSFedor Sergeev unsigned ClonesPower =
27012e3e224eSFedor Sergeev std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
27022e3e224eSFedor Sergeev
27032e3e224eSFedor Sergeev // Allowing top-level loops to spread a bit more than nested ones.
27042e3e224eSFedor Sergeev int SiblingsMultiplier =
27052e3e224eSFedor Sergeev std::max((ParentL ? SiblingsCount
27062e3e224eSFedor Sergeev : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
27072e3e224eSFedor Sergeev 1);
27082e3e224eSFedor Sergeev // Compute the cost multiplier in a way that won't overflow by saturating
27092e3e224eSFedor Sergeev // at an upper bound.
27102e3e224eSFedor Sergeev int CostMultiplier;
27112e3e224eSFedor Sergeev if (ClonesPower > Log2_32(UnswitchThreshold) ||
27122e3e224eSFedor Sergeev SiblingsMultiplier > UnswitchThreshold)
27132e3e224eSFedor Sergeev CostMultiplier = UnswitchThreshold;
27142e3e224eSFedor Sergeev else
27152e3e224eSFedor Sergeev CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
27162e3e224eSFedor Sergeev (int)UnswitchThreshold);
27172e3e224eSFedor Sergeev
27182e3e224eSFedor Sergeev LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier
27192e3e224eSFedor Sergeev << " (siblings " << SiblingsMultiplier << " * clones "
27202e3e224eSFedor Sergeev << (1 << ClonesPower) << ")"
27212e3e224eSFedor Sergeev << " for unswitch candidate: " << TI << "\n");
27222e3e224eSFedor Sergeev return CostMultiplier;
27232e3e224eSFedor Sergeev }
27242e3e224eSFedor Sergeev
unswitchBestCondition(Loop & L,DominatorTree & DT,LoopInfo & LI,AssumptionCache & AC,AAResults & AA,TargetTransformInfo & TTI,function_ref<void (bool,bool,ArrayRef<Loop * >)> UnswitchCB,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,function_ref<void (Loop &,StringRef)> DestroyLoopCB)2725f3a27511SJingu Kang static bool unswitchBestCondition(
2726f3a27511SJingu Kang Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
2727f3a27511SJingu Kang AAResults &AA, TargetTransformInfo &TTI,
2728f3a27511SJingu Kang function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
27290f0344ddSBjorn Pettersson ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
27300f0344ddSBjorn Pettersson function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
2731d1dab0c3SChandler Carruth // Collect all invariant conditions within this loop (as opposed to an inner
2732d1dab0c3SChandler Carruth // loop which would be handled when visiting that inner loop).
273360b2e054SChandler Carruth SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
2734d1dab0c3SChandler Carruth UnswitchCandidates;
2735619a8346SMax Kazantsev
2736619a8346SMax Kazantsev // Whether or not we should also collect guards in the loop.
2737619a8346SMax Kazantsev bool CollectGuards = false;
2738619a8346SMax Kazantsev if (UnswitchGuards) {
2739619a8346SMax Kazantsev auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2740619a8346SMax Kazantsev Intrinsic::getName(Intrinsic::experimental_guard));
2741619a8346SMax Kazantsev if (GuardDecl && !GuardDecl->use_empty())
2742619a8346SMax Kazantsev CollectGuards = true;
2743619a8346SMax Kazantsev }
2744619a8346SMax Kazantsev
2745f3a27511SJingu Kang IVConditionInfo PartialIVInfo;
2746d1dab0c3SChandler Carruth for (auto *BB : L.blocks()) {
2747d1dab0c3SChandler Carruth if (LI.getLoopFor(BB) != &L)
2748d1dab0c3SChandler Carruth continue;
27491353f9a4SChandler Carruth
2750619a8346SMax Kazantsev if (CollectGuards)
2751619a8346SMax Kazantsev for (auto &I : *BB)
2752619a8346SMax Kazantsev if (isGuard(&I)) {
2753619a8346SMax Kazantsev auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2754619a8346SMax Kazantsev // TODO: Support AND, OR conditions and partial unswitching.
2755619a8346SMax Kazantsev if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2756619a8346SMax Kazantsev UnswitchCandidates.push_back({&I, {Cond}});
2757619a8346SMax Kazantsev }
2758619a8346SMax Kazantsev
27591652996fSChandler Carruth if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
27601652996fSChandler Carruth // We can only consider fully loop-invariant switch conditions as we need
27611652996fSChandler Carruth // to completely eliminate the switch after unswitching.
27621652996fSChandler Carruth if (!isa<Constant>(SI->getCondition()) &&
2763d000f8b6SSerguei Katkov L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor())
27641652996fSChandler Carruth UnswitchCandidates.push_back({SI, {SI->getCondition()}});
27651652996fSChandler Carruth continue;
27661652996fSChandler Carruth }
27671652996fSChandler Carruth
2768d1dab0c3SChandler Carruth auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2769d1dab0c3SChandler Carruth if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2770d1dab0c3SChandler Carruth BI->getSuccessor(0) == BI->getSuccessor(1))
2771d1dab0c3SChandler Carruth continue;
27721353f9a4SChandler Carruth
277341e142fdSFlorian Hahn Value *Cond = skipTrivialSelect(BI->getCondition());
277445bd8d94SDaniil Suchkov if (isa<Constant>(Cond))
277545bd8d94SDaniil Suchkov continue;
277645bd8d94SDaniil Suchkov
277741e142fdSFlorian Hahn if (L.isLoopInvariant(Cond)) {
277841e142fdSFlorian Hahn UnswitchCandidates.push_back({BI, {Cond}});
2779d1dab0c3SChandler Carruth continue;
278071fd2704SChandler Carruth }
27811353f9a4SChandler Carruth
278241e142fdSFlorian Hahn Instruction &CondI = *cast<Instruction>(Cond);
2783f3a27511SJingu Kang if (match(&CondI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()))) {
2784d1dab0c3SChandler Carruth TinyPtrVector<Value *> Invariants =
2785d1dab0c3SChandler Carruth collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2786d1dab0c3SChandler Carruth if (Invariants.empty())
2787d1dab0c3SChandler Carruth continue;
2788d1dab0c3SChandler Carruth
2789d1dab0c3SChandler Carruth UnswitchCandidates.push_back({BI, std::move(Invariants)});
2790f3a27511SJingu Kang continue;
2791f3a27511SJingu Kang }
2792f3a27511SJingu Kang }
2793f3a27511SJingu Kang
2794f3a27511SJingu Kang Instruction *PartialIVCondBranch = nullptr;
2795f3a27511SJingu Kang if (MSSAU && !findOptionMDForLoop(&L, "llvm.loop.unswitch.partial.disable") &&
2796f3a27511SJingu Kang !any_of(UnswitchCandidates, [&L](auto &TerminatorAndInvariants) {
2797f3a27511SJingu Kang return TerminatorAndInvariants.first == L.getHeader()->getTerminator();
2798f3a27511SJingu Kang })) {
2799f3a27511SJingu Kang MemorySSA *MSSA = MSSAU->getMemorySSA();
2800f3a27511SJingu Kang if (auto Info = hasPartialIVCondition(L, MSSAThreshold, *MSSA, AA)) {
2801f3a27511SJingu Kang LLVM_DEBUG(
2802f3a27511SJingu Kang dbgs() << "simple-loop-unswitch: Found partially invariant condition "
2803f3a27511SJingu Kang << *Info->InstToDuplicate[0] << "\n");
2804f3a27511SJingu Kang PartialIVInfo = *Info;
2805f3a27511SJingu Kang PartialIVCondBranch = L.getHeader()->getTerminator();
2806f3a27511SJingu Kang TinyPtrVector<Value *> ValsToDuplicate;
28075d7b1a5fSKazu Hirata llvm::append_range(ValsToDuplicate, Info->InstToDuplicate);
2808f3a27511SJingu Kang UnswitchCandidates.push_back(
2809f3a27511SJingu Kang {L.getHeader()->getTerminator(), std::move(ValsToDuplicate)});
2810f3a27511SJingu Kang }
2811d1dab0c3SChandler Carruth }
2812693eedb1SChandler Carruth
2813693eedb1SChandler Carruth // If we didn't find any candidates, we're done.
2814693eedb1SChandler Carruth if (UnswitchCandidates.empty())
281571fd2704SChandler Carruth return false;
2816693eedb1SChandler Carruth
281732e62f9cSChandler Carruth // Check if there are irreducible CFG cycles in this loop. If so, we cannot
281832e62f9cSChandler Carruth // easily unswitch non-trivial edges out of the loop. Doing so might turn the
281932e62f9cSChandler Carruth // irreducible control flow into reducible control flow and introduce new
282032e62f9cSChandler Carruth // loops "out of thin air". If we ever discover important use cases for doing
282132e62f9cSChandler Carruth // this, we can add support to loop unswitch, but it is a lot of complexity
2822f209649dSHiroshi Inoue // for what seems little or no real world benefit.
282332e62f9cSChandler Carruth LoopBlocksRPO RPOT(&L);
282432e62f9cSChandler Carruth RPOT.perform(&LI);
282532e62f9cSChandler Carruth if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
282671fd2704SChandler Carruth return false;
282732e62f9cSChandler Carruth
2828bde31000SMax Kazantsev SmallVector<BasicBlock *, 4> ExitBlocks;
2829bde31000SMax Kazantsev L.getUniqueExitBlocks(ExitBlocks);
2830bde31000SMax Kazantsev
28315366de73SArthur Eubanks // We cannot unswitch if exit blocks contain a cleanuppad/catchswitch
28325366de73SArthur Eubanks // instruction as we don't know how to split those exit blocks.
2833bde31000SMax Kazantsev // FIXME: We should teach SplitBlock to handle this and remove this
2834bde31000SMax Kazantsev // restriction.
283570af2924SArthur Eubanks for (auto *ExitBB : ExitBlocks) {
28365366de73SArthur Eubanks auto *I = ExitBB->getFirstNonPHI();
28375366de73SArthur Eubanks if (isa<CleanupPadInst>(I) || isa<CatchSwitchInst>(I)) {
28385366de73SArthur Eubanks LLVM_DEBUG(dbgs() << "Cannot unswitch because of cleanuppad/catchswitch "
28395366de73SArthur Eubanks "in exit block\n");
2840bde31000SMax Kazantsev return false;
2841bde31000SMax Kazantsev }
284270af2924SArthur Eubanks }
2843bde31000SMax Kazantsev
2844d34e60caSNicola Zaghen LLVM_DEBUG(
2845d34e60caSNicola Zaghen dbgs() << "Considering " << UnswitchCandidates.size()
2846693eedb1SChandler Carruth << " non-trivial loop invariant conditions for unswitching.\n");
2847693eedb1SChandler Carruth
2848693eedb1SChandler Carruth // Given that unswitching these terminators will require duplicating parts of
2849693eedb1SChandler Carruth // the loop, so we need to be able to model that cost. Compute the ephemeral
2850693eedb1SChandler Carruth // values and set up a data structure to hold per-BB costs. We cache each
2851693eedb1SChandler Carruth // block's cost so that we don't recompute this when considering different
2852693eedb1SChandler Carruth // subsets of the loop for duplication during unswitching.
2853693eedb1SChandler Carruth SmallPtrSet<const Value *, 4> EphValues;
2854693eedb1SChandler Carruth CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
285500da3227SSander de Smalen SmallDenseMap<BasicBlock *, InstructionCost, 4> BBCostMap;
2856693eedb1SChandler Carruth
2857693eedb1SChandler Carruth // Compute the cost of each block, as well as the total loop cost. Also, bail
2858693eedb1SChandler Carruth // out if we see instructions which are incompatible with loop unswitching
2859693eedb1SChandler Carruth // (convergent, noduplicate, or cross-basic-block tokens).
2860693eedb1SChandler Carruth // FIXME: We might be able to safely handle some of these in non-duplicated
2861693eedb1SChandler Carruth // regions.
2862725400f9SSam Parker TargetTransformInfo::TargetCostKind CostKind =
2863725400f9SSam Parker L.getHeader()->getParent()->hasMinSize()
2864725400f9SSam Parker ? TargetTransformInfo::TCK_CodeSize
2865725400f9SSam Parker : TargetTransformInfo::TCK_SizeAndLatency;
286600da3227SSander de Smalen InstructionCost LoopCost = 0;
2867693eedb1SChandler Carruth for (auto *BB : L.blocks()) {
286800da3227SSander de Smalen InstructionCost Cost = 0;
2869693eedb1SChandler Carruth for (auto &I : *BB) {
2870693eedb1SChandler Carruth if (EphValues.count(&I))
2871693eedb1SChandler Carruth continue;
2872693eedb1SChandler Carruth
2873693eedb1SChandler Carruth if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
287471fd2704SChandler Carruth return false;
2875592d8e7dSCraig Topper if (auto *CB = dyn_cast<CallBase>(&I))
2876592d8e7dSCraig Topper if (CB->isConvergent() || CB->cannotDuplicate())
287771fd2704SChandler Carruth return false;
2878693eedb1SChandler Carruth
2879725400f9SSam Parker Cost += TTI.getUserCost(&I, CostKind);
2880693eedb1SChandler Carruth }
2881693eedb1SChandler Carruth assert(Cost >= 0 && "Must not have negative costs!");
2882693eedb1SChandler Carruth LoopCost += Cost;
2883693eedb1SChandler Carruth assert(LoopCost >= 0 && "Must not have negative loop costs!");
2884693eedb1SChandler Carruth BBCostMap[BB] = Cost;
2885693eedb1SChandler Carruth }
2886d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n");
2887693eedb1SChandler Carruth
2888693eedb1SChandler Carruth // Now we find the best candidate by searching for the one with the following
2889693eedb1SChandler Carruth // properties in order:
2890693eedb1SChandler Carruth //
2891693eedb1SChandler Carruth // 1) An unswitching cost below the threshold
2892693eedb1SChandler Carruth // 2) The smallest number of duplicated unswitch candidates (to avoid
2893693eedb1SChandler Carruth // creating redundant subsequent unswitching)
2894693eedb1SChandler Carruth // 3) The smallest cost after unswitching.
2895693eedb1SChandler Carruth //
2896693eedb1SChandler Carruth // We prioritize reducing fanout of unswitch candidates provided the cost
2897693eedb1SChandler Carruth // remains below the threshold because this has a multiplicative effect.
2898693eedb1SChandler Carruth //
2899693eedb1SChandler Carruth // This requires memoizing each dominator subtree to avoid redundant work.
2900693eedb1SChandler Carruth //
2901693eedb1SChandler Carruth // FIXME: Need to actually do the number of candidates part above.
290200da3227SSander de Smalen SmallDenseMap<DomTreeNode *, InstructionCost, 4> DTCostMap;
2903693eedb1SChandler Carruth // Given a terminator which might be unswitched, computes the non-duplicated
2904693eedb1SChandler Carruth // cost for that terminator.
290500da3227SSander de Smalen auto ComputeUnswitchedCost = [&](Instruction &TI,
290600da3227SSander de Smalen bool FullUnswitch) -> InstructionCost {
2907d1dab0c3SChandler Carruth BasicBlock &BB = *TI.getParent();
2908693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 4> Visited;
2909693eedb1SChandler Carruth
291000da3227SSander de Smalen InstructionCost Cost = 0;
2911693eedb1SChandler Carruth for (BasicBlock *SuccBB : successors(&BB)) {
2912693eedb1SChandler Carruth // Don't count successors more than once.
2913693eedb1SChandler Carruth if (!Visited.insert(SuccBB).second)
2914693eedb1SChandler Carruth continue;
2915693eedb1SChandler Carruth
2916d1dab0c3SChandler Carruth // If this is a partial unswitch candidate, then it must be a conditional
2917f3a27511SJingu Kang // branch with a condition of either `or`, `and`, their corresponding
2918f3a27511SJingu Kang // select forms or partially invariant instructions. In that case, one of
2919f3a27511SJingu Kang // the successors is necessarily duplicated, so don't even try to remove
2920f3a27511SJingu Kang // its cost.
2921d1dab0c3SChandler Carruth if (!FullUnswitch) {
2922d1dab0c3SChandler Carruth auto &BI = cast<BranchInst>(TI);
292341e142fdSFlorian Hahn Value *Cond = skipTrivialSelect(BI.getCondition());
292441e142fdSFlorian Hahn if (match(Cond, m_LogicalAnd())) {
2925d1dab0c3SChandler Carruth if (SuccBB == BI.getSuccessor(1))
2926d1dab0c3SChandler Carruth continue;
292741e142fdSFlorian Hahn } else if (match(Cond, m_LogicalOr())) {
2928d1dab0c3SChandler Carruth if (SuccBB == BI.getSuccessor(0))
2929d1dab0c3SChandler Carruth continue;
2930873ff5a7SJingu Kang } else if ((PartialIVInfo.KnownValue->isOneValue() &&
2931873ff5a7SJingu Kang SuccBB == BI.getSuccessor(0)) ||
2932873ff5a7SJingu Kang (!PartialIVInfo.KnownValue->isOneValue() &&
2933873ff5a7SJingu Kang SuccBB == BI.getSuccessor(1)))
2934f3a27511SJingu Kang continue;
2935d1dab0c3SChandler Carruth }
2936d1dab0c3SChandler Carruth
2937693eedb1SChandler Carruth // This successor's domtree will not need to be duplicated after
2938693eedb1SChandler Carruth // unswitching if the edge to the successor dominates it (and thus the
2939693eedb1SChandler Carruth // entire tree). This essentially means there is no other path into this
2940693eedb1SChandler Carruth // subtree and so it will end up live in only one clone of the loop.
2941693eedb1SChandler Carruth if (SuccBB->getUniquePredecessor() ||
2942693eedb1SChandler Carruth llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2943693eedb1SChandler Carruth return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2944693eedb1SChandler Carruth })) {
294500da3227SSander de Smalen Cost += computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
294600da3227SSander de Smalen assert(Cost <= LoopCost &&
2947693eedb1SChandler Carruth "Non-duplicated cost should never exceed total loop cost!");
2948693eedb1SChandler Carruth }
2949693eedb1SChandler Carruth }
2950693eedb1SChandler Carruth
2951693eedb1SChandler Carruth // Now scale the cost by the number of unique successors minus one. We
2952693eedb1SChandler Carruth // subtract one because there is already at least one copy of the entire
2953693eedb1SChandler Carruth // loop. This is computing the new cost of unswitching a condition.
2954619a8346SMax Kazantsev // Note that guards always have 2 unique successors that are implicit and
2955619a8346SMax Kazantsev // will be materialized if we decide to unswitch it.
2956619a8346SMax Kazantsev int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2957619a8346SMax Kazantsev assert(SuccessorsCount > 1 &&
2958693eedb1SChandler Carruth "Cannot unswitch a condition without multiple distinct successors!");
295900da3227SSander de Smalen return (LoopCost - Cost) * (SuccessorsCount - 1);
2960693eedb1SChandler Carruth };
296160b2e054SChandler Carruth Instruction *BestUnswitchTI = nullptr;
296200da3227SSander de Smalen InstructionCost BestUnswitchCost = 0;
2963d1dab0c3SChandler Carruth ArrayRef<Value *> BestUnswitchInvariants;
2964d1dab0c3SChandler Carruth for (auto &TerminatorAndInvariants : UnswitchCandidates) {
296560b2e054SChandler Carruth Instruction &TI = *TerminatorAndInvariants.first;
2966d1dab0c3SChandler Carruth ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2967d1dab0c3SChandler Carruth BranchInst *BI = dyn_cast<BranchInst>(&TI);
296800da3227SSander de Smalen InstructionCost CandidateCost = ComputeUnswitchedCost(
296941e142fdSFlorian Hahn TI, /*FullUnswitch*/ !BI ||
297041e142fdSFlorian Hahn (Invariants.size() == 1 &&
297141e142fdSFlorian Hahn Invariants[0] == skipTrivialSelect(BI->getCondition())));
29722e3e224eSFedor Sergeev // Calculate cost multiplier which is a tool to limit potentially
29732e3e224eSFedor Sergeev // exponential behavior of loop-unswitch.
29742e3e224eSFedor Sergeev if (EnableUnswitchCostMultiplier) {
29752e3e224eSFedor Sergeev int CostMultiplier =
29761c03cc5aSAlina Sbirlea CalculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
29772e3e224eSFedor Sergeev assert(
29782e3e224eSFedor Sergeev (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
29792e3e224eSFedor Sergeev "cost multiplier needs to be in the range of 1..UnswitchThreshold");
29802e3e224eSFedor Sergeev CandidateCost *= CostMultiplier;
29812e3e224eSFedor Sergeev LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
29822e3e224eSFedor Sergeev << " (multiplier: " << CostMultiplier << ")"
29832e3e224eSFedor Sergeev << " for unswitch candidate: " << TI << "\n");
29842e3e224eSFedor Sergeev } else {
2985d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2986d1dab0c3SChandler Carruth << " for unswitch candidate: " << TI << "\n");
29872e3e224eSFedor Sergeev }
29882e3e224eSFedor Sergeev
2989693eedb1SChandler Carruth if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2990d1dab0c3SChandler Carruth BestUnswitchTI = &TI;
2991693eedb1SChandler Carruth BestUnswitchCost = CandidateCost;
2992d1dab0c3SChandler Carruth BestUnswitchInvariants = Invariants;
2993693eedb1SChandler Carruth }
2994693eedb1SChandler Carruth }
2995c598ef7fSSimon Pilgrim assert(BestUnswitchTI && "Failed to find loop unswitch candidate");
2996693eedb1SChandler Carruth
299771fd2704SChandler Carruth if (BestUnswitchCost >= UnswitchThreshold) {
299871fd2704SChandler Carruth LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
299971fd2704SChandler Carruth << BestUnswitchCost << "\n");
300071fd2704SChandler Carruth return false;
300171fd2704SChandler Carruth }
300271fd2704SChandler Carruth
3003f3a27511SJingu Kang if (BestUnswitchTI != PartialIVCondBranch)
3004f3a27511SJingu Kang PartialIVInfo.InstToDuplicate.clear();
3005f3a27511SJingu Kang
3006619a8346SMax Kazantsev // If the best candidate is a guard, turn it into a branch.
3007619a8346SMax Kazantsev if (isGuard(BestUnswitchTI))
3008619a8346SMax Kazantsev BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
3009a2eebb82SAlina Sbirlea ExitBlocks, DT, LI, MSSAU);
3010619a8346SMax Kazantsev
3011bde31000SMax Kazantsev LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = "
30121652996fSChandler Carruth << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
30131652996fSChandler Carruth << "\n");
3014bde31000SMax Kazantsev unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
3015f3a27511SJingu Kang ExitBlocks, PartialIVInfo, DT, LI, AC,
30160f0344ddSBjorn Pettersson UnswitchCB, SE, MSSAU, DestroyLoopCB);
3017bde31000SMax Kazantsev return true;
30181353f9a4SChandler Carruth }
30191353f9a4SChandler Carruth
3020d1dab0c3SChandler Carruth /// Unswitch control flow predicated on loop invariant conditions.
3021d1dab0c3SChandler Carruth ///
3022d1dab0c3SChandler Carruth /// This first hoists all branches or switches which are trivial (IE, do not
3023d1dab0c3SChandler Carruth /// require duplicating any part of the loop) out of the loop body. It then
3024d1dab0c3SChandler Carruth /// looks at other loop invariant control flows and tries to unswitch those as
3025d1dab0c3SChandler Carruth /// well by cloning the loop if the result is small enough.
30263897ded6SChandler Carruth ///
3027f3a27511SJingu Kang /// The `DT`, `LI`, `AC`, `AA`, `TTI` parameters are required analyses that are
3028f3a27511SJingu Kang /// also updated based on the unswitch. The `MSSA` analysis is also updated if
3029f3a27511SJingu Kang /// valid (i.e. its use is enabled).
30303897ded6SChandler Carruth ///
30313897ded6SChandler Carruth /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
30323897ded6SChandler Carruth /// true, we will attempt to do non-trivial unswitching as well as trivial
30333897ded6SChandler Carruth /// unswitching.
30343897ded6SChandler Carruth ///
30353897ded6SChandler Carruth /// The `UnswitchCB` callback provided will be run after unswitching is
30363897ded6SChandler Carruth /// complete, with the first parameter set to `true` if the provided loop
30373897ded6SChandler Carruth /// remains a loop, and a list of new sibling loops created.
30383897ded6SChandler Carruth ///
30393897ded6SChandler Carruth /// If `SE` is non-null, we will update that analysis based on the unswitching
30403897ded6SChandler Carruth /// done.
3041f3a27511SJingu Kang static bool
unswitchLoop(Loop & L,DominatorTree & DT,LoopInfo & LI,AssumptionCache & AC,AAResults & AA,TargetTransformInfo & TTI,bool Trivial,bool NonTrivial,function_ref<void (bool,bool,ArrayRef<Loop * >)> UnswitchCB,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,function_ref<void (Loop &,StringRef)> DestroyLoopCB)3042f3a27511SJingu Kang unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
30430024ec59SArthur Eubanks AAResults &AA, TargetTransformInfo &TTI, bool Trivial,
30440024ec59SArthur Eubanks bool NonTrivial,
3045f3a27511SJingu Kang function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
30460f0344ddSBjorn Pettersson ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
30470f0344ddSBjorn Pettersson function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
3048d1dab0c3SChandler Carruth assert(L.isRecursivelyLCSSAForm(DT, LI) &&
3049d1dab0c3SChandler Carruth "Loops must be in LCSSA form before unswitching.");
3050d1dab0c3SChandler Carruth
3051d1dab0c3SChandler Carruth // Must be in loop simplified form: we need a preheader and dedicated exits.
3052d1dab0c3SChandler Carruth if (!L.isLoopSimplifyForm())
3053d1dab0c3SChandler Carruth return false;
3054d1dab0c3SChandler Carruth
3055d1dab0c3SChandler Carruth // Try trivial unswitch first before loop over other basic blocks in the loop.
30560024ec59SArthur Eubanks if (Trivial && unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
3057d1dab0c3SChandler Carruth // If we unswitched successfully we will want to clean up the loop before
3058d1dab0c3SChandler Carruth // processing it further so just mark it as unswitched and return.
3059f3a27511SJingu Kang UnswitchCB(/*CurrentLoopValid*/ true, false, {});
3060d1dab0c3SChandler Carruth return true;
3061d1dab0c3SChandler Carruth }
3062d1dab0c3SChandler Carruth
3063b92c8c22SSameer Sahasrabuddhe // Check whether we should continue with non-trivial conditions.
3064b92c8c22SSameer Sahasrabuddhe // EnableNonTrivialUnswitch: Global variable that forces non-trivial
3065b92c8c22SSameer Sahasrabuddhe // unswitching for testing and debugging.
3066b92c8c22SSameer Sahasrabuddhe // NonTrivial: Parameter that enables non-trivial unswitching for this
3067b92c8c22SSameer Sahasrabuddhe // invocation of the transform. But this should be allowed only
3068b92c8c22SSameer Sahasrabuddhe // for targets without branch divergence.
3069b92c8c22SSameer Sahasrabuddhe //
3070b92c8c22SSameer Sahasrabuddhe // FIXME: If divergence analysis becomes available to a loop
3071b92c8c22SSameer Sahasrabuddhe // transform, we should allow unswitching for non-trivial uniform
3072b92c8c22SSameer Sahasrabuddhe // branches even on targets that have divergence.
3073b92c8c22SSameer Sahasrabuddhe // https://bugs.llvm.org/show_bug.cgi?id=48819
3074b92c8c22SSameer Sahasrabuddhe bool ContinueWithNonTrivial =
3075b92c8c22SSameer Sahasrabuddhe EnableNonTrivialUnswitch || (NonTrivial && !TTI.hasBranchDivergence());
3076b92c8c22SSameer Sahasrabuddhe if (!ContinueWithNonTrivial)
3077d1dab0c3SChandler Carruth return false;
3078d1dab0c3SChandler Carruth
307939e6d242SArthur Eubanks // Skip non-trivial unswitching for optsize functions.
308039e6d242SArthur Eubanks if (L.getHeader()->getParent()->hasOptSize())
308139e6d242SArthur Eubanks return false;
308239e6d242SArthur Eubanks
30830eda4547SArthur Eubanks // Skip non-trivial unswitching for loops that cannot be cloned.
30840eda4547SArthur Eubanks if (!L.isSafeToClone())
30850eda4547SArthur Eubanks return false;
30860eda4547SArthur Eubanks
3087d1dab0c3SChandler Carruth // For non-trivial unswitching, because it often creates new loops, we rely on
3088d1dab0c3SChandler Carruth // the pass manager to iterate on the loops rather than trying to immediately
3089d1dab0c3SChandler Carruth // reach a fixed point. There is no substantial advantage to iterating
3090d1dab0c3SChandler Carruth // internally, and if any of the new loops are simplified enough to contain
3091d1dab0c3SChandler Carruth // trivial unswitching we want to prefer those.
3092d1dab0c3SChandler Carruth
3093d1dab0c3SChandler Carruth // Try to unswitch the best invariant condition. We prefer this full unswitch to
3094d1dab0c3SChandler Carruth // a partial unswitch when possible below the threshold.
30950f0344ddSBjorn Pettersson if (unswitchBestCondition(L, DT, LI, AC, AA, TTI, UnswitchCB, SE, MSSAU,
30960f0344ddSBjorn Pettersson DestroyLoopCB))
3097d1dab0c3SChandler Carruth return true;
3098d1dab0c3SChandler Carruth
3099d1dab0c3SChandler Carruth // No other opportunities to unswitch.
31003678ad88SMax Kazantsev return false;
3101d1dab0c3SChandler Carruth }
3102d1dab0c3SChandler Carruth
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater & U)31031353f9a4SChandler Carruth PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
31041353f9a4SChandler Carruth LoopStandardAnalysisResults &AR,
31051353f9a4SChandler Carruth LPMUpdater &U) {
31061353f9a4SChandler Carruth Function &F = *L.getHeader()->getParent();
31071353f9a4SChandler Carruth (void)F;
31081353f9a4SChandler Carruth
3109d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
3110d34e60caSNicola Zaghen << "\n");
31111353f9a4SChandler Carruth
3112693eedb1SChandler Carruth // Save the current loop name in a variable so that we can report it even
3113693eedb1SChandler Carruth // after it has been deleted.
3114adcd0268SBenjamin Kramer std::string LoopName = std::string(L.getName());
3115693eedb1SChandler Carruth
311671fd2704SChandler Carruth auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
3117f3a27511SJingu Kang bool PartiallyInvariant,
3118693eedb1SChandler Carruth ArrayRef<Loop *> NewLoops) {
3119693eedb1SChandler Carruth // If we did a non-trivial unswitch, we have added new (cloned) loops.
312071fd2704SChandler Carruth if (!NewLoops.empty())
3121693eedb1SChandler Carruth U.addSiblingLoops(NewLoops);
3122693eedb1SChandler Carruth
3123693eedb1SChandler Carruth // If the current loop remains valid, we should revisit it to catch any
3124693eedb1SChandler Carruth // other unswitch opportunities. Otherwise, we need to mark it as deleted.
3125f3a27511SJingu Kang if (CurrentLoopValid) {
3126f3a27511SJingu Kang if (PartiallyInvariant) {
3127f3a27511SJingu Kang // Mark the new loop as partially unswitched, to avoid unswitching on
3128f3a27511SJingu Kang // the same condition again.
3129f3a27511SJingu Kang auto &Context = L.getHeader()->getContext();
3130f3a27511SJingu Kang MDNode *DisableUnswitchMD = MDNode::get(
3131f3a27511SJingu Kang Context,
3132f3a27511SJingu Kang MDString::get(Context, "llvm.loop.unswitch.partial.disable"));
3133f3a27511SJingu Kang MDNode *NewLoopID = makePostTransformationMetadata(
3134f3a27511SJingu Kang Context, L.getLoopID(), {"llvm.loop.unswitch.partial"},
3135f3a27511SJingu Kang {DisableUnswitchMD});
3136f3a27511SJingu Kang L.setLoopID(NewLoopID);
3137f3a27511SJingu Kang } else
3138693eedb1SChandler Carruth U.revisitCurrentLoop();
3139f3a27511SJingu Kang } else
3140693eedb1SChandler Carruth U.markLoopAsDeleted(L, LoopName);
3141693eedb1SChandler Carruth };
3142693eedb1SChandler Carruth
31430f0344ddSBjorn Pettersson auto DestroyLoopCB = [&U](Loop &L, StringRef Name) {
31440f0344ddSBjorn Pettersson U.markLoopAsDeleted(L, Name);
31450f0344ddSBjorn Pettersson };
31460f0344ddSBjorn Pettersson
3147a2eebb82SAlina Sbirlea Optional<MemorySSAUpdater> MSSAU;
3148a2eebb82SAlina Sbirlea if (AR.MSSA) {
3149a2eebb82SAlina Sbirlea MSSAU = MemorySSAUpdater(AR.MSSA);
3150a2eebb82SAlina Sbirlea if (VerifyMemorySSA)
3151a2eebb82SAlina Sbirlea AR.MSSA->verifyMemorySSA();
3152a2eebb82SAlina Sbirlea }
31530024ec59SArthur Eubanks if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.AA, AR.TTI, Trivial, NonTrivial,
3154d66cbc56SKazu Hirata UnswitchCB, &AR.SE, MSSAU ? MSSAU.getPointer() : nullptr,
31550f0344ddSBjorn Pettersson DestroyLoopCB))
31561353f9a4SChandler Carruth return PreservedAnalyses::all();
31571353f9a4SChandler Carruth
3158a2eebb82SAlina Sbirlea if (AR.MSSA && VerifyMemorySSA)
3159a2eebb82SAlina Sbirlea AR.MSSA->verifyMemorySSA();
3160a2eebb82SAlina Sbirlea
31611353f9a4SChandler Carruth // Historically this pass has had issues with the dominator tree so verify it
31621353f9a4SChandler Carruth // in asserts builds.
31637c35de12SDavid Green assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
31643cef1f7dSAlina Sbirlea
31653cef1f7dSAlina Sbirlea auto PA = getLoopPassPreservedAnalyses();
3166f92109dcSAlina Sbirlea if (AR.MSSA)
31673cef1f7dSAlina Sbirlea PA.preserve<MemorySSAAnalysis>();
31683cef1f7dSAlina Sbirlea return PA;
31691353f9a4SChandler Carruth }
31701353f9a4SChandler Carruth
printPipeline(raw_ostream & OS,function_ref<StringRef (StringRef)> MapClassName2PassName)31711ac209edSMarkus Lavin void SimpleLoopUnswitchPass::printPipeline(
31721ac209edSMarkus Lavin raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
31731ac209edSMarkus Lavin static_cast<PassInfoMixin<SimpleLoopUnswitchPass> *>(this)->printPipeline(
31741ac209edSMarkus Lavin OS, MapClassName2PassName);
31751ac209edSMarkus Lavin
31761ac209edSMarkus Lavin OS << "<";
31771ac209edSMarkus Lavin OS << (NonTrivial ? "" : "no-") << "nontrivial;";
31781ac209edSMarkus Lavin OS << (Trivial ? "" : "no-") << "trivial";
31791ac209edSMarkus Lavin OS << ">";
31801ac209edSMarkus Lavin }
31811ac209edSMarkus Lavin
31821353f9a4SChandler Carruth namespace {
3183a369a457SEugene Zelenko
31841353f9a4SChandler Carruth class SimpleLoopUnswitchLegacyPass : public LoopPass {
3185693eedb1SChandler Carruth bool NonTrivial;
3186693eedb1SChandler Carruth
31871353f9a4SChandler Carruth public:
31881353f9a4SChandler Carruth static char ID; // Pass ID, replacement for typeid
3189a369a457SEugene Zelenko
SimpleLoopUnswitchLegacyPass(bool NonTrivial=false)3190693eedb1SChandler Carruth explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
3191693eedb1SChandler Carruth : LoopPass(ID), NonTrivial(NonTrivial) {
31921353f9a4SChandler Carruth initializeSimpleLoopUnswitchLegacyPassPass(
31931353f9a4SChandler Carruth *PassRegistry::getPassRegistry());
31941353f9a4SChandler Carruth }
31951353f9a4SChandler Carruth
31961353f9a4SChandler Carruth bool runOnLoop(Loop *L, LPPassManager &LPM) override;
31971353f9a4SChandler Carruth
getAnalysisUsage(AnalysisUsage & AU) const31981353f9a4SChandler Carruth void getAnalysisUsage(AnalysisUsage &AU) const override {
31991353f9a4SChandler Carruth AU.addRequired<AssumptionCacheTracker>();
3200693eedb1SChandler Carruth AU.addRequired<TargetTransformInfoWrapperPass>();
3201a2eebb82SAlina Sbirlea AU.addRequired<MemorySSAWrapperPass>();
3202a2eebb82SAlina Sbirlea AU.addPreserved<MemorySSAWrapperPass>();
32031353f9a4SChandler Carruth getLoopAnalysisUsage(AU);
32041353f9a4SChandler Carruth }
32051353f9a4SChandler Carruth };
3206a369a457SEugene Zelenko
3207a369a457SEugene Zelenko } // end anonymous namespace
32081353f9a4SChandler Carruth
runOnLoop(Loop * L,LPPassManager & LPM)32091353f9a4SChandler Carruth bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
32101353f9a4SChandler Carruth if (skipLoop(L))
32111353f9a4SChandler Carruth return false;
32121353f9a4SChandler Carruth
32131353f9a4SChandler Carruth Function &F = *L->getHeader()->getParent();
32141353f9a4SChandler Carruth
3215d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
3216d34e60caSNicola Zaghen << "\n");
32171353f9a4SChandler Carruth
32181353f9a4SChandler Carruth auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
32191353f9a4SChandler Carruth auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
32201353f9a4SChandler Carruth auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3221f3a27511SJingu Kang auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
3222693eedb1SChandler Carruth auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3223735a5904SNikita Popov MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
3224735a5904SNikita Popov MemorySSAUpdater MSSAU(MSSA);
32251353f9a4SChandler Carruth
32263897ded6SChandler Carruth auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
32273897ded6SChandler Carruth auto *SE = SEWP ? &SEWP->getSE() : nullptr;
32283897ded6SChandler Carruth
3229f3a27511SJingu Kang auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid, bool PartiallyInvariant,
3230693eedb1SChandler Carruth ArrayRef<Loop *> NewLoops) {
3231693eedb1SChandler Carruth // If we did a non-trivial unswitch, we have added new (cloned) loops.
3232693eedb1SChandler Carruth for (auto *NewL : NewLoops)
3233693eedb1SChandler Carruth LPM.addLoop(*NewL);
3234693eedb1SChandler Carruth
3235693eedb1SChandler Carruth // If the current loop remains valid, re-add it to the queue. This is
3236693eedb1SChandler Carruth // a little wasteful as we'll finish processing the current loop as well,
3237693eedb1SChandler Carruth // but it is the best we can do in the old PM.
3238f3a27511SJingu Kang if (CurrentLoopValid) {
3239f3a27511SJingu Kang // If the current loop has been unswitched using a partially invariant
3240f3a27511SJingu Kang // condition, we should not re-add the current loop to avoid unswitching
3241f3a27511SJingu Kang // on the same condition again.
3242f3a27511SJingu Kang if (!PartiallyInvariant)
3243693eedb1SChandler Carruth LPM.addLoop(*L);
3244f3a27511SJingu Kang } else
3245693eedb1SChandler Carruth LPM.markLoopAsDeleted(*L);
3246693eedb1SChandler Carruth };
3247693eedb1SChandler Carruth
32480f0344ddSBjorn Pettersson auto DestroyLoopCB = [&LPM](Loop &L, StringRef /* Name */) {
32490f0344ddSBjorn Pettersson LPM.markLoopAsDeleted(L);
32500f0344ddSBjorn Pettersson };
32510f0344ddSBjorn Pettersson
3252735a5904SNikita Popov if (VerifyMemorySSA)
3253a2eebb82SAlina Sbirlea MSSA->verifyMemorySSA();
3254a2eebb82SAlina Sbirlea
3255735a5904SNikita Popov bool Changed = unswitchLoop(*L, DT, LI, AC, AA, TTI, true, NonTrivial,
32560f0344ddSBjorn Pettersson UnswitchCB, SE, &MSSAU, DestroyLoopCB);
3257a2eebb82SAlina Sbirlea
3258735a5904SNikita Popov if (VerifyMemorySSA)
3259a2eebb82SAlina Sbirlea MSSA->verifyMemorySSA();
3260693eedb1SChandler Carruth
32611353f9a4SChandler Carruth // Historically this pass has had issues with the dominator tree so verify it
32621353f9a4SChandler Carruth // in asserts builds.
32637c35de12SDavid Green assert(DT.verify(DominatorTree::VerificationLevel::Fast));
32647c35de12SDavid Green
32651353f9a4SChandler Carruth return Changed;
32661353f9a4SChandler Carruth }
32671353f9a4SChandler Carruth
32681353f9a4SChandler Carruth char SimpleLoopUnswitchLegacyPass::ID = 0;
32691353f9a4SChandler Carruth INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
32701353f9a4SChandler Carruth "Simple unswitch loops", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)32711353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3272693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3273693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
32741353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopPass)
3275a2eebb82SAlina Sbirlea INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
32761353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
32771353f9a4SChandler Carruth INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
32781353f9a4SChandler Carruth "Simple unswitch loops", false, false)
32791353f9a4SChandler Carruth
3280693eedb1SChandler Carruth Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
3281693eedb1SChandler Carruth return new SimpleLoopUnswitchLegacyPass(NonTrivial);
32821353f9a4SChandler Carruth }
3283