1a369a457SEugene Zelenko //===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===// 21353f9a4SChandler Carruth // 31353f9a4SChandler Carruth // The LLVM Compiler Infrastructure 41353f9a4SChandler Carruth // 51353f9a4SChandler Carruth // This file is distributed under the University of Illinois Open Source 61353f9a4SChandler Carruth // License. See LICENSE.TXT for details. 71353f9a4SChandler Carruth // 81353f9a4SChandler Carruth //===----------------------------------------------------------------------===// 91353f9a4SChandler Carruth 106bda14b3SChandler Carruth #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 11a369a457SEugene Zelenko #include "llvm/ADT/DenseMap.h" 126bda14b3SChandler Carruth #include "llvm/ADT/STLExtras.h" 13a369a457SEugene Zelenko #include "llvm/ADT/Sequence.h" 14a369a457SEugene Zelenko #include "llvm/ADT/SetVector.h" 151353f9a4SChandler Carruth #include "llvm/ADT/SmallPtrSet.h" 16a369a457SEugene Zelenko #include "llvm/ADT/SmallVector.h" 171353f9a4SChandler Carruth #include "llvm/ADT/Statistic.h" 18a369a457SEugene Zelenko #include "llvm/ADT/Twine.h" 191353f9a4SChandler Carruth #include "llvm/Analysis/AssumptionCache.h" 2032e62f9cSChandler Carruth #include "llvm/Analysis/CFG.h" 21693eedb1SChandler Carruth #include "llvm/Analysis/CodeMetrics.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" 26a369a457SEugene Zelenko #include "llvm/IR/BasicBlock.h" 27a369a457SEugene Zelenko #include "llvm/IR/Constant.h" 281353f9a4SChandler Carruth #include "llvm/IR/Constants.h" 291353f9a4SChandler Carruth #include "llvm/IR/Dominators.h" 301353f9a4SChandler Carruth #include "llvm/IR/Function.h" 31a369a457SEugene Zelenko #include "llvm/IR/InstrTypes.h" 32a369a457SEugene Zelenko #include "llvm/IR/Instruction.h" 331353f9a4SChandler Carruth #include "llvm/IR/Instructions.h" 34693eedb1SChandler Carruth #include "llvm/IR/IntrinsicInst.h" 35a369a457SEugene Zelenko #include "llvm/IR/Use.h" 36a369a457SEugene Zelenko #include "llvm/IR/Value.h" 37a369a457SEugene Zelenko #include "llvm/Pass.h" 38a369a457SEugene Zelenko #include "llvm/Support/Casting.h" 391353f9a4SChandler Carruth #include "llvm/Support/Debug.h" 40a369a457SEugene Zelenko #include "llvm/Support/ErrorHandling.h" 41a369a457SEugene Zelenko #include "llvm/Support/GenericDomTree.h" 421353f9a4SChandler Carruth #include "llvm/Support/raw_ostream.h" 43693eedb1SChandler Carruth #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 441353f9a4SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h" 45693eedb1SChandler Carruth #include "llvm/Transforms/Utils/Cloning.h" 461353f9a4SChandler Carruth #include "llvm/Transforms/Utils/LoopUtils.h" 47693eedb1SChandler Carruth #include "llvm/Transforms/Utils/ValueMapper.h" 48a369a457SEugene Zelenko #include <algorithm> 49a369a457SEugene Zelenko #include <cassert> 50a369a457SEugene Zelenko #include <iterator> 51693eedb1SChandler Carruth #include <numeric> 52a369a457SEugene Zelenko #include <utility> 531353f9a4SChandler Carruth 541353f9a4SChandler Carruth #define DEBUG_TYPE "simple-loop-unswitch" 551353f9a4SChandler Carruth 561353f9a4SChandler Carruth using namespace llvm; 571353f9a4SChandler Carruth 581353f9a4SChandler Carruth STATISTIC(NumBranches, "Number of branches unswitched"); 591353f9a4SChandler Carruth STATISTIC(NumSwitches, "Number of switches unswitched"); 601353f9a4SChandler Carruth STATISTIC(NumTrivial, "Number of unswitches that are trivial"); 611353f9a4SChandler Carruth 62693eedb1SChandler Carruth static cl::opt<bool> EnableNonTrivialUnswitch( 63693eedb1SChandler Carruth "enable-nontrivial-unswitch", cl::init(false), cl::Hidden, 64693eedb1SChandler Carruth cl::desc("Forcibly enables non-trivial loop unswitching rather than " 65693eedb1SChandler Carruth "following the configuration passed into the pass.")); 66693eedb1SChandler Carruth 67693eedb1SChandler Carruth static cl::opt<int> 68693eedb1SChandler Carruth UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden, 69693eedb1SChandler Carruth cl::desc("The cost threshold for unswitching a loop.")); 70693eedb1SChandler Carruth 711353f9a4SChandler Carruth static void replaceLoopUsesWithConstant(Loop &L, Value &LIC, 721353f9a4SChandler Carruth Constant &Replacement) { 731353f9a4SChandler Carruth assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?"); 741353f9a4SChandler Carruth 751353f9a4SChandler Carruth // Replace uses of LIC in the loop with the given constant. 761353f9a4SChandler Carruth for (auto UI = LIC.use_begin(), UE = LIC.use_end(); UI != UE;) { 771353f9a4SChandler Carruth // Grab the use and walk past it so we can clobber it in the use list. 781353f9a4SChandler Carruth Use *U = &*UI++; 791353f9a4SChandler Carruth Instruction *UserI = dyn_cast<Instruction>(U->getUser()); 801353f9a4SChandler Carruth if (!UserI || !L.contains(UserI)) 811353f9a4SChandler Carruth continue; 821353f9a4SChandler Carruth 831353f9a4SChandler Carruth // Replace this use within the loop body. 841353f9a4SChandler Carruth *U = &Replacement; 851353f9a4SChandler Carruth } 861353f9a4SChandler Carruth } 871353f9a4SChandler Carruth 88d869b188SChandler Carruth /// Check that all the LCSSA PHI nodes in the loop exit block have trivial 89d869b188SChandler Carruth /// incoming values along this edge. 90d869b188SChandler Carruth static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB, 91d869b188SChandler Carruth BasicBlock &ExitBB) { 92d869b188SChandler Carruth for (Instruction &I : ExitBB) { 93d869b188SChandler Carruth auto *PN = dyn_cast<PHINode>(&I); 94d869b188SChandler Carruth if (!PN) 95d869b188SChandler Carruth // No more PHIs to check. 96d869b188SChandler Carruth return true; 97d869b188SChandler Carruth 98d869b188SChandler Carruth // If the incoming value for this edge isn't loop invariant the unswitch 99d869b188SChandler Carruth // won't be trivial. 100d869b188SChandler Carruth if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB))) 101d869b188SChandler Carruth return false; 102d869b188SChandler Carruth } 103d869b188SChandler Carruth llvm_unreachable("Basic blocks should never be empty!"); 104d869b188SChandler Carruth } 105d869b188SChandler Carruth 106d869b188SChandler Carruth /// Rewrite the PHI nodes in an unswitched loop exit basic block. 107d869b188SChandler Carruth /// 108d869b188SChandler Carruth /// Requires that the loop exit and unswitched basic block are the same, and 109d869b188SChandler Carruth /// that the exiting block was a unique predecessor of that block. Rewrites the 110d869b188SChandler Carruth /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial 111d869b188SChandler Carruth /// PHI nodes from the old preheader that now contains the unswitched 112d869b188SChandler Carruth /// terminator. 113d869b188SChandler Carruth static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB, 114d869b188SChandler Carruth BasicBlock &OldExitingBB, 115d869b188SChandler Carruth BasicBlock &OldPH) { 116c7fc81e6SBenjamin Kramer for (PHINode &PN : UnswitchedBB.phis()) { 117d869b188SChandler Carruth // When the loop exit is directly unswitched we just need to update the 118d869b188SChandler Carruth // incoming basic block. We loop to handle weird cases with repeated 119d869b188SChandler Carruth // incoming blocks, but expect to typically only have one operand here. 120c7fc81e6SBenjamin Kramer for (auto i : seq<int>(0, PN.getNumOperands())) { 121c7fc81e6SBenjamin Kramer assert(PN.getIncomingBlock(i) == &OldExitingBB && 122d869b188SChandler Carruth "Found incoming block different from unique predecessor!"); 123c7fc81e6SBenjamin Kramer PN.setIncomingBlock(i, &OldPH); 124d869b188SChandler Carruth } 125d869b188SChandler Carruth } 126d869b188SChandler Carruth } 127d869b188SChandler Carruth 128d869b188SChandler Carruth /// Rewrite the PHI nodes in the loop exit basic block and the split off 129d869b188SChandler Carruth /// unswitched block. 130d869b188SChandler Carruth /// 131d869b188SChandler Carruth /// Because the exit block remains an exit from the loop, this rewrites the 132d869b188SChandler Carruth /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI 133d869b188SChandler Carruth /// nodes into the unswitched basic block to select between the value in the 134d869b188SChandler Carruth /// old preheader and the loop exit. 135d869b188SChandler Carruth static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB, 136d869b188SChandler Carruth BasicBlock &UnswitchedBB, 137d869b188SChandler Carruth BasicBlock &OldExitingBB, 138d869b188SChandler Carruth BasicBlock &OldPH) { 139d869b188SChandler Carruth assert(&ExitBB != &UnswitchedBB && 140d869b188SChandler Carruth "Must have different loop exit and unswitched blocks!"); 141d869b188SChandler Carruth Instruction *InsertPt = &*UnswitchedBB.begin(); 142c7fc81e6SBenjamin Kramer for (PHINode &PN : ExitBB.phis()) { 143c7fc81e6SBenjamin Kramer auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2, 144c7fc81e6SBenjamin Kramer PN.getName() + ".split", InsertPt); 145d869b188SChandler Carruth 146d869b188SChandler Carruth // Walk backwards over the old PHI node's inputs to minimize the cost of 147d869b188SChandler Carruth // removing each one. We have to do this weird loop manually so that we 148d869b188SChandler Carruth // create the same number of new incoming edges in the new PHI as we expect 149d869b188SChandler Carruth // each case-based edge to be included in the unswitched switch in some 150d869b188SChandler Carruth // cases. 151d869b188SChandler Carruth // FIXME: This is really, really gross. It would be much cleaner if LLVM 152d869b188SChandler Carruth // allowed us to create a single entry for a predecessor block without 153d869b188SChandler Carruth // having separate entries for each "edge" even though these edges are 154d869b188SChandler Carruth // required to produce identical results. 155c7fc81e6SBenjamin Kramer for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) { 156c7fc81e6SBenjamin Kramer if (PN.getIncomingBlock(i) != &OldExitingBB) 157d869b188SChandler Carruth continue; 158d869b188SChandler Carruth 159c7fc81e6SBenjamin Kramer Value *Incoming = PN.removeIncomingValue(i); 160d869b188SChandler Carruth NewPN->addIncoming(Incoming, &OldPH); 161d869b188SChandler Carruth } 162d869b188SChandler Carruth 163d869b188SChandler Carruth // Now replace the old PHI with the new one and wire the old one in as an 164d869b188SChandler Carruth // input to the new one. 165c7fc81e6SBenjamin Kramer PN.replaceAllUsesWith(NewPN); 166c7fc81e6SBenjamin Kramer NewPN->addIncoming(&PN, &ExitBB); 167d869b188SChandler Carruth } 168d869b188SChandler Carruth } 169d869b188SChandler Carruth 1701353f9a4SChandler Carruth /// Unswitch a trivial branch if the condition is loop invariant. 1711353f9a4SChandler Carruth /// 1721353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the branch has 1731353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the 1741353f9a4SChandler Carruth /// condition is invariant and one of the successors is a loop exit. This 1751353f9a4SChandler Carruth /// allows us to unswitch without duplicating the loop, making it trivial. 1761353f9a4SChandler Carruth /// 1771353f9a4SChandler Carruth /// If this routine fails to unswitch the branch it returns false. 1781353f9a4SChandler Carruth /// 1791353f9a4SChandler Carruth /// If the branch can be unswitched, this routine splits the preheader and 1801353f9a4SChandler Carruth /// hoists the branch above that split. Preserves loop simplified form 1811353f9a4SChandler Carruth /// (splitting the exit block as necessary). It simplifies the branch within 1821353f9a4SChandler Carruth /// the loop to an unconditional branch but doesn't remove it entirely. Further 1831353f9a4SChandler Carruth /// cleanup can be done with some simplify-cfg like pass. 1841353f9a4SChandler Carruth static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT, 1851353f9a4SChandler Carruth LoopInfo &LI) { 1861353f9a4SChandler Carruth assert(BI.isConditional() && "Can only unswitch a conditional branch!"); 1871353f9a4SChandler Carruth DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n"); 1881353f9a4SChandler Carruth 1891353f9a4SChandler Carruth Value *LoopCond = BI.getCondition(); 1901353f9a4SChandler Carruth 1911353f9a4SChandler Carruth // Need a trivial loop condition to unswitch. 1921353f9a4SChandler Carruth if (!L.isLoopInvariant(LoopCond)) 1931353f9a4SChandler Carruth return false; 1941353f9a4SChandler Carruth 1951353f9a4SChandler Carruth // Check to see if a successor of the branch is guaranteed to 1961353f9a4SChandler Carruth // exit through a unique exit block without having any 1971353f9a4SChandler Carruth // side-effects. If so, determine the value of Cond that causes 1981353f9a4SChandler Carruth // it to do this. 1991353f9a4SChandler Carruth ConstantInt *CondVal = ConstantInt::getTrue(BI.getContext()); 2001353f9a4SChandler Carruth ConstantInt *Replacement = ConstantInt::getFalse(BI.getContext()); 2011353f9a4SChandler Carruth int LoopExitSuccIdx = 0; 2021353f9a4SChandler Carruth auto *LoopExitBB = BI.getSuccessor(0); 203*baf045fbSChandler Carruth if (L.contains(LoopExitBB)) { 2041353f9a4SChandler Carruth std::swap(CondVal, Replacement); 2051353f9a4SChandler Carruth LoopExitSuccIdx = 1; 2061353f9a4SChandler Carruth LoopExitBB = BI.getSuccessor(1); 207*baf045fbSChandler Carruth if (L.contains(LoopExitBB)) 2081353f9a4SChandler Carruth return false; 2091353f9a4SChandler Carruth } 2101353f9a4SChandler Carruth auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx); 211d869b188SChandler Carruth auto *ParentBB = BI.getParent(); 212d869b188SChandler Carruth if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) 2131353f9a4SChandler Carruth return false; 2141353f9a4SChandler Carruth 2151353f9a4SChandler Carruth DEBUG(dbgs() << " unswitching trivial branch when: " << CondVal 2161353f9a4SChandler Carruth << " == " << LoopCond << "\n"); 2171353f9a4SChandler Carruth 2181353f9a4SChandler Carruth // Split the preheader, so that we know that there is a safe place to insert 2191353f9a4SChandler Carruth // the conditional branch. We will change the preheader to have a conditional 2201353f9a4SChandler Carruth // branch on LoopCond. 2211353f9a4SChandler Carruth BasicBlock *OldPH = L.getLoopPreheader(); 2221353f9a4SChandler Carruth BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI); 2231353f9a4SChandler Carruth 2241353f9a4SChandler Carruth // Now that we have a place to insert the conditional branch, create a place 2251353f9a4SChandler Carruth // to branch to: this is the exit block out of the loop that we are 2261353f9a4SChandler Carruth // unswitching. We need to split this if there are other loop predecessors. 2271353f9a4SChandler Carruth // Because the loop is in simplified form, *any* other predecessor is enough. 2281353f9a4SChandler Carruth BasicBlock *UnswitchedBB; 2291353f9a4SChandler Carruth if (BasicBlock *PredBB = LoopExitBB->getUniquePredecessor()) { 2301353f9a4SChandler Carruth (void)PredBB; 231d869b188SChandler Carruth assert(PredBB == BI.getParent() && 232d869b188SChandler Carruth "A branch's parent isn't a predecessor!"); 2331353f9a4SChandler Carruth UnswitchedBB = LoopExitBB; 2341353f9a4SChandler Carruth } else { 2351353f9a4SChandler Carruth UnswitchedBB = SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI); 2361353f9a4SChandler Carruth } 2371353f9a4SChandler Carruth 2381353f9a4SChandler Carruth // Now splice the branch to gate reaching the new preheader and re-point its 2391353f9a4SChandler Carruth // successors. 2401353f9a4SChandler Carruth OldPH->getInstList().splice(std::prev(OldPH->end()), 2411353f9a4SChandler Carruth BI.getParent()->getInstList(), BI); 2421353f9a4SChandler Carruth OldPH->getTerminator()->eraseFromParent(); 2431353f9a4SChandler Carruth BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB); 2441353f9a4SChandler Carruth BI.setSuccessor(1 - LoopExitSuccIdx, NewPH); 2451353f9a4SChandler Carruth 2461353f9a4SChandler Carruth // Create a new unconditional branch that will continue the loop as a new 2471353f9a4SChandler Carruth // terminator. 2481353f9a4SChandler Carruth BranchInst::Create(ContinueBB, ParentBB); 2491353f9a4SChandler Carruth 250d869b188SChandler Carruth // Rewrite the relevant PHI nodes. 251d869b188SChandler Carruth if (UnswitchedBB == LoopExitBB) 252d869b188SChandler Carruth rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH); 253d869b188SChandler Carruth else 254d869b188SChandler Carruth rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB, 255d869b188SChandler Carruth *ParentBB, *OldPH); 256d869b188SChandler Carruth 2571353f9a4SChandler Carruth // Now we need to update the dominator tree. 2582c85a231SChandler Carruth DT.applyUpdates( 2592c85a231SChandler Carruth {{DT.Delete, ParentBB, UnswitchedBB}, {DT.Insert, OldPH, UnswitchedBB}}); 2601353f9a4SChandler Carruth 2611353f9a4SChandler Carruth // Since this is an i1 condition we can also trivially replace uses of it 2621353f9a4SChandler Carruth // within the loop with a constant. 2631353f9a4SChandler Carruth replaceLoopUsesWithConstant(L, *LoopCond, *Replacement); 2641353f9a4SChandler Carruth 2651353f9a4SChandler Carruth ++NumTrivial; 2661353f9a4SChandler Carruth ++NumBranches; 2671353f9a4SChandler Carruth return true; 2681353f9a4SChandler Carruth } 2691353f9a4SChandler Carruth 2701353f9a4SChandler Carruth /// Unswitch a trivial switch if the condition is loop invariant. 2711353f9a4SChandler Carruth /// 2721353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the switch has 2731353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the 2741353f9a4SChandler Carruth /// condition is invariant and that at least one of the successors is a loop 2751353f9a4SChandler Carruth /// exit. This allows us to unswitch without duplicating the loop, making it 2761353f9a4SChandler Carruth /// trivial. 2771353f9a4SChandler Carruth /// 2781353f9a4SChandler Carruth /// If this routine fails to unswitch the switch it returns false. 2791353f9a4SChandler Carruth /// 2801353f9a4SChandler Carruth /// If the switch can be unswitched, this routine splits the preheader and 2811353f9a4SChandler Carruth /// copies the switch above that split. If the default case is one of the 2821353f9a4SChandler Carruth /// exiting cases, it copies the non-exiting cases and points them at the new 2831353f9a4SChandler Carruth /// preheader. If the default case is not exiting, it copies the exiting cases 2841353f9a4SChandler Carruth /// and points the default at the preheader. It preserves loop simplified form 2851353f9a4SChandler Carruth /// (splitting the exit blocks as necessary). It simplifies the switch within 2861353f9a4SChandler Carruth /// the loop by removing now-dead cases. If the default case is one of those 2871353f9a4SChandler Carruth /// unswitched, it replaces its destination with a new basic block containing 2881353f9a4SChandler Carruth /// only unreachable. Such basic blocks, while technically loop exits, are not 2891353f9a4SChandler Carruth /// considered for unswitching so this is a stable transform and the same 2901353f9a4SChandler Carruth /// switch will not be revisited. If after unswitching there is only a single 2911353f9a4SChandler Carruth /// in-loop successor, the switch is further simplified to an unconditional 2921353f9a4SChandler Carruth /// branch. Still more cleanup can be done with some simplify-cfg like pass. 2931353f9a4SChandler Carruth static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, 2941353f9a4SChandler Carruth LoopInfo &LI) { 2951353f9a4SChandler Carruth DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n"); 2961353f9a4SChandler Carruth Value *LoopCond = SI.getCondition(); 2971353f9a4SChandler Carruth 2981353f9a4SChandler Carruth // If this isn't switching on an invariant condition, we can't unswitch it. 2991353f9a4SChandler Carruth if (!L.isLoopInvariant(LoopCond)) 3001353f9a4SChandler Carruth return false; 3011353f9a4SChandler Carruth 302d869b188SChandler Carruth auto *ParentBB = SI.getParent(); 303d869b188SChandler Carruth 3041353f9a4SChandler Carruth SmallVector<int, 4> ExitCaseIndices; 3051353f9a4SChandler Carruth for (auto Case : SI.cases()) { 3061353f9a4SChandler Carruth auto *SuccBB = Case.getCaseSuccessor(); 307*baf045fbSChandler Carruth if (!L.contains(SuccBB) && 308d869b188SChandler Carruth areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB)) 3091353f9a4SChandler Carruth ExitCaseIndices.push_back(Case.getCaseIndex()); 3101353f9a4SChandler Carruth } 3111353f9a4SChandler Carruth BasicBlock *DefaultExitBB = nullptr; 312*baf045fbSChandler Carruth if (!L.contains(SI.getDefaultDest()) && 313d869b188SChandler Carruth areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) && 3141353f9a4SChandler Carruth !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator())) 3151353f9a4SChandler Carruth DefaultExitBB = SI.getDefaultDest(); 3161353f9a4SChandler Carruth else if (ExitCaseIndices.empty()) 3171353f9a4SChandler Carruth return false; 3181353f9a4SChandler Carruth 3191353f9a4SChandler Carruth DEBUG(dbgs() << " unswitching trivial cases...\n"); 3201353f9a4SChandler Carruth 3211353f9a4SChandler Carruth SmallVector<std::pair<ConstantInt *, BasicBlock *>, 4> ExitCases; 3221353f9a4SChandler Carruth ExitCases.reserve(ExitCaseIndices.size()); 3231353f9a4SChandler Carruth // We walk the case indices backwards so that we remove the last case first 3241353f9a4SChandler Carruth // and don't disrupt the earlier indices. 3251353f9a4SChandler Carruth for (unsigned Index : reverse(ExitCaseIndices)) { 3261353f9a4SChandler Carruth auto CaseI = SI.case_begin() + Index; 3271353f9a4SChandler Carruth // Save the value of this case. 3281353f9a4SChandler Carruth ExitCases.push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()}); 3291353f9a4SChandler Carruth // Delete the unswitched cases. 3301353f9a4SChandler Carruth SI.removeCase(CaseI); 3311353f9a4SChandler Carruth } 3321353f9a4SChandler Carruth 3331353f9a4SChandler Carruth // Check if after this all of the remaining cases point at the same 3341353f9a4SChandler Carruth // successor. 3351353f9a4SChandler Carruth BasicBlock *CommonSuccBB = nullptr; 3361353f9a4SChandler Carruth if (SI.getNumCases() > 0 && 3371353f9a4SChandler Carruth std::all_of(std::next(SI.case_begin()), SI.case_end(), 3381353f9a4SChandler Carruth [&SI](const SwitchInst::CaseHandle &Case) { 3391353f9a4SChandler Carruth return Case.getCaseSuccessor() == 3401353f9a4SChandler Carruth SI.case_begin()->getCaseSuccessor(); 3411353f9a4SChandler Carruth })) 3421353f9a4SChandler Carruth CommonSuccBB = SI.case_begin()->getCaseSuccessor(); 3431353f9a4SChandler Carruth 3441353f9a4SChandler Carruth if (DefaultExitBB) { 3451353f9a4SChandler Carruth // We can't remove the default edge so replace it with an edge to either 3461353f9a4SChandler Carruth // the single common remaining successor (if we have one) or an unreachable 3471353f9a4SChandler Carruth // block. 3481353f9a4SChandler Carruth if (CommonSuccBB) { 3491353f9a4SChandler Carruth SI.setDefaultDest(CommonSuccBB); 3501353f9a4SChandler Carruth } else { 3511353f9a4SChandler Carruth BasicBlock *UnreachableBB = BasicBlock::Create( 3521353f9a4SChandler Carruth ParentBB->getContext(), 3531353f9a4SChandler Carruth Twine(ParentBB->getName()) + ".unreachable_default", 3541353f9a4SChandler Carruth ParentBB->getParent()); 3551353f9a4SChandler Carruth new UnreachableInst(ParentBB->getContext(), UnreachableBB); 3561353f9a4SChandler Carruth SI.setDefaultDest(UnreachableBB); 3571353f9a4SChandler Carruth DT.addNewBlock(UnreachableBB, ParentBB); 3581353f9a4SChandler Carruth } 3591353f9a4SChandler Carruth } else { 3601353f9a4SChandler Carruth // If we're not unswitching the default, we need it to match any cases to 3611353f9a4SChandler Carruth // have a common successor or if we have no cases it is the common 3621353f9a4SChandler Carruth // successor. 3631353f9a4SChandler Carruth if (SI.getNumCases() == 0) 3641353f9a4SChandler Carruth CommonSuccBB = SI.getDefaultDest(); 3651353f9a4SChandler Carruth else if (SI.getDefaultDest() != CommonSuccBB) 3661353f9a4SChandler Carruth CommonSuccBB = nullptr; 3671353f9a4SChandler Carruth } 3681353f9a4SChandler Carruth 3691353f9a4SChandler Carruth // Split the preheader, so that we know that there is a safe place to insert 3701353f9a4SChandler Carruth // the switch. 3711353f9a4SChandler Carruth BasicBlock *OldPH = L.getLoopPreheader(); 3721353f9a4SChandler Carruth BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI); 3731353f9a4SChandler Carruth OldPH->getTerminator()->eraseFromParent(); 3741353f9a4SChandler Carruth 3751353f9a4SChandler Carruth // Now add the unswitched switch. 3761353f9a4SChandler Carruth auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH); 3771353f9a4SChandler Carruth 378d869b188SChandler Carruth // Rewrite the IR for the unswitched basic blocks. This requires two steps. 379d869b188SChandler Carruth // First, we split any exit blocks with remaining in-loop predecessors. Then 380d869b188SChandler Carruth // we update the PHIs in one of two ways depending on if there was a split. 381d869b188SChandler Carruth // We walk in reverse so that we split in the same order as the cases 382d869b188SChandler Carruth // appeared. This is purely for convenience of reading the resulting IR, but 383d869b188SChandler Carruth // it doesn't cost anything really. 384d869b188SChandler Carruth SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs; 3851353f9a4SChandler Carruth SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap; 3861353f9a4SChandler Carruth // Handle the default exit if necessary. 3871353f9a4SChandler Carruth // FIXME: It'd be great if we could merge this with the loop below but LLVM's 3881353f9a4SChandler Carruth // ranges aren't quite powerful enough yet. 389d869b188SChandler Carruth if (DefaultExitBB) { 390d869b188SChandler Carruth if (pred_empty(DefaultExitBB)) { 391d869b188SChandler Carruth UnswitchedExitBBs.insert(DefaultExitBB); 392d869b188SChandler Carruth rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH); 393d869b188SChandler Carruth } else { 3941353f9a4SChandler Carruth auto *SplitBB = 3951353f9a4SChandler Carruth SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI); 396d869b188SChandler Carruth rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB, 397d869b188SChandler Carruth *ParentBB, *OldPH); 3981353f9a4SChandler Carruth DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB; 3991353f9a4SChandler Carruth } 400d869b188SChandler Carruth } 4011353f9a4SChandler Carruth // Note that we must use a reference in the for loop so that we update the 4021353f9a4SChandler Carruth // container. 4031353f9a4SChandler Carruth for (auto &CasePair : reverse(ExitCases)) { 4041353f9a4SChandler Carruth // Grab a reference to the exit block in the pair so that we can update it. 405d869b188SChandler Carruth BasicBlock *ExitBB = CasePair.second; 4061353f9a4SChandler Carruth 4071353f9a4SChandler Carruth // If this case is the last edge into the exit block, we can simply reuse it 4081353f9a4SChandler Carruth // as it will no longer be a loop exit. No mapping necessary. 409d869b188SChandler Carruth if (pred_empty(ExitBB)) { 410d869b188SChandler Carruth // Only rewrite once. 411d869b188SChandler Carruth if (UnswitchedExitBBs.insert(ExitBB).second) 412d869b188SChandler Carruth rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH); 4131353f9a4SChandler Carruth continue; 414d869b188SChandler Carruth } 4151353f9a4SChandler Carruth 4161353f9a4SChandler Carruth // Otherwise we need to split the exit block so that we retain an exit 4171353f9a4SChandler Carruth // block from the loop and a target for the unswitched condition. 4181353f9a4SChandler Carruth BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB]; 4191353f9a4SChandler Carruth if (!SplitExitBB) { 4201353f9a4SChandler Carruth // If this is the first time we see this, do the split and remember it. 4211353f9a4SChandler Carruth SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI); 422d869b188SChandler Carruth rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB, 423d869b188SChandler Carruth *ParentBB, *OldPH); 4241353f9a4SChandler Carruth } 425d869b188SChandler Carruth // Update the case pair to point to the split block. 426d869b188SChandler Carruth CasePair.second = SplitExitBB; 4271353f9a4SChandler Carruth } 4281353f9a4SChandler Carruth 4291353f9a4SChandler Carruth // Now add the unswitched cases. We do this in reverse order as we built them 4301353f9a4SChandler Carruth // in reverse order. 4311353f9a4SChandler Carruth for (auto CasePair : reverse(ExitCases)) { 4321353f9a4SChandler Carruth ConstantInt *CaseVal = CasePair.first; 4331353f9a4SChandler Carruth BasicBlock *UnswitchedBB = CasePair.second; 4341353f9a4SChandler Carruth 4351353f9a4SChandler Carruth NewSI->addCase(CaseVal, UnswitchedBB); 4361353f9a4SChandler Carruth } 4371353f9a4SChandler Carruth 4381353f9a4SChandler Carruth // If the default was unswitched, re-point it and add explicit cases for 4391353f9a4SChandler Carruth // entering the loop. 4401353f9a4SChandler Carruth if (DefaultExitBB) { 4411353f9a4SChandler Carruth NewSI->setDefaultDest(DefaultExitBB); 4421353f9a4SChandler Carruth 4431353f9a4SChandler Carruth // We removed all the exit cases, so we just copy the cases to the 4441353f9a4SChandler Carruth // unswitched switch. 4451353f9a4SChandler Carruth for (auto Case : SI.cases()) 4461353f9a4SChandler Carruth NewSI->addCase(Case.getCaseValue(), NewPH); 4471353f9a4SChandler Carruth } 4481353f9a4SChandler Carruth 4491353f9a4SChandler Carruth // If we ended up with a common successor for every path through the switch 4501353f9a4SChandler Carruth // after unswitching, rewrite it to an unconditional branch to make it easy 4511353f9a4SChandler Carruth // to recognize. Otherwise we potentially have to recognize the default case 4521353f9a4SChandler Carruth // pointing at unreachable and other complexity. 4531353f9a4SChandler Carruth if (CommonSuccBB) { 4541353f9a4SChandler Carruth BasicBlock *BB = SI.getParent(); 4551353f9a4SChandler Carruth SI.eraseFromParent(); 4561353f9a4SChandler Carruth BranchInst::Create(CommonSuccBB, BB); 4571353f9a4SChandler Carruth } 4581353f9a4SChandler Carruth 4592c85a231SChandler Carruth // Walk the unswitched exit blocks and the unswitched split blocks and update 4602c85a231SChandler Carruth // the dominator tree based on the CFG edits. While we are walking unordered 4612c85a231SChandler Carruth // containers here, the API for applyUpdates takes an unordered list of 4622c85a231SChandler Carruth // updates and requires them to not contain duplicates. 4632c85a231SChandler Carruth SmallVector<DominatorTree::UpdateType, 4> DTUpdates; 4642c85a231SChandler Carruth for (auto *UnswitchedExitBB : UnswitchedExitBBs) { 4652c85a231SChandler Carruth DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB}); 4662c85a231SChandler Carruth DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB}); 4672c85a231SChandler Carruth } 4682c85a231SChandler Carruth for (auto SplitUnswitchedPair : SplitExitBBMap) { 4692c85a231SChandler Carruth auto *UnswitchedBB = SplitUnswitchedPair.second; 4702c85a231SChandler Carruth DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedBB}); 4712c85a231SChandler Carruth DTUpdates.push_back({DT.Insert, OldPH, UnswitchedBB}); 4722c85a231SChandler Carruth } 4732c85a231SChandler Carruth DT.applyUpdates(DTUpdates); 4742c85a231SChandler Carruth 4757c35de12SDavid Green assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 4761353f9a4SChandler Carruth ++NumTrivial; 4771353f9a4SChandler Carruth ++NumSwitches; 4781353f9a4SChandler Carruth return true; 4791353f9a4SChandler Carruth } 4801353f9a4SChandler Carruth 4811353f9a4SChandler Carruth /// This routine scans the loop to find a branch or switch which occurs before 4821353f9a4SChandler Carruth /// any side effects occur. These can potentially be unswitched without 4831353f9a4SChandler Carruth /// duplicating the loop. If a branch or switch is successfully unswitched the 4841353f9a4SChandler Carruth /// scanning continues to see if subsequent branches or switches have become 4851353f9a4SChandler Carruth /// trivial. Once all trivial candidates have been unswitched, this routine 4861353f9a4SChandler Carruth /// returns. 4871353f9a4SChandler Carruth /// 4881353f9a4SChandler Carruth /// The return value indicates whether anything was unswitched (and therefore 4891353f9a4SChandler Carruth /// changed). 4901353f9a4SChandler Carruth static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT, 4911353f9a4SChandler Carruth LoopInfo &LI) { 4921353f9a4SChandler Carruth bool Changed = false; 4931353f9a4SChandler Carruth 4941353f9a4SChandler Carruth // If loop header has only one reachable successor we should keep looking for 4951353f9a4SChandler Carruth // trivial condition candidates in the successor as well. An alternative is 4961353f9a4SChandler Carruth // to constant fold conditions and merge successors into loop header (then we 4971353f9a4SChandler Carruth // only need to check header's terminator). The reason for not doing this in 4981353f9a4SChandler Carruth // LoopUnswitch pass is that it could potentially break LoopPassManager's 4991353f9a4SChandler Carruth // invariants. Folding dead branches could either eliminate the current loop 5001353f9a4SChandler Carruth // or make other loops unreachable. LCSSA form might also not be preserved 5011353f9a4SChandler Carruth // after deleting branches. The following code keeps traversing loop header's 5021353f9a4SChandler Carruth // successors until it finds the trivial condition candidate (condition that 5031353f9a4SChandler Carruth // is not a constant). Since unswitching generates branches with constant 5041353f9a4SChandler Carruth // conditions, this scenario could be very common in practice. 5051353f9a4SChandler Carruth BasicBlock *CurrentBB = L.getHeader(); 5061353f9a4SChandler Carruth SmallPtrSet<BasicBlock *, 8> Visited; 5071353f9a4SChandler Carruth Visited.insert(CurrentBB); 5081353f9a4SChandler Carruth do { 5091353f9a4SChandler Carruth // Check if there are any side-effecting instructions (e.g. stores, calls, 5101353f9a4SChandler Carruth // volatile loads) in the part of the loop that the code *would* execute 5111353f9a4SChandler Carruth // without unswitching. 5121353f9a4SChandler Carruth if (llvm::any_of(*CurrentBB, 5131353f9a4SChandler Carruth [](Instruction &I) { return I.mayHaveSideEffects(); })) 5141353f9a4SChandler Carruth return Changed; 5151353f9a4SChandler Carruth 5161353f9a4SChandler Carruth TerminatorInst *CurrentTerm = CurrentBB->getTerminator(); 5171353f9a4SChandler Carruth 5181353f9a4SChandler Carruth if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) { 5191353f9a4SChandler Carruth // Don't bother trying to unswitch past a switch with a constant 5201353f9a4SChandler Carruth // condition. This should be removed prior to running this pass by 5211353f9a4SChandler Carruth // simplify-cfg. 5221353f9a4SChandler Carruth if (isa<Constant>(SI->getCondition())) 5231353f9a4SChandler Carruth return Changed; 5241353f9a4SChandler Carruth 5251353f9a4SChandler Carruth if (!unswitchTrivialSwitch(L, *SI, DT, LI)) 5261353f9a4SChandler Carruth // Coludn't unswitch this one so we're done. 5271353f9a4SChandler Carruth return Changed; 5281353f9a4SChandler Carruth 5291353f9a4SChandler Carruth // Mark that we managed to unswitch something. 5301353f9a4SChandler Carruth Changed = true; 5311353f9a4SChandler Carruth 5321353f9a4SChandler Carruth // If unswitching turned the terminator into an unconditional branch then 5331353f9a4SChandler Carruth // we can continue. The unswitching logic specifically works to fold any 5341353f9a4SChandler Carruth // cases it can into an unconditional branch to make it easier to 5351353f9a4SChandler Carruth // recognize here. 5361353f9a4SChandler Carruth auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator()); 5371353f9a4SChandler Carruth if (!BI || BI->isConditional()) 5381353f9a4SChandler Carruth return Changed; 5391353f9a4SChandler Carruth 5401353f9a4SChandler Carruth CurrentBB = BI->getSuccessor(0); 5411353f9a4SChandler Carruth continue; 5421353f9a4SChandler Carruth } 5431353f9a4SChandler Carruth 5441353f9a4SChandler Carruth auto *BI = dyn_cast<BranchInst>(CurrentTerm); 5451353f9a4SChandler Carruth if (!BI) 5461353f9a4SChandler Carruth // We do not understand other terminator instructions. 5471353f9a4SChandler Carruth return Changed; 5481353f9a4SChandler Carruth 5491353f9a4SChandler Carruth // Don't bother trying to unswitch past an unconditional branch or a branch 5501353f9a4SChandler Carruth // with a constant value. These should be removed by simplify-cfg prior to 5511353f9a4SChandler Carruth // running this pass. 5521353f9a4SChandler Carruth if (!BI->isConditional() || isa<Constant>(BI->getCondition())) 5531353f9a4SChandler Carruth return Changed; 5541353f9a4SChandler Carruth 5551353f9a4SChandler Carruth // Found a trivial condition candidate: non-foldable conditional branch. If 5561353f9a4SChandler Carruth // we fail to unswitch this, we can't do anything else that is trivial. 5571353f9a4SChandler Carruth if (!unswitchTrivialBranch(L, *BI, DT, LI)) 5581353f9a4SChandler Carruth return Changed; 5591353f9a4SChandler Carruth 5601353f9a4SChandler Carruth // Mark that we managed to unswitch something. 5611353f9a4SChandler Carruth Changed = true; 5621353f9a4SChandler Carruth 5631353f9a4SChandler Carruth // We unswitched the branch. This should always leave us with an 5641353f9a4SChandler Carruth // unconditional branch that we can follow now. 5651353f9a4SChandler Carruth BI = cast<BranchInst>(CurrentBB->getTerminator()); 5661353f9a4SChandler Carruth assert(!BI->isConditional() && 5671353f9a4SChandler Carruth "Cannot form a conditional branch by unswitching1"); 5681353f9a4SChandler Carruth CurrentBB = BI->getSuccessor(0); 5691353f9a4SChandler Carruth 5701353f9a4SChandler Carruth // When continuing, if we exit the loop or reach a previous visited block, 5711353f9a4SChandler Carruth // then we can not reach any trivial condition candidates (unfoldable 5721353f9a4SChandler Carruth // branch instructions or switch instructions) and no unswitch can happen. 5731353f9a4SChandler Carruth } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second); 5741353f9a4SChandler Carruth 5751353f9a4SChandler Carruth return Changed; 5761353f9a4SChandler Carruth } 5771353f9a4SChandler Carruth 578693eedb1SChandler Carruth /// Build the cloned blocks for an unswitched copy of the given loop. 579693eedb1SChandler Carruth /// 580693eedb1SChandler Carruth /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and 581693eedb1SChandler Carruth /// after the split block (`SplitBB`) that will be used to select between the 582693eedb1SChandler Carruth /// cloned and original loop. 583693eedb1SChandler Carruth /// 584693eedb1SChandler Carruth /// This routine handles cloning all of the necessary loop blocks and exit 585693eedb1SChandler Carruth /// blocks including rewriting their instructions and the relevant PHI nodes. 586693eedb1SChandler Carruth /// It skips loop and exit blocks that are not necessary based on the provided 587693eedb1SChandler Carruth /// set. It also correctly creates the unconditional branch in the cloned 588693eedb1SChandler Carruth /// unswitched parent block to only point at the unswitched successor. 589693eedb1SChandler Carruth /// 590693eedb1SChandler Carruth /// This does not handle most of the necessary updates to `LoopInfo`. Only exit 591693eedb1SChandler Carruth /// block splitting is correctly reflected in `LoopInfo`, essentially all of 592693eedb1SChandler Carruth /// the cloned blocks (and their loops) are left without full `LoopInfo` 593693eedb1SChandler Carruth /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned 594693eedb1SChandler Carruth /// blocks to them but doesn't create the cloned `DominatorTree` structure and 595693eedb1SChandler Carruth /// instead the caller must recompute an accurate DT. It *does* correctly 596693eedb1SChandler Carruth /// update the `AssumptionCache` provided in `AC`. 597693eedb1SChandler Carruth static BasicBlock *buildClonedLoopBlocks( 598693eedb1SChandler Carruth Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB, 599693eedb1SChandler Carruth ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB, 600693eedb1SChandler Carruth BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB, 601693eedb1SChandler Carruth const SmallPtrSetImpl<BasicBlock *> &SkippedLoopAndExitBlocks, 60269e68f84SChandler Carruth ValueToValueMapTy &VMap, 60369e68f84SChandler Carruth SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC, 60469e68f84SChandler Carruth DominatorTree &DT, LoopInfo &LI) { 605693eedb1SChandler Carruth SmallVector<BasicBlock *, 4> NewBlocks; 606693eedb1SChandler Carruth NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size()); 607693eedb1SChandler Carruth 608693eedb1SChandler Carruth // We will need to clone a bunch of blocks, wrap up the clone operation in 609693eedb1SChandler Carruth // a helper. 610693eedb1SChandler Carruth auto CloneBlock = [&](BasicBlock *OldBB) { 611693eedb1SChandler Carruth // Clone the basic block and insert it before the new preheader. 612693eedb1SChandler Carruth BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent()); 613693eedb1SChandler Carruth NewBB->moveBefore(LoopPH); 614693eedb1SChandler Carruth 615693eedb1SChandler Carruth // Record this block and the mapping. 616693eedb1SChandler Carruth NewBlocks.push_back(NewBB); 617693eedb1SChandler Carruth VMap[OldBB] = NewBB; 618693eedb1SChandler Carruth 619693eedb1SChandler Carruth return NewBB; 620693eedb1SChandler Carruth }; 621693eedb1SChandler Carruth 622693eedb1SChandler Carruth // First, clone the preheader. 623693eedb1SChandler Carruth auto *ClonedPH = CloneBlock(LoopPH); 624693eedb1SChandler Carruth 625693eedb1SChandler Carruth // Then clone all the loop blocks, skipping the ones that aren't necessary. 626693eedb1SChandler Carruth for (auto *LoopBB : L.blocks()) 627693eedb1SChandler Carruth if (!SkippedLoopAndExitBlocks.count(LoopBB)) 628693eedb1SChandler Carruth CloneBlock(LoopBB); 629693eedb1SChandler Carruth 630693eedb1SChandler Carruth // Split all the loop exit edges so that when we clone the exit blocks, if 631693eedb1SChandler Carruth // any of the exit blocks are *also* a preheader for some other loop, we 632693eedb1SChandler Carruth // don't create multiple predecessors entering the loop header. 633693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) { 634693eedb1SChandler Carruth if (SkippedLoopAndExitBlocks.count(ExitBB)) 635693eedb1SChandler Carruth continue; 636693eedb1SChandler Carruth 637693eedb1SChandler Carruth // When we are going to clone an exit, we don't need to clone all the 638693eedb1SChandler Carruth // instructions in the exit block and we want to ensure we have an easy 639693eedb1SChandler Carruth // place to merge the CFG, so split the exit first. This is always safe to 640693eedb1SChandler Carruth // do because there cannot be any non-loop predecessors of a loop exit in 641693eedb1SChandler Carruth // loop simplified form. 642693eedb1SChandler Carruth auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI); 643693eedb1SChandler Carruth 644693eedb1SChandler Carruth // Rearrange the names to make it easier to write test cases by having the 645693eedb1SChandler Carruth // exit block carry the suffix rather than the merge block carrying the 646693eedb1SChandler Carruth // suffix. 647693eedb1SChandler Carruth MergeBB->takeName(ExitBB); 648693eedb1SChandler Carruth ExitBB->setName(Twine(MergeBB->getName()) + ".split"); 649693eedb1SChandler Carruth 650693eedb1SChandler Carruth // Now clone the original exit block. 651693eedb1SChandler Carruth auto *ClonedExitBB = CloneBlock(ExitBB); 652693eedb1SChandler Carruth assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 && 653693eedb1SChandler Carruth "Exit block should have been split to have one successor!"); 654693eedb1SChandler Carruth assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB && 655693eedb1SChandler Carruth "Cloned exit block has the wrong successor!"); 656693eedb1SChandler Carruth 657693eedb1SChandler Carruth // Remap any cloned instructions and create a merge phi node for them. 658693eedb1SChandler Carruth for (auto ZippedInsts : llvm::zip_first( 659693eedb1SChandler Carruth llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())), 660693eedb1SChandler Carruth llvm::make_range(ClonedExitBB->begin(), 661693eedb1SChandler Carruth std::prev(ClonedExitBB->end())))) { 662693eedb1SChandler Carruth Instruction &I = std::get<0>(ZippedInsts); 663693eedb1SChandler Carruth Instruction &ClonedI = std::get<1>(ZippedInsts); 664693eedb1SChandler Carruth 665693eedb1SChandler Carruth // The only instructions in the exit block should be PHI nodes and 666693eedb1SChandler Carruth // potentially a landing pad. 667693eedb1SChandler Carruth assert( 668693eedb1SChandler Carruth (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) && 669693eedb1SChandler Carruth "Bad instruction in exit block!"); 670693eedb1SChandler Carruth // We should have a value map between the instruction and its clone. 671693eedb1SChandler Carruth assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!"); 672693eedb1SChandler Carruth 673693eedb1SChandler Carruth auto *MergePN = 674693eedb1SChandler Carruth PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi", 675693eedb1SChandler Carruth &*MergeBB->getFirstInsertionPt()); 676693eedb1SChandler Carruth I.replaceAllUsesWith(MergePN); 677693eedb1SChandler Carruth MergePN->addIncoming(&I, ExitBB); 678693eedb1SChandler Carruth MergePN->addIncoming(&ClonedI, ClonedExitBB); 679693eedb1SChandler Carruth } 680693eedb1SChandler Carruth } 681693eedb1SChandler Carruth 682693eedb1SChandler Carruth // Rewrite the instructions in the cloned blocks to refer to the instructions 683693eedb1SChandler Carruth // in the cloned blocks. We have to do this as a second pass so that we have 684693eedb1SChandler Carruth // everything available. Also, we have inserted new instructions which may 685693eedb1SChandler Carruth // include assume intrinsics, so we update the assumption cache while 686693eedb1SChandler Carruth // processing this. 687693eedb1SChandler Carruth for (auto *ClonedBB : NewBlocks) 688693eedb1SChandler Carruth for (Instruction &I : *ClonedBB) { 689693eedb1SChandler Carruth RemapInstruction(&I, VMap, 690693eedb1SChandler Carruth RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 691693eedb1SChandler Carruth if (auto *II = dyn_cast<IntrinsicInst>(&I)) 692693eedb1SChandler Carruth if (II->getIntrinsicID() == Intrinsic::assume) 693693eedb1SChandler Carruth AC.registerAssumption(II); 694693eedb1SChandler Carruth } 695693eedb1SChandler Carruth 696693eedb1SChandler Carruth // Remove the cloned parent as a predecessor of the cloned continue successor 697693eedb1SChandler Carruth // if we did in fact clone it. 698693eedb1SChandler Carruth auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB)); 699693eedb1SChandler Carruth if (auto *ClonedContinueSuccBB = 700693eedb1SChandler Carruth cast_or_null<BasicBlock>(VMap.lookup(ContinueSuccBB))) 701693eedb1SChandler Carruth ClonedContinueSuccBB->removePredecessor(ClonedParentBB, 702693eedb1SChandler Carruth /*DontDeleteUselessPHIs*/ true); 703b5254241SChandler Carruth // Replace the cloned branch with an unconditional branch to the cloned 704693eedb1SChandler Carruth // unswitched successor. 705693eedb1SChandler Carruth auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB)); 706693eedb1SChandler Carruth ClonedParentBB->getTerminator()->eraseFromParent(); 707693eedb1SChandler Carruth BranchInst::Create(ClonedSuccBB, ClonedParentBB); 708693eedb1SChandler Carruth 709693eedb1SChandler Carruth // Update any PHI nodes in the cloned successors of the skipped blocks to not 710693eedb1SChandler Carruth // have spurious incoming values. 711693eedb1SChandler Carruth for (auto *LoopBB : L.blocks()) 712693eedb1SChandler Carruth if (SkippedLoopAndExitBlocks.count(LoopBB)) 713693eedb1SChandler Carruth for (auto *SuccBB : successors(LoopBB)) 714693eedb1SChandler Carruth if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB))) 715693eedb1SChandler Carruth for (PHINode &PN : ClonedSuccBB->phis()) 716693eedb1SChandler Carruth PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false); 717693eedb1SChandler Carruth 71869e68f84SChandler Carruth // Record the domtree updates for the new blocks. 71944aab925SChandler Carruth SmallPtrSet<BasicBlock *, 4> SuccSet; 72044aab925SChandler Carruth for (auto *ClonedBB : NewBlocks) { 72169e68f84SChandler Carruth for (auto *SuccBB : successors(ClonedBB)) 72244aab925SChandler Carruth if (SuccSet.insert(SuccBB).second) 72369e68f84SChandler Carruth DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB}); 72444aab925SChandler Carruth SuccSet.clear(); 72544aab925SChandler Carruth } 72669e68f84SChandler Carruth 727693eedb1SChandler Carruth return ClonedPH; 728693eedb1SChandler Carruth } 729693eedb1SChandler Carruth 730693eedb1SChandler Carruth /// Recursively clone the specified loop and all of its children. 731693eedb1SChandler Carruth /// 732693eedb1SChandler Carruth /// The target parent loop for the clone should be provided, or can be null if 733693eedb1SChandler Carruth /// the clone is a top-level loop. While cloning, all the blocks are mapped 734693eedb1SChandler Carruth /// with the provided value map. The entire original loop must be present in 735693eedb1SChandler Carruth /// the value map. The cloned loop is returned. 736693eedb1SChandler Carruth static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL, 737693eedb1SChandler Carruth const ValueToValueMapTy &VMap, LoopInfo &LI) { 738693eedb1SChandler Carruth auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) { 739693eedb1SChandler Carruth assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!"); 740693eedb1SChandler Carruth ClonedL.reserveBlocks(OrigL.getNumBlocks()); 741693eedb1SChandler Carruth for (auto *BB : OrigL.blocks()) { 742693eedb1SChandler Carruth auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB)); 743693eedb1SChandler Carruth ClonedL.addBlockEntry(ClonedBB); 7440ace148cSChandler Carruth if (LI.getLoopFor(BB) == &OrigL) 745693eedb1SChandler Carruth LI.changeLoopFor(ClonedBB, &ClonedL); 746693eedb1SChandler Carruth } 747693eedb1SChandler Carruth }; 748693eedb1SChandler Carruth 749693eedb1SChandler Carruth // We specially handle the first loop because it may get cloned into 750693eedb1SChandler Carruth // a different parent and because we most commonly are cloning leaf loops. 751693eedb1SChandler Carruth Loop *ClonedRootL = LI.AllocateLoop(); 752693eedb1SChandler Carruth if (RootParentL) 753693eedb1SChandler Carruth RootParentL->addChildLoop(ClonedRootL); 754693eedb1SChandler Carruth else 755693eedb1SChandler Carruth LI.addTopLevelLoop(ClonedRootL); 756693eedb1SChandler Carruth AddClonedBlocksToLoop(OrigRootL, *ClonedRootL); 757693eedb1SChandler Carruth 758693eedb1SChandler Carruth if (OrigRootL.empty()) 759693eedb1SChandler Carruth return ClonedRootL; 760693eedb1SChandler Carruth 761693eedb1SChandler Carruth // If we have a nest, we can quickly clone the entire loop nest using an 762693eedb1SChandler Carruth // iterative approach because it is a tree. We keep the cloned parent in the 763693eedb1SChandler Carruth // data structure to avoid repeatedly querying through a map to find it. 764693eedb1SChandler Carruth SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone; 765693eedb1SChandler Carruth // Build up the loops to clone in reverse order as we'll clone them from the 766693eedb1SChandler Carruth // back. 767693eedb1SChandler Carruth for (Loop *ChildL : llvm::reverse(OrigRootL)) 768693eedb1SChandler Carruth LoopsToClone.push_back({ClonedRootL, ChildL}); 769693eedb1SChandler Carruth do { 770693eedb1SChandler Carruth Loop *ClonedParentL, *L; 771693eedb1SChandler Carruth std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val(); 772693eedb1SChandler Carruth Loop *ClonedL = LI.AllocateLoop(); 773693eedb1SChandler Carruth ClonedParentL->addChildLoop(ClonedL); 774693eedb1SChandler Carruth AddClonedBlocksToLoop(*L, *ClonedL); 775693eedb1SChandler Carruth for (Loop *ChildL : llvm::reverse(*L)) 776693eedb1SChandler Carruth LoopsToClone.push_back({ClonedL, ChildL}); 777693eedb1SChandler Carruth } while (!LoopsToClone.empty()); 778693eedb1SChandler Carruth 779693eedb1SChandler Carruth return ClonedRootL; 780693eedb1SChandler Carruth } 781693eedb1SChandler Carruth 782693eedb1SChandler Carruth /// Build the cloned loops of an original loop from unswitching. 783693eedb1SChandler Carruth /// 784693eedb1SChandler Carruth /// Because unswitching simplifies the CFG of the loop, this isn't a trivial 785693eedb1SChandler Carruth /// operation. We need to re-verify that there even is a loop (as the backedge 786693eedb1SChandler Carruth /// may not have been cloned), and even if there are remaining backedges the 787693eedb1SChandler Carruth /// backedge set may be different. However, we know that each child loop is 788693eedb1SChandler Carruth /// undisturbed, we only need to find where to place each child loop within 789693eedb1SChandler Carruth /// either any parent loop or within a cloned version of the original loop. 790693eedb1SChandler Carruth /// 791693eedb1SChandler Carruth /// Because child loops may end up cloned outside of any cloned version of the 792693eedb1SChandler Carruth /// original loop, multiple cloned sibling loops may be created. All of them 793693eedb1SChandler Carruth /// are returned so that the newly introduced loop nest roots can be 794693eedb1SChandler Carruth /// identified. 795693eedb1SChandler Carruth static Loop *buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks, 796693eedb1SChandler Carruth const ValueToValueMapTy &VMap, LoopInfo &LI, 797693eedb1SChandler Carruth SmallVectorImpl<Loop *> &NonChildClonedLoops) { 798693eedb1SChandler Carruth Loop *ClonedL = nullptr; 799693eedb1SChandler Carruth 800693eedb1SChandler Carruth auto *OrigPH = OrigL.getLoopPreheader(); 801693eedb1SChandler Carruth auto *OrigHeader = OrigL.getHeader(); 802693eedb1SChandler Carruth 803693eedb1SChandler Carruth auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH)); 804693eedb1SChandler Carruth auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader)); 805693eedb1SChandler Carruth 806693eedb1SChandler Carruth // We need to know the loops of the cloned exit blocks to even compute the 807693eedb1SChandler Carruth // accurate parent loop. If we only clone exits to some parent of the 808693eedb1SChandler Carruth // original parent, we want to clone into that outer loop. We also keep track 809693eedb1SChandler Carruth // of the loops that our cloned exit blocks participate in. 810693eedb1SChandler Carruth Loop *ParentL = nullptr; 811693eedb1SChandler Carruth SmallVector<BasicBlock *, 4> ClonedExitsInLoops; 812693eedb1SChandler Carruth SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap; 813693eedb1SChandler Carruth ClonedExitsInLoops.reserve(ExitBlocks.size()); 814693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) 815693eedb1SChandler Carruth if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB))) 816693eedb1SChandler Carruth if (Loop *ExitL = LI.getLoopFor(ExitBB)) { 817693eedb1SChandler Carruth ExitLoopMap[ClonedExitBB] = ExitL; 818693eedb1SChandler Carruth ClonedExitsInLoops.push_back(ClonedExitBB); 819693eedb1SChandler Carruth if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL))) 820693eedb1SChandler Carruth ParentL = ExitL; 821693eedb1SChandler Carruth } 822693eedb1SChandler Carruth assert((!ParentL || ParentL == OrigL.getParentLoop() || 823693eedb1SChandler Carruth ParentL->contains(OrigL.getParentLoop())) && 824693eedb1SChandler Carruth "The computed parent loop should always contain (or be) the parent of " 825693eedb1SChandler Carruth "the original loop."); 826693eedb1SChandler Carruth 827693eedb1SChandler Carruth // We build the set of blocks dominated by the cloned header from the set of 828693eedb1SChandler Carruth // cloned blocks out of the original loop. While not all of these will 829693eedb1SChandler Carruth // necessarily be in the cloned loop, it is enough to establish that they 830693eedb1SChandler Carruth // aren't in unreachable cycles, etc. 831693eedb1SChandler Carruth SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks; 832693eedb1SChandler Carruth for (auto *BB : OrigL.blocks()) 833693eedb1SChandler Carruth if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB))) 834693eedb1SChandler Carruth ClonedLoopBlocks.insert(ClonedBB); 835693eedb1SChandler Carruth 836693eedb1SChandler Carruth // Rebuild the set of blocks that will end up in the cloned loop. We may have 837693eedb1SChandler Carruth // skipped cloning some region of this loop which can in turn skip some of 838693eedb1SChandler Carruth // the backedges so we have to rebuild the blocks in the loop based on the 839693eedb1SChandler Carruth // backedges that remain after cloning. 840693eedb1SChandler Carruth SmallVector<BasicBlock *, 16> Worklist; 841693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop; 842693eedb1SChandler Carruth for (auto *Pred : predecessors(ClonedHeader)) { 843693eedb1SChandler Carruth // The only possible non-loop header predecessor is the preheader because 844693eedb1SChandler Carruth // we know we cloned the loop in simplified form. 845693eedb1SChandler Carruth if (Pred == ClonedPH) 846693eedb1SChandler Carruth continue; 847693eedb1SChandler Carruth 848693eedb1SChandler Carruth // Because the loop was in simplified form, the only non-loop predecessor 849693eedb1SChandler Carruth // should be the preheader. 850693eedb1SChandler Carruth assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop " 851693eedb1SChandler Carruth "header other than the preheader " 852693eedb1SChandler Carruth "that is not part of the loop!"); 853693eedb1SChandler Carruth 854693eedb1SChandler Carruth // Insert this block into the loop set and on the first visit (and if it 855693eedb1SChandler Carruth // isn't the header we're currently walking) put it into the worklist to 856693eedb1SChandler Carruth // recurse through. 857693eedb1SChandler Carruth if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader) 858693eedb1SChandler Carruth Worklist.push_back(Pred); 859693eedb1SChandler Carruth } 860693eedb1SChandler Carruth 861693eedb1SChandler Carruth // If we had any backedges then there *is* a cloned loop. Put the header into 862693eedb1SChandler Carruth // the loop set and then walk the worklist backwards to find all the blocks 863693eedb1SChandler Carruth // that remain within the loop after cloning. 864693eedb1SChandler Carruth if (!BlocksInClonedLoop.empty()) { 865693eedb1SChandler Carruth BlocksInClonedLoop.insert(ClonedHeader); 866693eedb1SChandler Carruth 867693eedb1SChandler Carruth while (!Worklist.empty()) { 868693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val(); 869693eedb1SChandler Carruth assert(BlocksInClonedLoop.count(BB) && 870693eedb1SChandler Carruth "Didn't put block into the loop set!"); 871693eedb1SChandler Carruth 872693eedb1SChandler Carruth // Insert any predecessors that are in the possible set into the cloned 873693eedb1SChandler Carruth // set, and if the insert is successful, add them to the worklist. Note 874693eedb1SChandler Carruth // that we filter on the blocks that are definitely reachable via the 875693eedb1SChandler Carruth // backedge to the loop header so we may prune out dead code within the 876693eedb1SChandler Carruth // cloned loop. 877693eedb1SChandler Carruth for (auto *Pred : predecessors(BB)) 878693eedb1SChandler Carruth if (ClonedLoopBlocks.count(Pred) && 879693eedb1SChandler Carruth BlocksInClonedLoop.insert(Pred).second) 880693eedb1SChandler Carruth Worklist.push_back(Pred); 881693eedb1SChandler Carruth } 882693eedb1SChandler Carruth 883693eedb1SChandler Carruth ClonedL = LI.AllocateLoop(); 884693eedb1SChandler Carruth if (ParentL) { 885693eedb1SChandler Carruth ParentL->addBasicBlockToLoop(ClonedPH, LI); 886693eedb1SChandler Carruth ParentL->addChildLoop(ClonedL); 887693eedb1SChandler Carruth } else { 888693eedb1SChandler Carruth LI.addTopLevelLoop(ClonedL); 889693eedb1SChandler Carruth } 890693eedb1SChandler Carruth 891693eedb1SChandler Carruth ClonedL->reserveBlocks(BlocksInClonedLoop.size()); 892693eedb1SChandler Carruth // We don't want to just add the cloned loop blocks based on how we 893693eedb1SChandler Carruth // discovered them. The original order of blocks was carefully built in 894693eedb1SChandler Carruth // a way that doesn't rely on predecessor ordering. Rather than re-invent 895693eedb1SChandler Carruth // that logic, we just re-walk the original blocks (and those of the child 896693eedb1SChandler Carruth // loops) and filter them as we add them into the cloned loop. 897693eedb1SChandler Carruth for (auto *BB : OrigL.blocks()) { 898693eedb1SChandler Carruth auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)); 899693eedb1SChandler Carruth if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB)) 900693eedb1SChandler Carruth continue; 901693eedb1SChandler Carruth 902693eedb1SChandler Carruth // Directly add the blocks that are only in this loop. 903693eedb1SChandler Carruth if (LI.getLoopFor(BB) == &OrigL) { 904693eedb1SChandler Carruth ClonedL->addBasicBlockToLoop(ClonedBB, LI); 905693eedb1SChandler Carruth continue; 906693eedb1SChandler Carruth } 907693eedb1SChandler Carruth 908693eedb1SChandler Carruth // We want to manually add it to this loop and parents. 909693eedb1SChandler Carruth // Registering it with LoopInfo will happen when we clone the top 910693eedb1SChandler Carruth // loop for this block. 911693eedb1SChandler Carruth for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop()) 912693eedb1SChandler Carruth PL->addBlockEntry(ClonedBB); 913693eedb1SChandler Carruth } 914693eedb1SChandler Carruth 915693eedb1SChandler Carruth // Now add each child loop whose header remains within the cloned loop. All 916693eedb1SChandler Carruth // of the blocks within the loop must satisfy the same constraints as the 917693eedb1SChandler Carruth // header so once we pass the header checks we can just clone the entire 918693eedb1SChandler Carruth // child loop nest. 919693eedb1SChandler Carruth for (Loop *ChildL : OrigL) { 920693eedb1SChandler Carruth auto *ClonedChildHeader = 921693eedb1SChandler Carruth cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader())); 922693eedb1SChandler Carruth if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader)) 923693eedb1SChandler Carruth continue; 924693eedb1SChandler Carruth 925693eedb1SChandler Carruth #ifndef NDEBUG 926693eedb1SChandler Carruth // We should never have a cloned child loop header but fail to have 927693eedb1SChandler Carruth // all of the blocks for that child loop. 928693eedb1SChandler Carruth for (auto *ChildLoopBB : ChildL->blocks()) 929693eedb1SChandler Carruth assert(BlocksInClonedLoop.count( 930693eedb1SChandler Carruth cast<BasicBlock>(VMap.lookup(ChildLoopBB))) && 931693eedb1SChandler Carruth "Child cloned loop has a header within the cloned outer " 932693eedb1SChandler Carruth "loop but not all of its blocks!"); 933693eedb1SChandler Carruth #endif 934693eedb1SChandler Carruth 935693eedb1SChandler Carruth cloneLoopNest(*ChildL, ClonedL, VMap, LI); 936693eedb1SChandler Carruth } 937693eedb1SChandler Carruth } 938693eedb1SChandler Carruth 939693eedb1SChandler Carruth // Now that we've handled all the components of the original loop that were 940693eedb1SChandler Carruth // cloned into a new loop, we still need to handle anything from the original 941693eedb1SChandler Carruth // loop that wasn't in a cloned loop. 942693eedb1SChandler Carruth 943693eedb1SChandler Carruth // Figure out what blocks are left to place within any loop nest containing 944693eedb1SChandler Carruth // the unswitched loop. If we never formed a loop, the cloned PH is one of 945693eedb1SChandler Carruth // them. 946693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet; 947693eedb1SChandler Carruth if (BlocksInClonedLoop.empty()) 948693eedb1SChandler Carruth UnloopedBlockSet.insert(ClonedPH); 949693eedb1SChandler Carruth for (auto *ClonedBB : ClonedLoopBlocks) 950693eedb1SChandler Carruth if (!BlocksInClonedLoop.count(ClonedBB)) 951693eedb1SChandler Carruth UnloopedBlockSet.insert(ClonedBB); 952693eedb1SChandler Carruth 953693eedb1SChandler Carruth // Copy the cloned exits and sort them in ascending loop depth, we'll work 954693eedb1SChandler Carruth // backwards across these to process them inside out. The order shouldn't 955693eedb1SChandler Carruth // matter as we're just trying to build up the map from inside-out; we use 956693eedb1SChandler Carruth // the map in a more stably ordered way below. 957693eedb1SChandler Carruth auto OrderedClonedExitsInLoops = ClonedExitsInLoops; 958636d94dbSMandeep Singh Grang llvm::sort(OrderedClonedExitsInLoops.begin(), 959636d94dbSMandeep Singh Grang OrderedClonedExitsInLoops.end(), 960693eedb1SChandler Carruth [&](BasicBlock *LHS, BasicBlock *RHS) { 961693eedb1SChandler Carruth return ExitLoopMap.lookup(LHS)->getLoopDepth() < 962693eedb1SChandler Carruth ExitLoopMap.lookup(RHS)->getLoopDepth(); 963693eedb1SChandler Carruth }); 964693eedb1SChandler Carruth 965693eedb1SChandler Carruth // Populate the existing ExitLoopMap with everything reachable from each 966693eedb1SChandler Carruth // exit, starting from the inner most exit. 967693eedb1SChandler Carruth while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) { 968693eedb1SChandler Carruth assert(Worklist.empty() && "Didn't clear worklist!"); 969693eedb1SChandler Carruth 970693eedb1SChandler Carruth BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val(); 971693eedb1SChandler Carruth Loop *ExitL = ExitLoopMap.lookup(ExitBB); 972693eedb1SChandler Carruth 973693eedb1SChandler Carruth // Walk the CFG back until we hit the cloned PH adding everything reachable 974693eedb1SChandler Carruth // and in the unlooped set to this exit block's loop. 975693eedb1SChandler Carruth Worklist.push_back(ExitBB); 976693eedb1SChandler Carruth do { 977693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val(); 978693eedb1SChandler Carruth // We can stop recursing at the cloned preheader (if we get there). 979693eedb1SChandler Carruth if (BB == ClonedPH) 980693eedb1SChandler Carruth continue; 981693eedb1SChandler Carruth 982693eedb1SChandler Carruth for (BasicBlock *PredBB : predecessors(BB)) { 983693eedb1SChandler Carruth // If this pred has already been moved to our set or is part of some 984693eedb1SChandler Carruth // (inner) loop, no update needed. 985693eedb1SChandler Carruth if (!UnloopedBlockSet.erase(PredBB)) { 986693eedb1SChandler Carruth assert( 987693eedb1SChandler Carruth (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) && 988693eedb1SChandler Carruth "Predecessor not mapped to a loop!"); 989693eedb1SChandler Carruth continue; 990693eedb1SChandler Carruth } 991693eedb1SChandler Carruth 992693eedb1SChandler Carruth // We just insert into the loop set here. We'll add these blocks to the 993693eedb1SChandler Carruth // exit loop after we build up the set in an order that doesn't rely on 994693eedb1SChandler Carruth // predecessor order (which in turn relies on use list order). 995693eedb1SChandler Carruth bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second; 996693eedb1SChandler Carruth (void)Inserted; 997693eedb1SChandler Carruth assert(Inserted && "Should only visit an unlooped block once!"); 998693eedb1SChandler Carruth 999693eedb1SChandler Carruth // And recurse through to its predecessors. 1000693eedb1SChandler Carruth Worklist.push_back(PredBB); 1001693eedb1SChandler Carruth } 1002693eedb1SChandler Carruth } while (!Worklist.empty()); 1003693eedb1SChandler Carruth } 1004693eedb1SChandler Carruth 1005693eedb1SChandler Carruth // Now that the ExitLoopMap gives as mapping for all the non-looping cloned 1006693eedb1SChandler Carruth // blocks to their outer loops, walk the cloned blocks and the cloned exits 1007693eedb1SChandler Carruth // in their original order adding them to the correct loop. 1008693eedb1SChandler Carruth 1009693eedb1SChandler Carruth // We need a stable insertion order. We use the order of the original loop 1010693eedb1SChandler Carruth // order and map into the correct parent loop. 1011693eedb1SChandler Carruth for (auto *BB : llvm::concat<BasicBlock *const>( 1012693eedb1SChandler Carruth makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops)) 1013693eedb1SChandler Carruth if (Loop *OuterL = ExitLoopMap.lookup(BB)) 1014693eedb1SChandler Carruth OuterL->addBasicBlockToLoop(BB, LI); 1015693eedb1SChandler Carruth 1016693eedb1SChandler Carruth #ifndef NDEBUG 1017693eedb1SChandler Carruth for (auto &BBAndL : ExitLoopMap) { 1018693eedb1SChandler Carruth auto *BB = BBAndL.first; 1019693eedb1SChandler Carruth auto *OuterL = BBAndL.second; 1020693eedb1SChandler Carruth assert(LI.getLoopFor(BB) == OuterL && 1021693eedb1SChandler Carruth "Failed to put all blocks into outer loops!"); 1022693eedb1SChandler Carruth } 1023693eedb1SChandler Carruth #endif 1024693eedb1SChandler Carruth 1025693eedb1SChandler Carruth // Now that all the blocks are placed into the correct containing loop in the 1026693eedb1SChandler Carruth // absence of child loops, find all the potentially cloned child loops and 1027693eedb1SChandler Carruth // clone them into whatever outer loop we placed their header into. 1028693eedb1SChandler Carruth for (Loop *ChildL : OrigL) { 1029693eedb1SChandler Carruth auto *ClonedChildHeader = 1030693eedb1SChandler Carruth cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader())); 1031693eedb1SChandler Carruth if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader)) 1032693eedb1SChandler Carruth continue; 1033693eedb1SChandler Carruth 1034693eedb1SChandler Carruth #ifndef NDEBUG 1035693eedb1SChandler Carruth for (auto *ChildLoopBB : ChildL->blocks()) 1036693eedb1SChandler Carruth assert(VMap.count(ChildLoopBB) && 1037693eedb1SChandler Carruth "Cloned a child loop header but not all of that loops blocks!"); 1038693eedb1SChandler Carruth #endif 1039693eedb1SChandler Carruth 1040693eedb1SChandler Carruth NonChildClonedLoops.push_back(cloneLoopNest( 1041693eedb1SChandler Carruth *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI)); 1042693eedb1SChandler Carruth } 1043693eedb1SChandler Carruth 1044693eedb1SChandler Carruth // Return the main cloned loop if any. 1045693eedb1SChandler Carruth return ClonedL; 1046693eedb1SChandler Carruth } 1047693eedb1SChandler Carruth 104869e68f84SChandler Carruth static void 104969e68f84SChandler Carruth deleteDeadBlocksFromLoop(Loop &L, 105069e68f84SChandler Carruth const SmallVectorImpl<BasicBlock *> &DeadBlocks, 1051693eedb1SChandler Carruth SmallVectorImpl<BasicBlock *> &ExitBlocks, 1052693eedb1SChandler Carruth DominatorTree &DT, LoopInfo &LI) { 105369e68f84SChandler Carruth SmallPtrSet<BasicBlock *, 16> DeadBlockSet(DeadBlocks.begin(), 105469e68f84SChandler Carruth DeadBlocks.end()); 1055693eedb1SChandler Carruth 1056693eedb1SChandler Carruth // Filter out the dead blocks from the exit blocks list so that it can be 1057693eedb1SChandler Carruth // used in the caller. 1058693eedb1SChandler Carruth llvm::erase_if(ExitBlocks, 105969e68f84SChandler Carruth [&](BasicBlock *BB) { return DeadBlockSet.count(BB); }); 1060693eedb1SChandler Carruth 1061693eedb1SChandler Carruth // Remove these blocks from their successors. 1062693eedb1SChandler Carruth for (auto *BB : DeadBlocks) 1063693eedb1SChandler Carruth for (BasicBlock *SuccBB : successors(BB)) 1064693eedb1SChandler Carruth SuccBB->removePredecessor(BB, /*DontDeleteUselessPHIs*/ true); 1065693eedb1SChandler Carruth 1066693eedb1SChandler Carruth // Walk from this loop up through its parents removing all of the dead blocks. 1067693eedb1SChandler Carruth for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) { 1068693eedb1SChandler Carruth for (auto *BB : DeadBlocks) 1069693eedb1SChandler Carruth ParentL->getBlocksSet().erase(BB); 1070693eedb1SChandler Carruth llvm::erase_if(ParentL->getBlocksVector(), 107169e68f84SChandler Carruth [&](BasicBlock *BB) { return DeadBlockSet.count(BB); }); 1072693eedb1SChandler Carruth } 1073693eedb1SChandler Carruth 1074693eedb1SChandler Carruth // Now delete the dead child loops. This raw delete will clear them 1075693eedb1SChandler Carruth // recursively. 1076693eedb1SChandler Carruth llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) { 107769e68f84SChandler Carruth if (!DeadBlockSet.count(ChildL->getHeader())) 1078693eedb1SChandler Carruth return false; 1079693eedb1SChandler Carruth 1080693eedb1SChandler Carruth assert(llvm::all_of(ChildL->blocks(), 1081693eedb1SChandler Carruth [&](BasicBlock *ChildBB) { 108269e68f84SChandler Carruth return DeadBlockSet.count(ChildBB); 1083693eedb1SChandler Carruth }) && 1084693eedb1SChandler Carruth "If the child loop header is dead all blocks in the child loop must " 1085693eedb1SChandler Carruth "be dead as well!"); 1086693eedb1SChandler Carruth LI.destroy(ChildL); 1087693eedb1SChandler Carruth return true; 1088693eedb1SChandler Carruth }); 1089693eedb1SChandler Carruth 109069e68f84SChandler Carruth // Remove the loop mappings for the dead blocks and drop all the references 109169e68f84SChandler Carruth // from these blocks to others to handle cyclic references as we start 109269e68f84SChandler Carruth // deleting the blocks themselves. 109369e68f84SChandler Carruth for (auto *BB : DeadBlocks) { 109469e68f84SChandler Carruth // Check that the dominator tree has already been updated. 109569e68f84SChandler Carruth assert(!DT.getNode(BB) && "Should already have cleared domtree!"); 1096693eedb1SChandler Carruth LI.changeLoopFor(BB, nullptr); 1097693eedb1SChandler Carruth BB->dropAllReferences(); 1098693eedb1SChandler Carruth } 109969e68f84SChandler Carruth 110069e68f84SChandler Carruth // Actually delete the blocks now that they've been fully unhooked from the 110169e68f84SChandler Carruth // IR. 110269e68f84SChandler Carruth for (auto *BB : DeadBlocks) 110369e68f84SChandler Carruth BB->eraseFromParent(); 1104693eedb1SChandler Carruth } 1105693eedb1SChandler Carruth 1106693eedb1SChandler Carruth /// Recompute the set of blocks in a loop after unswitching. 1107693eedb1SChandler Carruth /// 1108693eedb1SChandler Carruth /// This walks from the original headers predecessors to rebuild the loop. We 1109693eedb1SChandler Carruth /// take advantage of the fact that new blocks can't have been added, and so we 1110693eedb1SChandler Carruth /// filter by the original loop's blocks. This also handles potentially 1111693eedb1SChandler Carruth /// unreachable code that we don't want to explore but might be found examining 1112693eedb1SChandler Carruth /// the predecessors of the header. 1113693eedb1SChandler Carruth /// 1114693eedb1SChandler Carruth /// If the original loop is no longer a loop, this will return an empty set. If 1115693eedb1SChandler Carruth /// it remains a loop, all the blocks within it will be added to the set 1116693eedb1SChandler Carruth /// (including those blocks in inner loops). 1117693eedb1SChandler Carruth static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L, 1118693eedb1SChandler Carruth LoopInfo &LI) { 1119693eedb1SChandler Carruth SmallPtrSet<const BasicBlock *, 16> LoopBlockSet; 1120693eedb1SChandler Carruth 1121693eedb1SChandler Carruth auto *PH = L.getLoopPreheader(); 1122693eedb1SChandler Carruth auto *Header = L.getHeader(); 1123693eedb1SChandler Carruth 1124693eedb1SChandler Carruth // A worklist to use while walking backwards from the header. 1125693eedb1SChandler Carruth SmallVector<BasicBlock *, 16> Worklist; 1126693eedb1SChandler Carruth 1127693eedb1SChandler Carruth // First walk the predecessors of the header to find the backedges. This will 1128693eedb1SChandler Carruth // form the basis of our walk. 1129693eedb1SChandler Carruth for (auto *Pred : predecessors(Header)) { 1130693eedb1SChandler Carruth // Skip the preheader. 1131693eedb1SChandler Carruth if (Pred == PH) 1132693eedb1SChandler Carruth continue; 1133693eedb1SChandler Carruth 1134693eedb1SChandler Carruth // Because the loop was in simplified form, the only non-loop predecessor 1135693eedb1SChandler Carruth // is the preheader. 1136693eedb1SChandler Carruth assert(L.contains(Pred) && "Found a predecessor of the loop header other " 1137693eedb1SChandler Carruth "than the preheader that is not part of the " 1138693eedb1SChandler Carruth "loop!"); 1139693eedb1SChandler Carruth 1140693eedb1SChandler Carruth // Insert this block into the loop set and on the first visit and, if it 1141693eedb1SChandler Carruth // isn't the header we're currently walking, put it into the worklist to 1142693eedb1SChandler Carruth // recurse through. 1143693eedb1SChandler Carruth if (LoopBlockSet.insert(Pred).second && Pred != Header) 1144693eedb1SChandler Carruth Worklist.push_back(Pred); 1145693eedb1SChandler Carruth } 1146693eedb1SChandler Carruth 1147693eedb1SChandler Carruth // If no backedges were found, we're done. 1148693eedb1SChandler Carruth if (LoopBlockSet.empty()) 1149693eedb1SChandler Carruth return LoopBlockSet; 1150693eedb1SChandler Carruth 1151693eedb1SChandler Carruth // We found backedges, recurse through them to identify the loop blocks. 1152693eedb1SChandler Carruth while (!Worklist.empty()) { 1153693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val(); 1154693eedb1SChandler Carruth assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!"); 1155693eedb1SChandler Carruth 115643acdb35SChandler Carruth // No need to walk past the header. 115743acdb35SChandler Carruth if (BB == Header) 115843acdb35SChandler Carruth continue; 115943acdb35SChandler Carruth 1160693eedb1SChandler Carruth // Because we know the inner loop structure remains valid we can use the 1161693eedb1SChandler Carruth // loop structure to jump immediately across the entire nested loop. 1162693eedb1SChandler Carruth // Further, because it is in loop simplified form, we can directly jump 1163693eedb1SChandler Carruth // to its preheader afterward. 1164693eedb1SChandler Carruth if (Loop *InnerL = LI.getLoopFor(BB)) 1165693eedb1SChandler Carruth if (InnerL != &L) { 1166693eedb1SChandler Carruth assert(L.contains(InnerL) && 1167693eedb1SChandler Carruth "Should not reach a loop *outside* this loop!"); 1168693eedb1SChandler Carruth // The preheader is the only possible predecessor of the loop so 1169693eedb1SChandler Carruth // insert it into the set and check whether it was already handled. 1170693eedb1SChandler Carruth auto *InnerPH = InnerL->getLoopPreheader(); 1171693eedb1SChandler Carruth assert(L.contains(InnerPH) && "Cannot contain an inner loop block " 1172693eedb1SChandler Carruth "but not contain the inner loop " 1173693eedb1SChandler Carruth "preheader!"); 1174693eedb1SChandler Carruth if (!LoopBlockSet.insert(InnerPH).second) 1175693eedb1SChandler Carruth // The only way to reach the preheader is through the loop body 1176693eedb1SChandler Carruth // itself so if it has been visited the loop is already handled. 1177693eedb1SChandler Carruth continue; 1178693eedb1SChandler Carruth 1179693eedb1SChandler Carruth // Insert all of the blocks (other than those already present) into 1180bf7190a1SChandler Carruth // the loop set. We expect at least the block that led us to find the 1181bf7190a1SChandler Carruth // inner loop to be in the block set, but we may also have other loop 1182bf7190a1SChandler Carruth // blocks if they were already enqueued as predecessors of some other 1183bf7190a1SChandler Carruth // outer loop block. 1184693eedb1SChandler Carruth for (auto *InnerBB : InnerL->blocks()) { 1185693eedb1SChandler Carruth if (InnerBB == BB) { 1186693eedb1SChandler Carruth assert(LoopBlockSet.count(InnerBB) && 1187693eedb1SChandler Carruth "Block should already be in the set!"); 1188693eedb1SChandler Carruth continue; 1189693eedb1SChandler Carruth } 1190693eedb1SChandler Carruth 1191bf7190a1SChandler Carruth LoopBlockSet.insert(InnerBB); 1192693eedb1SChandler Carruth } 1193693eedb1SChandler Carruth 1194693eedb1SChandler Carruth // Add the preheader to the worklist so we will continue past the 1195693eedb1SChandler Carruth // loop body. 1196693eedb1SChandler Carruth Worklist.push_back(InnerPH); 1197693eedb1SChandler Carruth continue; 1198693eedb1SChandler Carruth } 1199693eedb1SChandler Carruth 1200693eedb1SChandler Carruth // Insert any predecessors that were in the original loop into the new 1201693eedb1SChandler Carruth // set, and if the insert is successful, add them to the worklist. 1202693eedb1SChandler Carruth for (auto *Pred : predecessors(BB)) 1203693eedb1SChandler Carruth if (L.contains(Pred) && LoopBlockSet.insert(Pred).second) 1204693eedb1SChandler Carruth Worklist.push_back(Pred); 1205693eedb1SChandler Carruth } 1206693eedb1SChandler Carruth 120743acdb35SChandler Carruth assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!"); 120843acdb35SChandler Carruth 1209693eedb1SChandler Carruth // We've found all the blocks participating in the loop, return our completed 1210693eedb1SChandler Carruth // set. 1211693eedb1SChandler Carruth return LoopBlockSet; 1212693eedb1SChandler Carruth } 1213693eedb1SChandler Carruth 1214693eedb1SChandler Carruth /// Rebuild a loop after unswitching removes some subset of blocks and edges. 1215693eedb1SChandler Carruth /// 1216693eedb1SChandler Carruth /// The removal may have removed some child loops entirely but cannot have 1217693eedb1SChandler Carruth /// disturbed any remaining child loops. However, they may need to be hoisted 1218693eedb1SChandler Carruth /// to the parent loop (or to be top-level loops). The original loop may be 1219693eedb1SChandler Carruth /// completely removed. 1220693eedb1SChandler Carruth /// 1221693eedb1SChandler Carruth /// The sibling loops resulting from this update are returned. If the original 1222693eedb1SChandler Carruth /// loop remains a valid loop, it will be the first entry in this list with all 1223693eedb1SChandler Carruth /// of the newly sibling loops following it. 1224693eedb1SChandler Carruth /// 1225693eedb1SChandler Carruth /// Returns true if the loop remains a loop after unswitching, and false if it 1226693eedb1SChandler Carruth /// is no longer a loop after unswitching (and should not continue to be 1227693eedb1SChandler Carruth /// referenced). 1228693eedb1SChandler Carruth static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks, 1229693eedb1SChandler Carruth LoopInfo &LI, 1230693eedb1SChandler Carruth SmallVectorImpl<Loop *> &HoistedLoops) { 1231693eedb1SChandler Carruth auto *PH = L.getLoopPreheader(); 1232693eedb1SChandler Carruth 1233693eedb1SChandler Carruth // Compute the actual parent loop from the exit blocks. Because we may have 1234693eedb1SChandler Carruth // pruned some exits the loop may be different from the original parent. 1235693eedb1SChandler Carruth Loop *ParentL = nullptr; 1236693eedb1SChandler Carruth SmallVector<Loop *, 4> ExitLoops; 1237693eedb1SChandler Carruth SmallVector<BasicBlock *, 4> ExitsInLoops; 1238693eedb1SChandler Carruth ExitsInLoops.reserve(ExitBlocks.size()); 1239693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) 1240693eedb1SChandler Carruth if (Loop *ExitL = LI.getLoopFor(ExitBB)) { 1241693eedb1SChandler Carruth ExitLoops.push_back(ExitL); 1242693eedb1SChandler Carruth ExitsInLoops.push_back(ExitBB); 1243693eedb1SChandler Carruth if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL))) 1244693eedb1SChandler Carruth ParentL = ExitL; 1245693eedb1SChandler Carruth } 1246693eedb1SChandler Carruth 1247693eedb1SChandler Carruth // Recompute the blocks participating in this loop. This may be empty if it 1248693eedb1SChandler Carruth // is no longer a loop. 1249693eedb1SChandler Carruth auto LoopBlockSet = recomputeLoopBlockSet(L, LI); 1250693eedb1SChandler Carruth 1251693eedb1SChandler Carruth // If we still have a loop, we need to re-set the loop's parent as the exit 1252693eedb1SChandler Carruth // block set changing may have moved it within the loop nest. Note that this 1253693eedb1SChandler Carruth // can only happen when this loop has a parent as it can only hoist the loop 1254693eedb1SChandler Carruth // *up* the nest. 1255693eedb1SChandler Carruth if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) { 1256693eedb1SChandler Carruth // Remove this loop's (original) blocks from all of the intervening loops. 1257693eedb1SChandler Carruth for (Loop *IL = L.getParentLoop(); IL != ParentL; 1258693eedb1SChandler Carruth IL = IL->getParentLoop()) { 1259693eedb1SChandler Carruth IL->getBlocksSet().erase(PH); 1260693eedb1SChandler Carruth for (auto *BB : L.blocks()) 1261693eedb1SChandler Carruth IL->getBlocksSet().erase(BB); 1262693eedb1SChandler Carruth llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) { 1263693eedb1SChandler Carruth return BB == PH || L.contains(BB); 1264693eedb1SChandler Carruth }); 1265693eedb1SChandler Carruth } 1266693eedb1SChandler Carruth 1267693eedb1SChandler Carruth LI.changeLoopFor(PH, ParentL); 1268693eedb1SChandler Carruth L.getParentLoop()->removeChildLoop(&L); 1269693eedb1SChandler Carruth if (ParentL) 1270693eedb1SChandler Carruth ParentL->addChildLoop(&L); 1271693eedb1SChandler Carruth else 1272693eedb1SChandler Carruth LI.addTopLevelLoop(&L); 1273693eedb1SChandler Carruth } 1274693eedb1SChandler Carruth 1275693eedb1SChandler Carruth // Now we update all the blocks which are no longer within the loop. 1276693eedb1SChandler Carruth auto &Blocks = L.getBlocksVector(); 1277693eedb1SChandler Carruth auto BlocksSplitI = 1278693eedb1SChandler Carruth LoopBlockSet.empty() 1279693eedb1SChandler Carruth ? Blocks.begin() 1280693eedb1SChandler Carruth : std::stable_partition( 1281693eedb1SChandler Carruth Blocks.begin(), Blocks.end(), 1282693eedb1SChandler Carruth [&](BasicBlock *BB) { return LoopBlockSet.count(BB); }); 1283693eedb1SChandler Carruth 1284693eedb1SChandler Carruth // Before we erase the list of unlooped blocks, build a set of them. 1285693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end()); 1286693eedb1SChandler Carruth if (LoopBlockSet.empty()) 1287693eedb1SChandler Carruth UnloopedBlocks.insert(PH); 1288693eedb1SChandler Carruth 1289693eedb1SChandler Carruth // Now erase these blocks from the loop. 1290693eedb1SChandler Carruth for (auto *BB : make_range(BlocksSplitI, Blocks.end())) 1291693eedb1SChandler Carruth L.getBlocksSet().erase(BB); 1292693eedb1SChandler Carruth Blocks.erase(BlocksSplitI, Blocks.end()); 1293693eedb1SChandler Carruth 1294693eedb1SChandler Carruth // Sort the exits in ascending loop depth, we'll work backwards across these 1295693eedb1SChandler Carruth // to process them inside out. 1296693eedb1SChandler Carruth std::stable_sort(ExitsInLoops.begin(), ExitsInLoops.end(), 1297693eedb1SChandler Carruth [&](BasicBlock *LHS, BasicBlock *RHS) { 1298693eedb1SChandler Carruth return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS); 1299693eedb1SChandler Carruth }); 1300693eedb1SChandler Carruth 1301693eedb1SChandler Carruth // We'll build up a set for each exit loop. 1302693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks; 1303693eedb1SChandler Carruth Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop. 1304693eedb1SChandler Carruth 1305693eedb1SChandler Carruth auto RemoveUnloopedBlocksFromLoop = 1306693eedb1SChandler Carruth [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) { 1307693eedb1SChandler Carruth for (auto *BB : UnloopedBlocks) 1308693eedb1SChandler Carruth L.getBlocksSet().erase(BB); 1309693eedb1SChandler Carruth llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) { 1310693eedb1SChandler Carruth return UnloopedBlocks.count(BB); 1311693eedb1SChandler Carruth }); 1312693eedb1SChandler Carruth }; 1313693eedb1SChandler Carruth 1314693eedb1SChandler Carruth SmallVector<BasicBlock *, 16> Worklist; 1315693eedb1SChandler Carruth while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) { 1316693eedb1SChandler Carruth assert(Worklist.empty() && "Didn't clear worklist!"); 1317693eedb1SChandler Carruth assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!"); 1318693eedb1SChandler Carruth 1319693eedb1SChandler Carruth // Grab the next exit block, in decreasing loop depth order. 1320693eedb1SChandler Carruth BasicBlock *ExitBB = ExitsInLoops.pop_back_val(); 1321693eedb1SChandler Carruth Loop &ExitL = *LI.getLoopFor(ExitBB); 1322693eedb1SChandler Carruth assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!"); 1323693eedb1SChandler Carruth 1324693eedb1SChandler Carruth // Erase all of the unlooped blocks from the loops between the previous 1325693eedb1SChandler Carruth // exit loop and this exit loop. This works because the ExitInLoops list is 1326693eedb1SChandler Carruth // sorted in increasing order of loop depth and thus we visit loops in 1327693eedb1SChandler Carruth // decreasing order of loop depth. 1328693eedb1SChandler Carruth for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop()) 1329693eedb1SChandler Carruth RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks); 1330693eedb1SChandler Carruth 1331693eedb1SChandler Carruth // Walk the CFG back until we hit the cloned PH adding everything reachable 1332693eedb1SChandler Carruth // and in the unlooped set to this exit block's loop. 1333693eedb1SChandler Carruth Worklist.push_back(ExitBB); 1334693eedb1SChandler Carruth do { 1335693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val(); 1336693eedb1SChandler Carruth // We can stop recursing at the cloned preheader (if we get there). 1337693eedb1SChandler Carruth if (BB == PH) 1338693eedb1SChandler Carruth continue; 1339693eedb1SChandler Carruth 1340693eedb1SChandler Carruth for (BasicBlock *PredBB : predecessors(BB)) { 1341693eedb1SChandler Carruth // If this pred has already been moved to our set or is part of some 1342693eedb1SChandler Carruth // (inner) loop, no update needed. 1343693eedb1SChandler Carruth if (!UnloopedBlocks.erase(PredBB)) { 1344693eedb1SChandler Carruth assert((NewExitLoopBlocks.count(PredBB) || 1345693eedb1SChandler Carruth ExitL.contains(LI.getLoopFor(PredBB))) && 1346693eedb1SChandler Carruth "Predecessor not in a nested loop (or already visited)!"); 1347693eedb1SChandler Carruth continue; 1348693eedb1SChandler Carruth } 1349693eedb1SChandler Carruth 1350693eedb1SChandler Carruth // We just insert into the loop set here. We'll add these blocks to the 1351693eedb1SChandler Carruth // exit loop after we build up the set in a deterministic order rather 1352693eedb1SChandler Carruth // than the predecessor-influenced visit order. 1353693eedb1SChandler Carruth bool Inserted = NewExitLoopBlocks.insert(PredBB).second; 1354693eedb1SChandler Carruth (void)Inserted; 1355693eedb1SChandler Carruth assert(Inserted && "Should only visit an unlooped block once!"); 1356693eedb1SChandler Carruth 1357693eedb1SChandler Carruth // And recurse through to its predecessors. 1358693eedb1SChandler Carruth Worklist.push_back(PredBB); 1359693eedb1SChandler Carruth } 1360693eedb1SChandler Carruth } while (!Worklist.empty()); 1361693eedb1SChandler Carruth 1362693eedb1SChandler Carruth // If blocks in this exit loop were directly part of the original loop (as 1363693eedb1SChandler Carruth // opposed to a child loop) update the map to point to this exit loop. This 1364693eedb1SChandler Carruth // just updates a map and so the fact that the order is unstable is fine. 1365693eedb1SChandler Carruth for (auto *BB : NewExitLoopBlocks) 1366693eedb1SChandler Carruth if (Loop *BBL = LI.getLoopFor(BB)) 1367693eedb1SChandler Carruth if (BBL == &L || !L.contains(BBL)) 1368693eedb1SChandler Carruth LI.changeLoopFor(BB, &ExitL); 1369693eedb1SChandler Carruth 1370693eedb1SChandler Carruth // We will remove the remaining unlooped blocks from this loop in the next 1371693eedb1SChandler Carruth // iteration or below. 1372693eedb1SChandler Carruth NewExitLoopBlocks.clear(); 1373693eedb1SChandler Carruth } 1374693eedb1SChandler Carruth 1375693eedb1SChandler Carruth // Any remaining unlooped blocks are no longer part of any loop unless they 1376693eedb1SChandler Carruth // are part of some child loop. 1377693eedb1SChandler Carruth for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop()) 1378693eedb1SChandler Carruth RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks); 1379693eedb1SChandler Carruth for (auto *BB : UnloopedBlocks) 1380693eedb1SChandler Carruth if (Loop *BBL = LI.getLoopFor(BB)) 1381693eedb1SChandler Carruth if (BBL == &L || !L.contains(BBL)) 1382693eedb1SChandler Carruth LI.changeLoopFor(BB, nullptr); 1383693eedb1SChandler Carruth 1384693eedb1SChandler Carruth // Sink all the child loops whose headers are no longer in the loop set to 1385693eedb1SChandler Carruth // the parent (or to be top level loops). We reach into the loop and directly 1386693eedb1SChandler Carruth // update its subloop vector to make this batch update efficient. 1387693eedb1SChandler Carruth auto &SubLoops = L.getSubLoopsVector(); 1388693eedb1SChandler Carruth auto SubLoopsSplitI = 1389693eedb1SChandler Carruth LoopBlockSet.empty() 1390693eedb1SChandler Carruth ? SubLoops.begin() 1391693eedb1SChandler Carruth : std::stable_partition( 1392693eedb1SChandler Carruth SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) { 1393693eedb1SChandler Carruth return LoopBlockSet.count(SubL->getHeader()); 1394693eedb1SChandler Carruth }); 1395693eedb1SChandler Carruth for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) { 1396693eedb1SChandler Carruth HoistedLoops.push_back(HoistedL); 1397693eedb1SChandler Carruth HoistedL->setParentLoop(nullptr); 1398693eedb1SChandler Carruth 1399693eedb1SChandler Carruth // To compute the new parent of this hoisted loop we look at where we 1400693eedb1SChandler Carruth // placed the preheader above. We can't lookup the header itself because we 1401693eedb1SChandler Carruth // retained the mapping from the header to the hoisted loop. But the 1402693eedb1SChandler Carruth // preheader and header should have the exact same new parent computed 1403693eedb1SChandler Carruth // based on the set of exit blocks from the original loop as the preheader 1404693eedb1SChandler Carruth // is a predecessor of the header and so reached in the reverse walk. And 1405693eedb1SChandler Carruth // because the loops were all in simplified form the preheader of the 1406693eedb1SChandler Carruth // hoisted loop can't be part of some *other* loop. 1407693eedb1SChandler Carruth if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader())) 1408693eedb1SChandler Carruth NewParentL->addChildLoop(HoistedL); 1409693eedb1SChandler Carruth else 1410693eedb1SChandler Carruth LI.addTopLevelLoop(HoistedL); 1411693eedb1SChandler Carruth } 1412693eedb1SChandler Carruth SubLoops.erase(SubLoopsSplitI, SubLoops.end()); 1413693eedb1SChandler Carruth 1414693eedb1SChandler Carruth // Actually delete the loop if nothing remained within it. 1415693eedb1SChandler Carruth if (Blocks.empty()) { 1416693eedb1SChandler Carruth assert(SubLoops.empty() && 1417693eedb1SChandler Carruth "Failed to remove all subloops from the original loop!"); 1418693eedb1SChandler Carruth if (Loop *ParentL = L.getParentLoop()) 1419693eedb1SChandler Carruth ParentL->removeChildLoop(llvm::find(*ParentL, &L)); 1420693eedb1SChandler Carruth else 1421693eedb1SChandler Carruth LI.removeLoop(llvm::find(LI, &L)); 1422693eedb1SChandler Carruth LI.destroy(&L); 1423693eedb1SChandler Carruth return false; 1424693eedb1SChandler Carruth } 1425693eedb1SChandler Carruth 1426693eedb1SChandler Carruth return true; 1427693eedb1SChandler Carruth } 1428693eedb1SChandler Carruth 1429693eedb1SChandler Carruth /// Helper to visit a dominator subtree, invoking a callable on each node. 1430693eedb1SChandler Carruth /// 1431693eedb1SChandler Carruth /// Returning false at any point will stop walking past that node of the tree. 1432693eedb1SChandler Carruth template <typename CallableT> 1433693eedb1SChandler Carruth void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) { 1434693eedb1SChandler Carruth SmallVector<DomTreeNode *, 4> DomWorklist; 1435693eedb1SChandler Carruth DomWorklist.push_back(DT[BB]); 1436693eedb1SChandler Carruth #ifndef NDEBUG 1437693eedb1SChandler Carruth SmallPtrSet<DomTreeNode *, 4> Visited; 1438693eedb1SChandler Carruth Visited.insert(DT[BB]); 1439693eedb1SChandler Carruth #endif 1440693eedb1SChandler Carruth do { 1441693eedb1SChandler Carruth DomTreeNode *N = DomWorklist.pop_back_val(); 1442693eedb1SChandler Carruth 1443693eedb1SChandler Carruth // Visit this node. 1444693eedb1SChandler Carruth if (!Callable(N->getBlock())) 1445693eedb1SChandler Carruth continue; 1446693eedb1SChandler Carruth 1447693eedb1SChandler Carruth // Accumulate the child nodes. 1448693eedb1SChandler Carruth for (DomTreeNode *ChildN : *N) { 1449693eedb1SChandler Carruth assert(Visited.insert(ChildN).second && 1450693eedb1SChandler Carruth "Cannot visit a node twice when walking a tree!"); 1451693eedb1SChandler Carruth DomWorklist.push_back(ChildN); 1452693eedb1SChandler Carruth } 1453693eedb1SChandler Carruth } while (!DomWorklist.empty()); 1454693eedb1SChandler Carruth } 1455693eedb1SChandler Carruth 1456693eedb1SChandler Carruth /// Take an invariant branch that has been determined to be safe and worthwhile 1457693eedb1SChandler Carruth /// to unswitch despite being non-trivial to do so and perform the unswitch. 1458693eedb1SChandler Carruth /// 1459693eedb1SChandler Carruth /// This directly updates the CFG to hoist the predicate out of the loop, and 1460693eedb1SChandler Carruth /// clone the necessary parts of the loop to maintain behavior. 1461693eedb1SChandler Carruth /// 1462693eedb1SChandler Carruth /// It also updates both dominator tree and loopinfo based on the unswitching. 1463693eedb1SChandler Carruth /// 1464693eedb1SChandler Carruth /// Once unswitching has been performed it runs the provided callback to report 1465693eedb1SChandler Carruth /// the new loops and no-longer valid loops to the caller. 1466693eedb1SChandler Carruth static bool unswitchInvariantBranch( 1467693eedb1SChandler Carruth Loop &L, BranchInst &BI, DominatorTree &DT, LoopInfo &LI, 1468693eedb1SChandler Carruth AssumptionCache &AC, 1469693eedb1SChandler Carruth function_ref<void(bool, ArrayRef<Loop *>)> NonTrivialUnswitchCB) { 1470693eedb1SChandler Carruth assert(BI.isConditional() && "Can only unswitch a conditional branch!"); 1471693eedb1SChandler Carruth assert(L.isLoopInvariant(BI.getCondition()) && 1472693eedb1SChandler Carruth "Can only unswitch an invariant branch condition!"); 1473693eedb1SChandler Carruth 1474693eedb1SChandler Carruth // Constant and BBs tracking the cloned and continuing successor. 1475693eedb1SChandler Carruth const int ClonedSucc = 0; 1476693eedb1SChandler Carruth auto *ParentBB = BI.getParent(); 1477693eedb1SChandler Carruth auto *UnswitchedSuccBB = BI.getSuccessor(ClonedSucc); 1478693eedb1SChandler Carruth auto *ContinueSuccBB = BI.getSuccessor(1 - ClonedSucc); 1479693eedb1SChandler Carruth 1480693eedb1SChandler Carruth assert(UnswitchedSuccBB != ContinueSuccBB && 1481693eedb1SChandler Carruth "Should not unswitch a branch that always goes to the same place!"); 1482693eedb1SChandler Carruth 1483693eedb1SChandler Carruth // The branch should be in this exact loop. Any inner loop's invariant branch 1484693eedb1SChandler Carruth // should be handled by unswitching that inner loop. The caller of this 1485693eedb1SChandler Carruth // routine should filter out any candidates that remain (but were skipped for 1486693eedb1SChandler Carruth // whatever reason). 1487693eedb1SChandler Carruth assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!"); 1488693eedb1SChandler Carruth 1489693eedb1SChandler Carruth SmallVector<BasicBlock *, 4> ExitBlocks; 1490693eedb1SChandler Carruth L.getUniqueExitBlocks(ExitBlocks); 1491693eedb1SChandler Carruth 1492693eedb1SChandler Carruth // We cannot unswitch if exit blocks contain a cleanuppad instruction as we 1493693eedb1SChandler Carruth // don't know how to split those exit blocks. 1494693eedb1SChandler Carruth // FIXME: We should teach SplitBlock to handle this and remove this 1495693eedb1SChandler Carruth // restriction. 1496693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) 1497693eedb1SChandler Carruth if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) 1498693eedb1SChandler Carruth return false; 1499693eedb1SChandler Carruth 1500693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 4> ExitBlockSet(ExitBlocks.begin(), 1501693eedb1SChandler Carruth ExitBlocks.end()); 1502693eedb1SChandler Carruth 1503693eedb1SChandler Carruth // Compute the parent loop now before we start hacking on things. 1504693eedb1SChandler Carruth Loop *ParentL = L.getParentLoop(); 1505693eedb1SChandler Carruth 1506693eedb1SChandler Carruth // Compute the outer-most loop containing one of our exit blocks. This is the 1507693eedb1SChandler Carruth // furthest up our loopnest which can be mutated, which we will use below to 1508693eedb1SChandler Carruth // update things. 1509693eedb1SChandler Carruth Loop *OuterExitL = &L; 1510693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) { 1511693eedb1SChandler Carruth Loop *NewOuterExitL = LI.getLoopFor(ExitBB); 1512693eedb1SChandler Carruth if (!NewOuterExitL) { 1513693eedb1SChandler Carruth // We exited the entire nest with this block, so we're done. 1514693eedb1SChandler Carruth OuterExitL = nullptr; 1515693eedb1SChandler Carruth break; 1516693eedb1SChandler Carruth } 1517693eedb1SChandler Carruth if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL)) 1518693eedb1SChandler Carruth OuterExitL = NewOuterExitL; 1519693eedb1SChandler Carruth } 1520693eedb1SChandler Carruth 1521693eedb1SChandler Carruth // If the edge we *aren't* cloning in the unswitch (the continuing edge) 1522693eedb1SChandler Carruth // dominates its target, we can skip cloning the dominated region of the loop 1523693eedb1SChandler Carruth // and its exits. We compute this as a set of nodes to be skipped. 1524693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 4> SkippedLoopAndExitBlocks; 1525693eedb1SChandler Carruth if (ContinueSuccBB->getUniquePredecessor() || 1526693eedb1SChandler Carruth llvm::all_of(predecessors(ContinueSuccBB), [&](BasicBlock *PredBB) { 1527693eedb1SChandler Carruth return PredBB == ParentBB || DT.dominates(ContinueSuccBB, PredBB); 1528693eedb1SChandler Carruth })) { 1529693eedb1SChandler Carruth visitDomSubTree(DT, ContinueSuccBB, [&](BasicBlock *BB) { 1530693eedb1SChandler Carruth SkippedLoopAndExitBlocks.insert(BB); 1531693eedb1SChandler Carruth return true; 1532693eedb1SChandler Carruth }); 1533693eedb1SChandler Carruth } 1534693eedb1SChandler Carruth // Similarly, if the edge we *are* cloning in the unswitch (the unswitched 1535693eedb1SChandler Carruth // edge) dominates its target, we will end up with dead nodes in the original 1536693eedb1SChandler Carruth // loop and its exits that will need to be deleted. Here, we just retain that 1537693eedb1SChandler Carruth // the property holds and will compute the deleted set later. 1538693eedb1SChandler Carruth bool DeleteUnswitchedSucc = 1539693eedb1SChandler Carruth UnswitchedSuccBB->getUniquePredecessor() || 1540693eedb1SChandler Carruth llvm::all_of(predecessors(UnswitchedSuccBB), [&](BasicBlock *PredBB) { 1541693eedb1SChandler Carruth return PredBB == ParentBB || DT.dominates(UnswitchedSuccBB, PredBB); 1542693eedb1SChandler Carruth }); 1543693eedb1SChandler Carruth 1544693eedb1SChandler Carruth // Split the preheader, so that we know that there is a safe place to insert 1545693eedb1SChandler Carruth // the conditional branch. We will change the preheader to have a conditional 1546693eedb1SChandler Carruth // branch on LoopCond. The original preheader will become the split point 1547693eedb1SChandler Carruth // between the unswitched versions, and we will have a new preheader for the 1548693eedb1SChandler Carruth // original loop. 1549693eedb1SChandler Carruth BasicBlock *SplitBB = L.getLoopPreheader(); 1550693eedb1SChandler Carruth BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI); 1551693eedb1SChandler Carruth 1552693eedb1SChandler Carruth // Keep a mapping for the cloned values. 1553693eedb1SChandler Carruth ValueToValueMapTy VMap; 1554693eedb1SChandler Carruth 155569e68f84SChandler Carruth // Keep track of the dominator tree updates needed. 155669e68f84SChandler Carruth SmallVector<DominatorTree::UpdateType, 4> DTUpdates; 155769e68f84SChandler Carruth 1558693eedb1SChandler Carruth // Build the cloned blocks from the loop. 1559693eedb1SChandler Carruth auto *ClonedPH = buildClonedLoopBlocks( 1560693eedb1SChandler Carruth L, LoopPH, SplitBB, ExitBlocks, ParentBB, UnswitchedSuccBB, 156169e68f84SChandler Carruth ContinueSuccBB, SkippedLoopAndExitBlocks, VMap, DTUpdates, AC, DT, LI); 1562693eedb1SChandler Carruth 1563693eedb1SChandler Carruth // Remove the parent as a predecessor of the unswitched successor. 1564693eedb1SChandler Carruth UnswitchedSuccBB->removePredecessor(ParentBB, /*DontDeleteUselessPHIs*/ true); 1565693eedb1SChandler Carruth 1566693eedb1SChandler Carruth // Now splice the branch from the original loop and use it to select between 1567693eedb1SChandler Carruth // the two loops. 1568693eedb1SChandler Carruth SplitBB->getTerminator()->eraseFromParent(); 1569693eedb1SChandler Carruth SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), BI); 1570693eedb1SChandler Carruth BI.setSuccessor(ClonedSucc, ClonedPH); 1571693eedb1SChandler Carruth BI.setSuccessor(1 - ClonedSucc, LoopPH); 1572693eedb1SChandler Carruth 1573693eedb1SChandler Carruth // Create a new unconditional branch to the continuing block (as opposed to 1574693eedb1SChandler Carruth // the one cloned). 1575693eedb1SChandler Carruth BranchInst::Create(ContinueSuccBB, ParentBB); 1576693eedb1SChandler Carruth 157769e68f84SChandler Carruth // Before we update the dominator tree, collect the dead blocks if we're going 157869e68f84SChandler Carruth // to end up deleting the unswitched successor. 157969e68f84SChandler Carruth SmallVector<BasicBlock *, 16> DeadBlocks; 158069e68f84SChandler Carruth if (DeleteUnswitchedSucc) { 158169e68f84SChandler Carruth DeadBlocks.push_back(UnswitchedSuccBB); 158269e68f84SChandler Carruth for (int i = 0; i < (int)DeadBlocks.size(); ++i) { 158369e68f84SChandler Carruth // If we reach an exit block, stop recursing as the unswitched loop will 158469e68f84SChandler Carruth // end up reaching the merge block which we make the successor of the 158569e68f84SChandler Carruth // exit. 158669e68f84SChandler Carruth if (ExitBlockSet.count(DeadBlocks[i])) 158769e68f84SChandler Carruth continue; 158869e68f84SChandler Carruth 158969e68f84SChandler Carruth // Insert the children that are within the loop or exit block set. Other 159069e68f84SChandler Carruth // children may reach out of the loop. While we don't expect these to be 159169e68f84SChandler Carruth // dead (as the unswitched clone should reach them) we don't try to prove 159269e68f84SChandler Carruth // that here. 159369e68f84SChandler Carruth for (DomTreeNode *ChildN : *DT[DeadBlocks[i]]) 159469e68f84SChandler Carruth if (L.contains(ChildN->getBlock()) || 159569e68f84SChandler Carruth ExitBlockSet.count(ChildN->getBlock())) 159669e68f84SChandler Carruth DeadBlocks.push_back(ChildN->getBlock()); 159769e68f84SChandler Carruth } 159869e68f84SChandler Carruth } 159969e68f84SChandler Carruth 160069e68f84SChandler Carruth // Add the remaining edges to our updates and apply them to get an up-to-date 160169e68f84SChandler Carruth // dominator tree. Note that this will cause the dead blocks above to be 160269e68f84SChandler Carruth // unreachable and no longer in the dominator tree. 160369e68f84SChandler Carruth DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB}); 160469e68f84SChandler Carruth DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH}); 160569e68f84SChandler Carruth DT.applyUpdates(DTUpdates); 160669e68f84SChandler Carruth 160769e68f84SChandler Carruth // Build the cloned loop structure itself. This may be substantially 160869e68f84SChandler Carruth // different from the original structure due to the simplified CFG. This also 160969e68f84SChandler Carruth // handles inserting all the cloned blocks into the correct loops. 161069e68f84SChandler Carruth SmallVector<Loop *, 4> NonChildClonedLoops; 161169e68f84SChandler Carruth Loop *ClonedL = 161269e68f84SChandler Carruth buildClonedLoops(L, ExitBlocks, VMap, LI, NonChildClonedLoops); 161369e68f84SChandler Carruth 1614693eedb1SChandler Carruth // Delete anything that was made dead in the original loop due to 1615693eedb1SChandler Carruth // unswitching. 161669e68f84SChandler Carruth if (!DeadBlocks.empty()) 161769e68f84SChandler Carruth deleteDeadBlocksFromLoop(L, DeadBlocks, ExitBlocks, DT, LI); 1618693eedb1SChandler Carruth 1619693eedb1SChandler Carruth SmallVector<Loop *, 4> HoistedLoops; 1620693eedb1SChandler Carruth bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops); 1621693eedb1SChandler Carruth 162269e68f84SChandler Carruth // This transformation has a high risk of corrupting the dominator tree, and 162369e68f84SChandler Carruth // the below steps to rebuild loop structures will result in hard to debug 162469e68f84SChandler Carruth // errors in that case so verify that the dominator tree is sane first. 162569e68f84SChandler Carruth // FIXME: Remove this when the bugs stop showing up and rely on existing 162669e68f84SChandler Carruth // verification steps. 162769e68f84SChandler Carruth assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 1628693eedb1SChandler Carruth 1629693eedb1SChandler Carruth // We can change which blocks are exit blocks of all the cloned sibling 1630693eedb1SChandler Carruth // loops, the current loop, and any parent loops which shared exit blocks 1631693eedb1SChandler Carruth // with the current loop. As a consequence, we need to re-form LCSSA for 1632693eedb1SChandler Carruth // them. But we shouldn't need to re-form LCSSA for any child loops. 1633693eedb1SChandler Carruth // FIXME: This could be made more efficient by tracking which exit blocks are 1634693eedb1SChandler Carruth // new, and focusing on them, but that isn't likely to be necessary. 1635693eedb1SChandler Carruth // 1636693eedb1SChandler Carruth // In order to reasonably rebuild LCSSA we need to walk inside-out across the 1637693eedb1SChandler Carruth // loop nest and update every loop that could have had its exits changed. We 1638693eedb1SChandler Carruth // also need to cover any intervening loops. We add all of these loops to 1639693eedb1SChandler Carruth // a list and sort them by loop depth to achieve this without updating 1640693eedb1SChandler Carruth // unnecessary loops. 1641693eedb1SChandler Carruth auto UpdateLCSSA = [&](Loop &UpdateL) { 1642693eedb1SChandler Carruth #ifndef NDEBUG 164343acdb35SChandler Carruth UpdateL.verifyLoop(); 164443acdb35SChandler Carruth for (Loop *ChildL : UpdateL) { 164543acdb35SChandler Carruth ChildL->verifyLoop(); 1646693eedb1SChandler Carruth assert(ChildL->isRecursivelyLCSSAForm(DT, LI) && 1647693eedb1SChandler Carruth "Perturbed a child loop's LCSSA form!"); 164843acdb35SChandler Carruth } 1649693eedb1SChandler Carruth #endif 1650693eedb1SChandler Carruth formLCSSA(UpdateL, DT, &LI, nullptr); 1651693eedb1SChandler Carruth }; 1652693eedb1SChandler Carruth 1653693eedb1SChandler Carruth // For non-child cloned loops and hoisted loops, we just need to update LCSSA 1654693eedb1SChandler Carruth // and we can do it in any order as they don't nest relative to each other. 1655693eedb1SChandler Carruth for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) 1656693eedb1SChandler Carruth UpdateLCSSA(*UpdatedL); 1657693eedb1SChandler Carruth 1658693eedb1SChandler Carruth // If the original loop had exit blocks, walk up through the outer most loop 1659693eedb1SChandler Carruth // of those exit blocks to update LCSSA and form updated dedicated exits. 1660693eedb1SChandler Carruth if (OuterExitL != &L) { 1661693eedb1SChandler Carruth SmallVector<Loop *, 4> OuterLoops; 1662693eedb1SChandler Carruth // We start with the cloned loop and the current loop if they are loops and 1663693eedb1SChandler Carruth // move toward OuterExitL. Also, if either the cloned loop or the current 1664693eedb1SChandler Carruth // loop have become top level loops we need to walk all the way out. 1665693eedb1SChandler Carruth if (ClonedL) { 1666693eedb1SChandler Carruth OuterLoops.push_back(ClonedL); 1667693eedb1SChandler Carruth if (!ClonedL->getParentLoop()) 1668693eedb1SChandler Carruth OuterExitL = nullptr; 1669693eedb1SChandler Carruth } 1670693eedb1SChandler Carruth if (IsStillLoop) { 1671693eedb1SChandler Carruth OuterLoops.push_back(&L); 1672693eedb1SChandler Carruth if (!L.getParentLoop()) 1673693eedb1SChandler Carruth OuterExitL = nullptr; 1674693eedb1SChandler Carruth } 1675693eedb1SChandler Carruth // Grab all of the enclosing loops now. 1676693eedb1SChandler Carruth for (Loop *OuterL = ParentL; OuterL != OuterExitL; 1677693eedb1SChandler Carruth OuterL = OuterL->getParentLoop()) 1678693eedb1SChandler Carruth OuterLoops.push_back(OuterL); 1679693eedb1SChandler Carruth 1680693eedb1SChandler Carruth // Finally, update our list of outer loops. This is nicely ordered to work 1681693eedb1SChandler Carruth // inside-out. 1682693eedb1SChandler Carruth for (Loop *OuterL : OuterLoops) { 1683693eedb1SChandler Carruth // First build LCSSA for this loop so that we can preserve it when 1684693eedb1SChandler Carruth // forming dedicated exits. We don't want to perturb some other loop's 1685693eedb1SChandler Carruth // LCSSA while doing that CFG edit. 1686693eedb1SChandler Carruth UpdateLCSSA(*OuterL); 1687693eedb1SChandler Carruth 1688693eedb1SChandler Carruth // For loops reached by this loop's original exit blocks we may 1689693eedb1SChandler Carruth // introduced new, non-dedicated exits. At least try to re-form dedicated 1690693eedb1SChandler Carruth // exits for these loops. This may fail if they couldn't have dedicated 1691693eedb1SChandler Carruth // exits to start with. 1692693eedb1SChandler Carruth formDedicatedExitBlocks(OuterL, &DT, &LI, /*PreserveLCSSA*/ true); 1693693eedb1SChandler Carruth } 1694693eedb1SChandler Carruth } 1695693eedb1SChandler Carruth 1696693eedb1SChandler Carruth #ifndef NDEBUG 1697693eedb1SChandler Carruth // Verify the entire loop structure to catch any incorrect updates before we 1698693eedb1SChandler Carruth // progress in the pass pipeline. 1699693eedb1SChandler Carruth LI.verify(DT); 1700693eedb1SChandler Carruth #endif 1701693eedb1SChandler Carruth 1702693eedb1SChandler Carruth // Now that we've unswitched something, make callbacks to report the changes. 1703693eedb1SChandler Carruth // For that we need to merge together the updated loops and the cloned loops 1704693eedb1SChandler Carruth // and check whether the original loop survived. 1705693eedb1SChandler Carruth SmallVector<Loop *, 4> SibLoops; 1706693eedb1SChandler Carruth for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) 1707693eedb1SChandler Carruth if (UpdatedL->getParentLoop() == ParentL) 1708693eedb1SChandler Carruth SibLoops.push_back(UpdatedL); 1709693eedb1SChandler Carruth NonTrivialUnswitchCB(IsStillLoop, SibLoops); 1710693eedb1SChandler Carruth 1711693eedb1SChandler Carruth ++NumBranches; 1712693eedb1SChandler Carruth return true; 1713693eedb1SChandler Carruth } 1714693eedb1SChandler Carruth 1715693eedb1SChandler Carruth /// Recursively compute the cost of a dominator subtree based on the per-block 1716693eedb1SChandler Carruth /// cost map provided. 1717693eedb1SChandler Carruth /// 1718693eedb1SChandler Carruth /// The recursive computation is memozied into the provided DT-indexed cost map 1719693eedb1SChandler Carruth /// to allow querying it for most nodes in the domtree without it becoming 1720693eedb1SChandler Carruth /// quadratic. 1721693eedb1SChandler Carruth static int 1722693eedb1SChandler Carruth computeDomSubtreeCost(DomTreeNode &N, 1723693eedb1SChandler Carruth const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap, 1724693eedb1SChandler Carruth SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) { 1725693eedb1SChandler Carruth // Don't accumulate cost (or recurse through) blocks not in our block cost 1726693eedb1SChandler Carruth // map and thus not part of the duplication cost being considered. 1727693eedb1SChandler Carruth auto BBCostIt = BBCostMap.find(N.getBlock()); 1728693eedb1SChandler Carruth if (BBCostIt == BBCostMap.end()) 1729693eedb1SChandler Carruth return 0; 1730693eedb1SChandler Carruth 1731693eedb1SChandler Carruth // Lookup this node to see if we already computed its cost. 1732693eedb1SChandler Carruth auto DTCostIt = DTCostMap.find(&N); 1733693eedb1SChandler Carruth if (DTCostIt != DTCostMap.end()) 1734693eedb1SChandler Carruth return DTCostIt->second; 1735693eedb1SChandler Carruth 1736693eedb1SChandler Carruth // If not, we have to compute it. We can't use insert above and update 1737693eedb1SChandler Carruth // because computing the cost may insert more things into the map. 1738693eedb1SChandler Carruth int Cost = std::accumulate( 1739693eedb1SChandler Carruth N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) { 1740693eedb1SChandler Carruth return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap); 1741693eedb1SChandler Carruth }); 1742693eedb1SChandler Carruth bool Inserted = DTCostMap.insert({&N, Cost}).second; 1743693eedb1SChandler Carruth (void)Inserted; 1744693eedb1SChandler Carruth assert(Inserted && "Should not insert a node while visiting children!"); 1745693eedb1SChandler Carruth return Cost; 1746693eedb1SChandler Carruth } 1747693eedb1SChandler Carruth 17481353f9a4SChandler Carruth /// Unswitch control flow predicated on loop invariant conditions. 17491353f9a4SChandler Carruth /// 17501353f9a4SChandler Carruth /// This first hoists all branches or switches which are trivial (IE, do not 17511353f9a4SChandler Carruth /// require duplicating any part of the loop) out of the loop body. It then 17521353f9a4SChandler Carruth /// looks at other loop invariant control flows and tries to unswitch those as 17531353f9a4SChandler Carruth /// well by cloning the loop if the result is small enough. 1754693eedb1SChandler Carruth static bool 1755693eedb1SChandler Carruth unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, 1756693eedb1SChandler Carruth TargetTransformInfo &TTI, bool NonTrivial, 1757693eedb1SChandler Carruth function_ref<void(bool, ArrayRef<Loop *>)> NonTrivialUnswitchCB) { 1758693eedb1SChandler Carruth assert(L.isRecursivelyLCSSAForm(DT, LI) && 17591353f9a4SChandler Carruth "Loops must be in LCSSA form before unswitching."); 17601353f9a4SChandler Carruth bool Changed = false; 17611353f9a4SChandler Carruth 17621353f9a4SChandler Carruth // Must be in loop simplified form: we need a preheader and dedicated exits. 17631353f9a4SChandler Carruth if (!L.isLoopSimplifyForm()) 17641353f9a4SChandler Carruth return false; 17651353f9a4SChandler Carruth 17661353f9a4SChandler Carruth // Try trivial unswitch first before loop over other basic blocks in the loop. 17671353f9a4SChandler Carruth Changed |= unswitchAllTrivialConditions(L, DT, LI); 17681353f9a4SChandler Carruth 1769693eedb1SChandler Carruth // If we're not doing non-trivial unswitching, we're done. We both accept 1770693eedb1SChandler Carruth // a parameter but also check a local flag that can be used for testing 1771693eedb1SChandler Carruth // a debugging. 1772693eedb1SChandler Carruth if (!NonTrivial && !EnableNonTrivialUnswitch) 1773693eedb1SChandler Carruth return Changed; 1774693eedb1SChandler Carruth 1775693eedb1SChandler Carruth // Collect all remaining invariant branch conditions within this loop (as 1776693eedb1SChandler Carruth // opposed to an inner loop which would be handled when visiting that inner 1777693eedb1SChandler Carruth // loop). 1778693eedb1SChandler Carruth SmallVector<TerminatorInst *, 4> UnswitchCandidates; 1779693eedb1SChandler Carruth for (auto *BB : L.blocks()) 1780693eedb1SChandler Carruth if (LI.getLoopFor(BB) == &L) 1781693eedb1SChandler Carruth if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator())) 1782693eedb1SChandler Carruth if (BI->isConditional() && L.isLoopInvariant(BI->getCondition()) && 1783693eedb1SChandler Carruth BI->getSuccessor(0) != BI->getSuccessor(1)) 1784693eedb1SChandler Carruth UnswitchCandidates.push_back(BI); 1785693eedb1SChandler Carruth 1786693eedb1SChandler Carruth // If we didn't find any candidates, we're done. 1787693eedb1SChandler Carruth if (UnswitchCandidates.empty()) 1788693eedb1SChandler Carruth return Changed; 1789693eedb1SChandler Carruth 179032e62f9cSChandler Carruth // Check if there are irreducible CFG cycles in this loop. If so, we cannot 179132e62f9cSChandler Carruth // easily unswitch non-trivial edges out of the loop. Doing so might turn the 179232e62f9cSChandler Carruth // irreducible control flow into reducible control flow and introduce new 179332e62f9cSChandler Carruth // loops "out of thin air". If we ever discover important use cases for doing 179432e62f9cSChandler Carruth // this, we can add support to loop unswitch, but it is a lot of complexity 179532e62f9cSChandler Carruth // for what seems little or no real world benifit. 179632e62f9cSChandler Carruth LoopBlocksRPO RPOT(&L); 179732e62f9cSChandler Carruth RPOT.perform(&LI); 179832e62f9cSChandler Carruth if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI)) 179932e62f9cSChandler Carruth return Changed; 180032e62f9cSChandler Carruth 1801693eedb1SChandler Carruth DEBUG(dbgs() << "Considering " << UnswitchCandidates.size() 1802693eedb1SChandler Carruth << " non-trivial loop invariant conditions for unswitching.\n"); 1803693eedb1SChandler Carruth 1804693eedb1SChandler Carruth // Given that unswitching these terminators will require duplicating parts of 1805693eedb1SChandler Carruth // the loop, so we need to be able to model that cost. Compute the ephemeral 1806693eedb1SChandler Carruth // values and set up a data structure to hold per-BB costs. We cache each 1807693eedb1SChandler Carruth // block's cost so that we don't recompute this when considering different 1808693eedb1SChandler Carruth // subsets of the loop for duplication during unswitching. 1809693eedb1SChandler Carruth SmallPtrSet<const Value *, 4> EphValues; 1810693eedb1SChandler Carruth CodeMetrics::collectEphemeralValues(&L, &AC, EphValues); 1811693eedb1SChandler Carruth SmallDenseMap<BasicBlock *, int, 4> BBCostMap; 1812693eedb1SChandler Carruth 1813693eedb1SChandler Carruth // Compute the cost of each block, as well as the total loop cost. Also, bail 1814693eedb1SChandler Carruth // out if we see instructions which are incompatible with loop unswitching 1815693eedb1SChandler Carruth // (convergent, noduplicate, or cross-basic-block tokens). 1816693eedb1SChandler Carruth // FIXME: We might be able to safely handle some of these in non-duplicated 1817693eedb1SChandler Carruth // regions. 1818693eedb1SChandler Carruth int LoopCost = 0; 1819693eedb1SChandler Carruth for (auto *BB : L.blocks()) { 1820693eedb1SChandler Carruth int Cost = 0; 1821693eedb1SChandler Carruth for (auto &I : *BB) { 1822693eedb1SChandler Carruth if (EphValues.count(&I)) 1823693eedb1SChandler Carruth continue; 1824693eedb1SChandler Carruth 1825693eedb1SChandler Carruth if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB)) 1826693eedb1SChandler Carruth return Changed; 1827693eedb1SChandler Carruth if (auto CS = CallSite(&I)) 1828693eedb1SChandler Carruth if (CS.isConvergent() || CS.cannotDuplicate()) 1829693eedb1SChandler Carruth return Changed; 1830693eedb1SChandler Carruth 1831693eedb1SChandler Carruth Cost += TTI.getUserCost(&I); 1832693eedb1SChandler Carruth } 1833693eedb1SChandler Carruth assert(Cost >= 0 && "Must not have negative costs!"); 1834693eedb1SChandler Carruth LoopCost += Cost; 1835693eedb1SChandler Carruth assert(LoopCost >= 0 && "Must not have negative loop costs!"); 1836693eedb1SChandler Carruth BBCostMap[BB] = Cost; 1837693eedb1SChandler Carruth } 1838693eedb1SChandler Carruth DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n"); 1839693eedb1SChandler Carruth 1840693eedb1SChandler Carruth // Now we find the best candidate by searching for the one with the following 1841693eedb1SChandler Carruth // properties in order: 1842693eedb1SChandler Carruth // 1843693eedb1SChandler Carruth // 1) An unswitching cost below the threshold 1844693eedb1SChandler Carruth // 2) The smallest number of duplicated unswitch candidates (to avoid 1845693eedb1SChandler Carruth // creating redundant subsequent unswitching) 1846693eedb1SChandler Carruth // 3) The smallest cost after unswitching. 1847693eedb1SChandler Carruth // 1848693eedb1SChandler Carruth // We prioritize reducing fanout of unswitch candidates provided the cost 1849693eedb1SChandler Carruth // remains below the threshold because this has a multiplicative effect. 1850693eedb1SChandler Carruth // 1851693eedb1SChandler Carruth // This requires memoizing each dominator subtree to avoid redundant work. 1852693eedb1SChandler Carruth // 1853693eedb1SChandler Carruth // FIXME: Need to actually do the number of candidates part above. 1854693eedb1SChandler Carruth SmallDenseMap<DomTreeNode *, int, 4> DTCostMap; 1855693eedb1SChandler Carruth // Given a terminator which might be unswitched, computes the non-duplicated 1856693eedb1SChandler Carruth // cost for that terminator. 1857693eedb1SChandler Carruth auto ComputeUnswitchedCost = [&](TerminatorInst *TI) { 1858693eedb1SChandler Carruth BasicBlock &BB = *TI->getParent(); 1859693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 4> Visited; 1860693eedb1SChandler Carruth 1861693eedb1SChandler Carruth int Cost = LoopCost; 1862693eedb1SChandler Carruth for (BasicBlock *SuccBB : successors(&BB)) { 1863693eedb1SChandler Carruth // Don't count successors more than once. 1864693eedb1SChandler Carruth if (!Visited.insert(SuccBB).second) 1865693eedb1SChandler Carruth continue; 1866693eedb1SChandler Carruth 1867693eedb1SChandler Carruth // This successor's domtree will not need to be duplicated after 1868693eedb1SChandler Carruth // unswitching if the edge to the successor dominates it (and thus the 1869693eedb1SChandler Carruth // entire tree). This essentially means there is no other path into this 1870693eedb1SChandler Carruth // subtree and so it will end up live in only one clone of the loop. 1871693eedb1SChandler Carruth if (SuccBB->getUniquePredecessor() || 1872693eedb1SChandler Carruth llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) { 1873693eedb1SChandler Carruth return PredBB == &BB || DT.dominates(SuccBB, PredBB); 1874693eedb1SChandler Carruth })) { 1875693eedb1SChandler Carruth Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap); 1876693eedb1SChandler Carruth assert(Cost >= 0 && 1877693eedb1SChandler Carruth "Non-duplicated cost should never exceed total loop cost!"); 1878693eedb1SChandler Carruth } 1879693eedb1SChandler Carruth } 1880693eedb1SChandler Carruth 1881693eedb1SChandler Carruth // Now scale the cost by the number of unique successors minus one. We 1882693eedb1SChandler Carruth // subtract one because there is already at least one copy of the entire 1883693eedb1SChandler Carruth // loop. This is computing the new cost of unswitching a condition. 1884693eedb1SChandler Carruth assert(Visited.size() > 1 && 1885693eedb1SChandler Carruth "Cannot unswitch a condition without multiple distinct successors!"); 1886693eedb1SChandler Carruth return Cost * (Visited.size() - 1); 1887693eedb1SChandler Carruth }; 1888693eedb1SChandler Carruth TerminatorInst *BestUnswitchTI = nullptr; 1889693eedb1SChandler Carruth int BestUnswitchCost; 1890693eedb1SChandler Carruth for (TerminatorInst *CandidateTI : UnswitchCandidates) { 1891693eedb1SChandler Carruth int CandidateCost = ComputeUnswitchedCost(CandidateTI); 1892693eedb1SChandler Carruth DEBUG(dbgs() << " Computed cost of " << CandidateCost 1893693eedb1SChandler Carruth << " for unswitch candidate: " << *CandidateTI << "\n"); 1894693eedb1SChandler Carruth if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) { 1895693eedb1SChandler Carruth BestUnswitchTI = CandidateTI; 1896693eedb1SChandler Carruth BestUnswitchCost = CandidateCost; 1897693eedb1SChandler Carruth } 1898693eedb1SChandler Carruth } 1899693eedb1SChandler Carruth 1900693eedb1SChandler Carruth if (BestUnswitchCost < UnswitchThreshold) { 1901693eedb1SChandler Carruth DEBUG(dbgs() << " Trying to unswitch non-trivial (cost = " 1902693eedb1SChandler Carruth << BestUnswitchCost << ") branch: " << *BestUnswitchTI 1903693eedb1SChandler Carruth << "\n"); 1904693eedb1SChandler Carruth Changed |= unswitchInvariantBranch(L, cast<BranchInst>(*BestUnswitchTI), DT, 1905693eedb1SChandler Carruth LI, AC, NonTrivialUnswitchCB); 1906693eedb1SChandler Carruth } else { 1907693eedb1SChandler Carruth DEBUG(dbgs() << "Cannot unswitch, lowest cost found: " << BestUnswitchCost 1908693eedb1SChandler Carruth << "\n"); 1909693eedb1SChandler Carruth } 19101353f9a4SChandler Carruth 19111353f9a4SChandler Carruth return Changed; 19121353f9a4SChandler Carruth } 19131353f9a4SChandler Carruth 19141353f9a4SChandler Carruth PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM, 19151353f9a4SChandler Carruth LoopStandardAnalysisResults &AR, 19161353f9a4SChandler Carruth LPMUpdater &U) { 19171353f9a4SChandler Carruth Function &F = *L.getHeader()->getParent(); 19181353f9a4SChandler Carruth (void)F; 19191353f9a4SChandler Carruth 19201353f9a4SChandler Carruth DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L << "\n"); 19211353f9a4SChandler Carruth 1922693eedb1SChandler Carruth // Save the current loop name in a variable so that we can report it even 1923693eedb1SChandler Carruth // after it has been deleted. 1924693eedb1SChandler Carruth std::string LoopName = L.getName(); 1925693eedb1SChandler Carruth 1926693eedb1SChandler Carruth auto NonTrivialUnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid, 1927693eedb1SChandler Carruth ArrayRef<Loop *> NewLoops) { 1928693eedb1SChandler Carruth // If we did a non-trivial unswitch, we have added new (cloned) loops. 1929693eedb1SChandler Carruth U.addSiblingLoops(NewLoops); 1930693eedb1SChandler Carruth 1931693eedb1SChandler Carruth // If the current loop remains valid, we should revisit it to catch any 1932693eedb1SChandler Carruth // other unswitch opportunities. Otherwise, we need to mark it as deleted. 1933693eedb1SChandler Carruth if (CurrentLoopValid) 1934693eedb1SChandler Carruth U.revisitCurrentLoop(); 1935693eedb1SChandler Carruth else 1936693eedb1SChandler Carruth U.markLoopAsDeleted(L, LoopName); 1937693eedb1SChandler Carruth }; 1938693eedb1SChandler Carruth 1939693eedb1SChandler Carruth if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, 1940693eedb1SChandler Carruth NonTrivialUnswitchCB)) 19411353f9a4SChandler Carruth return PreservedAnalyses::all(); 19421353f9a4SChandler Carruth 19431353f9a4SChandler Carruth // Historically this pass has had issues with the dominator tree so verify it 19441353f9a4SChandler Carruth // in asserts builds. 19457c35de12SDavid Green assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast)); 19461353f9a4SChandler Carruth return getLoopPassPreservedAnalyses(); 19471353f9a4SChandler Carruth } 19481353f9a4SChandler Carruth 19491353f9a4SChandler Carruth namespace { 1950a369a457SEugene Zelenko 19511353f9a4SChandler Carruth class SimpleLoopUnswitchLegacyPass : public LoopPass { 1952693eedb1SChandler Carruth bool NonTrivial; 1953693eedb1SChandler Carruth 19541353f9a4SChandler Carruth public: 19551353f9a4SChandler Carruth static char ID; // Pass ID, replacement for typeid 1956a369a457SEugene Zelenko 1957693eedb1SChandler Carruth explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false) 1958693eedb1SChandler Carruth : LoopPass(ID), NonTrivial(NonTrivial) { 19591353f9a4SChandler Carruth initializeSimpleLoopUnswitchLegacyPassPass( 19601353f9a4SChandler Carruth *PassRegistry::getPassRegistry()); 19611353f9a4SChandler Carruth } 19621353f9a4SChandler Carruth 19631353f9a4SChandler Carruth bool runOnLoop(Loop *L, LPPassManager &LPM) override; 19641353f9a4SChandler Carruth 19651353f9a4SChandler Carruth void getAnalysisUsage(AnalysisUsage &AU) const override { 19661353f9a4SChandler Carruth AU.addRequired<AssumptionCacheTracker>(); 1967693eedb1SChandler Carruth AU.addRequired<TargetTransformInfoWrapperPass>(); 19681353f9a4SChandler Carruth getLoopAnalysisUsage(AU); 19691353f9a4SChandler Carruth } 19701353f9a4SChandler Carruth }; 1971a369a457SEugene Zelenko 1972a369a457SEugene Zelenko } // end anonymous namespace 19731353f9a4SChandler Carruth 19741353f9a4SChandler Carruth bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) { 19751353f9a4SChandler Carruth if (skipLoop(L)) 19761353f9a4SChandler Carruth return false; 19771353f9a4SChandler Carruth 19781353f9a4SChandler Carruth Function &F = *L->getHeader()->getParent(); 19791353f9a4SChandler Carruth 19801353f9a4SChandler Carruth DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L << "\n"); 19811353f9a4SChandler Carruth 19821353f9a4SChandler Carruth auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 19831353f9a4SChandler Carruth auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 19841353f9a4SChandler Carruth auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1985693eedb1SChandler Carruth auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 19861353f9a4SChandler Carruth 1987693eedb1SChandler Carruth auto NonTrivialUnswitchCB = [&L, &LPM](bool CurrentLoopValid, 1988693eedb1SChandler Carruth ArrayRef<Loop *> NewLoops) { 1989693eedb1SChandler Carruth // If we did a non-trivial unswitch, we have added new (cloned) loops. 1990693eedb1SChandler Carruth for (auto *NewL : NewLoops) 1991693eedb1SChandler Carruth LPM.addLoop(*NewL); 1992693eedb1SChandler Carruth 1993693eedb1SChandler Carruth // If the current loop remains valid, re-add it to the queue. This is 1994693eedb1SChandler Carruth // a little wasteful as we'll finish processing the current loop as well, 1995693eedb1SChandler Carruth // but it is the best we can do in the old PM. 1996693eedb1SChandler Carruth if (CurrentLoopValid) 1997693eedb1SChandler Carruth LPM.addLoop(*L); 1998693eedb1SChandler Carruth else 1999693eedb1SChandler Carruth LPM.markLoopAsDeleted(*L); 2000693eedb1SChandler Carruth }; 2001693eedb1SChandler Carruth 2002693eedb1SChandler Carruth bool Changed = 2003693eedb1SChandler Carruth unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, NonTrivialUnswitchCB); 2004693eedb1SChandler Carruth 2005693eedb1SChandler Carruth // If anything was unswitched, also clear any cached information about this 2006693eedb1SChandler Carruth // loop. 2007693eedb1SChandler Carruth LPM.deleteSimpleAnalysisLoop(L); 20081353f9a4SChandler Carruth 20091353f9a4SChandler Carruth // Historically this pass has had issues with the dominator tree so verify it 20101353f9a4SChandler Carruth // in asserts builds. 20117c35de12SDavid Green assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 20127c35de12SDavid Green 20131353f9a4SChandler Carruth return Changed; 20141353f9a4SChandler Carruth } 20151353f9a4SChandler Carruth 20161353f9a4SChandler Carruth char SimpleLoopUnswitchLegacyPass::ID = 0; 20171353f9a4SChandler Carruth INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch", 20181353f9a4SChandler Carruth "Simple unswitch loops", false, false) 20191353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 2020693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2021693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 20221353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopPass) 20231353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 20241353f9a4SChandler Carruth INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch", 20251353f9a4SChandler Carruth "Simple unswitch loops", false, false) 20261353f9a4SChandler Carruth 2027693eedb1SChandler Carruth Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) { 2028693eedb1SChandler Carruth return new SimpleLoopUnswitchLegacyPass(NonTrivial); 20291353f9a4SChandler Carruth } 2030