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"
20693eedb1SChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
21a369a457SEugene Zelenko #include "llvm/Analysis/LoopAnalysisManager.h"
221353f9a4SChandler Carruth #include "llvm/Analysis/LoopInfo.h"
231353f9a4SChandler Carruth #include "llvm/Analysis/LoopPass.h"
24a369a457SEugene Zelenko #include "llvm/IR/BasicBlock.h"
25a369a457SEugene Zelenko #include "llvm/IR/Constant.h"
261353f9a4SChandler Carruth #include "llvm/IR/Constants.h"
271353f9a4SChandler Carruth #include "llvm/IR/Dominators.h"
281353f9a4SChandler Carruth #include "llvm/IR/Function.h"
29a369a457SEugene Zelenko #include "llvm/IR/InstrTypes.h"
30a369a457SEugene Zelenko #include "llvm/IR/Instruction.h"
311353f9a4SChandler Carruth #include "llvm/IR/Instructions.h"
32693eedb1SChandler Carruth #include "llvm/IR/IntrinsicInst.h"
33a369a457SEugene Zelenko #include "llvm/IR/Use.h"
34a369a457SEugene Zelenko #include "llvm/IR/Value.h"
35a369a457SEugene Zelenko #include "llvm/Pass.h"
36a369a457SEugene Zelenko #include "llvm/Support/Casting.h"
371353f9a4SChandler Carruth #include "llvm/Support/Debug.h"
38a369a457SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
39a369a457SEugene Zelenko #include "llvm/Support/GenericDomTree.h"
401353f9a4SChandler Carruth #include "llvm/Support/raw_ostream.h"
41693eedb1SChandler Carruth #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
421353f9a4SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43693eedb1SChandler Carruth #include "llvm/Transforms/Utils/Cloning.h"
441353f9a4SChandler Carruth #include "llvm/Transforms/Utils/LoopUtils.h"
45693eedb1SChandler Carruth #include "llvm/Transforms/Utils/ValueMapper.h"
46a369a457SEugene Zelenko #include <algorithm>
47a369a457SEugene Zelenko #include <cassert>
48a369a457SEugene Zelenko #include <iterator>
49693eedb1SChandler Carruth #include <numeric>
50a369a457SEugene Zelenko #include <utility>
511353f9a4SChandler Carruth 
521353f9a4SChandler Carruth #define DEBUG_TYPE "simple-loop-unswitch"
531353f9a4SChandler Carruth 
541353f9a4SChandler Carruth using namespace llvm;
551353f9a4SChandler Carruth 
561353f9a4SChandler Carruth STATISTIC(NumBranches, "Number of branches unswitched");
571353f9a4SChandler Carruth STATISTIC(NumSwitches, "Number of switches unswitched");
581353f9a4SChandler Carruth STATISTIC(NumTrivial, "Number of unswitches that are trivial");
591353f9a4SChandler Carruth 
60693eedb1SChandler Carruth static cl::opt<bool> EnableNonTrivialUnswitch(
61693eedb1SChandler Carruth     "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
62693eedb1SChandler Carruth     cl::desc("Forcibly enables non-trivial loop unswitching rather than "
63693eedb1SChandler Carruth              "following the configuration passed into the pass."));
64693eedb1SChandler Carruth 
65693eedb1SChandler Carruth static cl::opt<int>
66693eedb1SChandler Carruth     UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
67693eedb1SChandler Carruth                       cl::desc("The cost threshold for unswitching a loop."));
68693eedb1SChandler Carruth 
691353f9a4SChandler Carruth static void replaceLoopUsesWithConstant(Loop &L, Value &LIC,
701353f9a4SChandler Carruth                                         Constant &Replacement) {
711353f9a4SChandler Carruth   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
721353f9a4SChandler Carruth 
731353f9a4SChandler Carruth   // Replace uses of LIC in the loop with the given constant.
741353f9a4SChandler Carruth   for (auto UI = LIC.use_begin(), UE = LIC.use_end(); UI != UE;) {
751353f9a4SChandler Carruth     // Grab the use and walk past it so we can clobber it in the use list.
761353f9a4SChandler Carruth     Use *U = &*UI++;
771353f9a4SChandler Carruth     Instruction *UserI = dyn_cast<Instruction>(U->getUser());
781353f9a4SChandler Carruth     if (!UserI || !L.contains(UserI))
791353f9a4SChandler Carruth       continue;
801353f9a4SChandler Carruth 
811353f9a4SChandler Carruth     // Replace this use within the loop body.
821353f9a4SChandler Carruth     *U = &Replacement;
831353f9a4SChandler Carruth   }
841353f9a4SChandler Carruth }
851353f9a4SChandler Carruth 
86693eedb1SChandler Carruth /// Update the IDom for a basic block whose predecessor set has changed.
87693eedb1SChandler Carruth ///
88693eedb1SChandler Carruth /// This routine is designed to work when the domtree update is relatively
89693eedb1SChandler Carruth /// localized by leveraging a known common dominator, often a loop header.
90693eedb1SChandler Carruth ///
91693eedb1SChandler Carruth /// FIXME: Should consider hand-rolling a slightly more efficient non-DFS
92693eedb1SChandler Carruth /// approach here as we can do that easily by persisting the candidate IDom's
93693eedb1SChandler Carruth /// dominating set between each predecessor.
94693eedb1SChandler Carruth ///
95693eedb1SChandler Carruth /// FIXME: Longer term, many uses of this can be replaced by an incremental
96693eedb1SChandler Carruth /// domtree update strategy that starts from a known dominating block and
97693eedb1SChandler Carruth /// rebuilds that subtree.
98693eedb1SChandler Carruth static bool updateIDomWithKnownCommonDominator(BasicBlock *BB,
99693eedb1SChandler Carruth                                                BasicBlock *KnownDominatingBB,
1001353f9a4SChandler Carruth                                                DominatorTree &DT) {
101693eedb1SChandler Carruth   assert(pred_begin(BB) != pred_end(BB) &&
102693eedb1SChandler Carruth          "This routine does not handle unreachable blocks!");
1031353f9a4SChandler Carruth 
104693eedb1SChandler Carruth   BasicBlock *OrigIDom = DT[BB]->getIDom()->getBlock();
105693eedb1SChandler Carruth 
106693eedb1SChandler Carruth   BasicBlock *IDom = *pred_begin(BB);
107693eedb1SChandler Carruth   assert(DT.dominates(KnownDominatingBB, IDom) &&
108693eedb1SChandler Carruth          "Bad known dominating block!");
109693eedb1SChandler Carruth 
1101353f9a4SChandler Carruth   // Walk all of the other predecessors finding the nearest common dominator
1111353f9a4SChandler Carruth   // until all predecessors are covered or we reach the loop header. The loop
1121353f9a4SChandler Carruth   // header necessarily dominates all loop exit blocks in loop simplified form
1131353f9a4SChandler Carruth   // so we can early-exit the moment we hit that block.
114693eedb1SChandler Carruth   for (auto PI = std::next(pred_begin(BB)), PE = pred_end(BB);
115693eedb1SChandler Carruth        PI != PE && IDom != KnownDominatingBB; ++PI) {
116693eedb1SChandler Carruth     assert(DT.dominates(KnownDominatingBB, *PI) &&
117693eedb1SChandler Carruth            "Bad known dominating block!");
1181353f9a4SChandler Carruth     IDom = DT.findNearestCommonDominator(IDom, *PI);
119693eedb1SChandler Carruth   }
1201353f9a4SChandler Carruth 
121693eedb1SChandler Carruth   if (IDom == OrigIDom)
122693eedb1SChandler Carruth     return false;
123693eedb1SChandler Carruth 
124693eedb1SChandler Carruth   DT.changeImmediateDominator(BB, IDom);
125693eedb1SChandler Carruth   return true;
126693eedb1SChandler Carruth }
127693eedb1SChandler Carruth 
128693eedb1SChandler Carruth // Note that we don't currently use the IDFCalculator here for two reasons:
129693eedb1SChandler Carruth // 1) It computes dominator tree levels for the entire function on each run
130693eedb1SChandler Carruth //    of 'compute'. While this isn't terrible, given that we expect to update
131693eedb1SChandler Carruth //    relatively small subtrees of the domtree, it isn't necessarily the right
132693eedb1SChandler Carruth //    tradeoff.
133693eedb1SChandler Carruth // 2) The interface doesn't fit this usage well. It doesn't operate in
134693eedb1SChandler Carruth //    append-only, and builds several sets that we don't need.
135693eedb1SChandler Carruth //
136693eedb1SChandler Carruth // FIXME: Neither of these issues are a big deal and could be addressed with
137693eedb1SChandler Carruth // some amount of refactoring of IDFCalculator. That would allow us to share
138693eedb1SChandler Carruth // the core logic here (which is solving the same core problem).
13951ebcaafSBenjamin Kramer static void appendDomFrontier(DomTreeNode *Node,
140693eedb1SChandler Carruth                               SmallSetVector<BasicBlock *, 4> &Worklist,
141693eedb1SChandler Carruth                               SmallVectorImpl<DomTreeNode *> &DomNodes,
142693eedb1SChandler Carruth                               SmallPtrSetImpl<BasicBlock *> &DomSet) {
143693eedb1SChandler Carruth   assert(DomNodes.empty() && "Must start with no dominator nodes.");
144693eedb1SChandler Carruth   assert(DomSet.empty() && "Must start with an empty dominator set.");
145693eedb1SChandler Carruth 
146693eedb1SChandler Carruth   // First flatten this subtree into sequence of nodes by doing a pre-order
147693eedb1SChandler Carruth   // walk.
148693eedb1SChandler Carruth   DomNodes.push_back(Node);
149693eedb1SChandler Carruth   // We intentionally re-evaluate the size as each node can add new children.
150693eedb1SChandler Carruth   // Because this is a tree walk, this cannot add any duplicates.
151693eedb1SChandler Carruth   for (int i = 0; i < (int)DomNodes.size(); ++i)
152693eedb1SChandler Carruth     DomNodes.insert(DomNodes.end(), DomNodes[i]->begin(), DomNodes[i]->end());
153693eedb1SChandler Carruth 
154693eedb1SChandler Carruth   // Now create a set of the basic blocks so we can quickly test for
155693eedb1SChandler Carruth   // dominated successors. We could in theory use the DFS numbers of the
156693eedb1SChandler Carruth   // dominator tree for this, but we want this to remain predictably fast
157693eedb1SChandler Carruth   // even while we mutate the dominator tree in ways that would invalidate
158693eedb1SChandler Carruth   // the DFS numbering.
159693eedb1SChandler Carruth   for (DomTreeNode *InnerN : DomNodes)
160693eedb1SChandler Carruth     DomSet.insert(InnerN->getBlock());
161693eedb1SChandler Carruth 
162693eedb1SChandler Carruth   // Now re-walk the nodes, appending every successor of every node that isn't
163693eedb1SChandler Carruth   // in the set. Note that we don't append the node itself, even though if it
164693eedb1SChandler Carruth   // is a successor it does not strictly dominate itself and thus it would be
165693eedb1SChandler Carruth   // part of the dominance frontier. The reason we don't append it is that
166693eedb1SChandler Carruth   // the node passed in came *from* the worklist and so it has already been
167693eedb1SChandler Carruth   // processed.
168693eedb1SChandler Carruth   for (DomTreeNode *InnerN : DomNodes)
169693eedb1SChandler Carruth     for (BasicBlock *SuccBB : successors(InnerN->getBlock()))
170693eedb1SChandler Carruth       if (!DomSet.count(SuccBB))
171693eedb1SChandler Carruth         Worklist.insert(SuccBB);
172693eedb1SChandler Carruth 
173693eedb1SChandler Carruth   DomNodes.clear();
174693eedb1SChandler Carruth   DomSet.clear();
1751353f9a4SChandler Carruth }
1761353f9a4SChandler Carruth 
1771353f9a4SChandler Carruth /// Update the dominator tree after unswitching a particular former exit block.
1781353f9a4SChandler Carruth ///
1791353f9a4SChandler Carruth /// This handles the full update of the dominator tree after hoisting a block
1801353f9a4SChandler Carruth /// that previously was an exit block (or split off of an exit block) up to be
1811353f9a4SChandler Carruth /// reached from the new immediate dominator of the preheader.
1821353f9a4SChandler Carruth ///
1831353f9a4SChandler Carruth /// The common case is simple -- we just move the unswitched block to have an
1841353f9a4SChandler Carruth /// immediate dominator of the old preheader. But in complex cases, there may
1851353f9a4SChandler Carruth /// be other blocks reachable from the unswitched block that are immediately
1861353f9a4SChandler Carruth /// dominated by some node between the unswitched one and the old preheader.
1871353f9a4SChandler Carruth /// All of these also need to be hoisted in the dominator tree. We also want to
1881353f9a4SChandler Carruth /// minimize queries to the dominator tree because each step of this
1891353f9a4SChandler Carruth /// invalidates any DFS numbers that would make queries fast.
1901353f9a4SChandler Carruth static void updateDTAfterUnswitch(BasicBlock *UnswitchedBB, BasicBlock *OldPH,
1911353f9a4SChandler Carruth                                   DominatorTree &DT) {
1921353f9a4SChandler Carruth   DomTreeNode *OldPHNode = DT[OldPH];
1931353f9a4SChandler Carruth   DomTreeNode *UnswitchedNode = DT[UnswitchedBB];
1941353f9a4SChandler Carruth   // If the dominator tree has already been updated for this unswitched node,
1951353f9a4SChandler Carruth   // we're done. This makes it easier to use this routine if there are multiple
1961353f9a4SChandler Carruth   // paths to the same unswitched destination.
1971353f9a4SChandler Carruth   if (UnswitchedNode->getIDom() == OldPHNode)
1981353f9a4SChandler Carruth     return;
1991353f9a4SChandler Carruth 
2001353f9a4SChandler Carruth   // First collect the domtree nodes that we are hoisting over. These are the
2011353f9a4SChandler Carruth   // set of nodes which may have children that need to be hoisted as well.
2021353f9a4SChandler Carruth   SmallPtrSet<DomTreeNode *, 4> DomChain;
2031353f9a4SChandler Carruth   for (auto *IDom = UnswitchedNode->getIDom(); IDom != OldPHNode;
2041353f9a4SChandler Carruth        IDom = IDom->getIDom())
2051353f9a4SChandler Carruth     DomChain.insert(IDom);
2061353f9a4SChandler Carruth 
2071353f9a4SChandler Carruth   // The unswitched block ends up immediately dominated by the old preheader --
2081353f9a4SChandler Carruth   // regardless of whether it is the loop exit block or split off of the loop
2091353f9a4SChandler Carruth   // exit block.
2101353f9a4SChandler Carruth   DT.changeImmediateDominator(UnswitchedNode, OldPHNode);
2111353f9a4SChandler Carruth 
212dd2e275aSChandler Carruth   // For everything that moves up the dominator tree, we need to examine the
213dd2e275aSChandler Carruth   // dominator frontier to see if it additionally should move up the dominator
214dd2e275aSChandler Carruth   // tree. This lambda appends the dominator frontier for a node on the
215dd2e275aSChandler Carruth   // worklist.
2161353f9a4SChandler Carruth   SmallSetVector<BasicBlock *, 4> Worklist;
217693eedb1SChandler Carruth 
218693eedb1SChandler Carruth   // Scratch data structures reused by domfrontier finding.
219dd2e275aSChandler Carruth   SmallVector<DomTreeNode *, 4> DomNodes;
220dd2e275aSChandler Carruth   SmallPtrSet<BasicBlock *, 4> DomSet;
221dd2e275aSChandler Carruth 
222dd2e275aSChandler Carruth   // Append the initial dom frontier nodes.
223693eedb1SChandler Carruth   appendDomFrontier(UnswitchedNode, Worklist, DomNodes, DomSet);
224dd2e275aSChandler Carruth 
2251353f9a4SChandler Carruth   // Walk the worklist. We grow the list in the loop and so must recompute size.
2261353f9a4SChandler Carruth   for (int i = 0; i < (int)Worklist.size(); ++i) {
2271353f9a4SChandler Carruth     auto *BB = Worklist[i];
2281353f9a4SChandler Carruth 
2291353f9a4SChandler Carruth     DomTreeNode *Node = DT[BB];
2301353f9a4SChandler Carruth     assert(!DomChain.count(Node) &&
2311353f9a4SChandler Carruth            "Cannot be dominated by a block you can reach!");
232dd2e275aSChandler Carruth 
233dd2e275aSChandler Carruth     // If this block had an immediate dominator somewhere in the chain
234dd2e275aSChandler Carruth     // we hoisted over, then its position in the domtree needs to move as it is
235dd2e275aSChandler Carruth     // reachable from a node hoisted over this chain.
2361353f9a4SChandler Carruth     if (!DomChain.count(Node->getIDom()))
2371353f9a4SChandler Carruth       continue;
2381353f9a4SChandler Carruth 
2391353f9a4SChandler Carruth     DT.changeImmediateDominator(Node, OldPHNode);
240dd2e275aSChandler Carruth 
241dd2e275aSChandler Carruth     // Now add this node's dominator frontier to the worklist as well.
242693eedb1SChandler Carruth     appendDomFrontier(Node, Worklist, DomNodes, DomSet);
2431353f9a4SChandler Carruth   }
2441353f9a4SChandler Carruth }
2451353f9a4SChandler Carruth 
246d869b188SChandler Carruth /// Check that all the LCSSA PHI nodes in the loop exit block have trivial
247d869b188SChandler Carruth /// incoming values along this edge.
248d869b188SChandler Carruth static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
249d869b188SChandler Carruth                                          BasicBlock &ExitBB) {
250d869b188SChandler Carruth   for (Instruction &I : ExitBB) {
251d869b188SChandler Carruth     auto *PN = dyn_cast<PHINode>(&I);
252d869b188SChandler Carruth     if (!PN)
253d869b188SChandler Carruth       // No more PHIs to check.
254d869b188SChandler Carruth       return true;
255d869b188SChandler Carruth 
256d869b188SChandler Carruth     // If the incoming value for this edge isn't loop invariant the unswitch
257d869b188SChandler Carruth     // won't be trivial.
258d869b188SChandler Carruth     if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
259d869b188SChandler Carruth       return false;
260d869b188SChandler Carruth   }
261d869b188SChandler Carruth   llvm_unreachable("Basic blocks should never be empty!");
262d869b188SChandler Carruth }
263d869b188SChandler Carruth 
264d869b188SChandler Carruth /// Rewrite the PHI nodes in an unswitched loop exit basic block.
265d869b188SChandler Carruth ///
266d869b188SChandler Carruth /// Requires that the loop exit and unswitched basic block are the same, and
267d869b188SChandler Carruth /// that the exiting block was a unique predecessor of that block. Rewrites the
268d869b188SChandler Carruth /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
269d869b188SChandler Carruth /// PHI nodes from the old preheader that now contains the unswitched
270d869b188SChandler Carruth /// terminator.
271d869b188SChandler Carruth static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
272d869b188SChandler Carruth                                                   BasicBlock &OldExitingBB,
273d869b188SChandler Carruth                                                   BasicBlock &OldPH) {
274c7fc81e6SBenjamin Kramer   for (PHINode &PN : UnswitchedBB.phis()) {
275d869b188SChandler Carruth     // When the loop exit is directly unswitched we just need to update the
276d869b188SChandler Carruth     // incoming basic block. We loop to handle weird cases with repeated
277d869b188SChandler Carruth     // incoming blocks, but expect to typically only have one operand here.
278c7fc81e6SBenjamin Kramer     for (auto i : seq<int>(0, PN.getNumOperands())) {
279c7fc81e6SBenjamin Kramer       assert(PN.getIncomingBlock(i) == &OldExitingBB &&
280d869b188SChandler Carruth              "Found incoming block different from unique predecessor!");
281c7fc81e6SBenjamin Kramer       PN.setIncomingBlock(i, &OldPH);
282d869b188SChandler Carruth     }
283d869b188SChandler Carruth   }
284d869b188SChandler Carruth }
285d869b188SChandler Carruth 
286d869b188SChandler Carruth /// Rewrite the PHI nodes in the loop exit basic block and the split off
287d869b188SChandler Carruth /// unswitched block.
288d869b188SChandler Carruth ///
289d869b188SChandler Carruth /// Because the exit block remains an exit from the loop, this rewrites the
290d869b188SChandler Carruth /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
291d869b188SChandler Carruth /// nodes into the unswitched basic block to select between the value in the
292d869b188SChandler Carruth /// old preheader and the loop exit.
293d869b188SChandler Carruth static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
294d869b188SChandler Carruth                                                       BasicBlock &UnswitchedBB,
295d869b188SChandler Carruth                                                       BasicBlock &OldExitingBB,
296d869b188SChandler Carruth                                                       BasicBlock &OldPH) {
297d869b188SChandler Carruth   assert(&ExitBB != &UnswitchedBB &&
298d869b188SChandler Carruth          "Must have different loop exit and unswitched blocks!");
299d869b188SChandler Carruth   Instruction *InsertPt = &*UnswitchedBB.begin();
300c7fc81e6SBenjamin Kramer   for (PHINode &PN : ExitBB.phis()) {
301c7fc81e6SBenjamin Kramer     auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
302c7fc81e6SBenjamin Kramer                                   PN.getName() + ".split", InsertPt);
303d869b188SChandler Carruth 
304d869b188SChandler Carruth     // Walk backwards over the old PHI node's inputs to minimize the cost of
305d869b188SChandler Carruth     // removing each one. We have to do this weird loop manually so that we
306d869b188SChandler Carruth     // create the same number of new incoming edges in the new PHI as we expect
307d869b188SChandler Carruth     // each case-based edge to be included in the unswitched switch in some
308d869b188SChandler Carruth     // cases.
309d869b188SChandler Carruth     // FIXME: This is really, really gross. It would be much cleaner if LLVM
310d869b188SChandler Carruth     // allowed us to create a single entry for a predecessor block without
311d869b188SChandler Carruth     // having separate entries for each "edge" even though these edges are
312d869b188SChandler Carruth     // required to produce identical results.
313c7fc81e6SBenjamin Kramer     for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
314c7fc81e6SBenjamin Kramer       if (PN.getIncomingBlock(i) != &OldExitingBB)
315d869b188SChandler Carruth         continue;
316d869b188SChandler Carruth 
317c7fc81e6SBenjamin Kramer       Value *Incoming = PN.removeIncomingValue(i);
318d869b188SChandler Carruth       NewPN->addIncoming(Incoming, &OldPH);
319d869b188SChandler Carruth     }
320d869b188SChandler Carruth 
321d869b188SChandler Carruth     // Now replace the old PHI with the new one and wire the old one in as an
322d869b188SChandler Carruth     // input to the new one.
323c7fc81e6SBenjamin Kramer     PN.replaceAllUsesWith(NewPN);
324c7fc81e6SBenjamin Kramer     NewPN->addIncoming(&PN, &ExitBB);
325d869b188SChandler Carruth   }
326d869b188SChandler Carruth }
327d869b188SChandler Carruth 
3281353f9a4SChandler Carruth /// Unswitch a trivial branch if the condition is loop invariant.
3291353f9a4SChandler Carruth ///
3301353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the branch has
3311353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the
3321353f9a4SChandler Carruth /// condition is invariant and one of the successors is a loop exit. This
3331353f9a4SChandler Carruth /// allows us to unswitch without duplicating the loop, making it trivial.
3341353f9a4SChandler Carruth ///
3351353f9a4SChandler Carruth /// If this routine fails to unswitch the branch it returns false.
3361353f9a4SChandler Carruth ///
3371353f9a4SChandler Carruth /// If the branch can be unswitched, this routine splits the preheader and
3381353f9a4SChandler Carruth /// hoists the branch above that split. Preserves loop simplified form
3391353f9a4SChandler Carruth /// (splitting the exit block as necessary). It simplifies the branch within
3401353f9a4SChandler Carruth /// the loop to an unconditional branch but doesn't remove it entirely. Further
3411353f9a4SChandler Carruth /// cleanup can be done with some simplify-cfg like pass.
3421353f9a4SChandler Carruth static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
3431353f9a4SChandler Carruth                                   LoopInfo &LI) {
3441353f9a4SChandler Carruth   assert(BI.isConditional() && "Can only unswitch a conditional branch!");
3451353f9a4SChandler Carruth   DEBUG(dbgs() << "  Trying to unswitch branch: " << BI << "\n");
3461353f9a4SChandler Carruth 
3471353f9a4SChandler Carruth   Value *LoopCond = BI.getCondition();
3481353f9a4SChandler Carruth 
3491353f9a4SChandler Carruth   // Need a trivial loop condition to unswitch.
3501353f9a4SChandler Carruth   if (!L.isLoopInvariant(LoopCond))
3511353f9a4SChandler Carruth     return false;
3521353f9a4SChandler Carruth 
3531353f9a4SChandler Carruth   // FIXME: We should compute this once at the start and update it!
3541353f9a4SChandler Carruth   SmallVector<BasicBlock *, 16> ExitBlocks;
3551353f9a4SChandler Carruth   L.getExitBlocks(ExitBlocks);
3561353f9a4SChandler Carruth   SmallPtrSet<BasicBlock *, 16> ExitBlockSet(ExitBlocks.begin(),
3571353f9a4SChandler Carruth                                              ExitBlocks.end());
3581353f9a4SChandler Carruth 
3591353f9a4SChandler Carruth   // Check to see if a successor of the branch is guaranteed to
3601353f9a4SChandler Carruth   // exit through a unique exit block without having any
3611353f9a4SChandler Carruth   // side-effects.  If so, determine the value of Cond that causes
3621353f9a4SChandler Carruth   // it to do this.
3631353f9a4SChandler Carruth   ConstantInt *CondVal = ConstantInt::getTrue(BI.getContext());
3641353f9a4SChandler Carruth   ConstantInt *Replacement = ConstantInt::getFalse(BI.getContext());
3651353f9a4SChandler Carruth   int LoopExitSuccIdx = 0;
3661353f9a4SChandler Carruth   auto *LoopExitBB = BI.getSuccessor(0);
3671353f9a4SChandler Carruth   if (!ExitBlockSet.count(LoopExitBB)) {
3681353f9a4SChandler Carruth     std::swap(CondVal, Replacement);
3691353f9a4SChandler Carruth     LoopExitSuccIdx = 1;
3701353f9a4SChandler Carruth     LoopExitBB = BI.getSuccessor(1);
3711353f9a4SChandler Carruth     if (!ExitBlockSet.count(LoopExitBB))
3721353f9a4SChandler Carruth       return false;
3731353f9a4SChandler Carruth   }
3741353f9a4SChandler Carruth   auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
3751353f9a4SChandler Carruth   assert(L.contains(ContinueBB) &&
3761353f9a4SChandler Carruth          "Cannot have both successors exit and still be in the loop!");
3771353f9a4SChandler Carruth 
378d869b188SChandler Carruth   auto *ParentBB = BI.getParent();
379d869b188SChandler Carruth   if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
3801353f9a4SChandler Carruth     return false;
3811353f9a4SChandler Carruth 
3821353f9a4SChandler Carruth   DEBUG(dbgs() << "    unswitching trivial branch when: " << CondVal
3831353f9a4SChandler Carruth                << " == " << LoopCond << "\n");
3841353f9a4SChandler Carruth 
3851353f9a4SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
3861353f9a4SChandler Carruth   // the conditional branch. We will change the preheader to have a conditional
3871353f9a4SChandler Carruth   // branch on LoopCond.
3881353f9a4SChandler Carruth   BasicBlock *OldPH = L.getLoopPreheader();
3891353f9a4SChandler Carruth   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI);
3901353f9a4SChandler Carruth 
3911353f9a4SChandler Carruth   // Now that we have a place to insert the conditional branch, create a place
3921353f9a4SChandler Carruth   // to branch to: this is the exit block out of the loop that we are
3931353f9a4SChandler Carruth   // unswitching. We need to split this if there are other loop predecessors.
3941353f9a4SChandler Carruth   // Because the loop is in simplified form, *any* other predecessor is enough.
3951353f9a4SChandler Carruth   BasicBlock *UnswitchedBB;
3961353f9a4SChandler Carruth   if (BasicBlock *PredBB = LoopExitBB->getUniquePredecessor()) {
3971353f9a4SChandler Carruth     (void)PredBB;
398d869b188SChandler Carruth     assert(PredBB == BI.getParent() &&
399d869b188SChandler Carruth            "A branch's parent isn't a predecessor!");
4001353f9a4SChandler Carruth     UnswitchedBB = LoopExitBB;
4011353f9a4SChandler Carruth   } else {
4021353f9a4SChandler Carruth     UnswitchedBB = SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI);
4031353f9a4SChandler Carruth   }
4041353f9a4SChandler Carruth 
4051353f9a4SChandler Carruth   // Now splice the branch to gate reaching the new preheader and re-point its
4061353f9a4SChandler Carruth   // successors.
4071353f9a4SChandler Carruth   OldPH->getInstList().splice(std::prev(OldPH->end()),
4081353f9a4SChandler Carruth                               BI.getParent()->getInstList(), BI);
4091353f9a4SChandler Carruth   OldPH->getTerminator()->eraseFromParent();
4101353f9a4SChandler Carruth   BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
4111353f9a4SChandler Carruth   BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
4121353f9a4SChandler Carruth 
4131353f9a4SChandler Carruth   // Create a new unconditional branch that will continue the loop as a new
4141353f9a4SChandler Carruth   // terminator.
4151353f9a4SChandler Carruth   BranchInst::Create(ContinueBB, ParentBB);
4161353f9a4SChandler Carruth 
417d869b188SChandler Carruth   // Rewrite the relevant PHI nodes.
418d869b188SChandler Carruth   if (UnswitchedBB == LoopExitBB)
419d869b188SChandler Carruth     rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
420d869b188SChandler Carruth   else
421d869b188SChandler Carruth     rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
422d869b188SChandler Carruth                                               *ParentBB, *OldPH);
423d869b188SChandler Carruth 
4241353f9a4SChandler Carruth   // Now we need to update the dominator tree.
4251353f9a4SChandler Carruth   updateDTAfterUnswitch(UnswitchedBB, OldPH, DT);
4261353f9a4SChandler Carruth   // But if we split something off of the loop exit block then we also removed
4271353f9a4SChandler Carruth   // one of the predecessors for the loop exit block and may need to update its
4281353f9a4SChandler Carruth   // idom.
4291353f9a4SChandler Carruth   if (UnswitchedBB != LoopExitBB)
430693eedb1SChandler Carruth     updateIDomWithKnownCommonDominator(LoopExitBB, L.getHeader(), DT);
4311353f9a4SChandler Carruth 
4321353f9a4SChandler Carruth   // Since this is an i1 condition we can also trivially replace uses of it
4331353f9a4SChandler Carruth   // within the loop with a constant.
4341353f9a4SChandler Carruth   replaceLoopUsesWithConstant(L, *LoopCond, *Replacement);
4351353f9a4SChandler Carruth 
4361353f9a4SChandler Carruth   ++NumTrivial;
4371353f9a4SChandler Carruth   ++NumBranches;
4381353f9a4SChandler Carruth   return true;
4391353f9a4SChandler Carruth }
4401353f9a4SChandler Carruth 
4411353f9a4SChandler Carruth /// Unswitch a trivial switch if the condition is loop invariant.
4421353f9a4SChandler Carruth ///
4431353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the switch has
4441353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the
4451353f9a4SChandler Carruth /// condition is invariant and that at least one of the successors is a loop
4461353f9a4SChandler Carruth /// exit. This allows us to unswitch without duplicating the loop, making it
4471353f9a4SChandler Carruth /// trivial.
4481353f9a4SChandler Carruth ///
4491353f9a4SChandler Carruth /// If this routine fails to unswitch the switch it returns false.
4501353f9a4SChandler Carruth ///
4511353f9a4SChandler Carruth /// If the switch can be unswitched, this routine splits the preheader and
4521353f9a4SChandler Carruth /// copies the switch above that split. If the default case is one of the
4531353f9a4SChandler Carruth /// exiting cases, it copies the non-exiting cases and points them at the new
4541353f9a4SChandler Carruth /// preheader. If the default case is not exiting, it copies the exiting cases
4551353f9a4SChandler Carruth /// and points the default at the preheader. It preserves loop simplified form
4561353f9a4SChandler Carruth /// (splitting the exit blocks as necessary). It simplifies the switch within
4571353f9a4SChandler Carruth /// the loop by removing now-dead cases. If the default case is one of those
4581353f9a4SChandler Carruth /// unswitched, it replaces its destination with a new basic block containing
4591353f9a4SChandler Carruth /// only unreachable. Such basic blocks, while technically loop exits, are not
4601353f9a4SChandler Carruth /// considered for unswitching so this is a stable transform and the same
4611353f9a4SChandler Carruth /// switch will not be revisited. If after unswitching there is only a single
4621353f9a4SChandler Carruth /// in-loop successor, the switch is further simplified to an unconditional
4631353f9a4SChandler Carruth /// branch. Still more cleanup can be done with some simplify-cfg like pass.
4641353f9a4SChandler Carruth static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
4651353f9a4SChandler Carruth                                   LoopInfo &LI) {
4661353f9a4SChandler Carruth   DEBUG(dbgs() << "  Trying to unswitch switch: " << SI << "\n");
4671353f9a4SChandler Carruth   Value *LoopCond = SI.getCondition();
4681353f9a4SChandler Carruth 
4691353f9a4SChandler Carruth   // If this isn't switching on an invariant condition, we can't unswitch it.
4701353f9a4SChandler Carruth   if (!L.isLoopInvariant(LoopCond))
4711353f9a4SChandler Carruth     return false;
4721353f9a4SChandler Carruth 
473d869b188SChandler Carruth   auto *ParentBB = SI.getParent();
474d869b188SChandler Carruth 
4751353f9a4SChandler Carruth   // FIXME: We should compute this once at the start and update it!
4761353f9a4SChandler Carruth   SmallVector<BasicBlock *, 16> ExitBlocks;
4771353f9a4SChandler Carruth   L.getExitBlocks(ExitBlocks);
4781353f9a4SChandler Carruth   SmallPtrSet<BasicBlock *, 16> ExitBlockSet(ExitBlocks.begin(),
4791353f9a4SChandler Carruth                                              ExitBlocks.end());
4801353f9a4SChandler Carruth 
4811353f9a4SChandler Carruth   SmallVector<int, 4> ExitCaseIndices;
4821353f9a4SChandler Carruth   for (auto Case : SI.cases()) {
4831353f9a4SChandler Carruth     auto *SuccBB = Case.getCaseSuccessor();
484d869b188SChandler Carruth     if (ExitBlockSet.count(SuccBB) &&
485d869b188SChandler Carruth         areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB))
4861353f9a4SChandler Carruth       ExitCaseIndices.push_back(Case.getCaseIndex());
4871353f9a4SChandler Carruth   }
4881353f9a4SChandler Carruth   BasicBlock *DefaultExitBB = nullptr;
4891353f9a4SChandler Carruth   if (ExitBlockSet.count(SI.getDefaultDest()) &&
490d869b188SChandler Carruth       areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) &&
4911353f9a4SChandler Carruth       !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator()))
4921353f9a4SChandler Carruth     DefaultExitBB = SI.getDefaultDest();
4931353f9a4SChandler Carruth   else if (ExitCaseIndices.empty())
4941353f9a4SChandler Carruth     return false;
4951353f9a4SChandler Carruth 
4961353f9a4SChandler Carruth   DEBUG(dbgs() << "    unswitching trivial cases...\n");
4971353f9a4SChandler Carruth 
4981353f9a4SChandler Carruth   SmallVector<std::pair<ConstantInt *, BasicBlock *>, 4> ExitCases;
4991353f9a4SChandler Carruth   ExitCases.reserve(ExitCaseIndices.size());
5001353f9a4SChandler Carruth   // We walk the case indices backwards so that we remove the last case first
5011353f9a4SChandler Carruth   // and don't disrupt the earlier indices.
5021353f9a4SChandler Carruth   for (unsigned Index : reverse(ExitCaseIndices)) {
5031353f9a4SChandler Carruth     auto CaseI = SI.case_begin() + Index;
5041353f9a4SChandler Carruth     // Save the value of this case.
5051353f9a4SChandler Carruth     ExitCases.push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()});
5061353f9a4SChandler Carruth     // Delete the unswitched cases.
5071353f9a4SChandler Carruth     SI.removeCase(CaseI);
5081353f9a4SChandler Carruth   }
5091353f9a4SChandler Carruth 
5101353f9a4SChandler Carruth   // Check if after this all of the remaining cases point at the same
5111353f9a4SChandler Carruth   // successor.
5121353f9a4SChandler Carruth   BasicBlock *CommonSuccBB = nullptr;
5131353f9a4SChandler Carruth   if (SI.getNumCases() > 0 &&
5141353f9a4SChandler Carruth       std::all_of(std::next(SI.case_begin()), SI.case_end(),
5151353f9a4SChandler Carruth                   [&SI](const SwitchInst::CaseHandle &Case) {
5161353f9a4SChandler Carruth                     return Case.getCaseSuccessor() ==
5171353f9a4SChandler Carruth                            SI.case_begin()->getCaseSuccessor();
5181353f9a4SChandler Carruth                   }))
5191353f9a4SChandler Carruth     CommonSuccBB = SI.case_begin()->getCaseSuccessor();
5201353f9a4SChandler Carruth 
5211353f9a4SChandler Carruth   if (DefaultExitBB) {
5221353f9a4SChandler Carruth     // We can't remove the default edge so replace it with an edge to either
5231353f9a4SChandler Carruth     // the single common remaining successor (if we have one) or an unreachable
5241353f9a4SChandler Carruth     // block.
5251353f9a4SChandler Carruth     if (CommonSuccBB) {
5261353f9a4SChandler Carruth       SI.setDefaultDest(CommonSuccBB);
5271353f9a4SChandler Carruth     } else {
5281353f9a4SChandler Carruth       BasicBlock *UnreachableBB = BasicBlock::Create(
5291353f9a4SChandler Carruth           ParentBB->getContext(),
5301353f9a4SChandler Carruth           Twine(ParentBB->getName()) + ".unreachable_default",
5311353f9a4SChandler Carruth           ParentBB->getParent());
5321353f9a4SChandler Carruth       new UnreachableInst(ParentBB->getContext(), UnreachableBB);
5331353f9a4SChandler Carruth       SI.setDefaultDest(UnreachableBB);
5341353f9a4SChandler Carruth       DT.addNewBlock(UnreachableBB, ParentBB);
5351353f9a4SChandler Carruth     }
5361353f9a4SChandler Carruth   } else {
5371353f9a4SChandler Carruth     // If we're not unswitching the default, we need it to match any cases to
5381353f9a4SChandler Carruth     // have a common successor or if we have no cases it is the common
5391353f9a4SChandler Carruth     // successor.
5401353f9a4SChandler Carruth     if (SI.getNumCases() == 0)
5411353f9a4SChandler Carruth       CommonSuccBB = SI.getDefaultDest();
5421353f9a4SChandler Carruth     else if (SI.getDefaultDest() != CommonSuccBB)
5431353f9a4SChandler Carruth       CommonSuccBB = nullptr;
5441353f9a4SChandler Carruth   }
5451353f9a4SChandler Carruth 
5461353f9a4SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
5471353f9a4SChandler Carruth   // the switch.
5481353f9a4SChandler Carruth   BasicBlock *OldPH = L.getLoopPreheader();
5491353f9a4SChandler Carruth   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI);
5501353f9a4SChandler Carruth   OldPH->getTerminator()->eraseFromParent();
5511353f9a4SChandler Carruth 
5521353f9a4SChandler Carruth   // Now add the unswitched switch.
5531353f9a4SChandler Carruth   auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
5541353f9a4SChandler Carruth 
555d869b188SChandler Carruth   // Rewrite the IR for the unswitched basic blocks. This requires two steps.
556d869b188SChandler Carruth   // First, we split any exit blocks with remaining in-loop predecessors. Then
557d869b188SChandler Carruth   // we update the PHIs in one of two ways depending on if there was a split.
558d869b188SChandler Carruth   // We walk in reverse so that we split in the same order as the cases
559d869b188SChandler Carruth   // appeared. This is purely for convenience of reading the resulting IR, but
560d869b188SChandler Carruth   // it doesn't cost anything really.
561d869b188SChandler Carruth   SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
5621353f9a4SChandler Carruth   SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
5631353f9a4SChandler Carruth   // Handle the default exit if necessary.
5641353f9a4SChandler Carruth   // FIXME: It'd be great if we could merge this with the loop below but LLVM's
5651353f9a4SChandler Carruth   // ranges aren't quite powerful enough yet.
566d869b188SChandler Carruth   if (DefaultExitBB) {
567d869b188SChandler Carruth     if (pred_empty(DefaultExitBB)) {
568d869b188SChandler Carruth       UnswitchedExitBBs.insert(DefaultExitBB);
569d869b188SChandler Carruth       rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
570d869b188SChandler Carruth     } else {
5711353f9a4SChandler Carruth       auto *SplitBB =
5721353f9a4SChandler Carruth           SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI);
573d869b188SChandler Carruth       rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
574d869b188SChandler Carruth                                                 *ParentBB, *OldPH);
575693eedb1SChandler Carruth       updateIDomWithKnownCommonDominator(DefaultExitBB, L.getHeader(), DT);
5761353f9a4SChandler Carruth       DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
5771353f9a4SChandler Carruth     }
578d869b188SChandler Carruth   }
5791353f9a4SChandler Carruth   // Note that we must use a reference in the for loop so that we update the
5801353f9a4SChandler Carruth   // container.
5811353f9a4SChandler Carruth   for (auto &CasePair : reverse(ExitCases)) {
5821353f9a4SChandler Carruth     // Grab a reference to the exit block in the pair so that we can update it.
583d869b188SChandler Carruth     BasicBlock *ExitBB = CasePair.second;
5841353f9a4SChandler Carruth 
5851353f9a4SChandler Carruth     // If this case is the last edge into the exit block, we can simply reuse it
5861353f9a4SChandler Carruth     // as it will no longer be a loop exit. No mapping necessary.
587d869b188SChandler Carruth     if (pred_empty(ExitBB)) {
588d869b188SChandler Carruth       // Only rewrite once.
589d869b188SChandler Carruth       if (UnswitchedExitBBs.insert(ExitBB).second)
590d869b188SChandler Carruth         rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
5911353f9a4SChandler Carruth       continue;
592d869b188SChandler Carruth     }
5931353f9a4SChandler Carruth 
5941353f9a4SChandler Carruth     // Otherwise we need to split the exit block so that we retain an exit
5951353f9a4SChandler Carruth     // block from the loop and a target for the unswitched condition.
5961353f9a4SChandler Carruth     BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
5971353f9a4SChandler Carruth     if (!SplitExitBB) {
5981353f9a4SChandler Carruth       // If this is the first time we see this, do the split and remember it.
5991353f9a4SChandler Carruth       SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI);
600d869b188SChandler Carruth       rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
601d869b188SChandler Carruth                                                 *ParentBB, *OldPH);
602693eedb1SChandler Carruth       updateIDomWithKnownCommonDominator(ExitBB, L.getHeader(), DT);
6031353f9a4SChandler Carruth     }
604d869b188SChandler Carruth     // Update the case pair to point to the split block.
605d869b188SChandler Carruth     CasePair.second = SplitExitBB;
6061353f9a4SChandler Carruth   }
6071353f9a4SChandler Carruth 
6081353f9a4SChandler Carruth   // Now add the unswitched cases. We do this in reverse order as we built them
6091353f9a4SChandler Carruth   // in reverse order.
6101353f9a4SChandler Carruth   for (auto CasePair : reverse(ExitCases)) {
6111353f9a4SChandler Carruth     ConstantInt *CaseVal = CasePair.first;
6121353f9a4SChandler Carruth     BasicBlock *UnswitchedBB = CasePair.second;
6131353f9a4SChandler Carruth 
6141353f9a4SChandler Carruth     NewSI->addCase(CaseVal, UnswitchedBB);
6151353f9a4SChandler Carruth     updateDTAfterUnswitch(UnswitchedBB, OldPH, DT);
6161353f9a4SChandler Carruth   }
6171353f9a4SChandler Carruth 
6181353f9a4SChandler Carruth   // If the default was unswitched, re-point it and add explicit cases for
6191353f9a4SChandler Carruth   // entering the loop.
6201353f9a4SChandler Carruth   if (DefaultExitBB) {
6211353f9a4SChandler Carruth     NewSI->setDefaultDest(DefaultExitBB);
6221353f9a4SChandler Carruth     updateDTAfterUnswitch(DefaultExitBB, OldPH, DT);
6231353f9a4SChandler Carruth 
6241353f9a4SChandler Carruth     // We removed all the exit cases, so we just copy the cases to the
6251353f9a4SChandler Carruth     // unswitched switch.
6261353f9a4SChandler Carruth     for (auto Case : SI.cases())
6271353f9a4SChandler Carruth       NewSI->addCase(Case.getCaseValue(), NewPH);
6281353f9a4SChandler Carruth   }
6291353f9a4SChandler Carruth 
6301353f9a4SChandler Carruth   // If we ended up with a common successor for every path through the switch
6311353f9a4SChandler Carruth   // after unswitching, rewrite it to an unconditional branch to make it easy
6321353f9a4SChandler Carruth   // to recognize. Otherwise we potentially have to recognize the default case
6331353f9a4SChandler Carruth   // pointing at unreachable and other complexity.
6341353f9a4SChandler Carruth   if (CommonSuccBB) {
6351353f9a4SChandler Carruth     BasicBlock *BB = SI.getParent();
6361353f9a4SChandler Carruth     SI.eraseFromParent();
6371353f9a4SChandler Carruth     BranchInst::Create(CommonSuccBB, BB);
6381353f9a4SChandler Carruth   }
6391353f9a4SChandler Carruth 
6407c35de12SDavid Green   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
6411353f9a4SChandler Carruth   ++NumTrivial;
6421353f9a4SChandler Carruth   ++NumSwitches;
6431353f9a4SChandler Carruth   return true;
6441353f9a4SChandler Carruth }
6451353f9a4SChandler Carruth 
6461353f9a4SChandler Carruth /// This routine scans the loop to find a branch or switch which occurs before
6471353f9a4SChandler Carruth /// any side effects occur. These can potentially be unswitched without
6481353f9a4SChandler Carruth /// duplicating the loop. If a branch or switch is successfully unswitched the
6491353f9a4SChandler Carruth /// scanning continues to see if subsequent branches or switches have become
6501353f9a4SChandler Carruth /// trivial. Once all trivial candidates have been unswitched, this routine
6511353f9a4SChandler Carruth /// returns.
6521353f9a4SChandler Carruth ///
6531353f9a4SChandler Carruth /// The return value indicates whether anything was unswitched (and therefore
6541353f9a4SChandler Carruth /// changed).
6551353f9a4SChandler Carruth static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
6561353f9a4SChandler Carruth                                          LoopInfo &LI) {
6571353f9a4SChandler Carruth   bool Changed = false;
6581353f9a4SChandler Carruth 
6591353f9a4SChandler Carruth   // If loop header has only one reachable successor we should keep looking for
6601353f9a4SChandler Carruth   // trivial condition candidates in the successor as well. An alternative is
6611353f9a4SChandler Carruth   // to constant fold conditions and merge successors into loop header (then we
6621353f9a4SChandler Carruth   // only need to check header's terminator). The reason for not doing this in
6631353f9a4SChandler Carruth   // LoopUnswitch pass is that it could potentially break LoopPassManager's
6641353f9a4SChandler Carruth   // invariants. Folding dead branches could either eliminate the current loop
6651353f9a4SChandler Carruth   // or make other loops unreachable. LCSSA form might also not be preserved
6661353f9a4SChandler Carruth   // after deleting branches. The following code keeps traversing loop header's
6671353f9a4SChandler Carruth   // successors until it finds the trivial condition candidate (condition that
6681353f9a4SChandler Carruth   // is not a constant). Since unswitching generates branches with constant
6691353f9a4SChandler Carruth   // conditions, this scenario could be very common in practice.
6701353f9a4SChandler Carruth   BasicBlock *CurrentBB = L.getHeader();
6711353f9a4SChandler Carruth   SmallPtrSet<BasicBlock *, 8> Visited;
6721353f9a4SChandler Carruth   Visited.insert(CurrentBB);
6731353f9a4SChandler Carruth   do {
6741353f9a4SChandler Carruth     // Check if there are any side-effecting instructions (e.g. stores, calls,
6751353f9a4SChandler Carruth     // volatile loads) in the part of the loop that the code *would* execute
6761353f9a4SChandler Carruth     // without unswitching.
6771353f9a4SChandler Carruth     if (llvm::any_of(*CurrentBB,
6781353f9a4SChandler Carruth                      [](Instruction &I) { return I.mayHaveSideEffects(); }))
6791353f9a4SChandler Carruth       return Changed;
6801353f9a4SChandler Carruth 
6811353f9a4SChandler Carruth     TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
6821353f9a4SChandler Carruth 
6831353f9a4SChandler Carruth     if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
6841353f9a4SChandler Carruth       // Don't bother trying to unswitch past a switch with a constant
6851353f9a4SChandler Carruth       // condition. This should be removed prior to running this pass by
6861353f9a4SChandler Carruth       // simplify-cfg.
6871353f9a4SChandler Carruth       if (isa<Constant>(SI->getCondition()))
6881353f9a4SChandler Carruth         return Changed;
6891353f9a4SChandler Carruth 
6901353f9a4SChandler Carruth       if (!unswitchTrivialSwitch(L, *SI, DT, LI))
6911353f9a4SChandler Carruth         // Coludn't unswitch this one so we're done.
6921353f9a4SChandler Carruth         return Changed;
6931353f9a4SChandler Carruth 
6941353f9a4SChandler Carruth       // Mark that we managed to unswitch something.
6951353f9a4SChandler Carruth       Changed = true;
6961353f9a4SChandler Carruth 
6971353f9a4SChandler Carruth       // If unswitching turned the terminator into an unconditional branch then
6981353f9a4SChandler Carruth       // we can continue. The unswitching logic specifically works to fold any
6991353f9a4SChandler Carruth       // cases it can into an unconditional branch to make it easier to
7001353f9a4SChandler Carruth       // recognize here.
7011353f9a4SChandler Carruth       auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
7021353f9a4SChandler Carruth       if (!BI || BI->isConditional())
7031353f9a4SChandler Carruth         return Changed;
7041353f9a4SChandler Carruth 
7051353f9a4SChandler Carruth       CurrentBB = BI->getSuccessor(0);
7061353f9a4SChandler Carruth       continue;
7071353f9a4SChandler Carruth     }
7081353f9a4SChandler Carruth 
7091353f9a4SChandler Carruth     auto *BI = dyn_cast<BranchInst>(CurrentTerm);
7101353f9a4SChandler Carruth     if (!BI)
7111353f9a4SChandler Carruth       // We do not understand other terminator instructions.
7121353f9a4SChandler Carruth       return Changed;
7131353f9a4SChandler Carruth 
7141353f9a4SChandler Carruth     // Don't bother trying to unswitch past an unconditional branch or a branch
7151353f9a4SChandler Carruth     // with a constant value. These should be removed by simplify-cfg prior to
7161353f9a4SChandler Carruth     // running this pass.
7171353f9a4SChandler Carruth     if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
7181353f9a4SChandler Carruth       return Changed;
7191353f9a4SChandler Carruth 
7201353f9a4SChandler Carruth     // Found a trivial condition candidate: non-foldable conditional branch. If
7211353f9a4SChandler Carruth     // we fail to unswitch this, we can't do anything else that is trivial.
7221353f9a4SChandler Carruth     if (!unswitchTrivialBranch(L, *BI, DT, LI))
7231353f9a4SChandler Carruth       return Changed;
7241353f9a4SChandler Carruth 
7251353f9a4SChandler Carruth     // Mark that we managed to unswitch something.
7261353f9a4SChandler Carruth     Changed = true;
7271353f9a4SChandler Carruth 
7281353f9a4SChandler Carruth     // We unswitched the branch. This should always leave us with an
7291353f9a4SChandler Carruth     // unconditional branch that we can follow now.
7301353f9a4SChandler Carruth     BI = cast<BranchInst>(CurrentBB->getTerminator());
7311353f9a4SChandler Carruth     assert(!BI->isConditional() &&
7321353f9a4SChandler Carruth            "Cannot form a conditional branch by unswitching1");
7331353f9a4SChandler Carruth     CurrentBB = BI->getSuccessor(0);
7341353f9a4SChandler Carruth 
7351353f9a4SChandler Carruth     // When continuing, if we exit the loop or reach a previous visited block,
7361353f9a4SChandler Carruth     // then we can not reach any trivial condition candidates (unfoldable
7371353f9a4SChandler Carruth     // branch instructions or switch instructions) and no unswitch can happen.
7381353f9a4SChandler Carruth   } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
7391353f9a4SChandler Carruth 
7401353f9a4SChandler Carruth   return Changed;
7411353f9a4SChandler Carruth }
7421353f9a4SChandler Carruth 
743693eedb1SChandler Carruth /// Build the cloned blocks for an unswitched copy of the given loop.
744693eedb1SChandler Carruth ///
745693eedb1SChandler Carruth /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
746693eedb1SChandler Carruth /// after the split block (`SplitBB`) that will be used to select between the
747693eedb1SChandler Carruth /// cloned and original loop.
748693eedb1SChandler Carruth ///
749693eedb1SChandler Carruth /// This routine handles cloning all of the necessary loop blocks and exit
750693eedb1SChandler Carruth /// blocks including rewriting their instructions and the relevant PHI nodes.
751693eedb1SChandler Carruth /// It skips loop and exit blocks that are not necessary based on the provided
752693eedb1SChandler Carruth /// set. It also correctly creates the unconditional branch in the cloned
753693eedb1SChandler Carruth /// unswitched parent block to only point at the unswitched successor.
754693eedb1SChandler Carruth ///
755693eedb1SChandler Carruth /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
756693eedb1SChandler Carruth /// block splitting is correctly reflected in `LoopInfo`, essentially all of
757693eedb1SChandler Carruth /// the cloned blocks (and their loops) are left without full `LoopInfo`
758693eedb1SChandler Carruth /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
759693eedb1SChandler Carruth /// blocks to them but doesn't create the cloned `DominatorTree` structure and
760693eedb1SChandler Carruth /// instead the caller must recompute an accurate DT. It *does* correctly
761693eedb1SChandler Carruth /// update the `AssumptionCache` provided in `AC`.
762693eedb1SChandler Carruth static BasicBlock *buildClonedLoopBlocks(
763693eedb1SChandler Carruth     Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
764693eedb1SChandler Carruth     ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
765693eedb1SChandler Carruth     BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
766693eedb1SChandler Carruth     const SmallPtrSetImpl<BasicBlock *> &SkippedLoopAndExitBlocks,
767693eedb1SChandler Carruth     ValueToValueMapTy &VMap, AssumptionCache &AC, DominatorTree &DT,
768693eedb1SChandler Carruth     LoopInfo &LI) {
769693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> NewBlocks;
770693eedb1SChandler Carruth   NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
771693eedb1SChandler Carruth 
772693eedb1SChandler Carruth   // We will need to clone a bunch of blocks, wrap up the clone operation in
773693eedb1SChandler Carruth   // a helper.
774693eedb1SChandler Carruth   auto CloneBlock = [&](BasicBlock *OldBB) {
775693eedb1SChandler Carruth     // Clone the basic block and insert it before the new preheader.
776693eedb1SChandler Carruth     BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
777693eedb1SChandler Carruth     NewBB->moveBefore(LoopPH);
778693eedb1SChandler Carruth 
779693eedb1SChandler Carruth     // Record this block and the mapping.
780693eedb1SChandler Carruth     NewBlocks.push_back(NewBB);
781693eedb1SChandler Carruth     VMap[OldBB] = NewBB;
782693eedb1SChandler Carruth 
783693eedb1SChandler Carruth     // Add the block to the domtree. We'll move it to the correct position
784693eedb1SChandler Carruth     // below.
785693eedb1SChandler Carruth     DT.addNewBlock(NewBB, SplitBB);
786693eedb1SChandler Carruth 
787693eedb1SChandler Carruth     return NewBB;
788693eedb1SChandler Carruth   };
789693eedb1SChandler Carruth 
790693eedb1SChandler Carruth   // First, clone the preheader.
791693eedb1SChandler Carruth   auto *ClonedPH = CloneBlock(LoopPH);
792693eedb1SChandler Carruth 
793693eedb1SChandler Carruth   // Then clone all the loop blocks, skipping the ones that aren't necessary.
794693eedb1SChandler Carruth   for (auto *LoopBB : L.blocks())
795693eedb1SChandler Carruth     if (!SkippedLoopAndExitBlocks.count(LoopBB))
796693eedb1SChandler Carruth       CloneBlock(LoopBB);
797693eedb1SChandler Carruth 
798693eedb1SChandler Carruth   // Split all the loop exit edges so that when we clone the exit blocks, if
799693eedb1SChandler Carruth   // any of the exit blocks are *also* a preheader for some other loop, we
800693eedb1SChandler Carruth   // don't create multiple predecessors entering the loop header.
801693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks) {
802693eedb1SChandler Carruth     if (SkippedLoopAndExitBlocks.count(ExitBB))
803693eedb1SChandler Carruth       continue;
804693eedb1SChandler Carruth 
805693eedb1SChandler Carruth     // When we are going to clone an exit, we don't need to clone all the
806693eedb1SChandler Carruth     // instructions in the exit block and we want to ensure we have an easy
807693eedb1SChandler Carruth     // place to merge the CFG, so split the exit first. This is always safe to
808693eedb1SChandler Carruth     // do because there cannot be any non-loop predecessors of a loop exit in
809693eedb1SChandler Carruth     // loop simplified form.
810693eedb1SChandler Carruth     auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI);
811693eedb1SChandler Carruth 
812693eedb1SChandler Carruth     // Rearrange the names to make it easier to write test cases by having the
813693eedb1SChandler Carruth     // exit block carry the suffix rather than the merge block carrying the
814693eedb1SChandler Carruth     // suffix.
815693eedb1SChandler Carruth     MergeBB->takeName(ExitBB);
816693eedb1SChandler Carruth     ExitBB->setName(Twine(MergeBB->getName()) + ".split");
817693eedb1SChandler Carruth 
818693eedb1SChandler Carruth     // Now clone the original exit block.
819693eedb1SChandler Carruth     auto *ClonedExitBB = CloneBlock(ExitBB);
820693eedb1SChandler Carruth     assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
821693eedb1SChandler Carruth            "Exit block should have been split to have one successor!");
822693eedb1SChandler Carruth     assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
823693eedb1SChandler Carruth            "Cloned exit block has the wrong successor!");
824693eedb1SChandler Carruth 
825693eedb1SChandler Carruth     // Move the merge block's idom to be the split point as one exit is
826693eedb1SChandler Carruth     // dominated by one header, and the other by another, so we know the split
827693eedb1SChandler Carruth     // point dominates both. While the dominator tree isn't fully accurate, we
828693eedb1SChandler Carruth     // want sub-trees within the original loop to be correctly reflect
829693eedb1SChandler Carruth     // dominance within that original loop (at least) and that requires moving
830693eedb1SChandler Carruth     // the merge block out of that subtree.
831693eedb1SChandler Carruth     // FIXME: This is very brittle as we essentially have a partial contract on
832693eedb1SChandler Carruth     // the dominator tree. We really need to instead update it and keep it
833693eedb1SChandler Carruth     // valid or stop relying on it.
834693eedb1SChandler Carruth     DT.changeImmediateDominator(MergeBB, SplitBB);
835693eedb1SChandler Carruth 
836693eedb1SChandler Carruth     // Remap any cloned instructions and create a merge phi node for them.
837693eedb1SChandler Carruth     for (auto ZippedInsts : llvm::zip_first(
838693eedb1SChandler Carruth              llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
839693eedb1SChandler Carruth              llvm::make_range(ClonedExitBB->begin(),
840693eedb1SChandler Carruth                               std::prev(ClonedExitBB->end())))) {
841693eedb1SChandler Carruth       Instruction &I = std::get<0>(ZippedInsts);
842693eedb1SChandler Carruth       Instruction &ClonedI = std::get<1>(ZippedInsts);
843693eedb1SChandler Carruth 
844693eedb1SChandler Carruth       // The only instructions in the exit block should be PHI nodes and
845693eedb1SChandler Carruth       // potentially a landing pad.
846693eedb1SChandler Carruth       assert(
847693eedb1SChandler Carruth           (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
848693eedb1SChandler Carruth           "Bad instruction in exit block!");
849693eedb1SChandler Carruth       // We should have a value map between the instruction and its clone.
850693eedb1SChandler Carruth       assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
851693eedb1SChandler Carruth 
852693eedb1SChandler Carruth       auto *MergePN =
853693eedb1SChandler Carruth           PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
854693eedb1SChandler Carruth                           &*MergeBB->getFirstInsertionPt());
855693eedb1SChandler Carruth       I.replaceAllUsesWith(MergePN);
856693eedb1SChandler Carruth       MergePN->addIncoming(&I, ExitBB);
857693eedb1SChandler Carruth       MergePN->addIncoming(&ClonedI, ClonedExitBB);
858693eedb1SChandler Carruth     }
859693eedb1SChandler Carruth   }
860693eedb1SChandler Carruth 
861693eedb1SChandler Carruth   // Rewrite the instructions in the cloned blocks to refer to the instructions
862693eedb1SChandler Carruth   // in the cloned blocks. We have to do this as a second pass so that we have
863693eedb1SChandler Carruth   // everything available. Also, we have inserted new instructions which may
864693eedb1SChandler Carruth   // include assume intrinsics, so we update the assumption cache while
865693eedb1SChandler Carruth   // processing this.
866693eedb1SChandler Carruth   for (auto *ClonedBB : NewBlocks)
867693eedb1SChandler Carruth     for (Instruction &I : *ClonedBB) {
868693eedb1SChandler Carruth       RemapInstruction(&I, VMap,
869693eedb1SChandler Carruth                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
870693eedb1SChandler Carruth       if (auto *II = dyn_cast<IntrinsicInst>(&I))
871693eedb1SChandler Carruth         if (II->getIntrinsicID() == Intrinsic::assume)
872693eedb1SChandler Carruth           AC.registerAssumption(II);
873693eedb1SChandler Carruth     }
874693eedb1SChandler Carruth 
875693eedb1SChandler Carruth   // Remove the cloned parent as a predecessor of the cloned continue successor
876693eedb1SChandler Carruth   // if we did in fact clone it.
877693eedb1SChandler Carruth   auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
878693eedb1SChandler Carruth   if (auto *ClonedContinueSuccBB =
879693eedb1SChandler Carruth           cast_or_null<BasicBlock>(VMap.lookup(ContinueSuccBB)))
880693eedb1SChandler Carruth     ClonedContinueSuccBB->removePredecessor(ClonedParentBB,
881693eedb1SChandler Carruth                                             /*DontDeleteUselessPHIs*/ true);
882693eedb1SChandler Carruth   // Replace the cloned branch with an unconditional branch to the cloneed
883693eedb1SChandler Carruth   // unswitched successor.
884693eedb1SChandler Carruth   auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
885693eedb1SChandler Carruth   ClonedParentBB->getTerminator()->eraseFromParent();
886693eedb1SChandler Carruth   BranchInst::Create(ClonedSuccBB, ClonedParentBB);
887693eedb1SChandler Carruth 
888693eedb1SChandler Carruth   // Update any PHI nodes in the cloned successors of the skipped blocks to not
889693eedb1SChandler Carruth   // have spurious incoming values.
890693eedb1SChandler Carruth   for (auto *LoopBB : L.blocks())
891693eedb1SChandler Carruth     if (SkippedLoopAndExitBlocks.count(LoopBB))
892693eedb1SChandler Carruth       for (auto *SuccBB : successors(LoopBB))
893693eedb1SChandler Carruth         if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
894693eedb1SChandler Carruth           for (PHINode &PN : ClonedSuccBB->phis())
895693eedb1SChandler Carruth             PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
896693eedb1SChandler Carruth 
897693eedb1SChandler Carruth   return ClonedPH;
898693eedb1SChandler Carruth }
899693eedb1SChandler Carruth 
900693eedb1SChandler Carruth /// Recursively clone the specified loop and all of its children.
901693eedb1SChandler Carruth ///
902693eedb1SChandler Carruth /// The target parent loop for the clone should be provided, or can be null if
903693eedb1SChandler Carruth /// the clone is a top-level loop. While cloning, all the blocks are mapped
904693eedb1SChandler Carruth /// with the provided value map. The entire original loop must be present in
905693eedb1SChandler Carruth /// the value map. The cloned loop is returned.
906693eedb1SChandler Carruth static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
907693eedb1SChandler Carruth                            const ValueToValueMapTy &VMap, LoopInfo &LI) {
908693eedb1SChandler Carruth   auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
909693eedb1SChandler Carruth     assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
910693eedb1SChandler Carruth     ClonedL.reserveBlocks(OrigL.getNumBlocks());
911693eedb1SChandler Carruth     for (auto *BB : OrigL.blocks()) {
912693eedb1SChandler Carruth       auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
913693eedb1SChandler Carruth       ClonedL.addBlockEntry(ClonedBB);
914693eedb1SChandler Carruth       if (LI.getLoopFor(BB) == &OrigL) {
915693eedb1SChandler Carruth         assert(!LI.getLoopFor(ClonedBB) &&
916693eedb1SChandler Carruth                "Should not have an existing loop for this block!");
917693eedb1SChandler Carruth         LI.changeLoopFor(ClonedBB, &ClonedL);
918693eedb1SChandler Carruth       }
919693eedb1SChandler Carruth     }
920693eedb1SChandler Carruth   };
921693eedb1SChandler Carruth 
922693eedb1SChandler Carruth   // We specially handle the first loop because it may get cloned into
923693eedb1SChandler Carruth   // a different parent and because we most commonly are cloning leaf loops.
924693eedb1SChandler Carruth   Loop *ClonedRootL = LI.AllocateLoop();
925693eedb1SChandler Carruth   if (RootParentL)
926693eedb1SChandler Carruth     RootParentL->addChildLoop(ClonedRootL);
927693eedb1SChandler Carruth   else
928693eedb1SChandler Carruth     LI.addTopLevelLoop(ClonedRootL);
929693eedb1SChandler Carruth   AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
930693eedb1SChandler Carruth 
931693eedb1SChandler Carruth   if (OrigRootL.empty())
932693eedb1SChandler Carruth     return ClonedRootL;
933693eedb1SChandler Carruth 
934693eedb1SChandler Carruth   // If we have a nest, we can quickly clone the entire loop nest using an
935693eedb1SChandler Carruth   // iterative approach because it is a tree. We keep the cloned parent in the
936693eedb1SChandler Carruth   // data structure to avoid repeatedly querying through a map to find it.
937693eedb1SChandler Carruth   SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
938693eedb1SChandler Carruth   // Build up the loops to clone in reverse order as we'll clone them from the
939693eedb1SChandler Carruth   // back.
940693eedb1SChandler Carruth   for (Loop *ChildL : llvm::reverse(OrigRootL))
941693eedb1SChandler Carruth     LoopsToClone.push_back({ClonedRootL, ChildL});
942693eedb1SChandler Carruth   do {
943693eedb1SChandler Carruth     Loop *ClonedParentL, *L;
944693eedb1SChandler Carruth     std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
945693eedb1SChandler Carruth     Loop *ClonedL = LI.AllocateLoop();
946693eedb1SChandler Carruth     ClonedParentL->addChildLoop(ClonedL);
947693eedb1SChandler Carruth     AddClonedBlocksToLoop(*L, *ClonedL);
948693eedb1SChandler Carruth     for (Loop *ChildL : llvm::reverse(*L))
949693eedb1SChandler Carruth       LoopsToClone.push_back({ClonedL, ChildL});
950693eedb1SChandler Carruth   } while (!LoopsToClone.empty());
951693eedb1SChandler Carruth 
952693eedb1SChandler Carruth   return ClonedRootL;
953693eedb1SChandler Carruth }
954693eedb1SChandler Carruth 
955693eedb1SChandler Carruth /// Build the cloned loops of an original loop from unswitching.
956693eedb1SChandler Carruth ///
957693eedb1SChandler Carruth /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
958693eedb1SChandler Carruth /// operation. We need to re-verify that there even is a loop (as the backedge
959693eedb1SChandler Carruth /// may not have been cloned), and even if there are remaining backedges the
960693eedb1SChandler Carruth /// backedge set may be different. However, we know that each child loop is
961693eedb1SChandler Carruth /// undisturbed, we only need to find where to place each child loop within
962693eedb1SChandler Carruth /// either any parent loop or within a cloned version of the original loop.
963693eedb1SChandler Carruth ///
964693eedb1SChandler Carruth /// Because child loops may end up cloned outside of any cloned version of the
965693eedb1SChandler Carruth /// original loop, multiple cloned sibling loops may be created. All of them
966693eedb1SChandler Carruth /// are returned so that the newly introduced loop nest roots can be
967693eedb1SChandler Carruth /// identified.
968693eedb1SChandler Carruth static Loop *buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
969693eedb1SChandler Carruth                               const ValueToValueMapTy &VMap, LoopInfo &LI,
970693eedb1SChandler Carruth                               SmallVectorImpl<Loop *> &NonChildClonedLoops) {
971693eedb1SChandler Carruth   Loop *ClonedL = nullptr;
972693eedb1SChandler Carruth 
973693eedb1SChandler Carruth   auto *OrigPH = OrigL.getLoopPreheader();
974693eedb1SChandler Carruth   auto *OrigHeader = OrigL.getHeader();
975693eedb1SChandler Carruth 
976693eedb1SChandler Carruth   auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
977693eedb1SChandler Carruth   auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
978693eedb1SChandler Carruth 
979693eedb1SChandler Carruth   // We need to know the loops of the cloned exit blocks to even compute the
980693eedb1SChandler Carruth   // accurate parent loop. If we only clone exits to some parent of the
981693eedb1SChandler Carruth   // original parent, we want to clone into that outer loop. We also keep track
982693eedb1SChandler Carruth   // of the loops that our cloned exit blocks participate in.
983693eedb1SChandler Carruth   Loop *ParentL = nullptr;
984693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
985693eedb1SChandler Carruth   SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
986693eedb1SChandler Carruth   ClonedExitsInLoops.reserve(ExitBlocks.size());
987693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks)
988693eedb1SChandler Carruth     if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
989693eedb1SChandler Carruth       if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
990693eedb1SChandler Carruth         ExitLoopMap[ClonedExitBB] = ExitL;
991693eedb1SChandler Carruth         ClonedExitsInLoops.push_back(ClonedExitBB);
992693eedb1SChandler Carruth         if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
993693eedb1SChandler Carruth           ParentL = ExitL;
994693eedb1SChandler Carruth       }
995693eedb1SChandler Carruth   assert((!ParentL || ParentL == OrigL.getParentLoop() ||
996693eedb1SChandler Carruth           ParentL->contains(OrigL.getParentLoop())) &&
997693eedb1SChandler Carruth          "The computed parent loop should always contain (or be) the parent of "
998693eedb1SChandler Carruth          "the original loop.");
999693eedb1SChandler Carruth 
1000693eedb1SChandler Carruth   // We build the set of blocks dominated by the cloned header from the set of
1001693eedb1SChandler Carruth   // cloned blocks out of the original loop. While not all of these will
1002693eedb1SChandler Carruth   // necessarily be in the cloned loop, it is enough to establish that they
1003693eedb1SChandler Carruth   // aren't in unreachable cycles, etc.
1004693eedb1SChandler Carruth   SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1005693eedb1SChandler Carruth   for (auto *BB : OrigL.blocks())
1006693eedb1SChandler Carruth     if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1007693eedb1SChandler Carruth       ClonedLoopBlocks.insert(ClonedBB);
1008693eedb1SChandler Carruth 
1009693eedb1SChandler Carruth   // Rebuild the set of blocks that will end up in the cloned loop. We may have
1010693eedb1SChandler Carruth   // skipped cloning some region of this loop which can in turn skip some of
1011693eedb1SChandler Carruth   // the backedges so we have to rebuild the blocks in the loop based on the
1012693eedb1SChandler Carruth   // backedges that remain after cloning.
1013693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1014693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1015693eedb1SChandler Carruth   for (auto *Pred : predecessors(ClonedHeader)) {
1016693eedb1SChandler Carruth     // The only possible non-loop header predecessor is the preheader because
1017693eedb1SChandler Carruth     // we know we cloned the loop in simplified form.
1018693eedb1SChandler Carruth     if (Pred == ClonedPH)
1019693eedb1SChandler Carruth       continue;
1020693eedb1SChandler Carruth 
1021693eedb1SChandler Carruth     // Because the loop was in simplified form, the only non-loop predecessor
1022693eedb1SChandler Carruth     // should be the preheader.
1023693eedb1SChandler Carruth     assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1024693eedb1SChandler Carruth                                            "header other than the preheader "
1025693eedb1SChandler Carruth                                            "that is not part of the loop!");
1026693eedb1SChandler Carruth 
1027693eedb1SChandler Carruth     // Insert this block into the loop set and on the first visit (and if it
1028693eedb1SChandler Carruth     // isn't the header we're currently walking) put it into the worklist to
1029693eedb1SChandler Carruth     // recurse through.
1030693eedb1SChandler Carruth     if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1031693eedb1SChandler Carruth       Worklist.push_back(Pred);
1032693eedb1SChandler Carruth   }
1033693eedb1SChandler Carruth 
1034693eedb1SChandler Carruth   // If we had any backedges then there *is* a cloned loop. Put the header into
1035693eedb1SChandler Carruth   // the loop set and then walk the worklist backwards to find all the blocks
1036693eedb1SChandler Carruth   // that remain within the loop after cloning.
1037693eedb1SChandler Carruth   if (!BlocksInClonedLoop.empty()) {
1038693eedb1SChandler Carruth     BlocksInClonedLoop.insert(ClonedHeader);
1039693eedb1SChandler Carruth 
1040693eedb1SChandler Carruth     while (!Worklist.empty()) {
1041693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1042693eedb1SChandler Carruth       assert(BlocksInClonedLoop.count(BB) &&
1043693eedb1SChandler Carruth              "Didn't put block into the loop set!");
1044693eedb1SChandler Carruth 
1045693eedb1SChandler Carruth       // Insert any predecessors that are in the possible set into the cloned
1046693eedb1SChandler Carruth       // set, and if the insert is successful, add them to the worklist. Note
1047693eedb1SChandler Carruth       // that we filter on the blocks that are definitely reachable via the
1048693eedb1SChandler Carruth       // backedge to the loop header so we may prune out dead code within the
1049693eedb1SChandler Carruth       // cloned loop.
1050693eedb1SChandler Carruth       for (auto *Pred : predecessors(BB))
1051693eedb1SChandler Carruth         if (ClonedLoopBlocks.count(Pred) &&
1052693eedb1SChandler Carruth             BlocksInClonedLoop.insert(Pred).second)
1053693eedb1SChandler Carruth           Worklist.push_back(Pred);
1054693eedb1SChandler Carruth     }
1055693eedb1SChandler Carruth 
1056693eedb1SChandler Carruth     ClonedL = LI.AllocateLoop();
1057693eedb1SChandler Carruth     if (ParentL) {
1058693eedb1SChandler Carruth       ParentL->addBasicBlockToLoop(ClonedPH, LI);
1059693eedb1SChandler Carruth       ParentL->addChildLoop(ClonedL);
1060693eedb1SChandler Carruth     } else {
1061693eedb1SChandler Carruth       LI.addTopLevelLoop(ClonedL);
1062693eedb1SChandler Carruth     }
1063693eedb1SChandler Carruth 
1064693eedb1SChandler Carruth     ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1065693eedb1SChandler Carruth     // We don't want to just add the cloned loop blocks based on how we
1066693eedb1SChandler Carruth     // discovered them. The original order of blocks was carefully built in
1067693eedb1SChandler Carruth     // a way that doesn't rely on predecessor ordering. Rather than re-invent
1068693eedb1SChandler Carruth     // that logic, we just re-walk the original blocks (and those of the child
1069693eedb1SChandler Carruth     // loops) and filter them as we add them into the cloned loop.
1070693eedb1SChandler Carruth     for (auto *BB : OrigL.blocks()) {
1071693eedb1SChandler Carruth       auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1072693eedb1SChandler Carruth       if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1073693eedb1SChandler Carruth         continue;
1074693eedb1SChandler Carruth 
1075693eedb1SChandler Carruth       // Directly add the blocks that are only in this loop.
1076693eedb1SChandler Carruth       if (LI.getLoopFor(BB) == &OrigL) {
1077693eedb1SChandler Carruth         ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1078693eedb1SChandler Carruth         continue;
1079693eedb1SChandler Carruth       }
1080693eedb1SChandler Carruth 
1081693eedb1SChandler Carruth       // We want to manually add it to this loop and parents.
1082693eedb1SChandler Carruth       // Registering it with LoopInfo will happen when we clone the top
1083693eedb1SChandler Carruth       // loop for this block.
1084693eedb1SChandler Carruth       for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1085693eedb1SChandler Carruth         PL->addBlockEntry(ClonedBB);
1086693eedb1SChandler Carruth     }
1087693eedb1SChandler Carruth 
1088693eedb1SChandler Carruth     // Now add each child loop whose header remains within the cloned loop. All
1089693eedb1SChandler Carruth     // of the blocks within the loop must satisfy the same constraints as the
1090693eedb1SChandler Carruth     // header so once we pass the header checks we can just clone the entire
1091693eedb1SChandler Carruth     // child loop nest.
1092693eedb1SChandler Carruth     for (Loop *ChildL : OrigL) {
1093693eedb1SChandler Carruth       auto *ClonedChildHeader =
1094693eedb1SChandler Carruth           cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1095693eedb1SChandler Carruth       if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1096693eedb1SChandler Carruth         continue;
1097693eedb1SChandler Carruth 
1098693eedb1SChandler Carruth #ifndef NDEBUG
1099693eedb1SChandler Carruth       // We should never have a cloned child loop header but fail to have
1100693eedb1SChandler Carruth       // all of the blocks for that child loop.
1101693eedb1SChandler Carruth       for (auto *ChildLoopBB : ChildL->blocks())
1102693eedb1SChandler Carruth         assert(BlocksInClonedLoop.count(
1103693eedb1SChandler Carruth                    cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1104693eedb1SChandler Carruth                "Child cloned loop has a header within the cloned outer "
1105693eedb1SChandler Carruth                "loop but not all of its blocks!");
1106693eedb1SChandler Carruth #endif
1107693eedb1SChandler Carruth 
1108693eedb1SChandler Carruth       cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1109693eedb1SChandler Carruth     }
1110693eedb1SChandler Carruth   }
1111693eedb1SChandler Carruth 
1112693eedb1SChandler Carruth   // Now that we've handled all the components of the original loop that were
1113693eedb1SChandler Carruth   // cloned into a new loop, we still need to handle anything from the original
1114693eedb1SChandler Carruth   // loop that wasn't in a cloned loop.
1115693eedb1SChandler Carruth 
1116693eedb1SChandler Carruth   // Figure out what blocks are left to place within any loop nest containing
1117693eedb1SChandler Carruth   // the unswitched loop. If we never formed a loop, the cloned PH is one of
1118693eedb1SChandler Carruth   // them.
1119693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1120693eedb1SChandler Carruth   if (BlocksInClonedLoop.empty())
1121693eedb1SChandler Carruth     UnloopedBlockSet.insert(ClonedPH);
1122693eedb1SChandler Carruth   for (auto *ClonedBB : ClonedLoopBlocks)
1123693eedb1SChandler Carruth     if (!BlocksInClonedLoop.count(ClonedBB))
1124693eedb1SChandler Carruth       UnloopedBlockSet.insert(ClonedBB);
1125693eedb1SChandler Carruth 
1126693eedb1SChandler Carruth   // Copy the cloned exits and sort them in ascending loop depth, we'll work
1127693eedb1SChandler Carruth   // backwards across these to process them inside out. The order shouldn't
1128693eedb1SChandler Carruth   // matter as we're just trying to build up the map from inside-out; we use
1129693eedb1SChandler Carruth   // the map in a more stably ordered way below.
1130693eedb1SChandler Carruth   auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
1131*636d94dbSMandeep Singh Grang   llvm::sort(OrderedClonedExitsInLoops.begin(),
1132*636d94dbSMandeep Singh Grang              OrderedClonedExitsInLoops.end(),
1133693eedb1SChandler Carruth              [&](BasicBlock *LHS, BasicBlock *RHS) {
1134693eedb1SChandler Carruth                return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1135693eedb1SChandler Carruth                       ExitLoopMap.lookup(RHS)->getLoopDepth();
1136693eedb1SChandler Carruth              });
1137693eedb1SChandler Carruth 
1138693eedb1SChandler Carruth   // Populate the existing ExitLoopMap with everything reachable from each
1139693eedb1SChandler Carruth   // exit, starting from the inner most exit.
1140693eedb1SChandler Carruth   while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1141693eedb1SChandler Carruth     assert(Worklist.empty() && "Didn't clear worklist!");
1142693eedb1SChandler Carruth 
1143693eedb1SChandler Carruth     BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1144693eedb1SChandler Carruth     Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1145693eedb1SChandler Carruth 
1146693eedb1SChandler Carruth     // Walk the CFG back until we hit the cloned PH adding everything reachable
1147693eedb1SChandler Carruth     // and in the unlooped set to this exit block's loop.
1148693eedb1SChandler Carruth     Worklist.push_back(ExitBB);
1149693eedb1SChandler Carruth     do {
1150693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1151693eedb1SChandler Carruth       // We can stop recursing at the cloned preheader (if we get there).
1152693eedb1SChandler Carruth       if (BB == ClonedPH)
1153693eedb1SChandler Carruth         continue;
1154693eedb1SChandler Carruth 
1155693eedb1SChandler Carruth       for (BasicBlock *PredBB : predecessors(BB)) {
1156693eedb1SChandler Carruth         // If this pred has already been moved to our set or is part of some
1157693eedb1SChandler Carruth         // (inner) loop, no update needed.
1158693eedb1SChandler Carruth         if (!UnloopedBlockSet.erase(PredBB)) {
1159693eedb1SChandler Carruth           assert(
1160693eedb1SChandler Carruth               (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1161693eedb1SChandler Carruth               "Predecessor not mapped to a loop!");
1162693eedb1SChandler Carruth           continue;
1163693eedb1SChandler Carruth         }
1164693eedb1SChandler Carruth 
1165693eedb1SChandler Carruth         // We just insert into the loop set here. We'll add these blocks to the
1166693eedb1SChandler Carruth         // exit loop after we build up the set in an order that doesn't rely on
1167693eedb1SChandler Carruth         // predecessor order (which in turn relies on use list order).
1168693eedb1SChandler Carruth         bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1169693eedb1SChandler Carruth         (void)Inserted;
1170693eedb1SChandler Carruth         assert(Inserted && "Should only visit an unlooped block once!");
1171693eedb1SChandler Carruth 
1172693eedb1SChandler Carruth         // And recurse through to its predecessors.
1173693eedb1SChandler Carruth         Worklist.push_back(PredBB);
1174693eedb1SChandler Carruth       }
1175693eedb1SChandler Carruth     } while (!Worklist.empty());
1176693eedb1SChandler Carruth   }
1177693eedb1SChandler Carruth 
1178693eedb1SChandler Carruth   // Now that the ExitLoopMap gives as  mapping for all the non-looping cloned
1179693eedb1SChandler Carruth   // blocks to their outer loops, walk the cloned blocks and the cloned exits
1180693eedb1SChandler Carruth   // in their original order adding them to the correct loop.
1181693eedb1SChandler Carruth 
1182693eedb1SChandler Carruth   // We need a stable insertion order. We use the order of the original loop
1183693eedb1SChandler Carruth   // order and map into the correct parent loop.
1184693eedb1SChandler Carruth   for (auto *BB : llvm::concat<BasicBlock *const>(
1185693eedb1SChandler Carruth            makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1186693eedb1SChandler Carruth     if (Loop *OuterL = ExitLoopMap.lookup(BB))
1187693eedb1SChandler Carruth       OuterL->addBasicBlockToLoop(BB, LI);
1188693eedb1SChandler Carruth 
1189693eedb1SChandler Carruth #ifndef NDEBUG
1190693eedb1SChandler Carruth   for (auto &BBAndL : ExitLoopMap) {
1191693eedb1SChandler Carruth     auto *BB = BBAndL.first;
1192693eedb1SChandler Carruth     auto *OuterL = BBAndL.second;
1193693eedb1SChandler Carruth     assert(LI.getLoopFor(BB) == OuterL &&
1194693eedb1SChandler Carruth            "Failed to put all blocks into outer loops!");
1195693eedb1SChandler Carruth   }
1196693eedb1SChandler Carruth #endif
1197693eedb1SChandler Carruth 
1198693eedb1SChandler Carruth   // Now that all the blocks are placed into the correct containing loop in the
1199693eedb1SChandler Carruth   // absence of child loops, find all the potentially cloned child loops and
1200693eedb1SChandler Carruth   // clone them into whatever outer loop we placed their header into.
1201693eedb1SChandler Carruth   for (Loop *ChildL : OrigL) {
1202693eedb1SChandler Carruth     auto *ClonedChildHeader =
1203693eedb1SChandler Carruth         cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1204693eedb1SChandler Carruth     if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1205693eedb1SChandler Carruth       continue;
1206693eedb1SChandler Carruth 
1207693eedb1SChandler Carruth #ifndef NDEBUG
1208693eedb1SChandler Carruth     for (auto *ChildLoopBB : ChildL->blocks())
1209693eedb1SChandler Carruth       assert(VMap.count(ChildLoopBB) &&
1210693eedb1SChandler Carruth              "Cloned a child loop header but not all of that loops blocks!");
1211693eedb1SChandler Carruth #endif
1212693eedb1SChandler Carruth 
1213693eedb1SChandler Carruth     NonChildClonedLoops.push_back(cloneLoopNest(
1214693eedb1SChandler Carruth         *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1215693eedb1SChandler Carruth   }
1216693eedb1SChandler Carruth 
1217693eedb1SChandler Carruth   // Return the main cloned loop if any.
1218693eedb1SChandler Carruth   return ClonedL;
1219693eedb1SChandler Carruth }
1220693eedb1SChandler Carruth 
1221693eedb1SChandler Carruth static void deleteDeadBlocksFromLoop(Loop &L, BasicBlock *DeadSubtreeRoot,
1222693eedb1SChandler Carruth                                      SmallVectorImpl<BasicBlock *> &ExitBlocks,
1223693eedb1SChandler Carruth                                      DominatorTree &DT, LoopInfo &LI) {
1224693eedb1SChandler Carruth   // Walk the dominator tree to build up the set of blocks we will delete here.
1225693eedb1SChandler Carruth   // The order is designed to allow us to always delete bottom-up and avoid any
1226693eedb1SChandler Carruth   // dangling uses.
1227693eedb1SChandler Carruth   SmallSetVector<BasicBlock *, 16> DeadBlocks;
1228693eedb1SChandler Carruth   DeadBlocks.insert(DeadSubtreeRoot);
1229693eedb1SChandler Carruth   for (int i = 0; i < (int)DeadBlocks.size(); ++i)
1230693eedb1SChandler Carruth     for (DomTreeNode *ChildN : *DT[DeadBlocks[i]]) {
1231693eedb1SChandler Carruth       // FIXME: This assert should pass and that means we don't change nearly
1232693eedb1SChandler Carruth       // as much below! Consider rewriting all of this to avoid deleting
1233693eedb1SChandler Carruth       // blocks. They are always cloned before being deleted, and so instead
1234693eedb1SChandler Carruth       // could just be moved.
1235693eedb1SChandler Carruth       // FIXME: This in turn means that we might actually be more able to
1236693eedb1SChandler Carruth       // update the domtree.
1237693eedb1SChandler Carruth       assert((L.contains(ChildN->getBlock()) ||
1238693eedb1SChandler Carruth               llvm::find(ExitBlocks, ChildN->getBlock()) != ExitBlocks.end()) &&
1239693eedb1SChandler Carruth              "Should never reach beyond the loop and exits when deleting!");
1240693eedb1SChandler Carruth       DeadBlocks.insert(ChildN->getBlock());
1241693eedb1SChandler Carruth     }
1242693eedb1SChandler Carruth 
1243693eedb1SChandler Carruth   // Filter out the dead blocks from the exit blocks list so that it can be
1244693eedb1SChandler Carruth   // used in the caller.
1245693eedb1SChandler Carruth   llvm::erase_if(ExitBlocks,
1246693eedb1SChandler Carruth                  [&](BasicBlock *BB) { return DeadBlocks.count(BB); });
1247693eedb1SChandler Carruth 
1248693eedb1SChandler Carruth   // Remove these blocks from their successors.
1249693eedb1SChandler Carruth   for (auto *BB : DeadBlocks)
1250693eedb1SChandler Carruth     for (BasicBlock *SuccBB : successors(BB))
1251693eedb1SChandler Carruth       SuccBB->removePredecessor(BB, /*DontDeleteUselessPHIs*/ true);
1252693eedb1SChandler Carruth 
1253693eedb1SChandler Carruth   // Walk from this loop up through its parents removing all of the dead blocks.
1254693eedb1SChandler Carruth   for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
1255693eedb1SChandler Carruth     for (auto *BB : DeadBlocks)
1256693eedb1SChandler Carruth       ParentL->getBlocksSet().erase(BB);
1257693eedb1SChandler Carruth     llvm::erase_if(ParentL->getBlocksVector(),
1258693eedb1SChandler Carruth                    [&](BasicBlock *BB) { return DeadBlocks.count(BB); });
1259693eedb1SChandler Carruth   }
1260693eedb1SChandler Carruth 
1261693eedb1SChandler Carruth   // Now delete the dead child loops. This raw delete will clear them
1262693eedb1SChandler Carruth   // recursively.
1263693eedb1SChandler Carruth   llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
1264693eedb1SChandler Carruth     if (!DeadBlocks.count(ChildL->getHeader()))
1265693eedb1SChandler Carruth       return false;
1266693eedb1SChandler Carruth 
1267693eedb1SChandler Carruth     assert(llvm::all_of(ChildL->blocks(),
1268693eedb1SChandler Carruth                         [&](BasicBlock *ChildBB) {
1269693eedb1SChandler Carruth                           return DeadBlocks.count(ChildBB);
1270693eedb1SChandler Carruth                         }) &&
1271693eedb1SChandler Carruth            "If the child loop header is dead all blocks in the child loop must "
1272693eedb1SChandler Carruth            "be dead as well!");
1273693eedb1SChandler Carruth     LI.destroy(ChildL);
1274693eedb1SChandler Carruth     return true;
1275693eedb1SChandler Carruth   });
1276693eedb1SChandler Carruth 
1277693eedb1SChandler Carruth   // Remove the mappings for the dead blocks.
1278693eedb1SChandler Carruth   for (auto *BB : DeadBlocks)
1279693eedb1SChandler Carruth     LI.changeLoopFor(BB, nullptr);
1280693eedb1SChandler Carruth 
1281693eedb1SChandler Carruth   // Drop all the references from these blocks to others to handle cyclic
1282693eedb1SChandler Carruth   // references as we start deleting the blocks themselves.
1283693eedb1SChandler Carruth   for (auto *BB : DeadBlocks)
1284693eedb1SChandler Carruth     BB->dropAllReferences();
1285693eedb1SChandler Carruth 
1286693eedb1SChandler Carruth   for (auto *BB : llvm::reverse(DeadBlocks)) {
1287693eedb1SChandler Carruth     DT.eraseNode(BB);
1288693eedb1SChandler Carruth     BB->eraseFromParent();
1289693eedb1SChandler Carruth   }
1290693eedb1SChandler Carruth }
1291693eedb1SChandler Carruth 
1292693eedb1SChandler Carruth /// Recompute the set of blocks in a loop after unswitching.
1293693eedb1SChandler Carruth ///
1294693eedb1SChandler Carruth /// This walks from the original headers predecessors to rebuild the loop. We
1295693eedb1SChandler Carruth /// take advantage of the fact that new blocks can't have been added, and so we
1296693eedb1SChandler Carruth /// filter by the original loop's blocks. This also handles potentially
1297693eedb1SChandler Carruth /// unreachable code that we don't want to explore but might be found examining
1298693eedb1SChandler Carruth /// the predecessors of the header.
1299693eedb1SChandler Carruth ///
1300693eedb1SChandler Carruth /// If the original loop is no longer a loop, this will return an empty set. If
1301693eedb1SChandler Carruth /// it remains a loop, all the blocks within it will be added to the set
1302693eedb1SChandler Carruth /// (including those blocks in inner loops).
1303693eedb1SChandler Carruth static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1304693eedb1SChandler Carruth                                                                  LoopInfo &LI) {
1305693eedb1SChandler Carruth   SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1306693eedb1SChandler Carruth 
1307693eedb1SChandler Carruth   auto *PH = L.getLoopPreheader();
1308693eedb1SChandler Carruth   auto *Header = L.getHeader();
1309693eedb1SChandler Carruth 
1310693eedb1SChandler Carruth   // A worklist to use while walking backwards from the header.
1311693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1312693eedb1SChandler Carruth 
1313693eedb1SChandler Carruth   // First walk the predecessors of the header to find the backedges. This will
1314693eedb1SChandler Carruth   // form the basis of our walk.
1315693eedb1SChandler Carruth   for (auto *Pred : predecessors(Header)) {
1316693eedb1SChandler Carruth     // Skip the preheader.
1317693eedb1SChandler Carruth     if (Pred == PH)
1318693eedb1SChandler Carruth       continue;
1319693eedb1SChandler Carruth 
1320693eedb1SChandler Carruth     // Because the loop was in simplified form, the only non-loop predecessor
1321693eedb1SChandler Carruth     // is the preheader.
1322693eedb1SChandler Carruth     assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1323693eedb1SChandler Carruth                                "than the preheader that is not part of the "
1324693eedb1SChandler Carruth                                "loop!");
1325693eedb1SChandler Carruth 
1326693eedb1SChandler Carruth     // Insert this block into the loop set and on the first visit and, if it
1327693eedb1SChandler Carruth     // isn't the header we're currently walking, put it into the worklist to
1328693eedb1SChandler Carruth     // recurse through.
1329693eedb1SChandler Carruth     if (LoopBlockSet.insert(Pred).second && Pred != Header)
1330693eedb1SChandler Carruth       Worklist.push_back(Pred);
1331693eedb1SChandler Carruth   }
1332693eedb1SChandler Carruth 
1333693eedb1SChandler Carruth   // If no backedges were found, we're done.
1334693eedb1SChandler Carruth   if (LoopBlockSet.empty())
1335693eedb1SChandler Carruth     return LoopBlockSet;
1336693eedb1SChandler Carruth 
1337693eedb1SChandler Carruth   // Add the loop header to the set.
1338693eedb1SChandler Carruth   LoopBlockSet.insert(Header);
1339693eedb1SChandler Carruth 
1340693eedb1SChandler Carruth   // We found backedges, recurse through them to identify the loop blocks.
1341693eedb1SChandler Carruth   while (!Worklist.empty()) {
1342693eedb1SChandler Carruth     BasicBlock *BB = Worklist.pop_back_val();
1343693eedb1SChandler Carruth     assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1344693eedb1SChandler Carruth 
1345693eedb1SChandler Carruth     // Because we know the inner loop structure remains valid we can use the
1346693eedb1SChandler Carruth     // loop structure to jump immediately across the entire nested loop.
1347693eedb1SChandler Carruth     // Further, because it is in loop simplified form, we can directly jump
1348693eedb1SChandler Carruth     // to its preheader afterward.
1349693eedb1SChandler Carruth     if (Loop *InnerL = LI.getLoopFor(BB))
1350693eedb1SChandler Carruth       if (InnerL != &L) {
1351693eedb1SChandler Carruth         assert(L.contains(InnerL) &&
1352693eedb1SChandler Carruth                "Should not reach a loop *outside* this loop!");
1353693eedb1SChandler Carruth         // The preheader is the only possible predecessor of the loop so
1354693eedb1SChandler Carruth         // insert it into the set and check whether it was already handled.
1355693eedb1SChandler Carruth         auto *InnerPH = InnerL->getLoopPreheader();
1356693eedb1SChandler Carruth         assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1357693eedb1SChandler Carruth                                       "but not contain the inner loop "
1358693eedb1SChandler Carruth                                       "preheader!");
1359693eedb1SChandler Carruth         if (!LoopBlockSet.insert(InnerPH).second)
1360693eedb1SChandler Carruth           // The only way to reach the preheader is through the loop body
1361693eedb1SChandler Carruth           // itself so if it has been visited the loop is already handled.
1362693eedb1SChandler Carruth           continue;
1363693eedb1SChandler Carruth 
1364693eedb1SChandler Carruth         // Insert all of the blocks (other than those already present) into
1365693eedb1SChandler Carruth         // the loop set. The only block we expect to already be in the set is
1366693eedb1SChandler Carruth         // the one we used to find this loop as we immediately handle the
1367693eedb1SChandler Carruth         // others the first time we encounter the loop.
1368693eedb1SChandler Carruth         for (auto *InnerBB : InnerL->blocks()) {
1369693eedb1SChandler Carruth           if (InnerBB == BB) {
1370693eedb1SChandler Carruth             assert(LoopBlockSet.count(InnerBB) &&
1371693eedb1SChandler Carruth                    "Block should already be in the set!");
1372693eedb1SChandler Carruth             continue;
1373693eedb1SChandler Carruth           }
1374693eedb1SChandler Carruth 
1375693eedb1SChandler Carruth           bool Inserted = LoopBlockSet.insert(InnerBB).second;
1376693eedb1SChandler Carruth           (void)Inserted;
1377693eedb1SChandler Carruth           assert(Inserted && "Should only insert an inner loop once!");
1378693eedb1SChandler Carruth         }
1379693eedb1SChandler Carruth 
1380693eedb1SChandler Carruth         // Add the preheader to the worklist so we will continue past the
1381693eedb1SChandler Carruth         // loop body.
1382693eedb1SChandler Carruth         Worklist.push_back(InnerPH);
1383693eedb1SChandler Carruth         continue;
1384693eedb1SChandler Carruth       }
1385693eedb1SChandler Carruth 
1386693eedb1SChandler Carruth     // Insert any predecessors that were in the original loop into the new
1387693eedb1SChandler Carruth     // set, and if the insert is successful, add them to the worklist.
1388693eedb1SChandler Carruth     for (auto *Pred : predecessors(BB))
1389693eedb1SChandler Carruth       if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1390693eedb1SChandler Carruth         Worklist.push_back(Pred);
1391693eedb1SChandler Carruth   }
1392693eedb1SChandler Carruth 
1393693eedb1SChandler Carruth   // We've found all the blocks participating in the loop, return our completed
1394693eedb1SChandler Carruth   // set.
1395693eedb1SChandler Carruth   return LoopBlockSet;
1396693eedb1SChandler Carruth }
1397693eedb1SChandler Carruth 
1398693eedb1SChandler Carruth /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1399693eedb1SChandler Carruth ///
1400693eedb1SChandler Carruth /// The removal may have removed some child loops entirely but cannot have
1401693eedb1SChandler Carruth /// disturbed any remaining child loops. However, they may need to be hoisted
1402693eedb1SChandler Carruth /// to the parent loop (or to be top-level loops). The original loop may be
1403693eedb1SChandler Carruth /// completely removed.
1404693eedb1SChandler Carruth ///
1405693eedb1SChandler Carruth /// The sibling loops resulting from this update are returned. If the original
1406693eedb1SChandler Carruth /// loop remains a valid loop, it will be the first entry in this list with all
1407693eedb1SChandler Carruth /// of the newly sibling loops following it.
1408693eedb1SChandler Carruth ///
1409693eedb1SChandler Carruth /// Returns true if the loop remains a loop after unswitching, and false if it
1410693eedb1SChandler Carruth /// is no longer a loop after unswitching (and should not continue to be
1411693eedb1SChandler Carruth /// referenced).
1412693eedb1SChandler Carruth static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1413693eedb1SChandler Carruth                                      LoopInfo &LI,
1414693eedb1SChandler Carruth                                      SmallVectorImpl<Loop *> &HoistedLoops) {
1415693eedb1SChandler Carruth   auto *PH = L.getLoopPreheader();
1416693eedb1SChandler Carruth 
1417693eedb1SChandler Carruth   // Compute the actual parent loop from the exit blocks. Because we may have
1418693eedb1SChandler Carruth   // pruned some exits the loop may be different from the original parent.
1419693eedb1SChandler Carruth   Loop *ParentL = nullptr;
1420693eedb1SChandler Carruth   SmallVector<Loop *, 4> ExitLoops;
1421693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> ExitsInLoops;
1422693eedb1SChandler Carruth   ExitsInLoops.reserve(ExitBlocks.size());
1423693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks)
1424693eedb1SChandler Carruth     if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1425693eedb1SChandler Carruth       ExitLoops.push_back(ExitL);
1426693eedb1SChandler Carruth       ExitsInLoops.push_back(ExitBB);
1427693eedb1SChandler Carruth       if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1428693eedb1SChandler Carruth         ParentL = ExitL;
1429693eedb1SChandler Carruth     }
1430693eedb1SChandler Carruth 
1431693eedb1SChandler Carruth   // Recompute the blocks participating in this loop. This may be empty if it
1432693eedb1SChandler Carruth   // is no longer a loop.
1433693eedb1SChandler Carruth   auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1434693eedb1SChandler Carruth 
1435693eedb1SChandler Carruth   // If we still have a loop, we need to re-set the loop's parent as the exit
1436693eedb1SChandler Carruth   // block set changing may have moved it within the loop nest. Note that this
1437693eedb1SChandler Carruth   // can only happen when this loop has a parent as it can only hoist the loop
1438693eedb1SChandler Carruth   // *up* the nest.
1439693eedb1SChandler Carruth   if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1440693eedb1SChandler Carruth     // Remove this loop's (original) blocks from all of the intervening loops.
1441693eedb1SChandler Carruth     for (Loop *IL = L.getParentLoop(); IL != ParentL;
1442693eedb1SChandler Carruth          IL = IL->getParentLoop()) {
1443693eedb1SChandler Carruth       IL->getBlocksSet().erase(PH);
1444693eedb1SChandler Carruth       for (auto *BB : L.blocks())
1445693eedb1SChandler Carruth         IL->getBlocksSet().erase(BB);
1446693eedb1SChandler Carruth       llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1447693eedb1SChandler Carruth         return BB == PH || L.contains(BB);
1448693eedb1SChandler Carruth       });
1449693eedb1SChandler Carruth     }
1450693eedb1SChandler Carruth 
1451693eedb1SChandler Carruth     LI.changeLoopFor(PH, ParentL);
1452693eedb1SChandler Carruth     L.getParentLoop()->removeChildLoop(&L);
1453693eedb1SChandler Carruth     if (ParentL)
1454693eedb1SChandler Carruth       ParentL->addChildLoop(&L);
1455693eedb1SChandler Carruth     else
1456693eedb1SChandler Carruth       LI.addTopLevelLoop(&L);
1457693eedb1SChandler Carruth   }
1458693eedb1SChandler Carruth 
1459693eedb1SChandler Carruth   // Now we update all the blocks which are no longer within the loop.
1460693eedb1SChandler Carruth   auto &Blocks = L.getBlocksVector();
1461693eedb1SChandler Carruth   auto BlocksSplitI =
1462693eedb1SChandler Carruth       LoopBlockSet.empty()
1463693eedb1SChandler Carruth           ? Blocks.begin()
1464693eedb1SChandler Carruth           : std::stable_partition(
1465693eedb1SChandler Carruth                 Blocks.begin(), Blocks.end(),
1466693eedb1SChandler Carruth                 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1467693eedb1SChandler Carruth 
1468693eedb1SChandler Carruth   // Before we erase the list of unlooped blocks, build a set of them.
1469693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1470693eedb1SChandler Carruth   if (LoopBlockSet.empty())
1471693eedb1SChandler Carruth     UnloopedBlocks.insert(PH);
1472693eedb1SChandler Carruth 
1473693eedb1SChandler Carruth   // Now erase these blocks from the loop.
1474693eedb1SChandler Carruth   for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1475693eedb1SChandler Carruth     L.getBlocksSet().erase(BB);
1476693eedb1SChandler Carruth   Blocks.erase(BlocksSplitI, Blocks.end());
1477693eedb1SChandler Carruth 
1478693eedb1SChandler Carruth   // Sort the exits in ascending loop depth, we'll work backwards across these
1479693eedb1SChandler Carruth   // to process them inside out.
1480693eedb1SChandler Carruth   std::stable_sort(ExitsInLoops.begin(), ExitsInLoops.end(),
1481693eedb1SChandler Carruth                    [&](BasicBlock *LHS, BasicBlock *RHS) {
1482693eedb1SChandler Carruth                      return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1483693eedb1SChandler Carruth                    });
1484693eedb1SChandler Carruth 
1485693eedb1SChandler Carruth   // We'll build up a set for each exit loop.
1486693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1487693eedb1SChandler Carruth   Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1488693eedb1SChandler Carruth 
1489693eedb1SChandler Carruth   auto RemoveUnloopedBlocksFromLoop =
1490693eedb1SChandler Carruth       [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1491693eedb1SChandler Carruth         for (auto *BB : UnloopedBlocks)
1492693eedb1SChandler Carruth           L.getBlocksSet().erase(BB);
1493693eedb1SChandler Carruth         llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1494693eedb1SChandler Carruth           return UnloopedBlocks.count(BB);
1495693eedb1SChandler Carruth         });
1496693eedb1SChandler Carruth       };
1497693eedb1SChandler Carruth 
1498693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1499693eedb1SChandler Carruth   while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1500693eedb1SChandler Carruth     assert(Worklist.empty() && "Didn't clear worklist!");
1501693eedb1SChandler Carruth     assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1502693eedb1SChandler Carruth 
1503693eedb1SChandler Carruth     // Grab the next exit block, in decreasing loop depth order.
1504693eedb1SChandler Carruth     BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1505693eedb1SChandler Carruth     Loop &ExitL = *LI.getLoopFor(ExitBB);
1506693eedb1SChandler Carruth     assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1507693eedb1SChandler Carruth 
1508693eedb1SChandler Carruth     // Erase all of the unlooped blocks from the loops between the previous
1509693eedb1SChandler Carruth     // exit loop and this exit loop. This works because the ExitInLoops list is
1510693eedb1SChandler Carruth     // sorted in increasing order of loop depth and thus we visit loops in
1511693eedb1SChandler Carruth     // decreasing order of loop depth.
1512693eedb1SChandler Carruth     for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1513693eedb1SChandler Carruth       RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1514693eedb1SChandler Carruth 
1515693eedb1SChandler Carruth     // Walk the CFG back until we hit the cloned PH adding everything reachable
1516693eedb1SChandler Carruth     // and in the unlooped set to this exit block's loop.
1517693eedb1SChandler Carruth     Worklist.push_back(ExitBB);
1518693eedb1SChandler Carruth     do {
1519693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1520693eedb1SChandler Carruth       // We can stop recursing at the cloned preheader (if we get there).
1521693eedb1SChandler Carruth       if (BB == PH)
1522693eedb1SChandler Carruth         continue;
1523693eedb1SChandler Carruth 
1524693eedb1SChandler Carruth       for (BasicBlock *PredBB : predecessors(BB)) {
1525693eedb1SChandler Carruth         // If this pred has already been moved to our set or is part of some
1526693eedb1SChandler Carruth         // (inner) loop, no update needed.
1527693eedb1SChandler Carruth         if (!UnloopedBlocks.erase(PredBB)) {
1528693eedb1SChandler Carruth           assert((NewExitLoopBlocks.count(PredBB) ||
1529693eedb1SChandler Carruth                   ExitL.contains(LI.getLoopFor(PredBB))) &&
1530693eedb1SChandler Carruth                  "Predecessor not in a nested loop (or already visited)!");
1531693eedb1SChandler Carruth           continue;
1532693eedb1SChandler Carruth         }
1533693eedb1SChandler Carruth 
1534693eedb1SChandler Carruth         // We just insert into the loop set here. We'll add these blocks to the
1535693eedb1SChandler Carruth         // exit loop after we build up the set in a deterministic order rather
1536693eedb1SChandler Carruth         // than the predecessor-influenced visit order.
1537693eedb1SChandler Carruth         bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1538693eedb1SChandler Carruth         (void)Inserted;
1539693eedb1SChandler Carruth         assert(Inserted && "Should only visit an unlooped block once!");
1540693eedb1SChandler Carruth 
1541693eedb1SChandler Carruth         // And recurse through to its predecessors.
1542693eedb1SChandler Carruth         Worklist.push_back(PredBB);
1543693eedb1SChandler Carruth       }
1544693eedb1SChandler Carruth     } while (!Worklist.empty());
1545693eedb1SChandler Carruth 
1546693eedb1SChandler Carruth     // If blocks in this exit loop were directly part of the original loop (as
1547693eedb1SChandler Carruth     // opposed to a child loop) update the map to point to this exit loop. This
1548693eedb1SChandler Carruth     // just updates a map and so the fact that the order is unstable is fine.
1549693eedb1SChandler Carruth     for (auto *BB : NewExitLoopBlocks)
1550693eedb1SChandler Carruth       if (Loop *BBL = LI.getLoopFor(BB))
1551693eedb1SChandler Carruth         if (BBL == &L || !L.contains(BBL))
1552693eedb1SChandler Carruth           LI.changeLoopFor(BB, &ExitL);
1553693eedb1SChandler Carruth 
1554693eedb1SChandler Carruth     // We will remove the remaining unlooped blocks from this loop in the next
1555693eedb1SChandler Carruth     // iteration or below.
1556693eedb1SChandler Carruth     NewExitLoopBlocks.clear();
1557693eedb1SChandler Carruth   }
1558693eedb1SChandler Carruth 
1559693eedb1SChandler Carruth   // Any remaining unlooped blocks are no longer part of any loop unless they
1560693eedb1SChandler Carruth   // are part of some child loop.
1561693eedb1SChandler Carruth   for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1562693eedb1SChandler Carruth     RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1563693eedb1SChandler Carruth   for (auto *BB : UnloopedBlocks)
1564693eedb1SChandler Carruth     if (Loop *BBL = LI.getLoopFor(BB))
1565693eedb1SChandler Carruth       if (BBL == &L || !L.contains(BBL))
1566693eedb1SChandler Carruth         LI.changeLoopFor(BB, nullptr);
1567693eedb1SChandler Carruth 
1568693eedb1SChandler Carruth   // Sink all the child loops whose headers are no longer in the loop set to
1569693eedb1SChandler Carruth   // the parent (or to be top level loops). We reach into the loop and directly
1570693eedb1SChandler Carruth   // update its subloop vector to make this batch update efficient.
1571693eedb1SChandler Carruth   auto &SubLoops = L.getSubLoopsVector();
1572693eedb1SChandler Carruth   auto SubLoopsSplitI =
1573693eedb1SChandler Carruth       LoopBlockSet.empty()
1574693eedb1SChandler Carruth           ? SubLoops.begin()
1575693eedb1SChandler Carruth           : std::stable_partition(
1576693eedb1SChandler Carruth                 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1577693eedb1SChandler Carruth                   return LoopBlockSet.count(SubL->getHeader());
1578693eedb1SChandler Carruth                 });
1579693eedb1SChandler Carruth   for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1580693eedb1SChandler Carruth     HoistedLoops.push_back(HoistedL);
1581693eedb1SChandler Carruth     HoistedL->setParentLoop(nullptr);
1582693eedb1SChandler Carruth 
1583693eedb1SChandler Carruth     // To compute the new parent of this hoisted loop we look at where we
1584693eedb1SChandler Carruth     // placed the preheader above. We can't lookup the header itself because we
1585693eedb1SChandler Carruth     // retained the mapping from the header to the hoisted loop. But the
1586693eedb1SChandler Carruth     // preheader and header should have the exact same new parent computed
1587693eedb1SChandler Carruth     // based on the set of exit blocks from the original loop as the preheader
1588693eedb1SChandler Carruth     // is a predecessor of the header and so reached in the reverse walk. And
1589693eedb1SChandler Carruth     // because the loops were all in simplified form the preheader of the
1590693eedb1SChandler Carruth     // hoisted loop can't be part of some *other* loop.
1591693eedb1SChandler Carruth     if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1592693eedb1SChandler Carruth       NewParentL->addChildLoop(HoistedL);
1593693eedb1SChandler Carruth     else
1594693eedb1SChandler Carruth       LI.addTopLevelLoop(HoistedL);
1595693eedb1SChandler Carruth   }
1596693eedb1SChandler Carruth   SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1597693eedb1SChandler Carruth 
1598693eedb1SChandler Carruth   // Actually delete the loop if nothing remained within it.
1599693eedb1SChandler Carruth   if (Blocks.empty()) {
1600693eedb1SChandler Carruth     assert(SubLoops.empty() &&
1601693eedb1SChandler Carruth            "Failed to remove all subloops from the original loop!");
1602693eedb1SChandler Carruth     if (Loop *ParentL = L.getParentLoop())
1603693eedb1SChandler Carruth       ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1604693eedb1SChandler Carruth     else
1605693eedb1SChandler Carruth       LI.removeLoop(llvm::find(LI, &L));
1606693eedb1SChandler Carruth     LI.destroy(&L);
1607693eedb1SChandler Carruth     return false;
1608693eedb1SChandler Carruth   }
1609693eedb1SChandler Carruth 
1610693eedb1SChandler Carruth   return true;
1611693eedb1SChandler Carruth }
1612693eedb1SChandler Carruth 
1613693eedb1SChandler Carruth /// Helper to visit a dominator subtree, invoking a callable on each node.
1614693eedb1SChandler Carruth ///
1615693eedb1SChandler Carruth /// Returning false at any point will stop walking past that node of the tree.
1616693eedb1SChandler Carruth template <typename CallableT>
1617693eedb1SChandler Carruth void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1618693eedb1SChandler Carruth   SmallVector<DomTreeNode *, 4> DomWorklist;
1619693eedb1SChandler Carruth   DomWorklist.push_back(DT[BB]);
1620693eedb1SChandler Carruth #ifndef NDEBUG
1621693eedb1SChandler Carruth   SmallPtrSet<DomTreeNode *, 4> Visited;
1622693eedb1SChandler Carruth   Visited.insert(DT[BB]);
1623693eedb1SChandler Carruth #endif
1624693eedb1SChandler Carruth   do {
1625693eedb1SChandler Carruth     DomTreeNode *N = DomWorklist.pop_back_val();
1626693eedb1SChandler Carruth 
1627693eedb1SChandler Carruth     // Visit this node.
1628693eedb1SChandler Carruth     if (!Callable(N->getBlock()))
1629693eedb1SChandler Carruth       continue;
1630693eedb1SChandler Carruth 
1631693eedb1SChandler Carruth     // Accumulate the child nodes.
1632693eedb1SChandler Carruth     for (DomTreeNode *ChildN : *N) {
1633693eedb1SChandler Carruth       assert(Visited.insert(ChildN).second &&
1634693eedb1SChandler Carruth              "Cannot visit a node twice when walking a tree!");
1635693eedb1SChandler Carruth       DomWorklist.push_back(ChildN);
1636693eedb1SChandler Carruth     }
1637693eedb1SChandler Carruth   } while (!DomWorklist.empty());
1638693eedb1SChandler Carruth }
1639693eedb1SChandler Carruth 
1640693eedb1SChandler Carruth /// Take an invariant branch that has been determined to be safe and worthwhile
1641693eedb1SChandler Carruth /// to unswitch despite being non-trivial to do so and perform the unswitch.
1642693eedb1SChandler Carruth ///
1643693eedb1SChandler Carruth /// This directly updates the CFG to hoist the predicate out of the loop, and
1644693eedb1SChandler Carruth /// clone the necessary parts of the loop to maintain behavior.
1645693eedb1SChandler Carruth ///
1646693eedb1SChandler Carruth /// It also updates both dominator tree and loopinfo based on the unswitching.
1647693eedb1SChandler Carruth ///
1648693eedb1SChandler Carruth /// Once unswitching has been performed it runs the provided callback to report
1649693eedb1SChandler Carruth /// the new loops and no-longer valid loops to the caller.
1650693eedb1SChandler Carruth static bool unswitchInvariantBranch(
1651693eedb1SChandler Carruth     Loop &L, BranchInst &BI, DominatorTree &DT, LoopInfo &LI,
1652693eedb1SChandler Carruth     AssumptionCache &AC,
1653693eedb1SChandler Carruth     function_ref<void(bool, ArrayRef<Loop *>)> NonTrivialUnswitchCB) {
1654693eedb1SChandler Carruth   assert(BI.isConditional() && "Can only unswitch a conditional branch!");
1655693eedb1SChandler Carruth   assert(L.isLoopInvariant(BI.getCondition()) &&
1656693eedb1SChandler Carruth          "Can only unswitch an invariant branch condition!");
1657693eedb1SChandler Carruth 
1658693eedb1SChandler Carruth   // Constant and BBs tracking the cloned and continuing successor.
1659693eedb1SChandler Carruth   const int ClonedSucc = 0;
1660693eedb1SChandler Carruth   auto *ParentBB = BI.getParent();
1661693eedb1SChandler Carruth   auto *UnswitchedSuccBB = BI.getSuccessor(ClonedSucc);
1662693eedb1SChandler Carruth   auto *ContinueSuccBB = BI.getSuccessor(1 - ClonedSucc);
1663693eedb1SChandler Carruth 
1664693eedb1SChandler Carruth   assert(UnswitchedSuccBB != ContinueSuccBB &&
1665693eedb1SChandler Carruth          "Should not unswitch a branch that always goes to the same place!");
1666693eedb1SChandler Carruth 
1667693eedb1SChandler Carruth   // The branch should be in this exact loop. Any inner loop's invariant branch
1668693eedb1SChandler Carruth   // should be handled by unswitching that inner loop. The caller of this
1669693eedb1SChandler Carruth   // routine should filter out any candidates that remain (but were skipped for
1670693eedb1SChandler Carruth   // whatever reason).
1671693eedb1SChandler Carruth   assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1672693eedb1SChandler Carruth 
1673693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> ExitBlocks;
1674693eedb1SChandler Carruth   L.getUniqueExitBlocks(ExitBlocks);
1675693eedb1SChandler Carruth 
1676693eedb1SChandler Carruth   // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
1677693eedb1SChandler Carruth   // don't know how to split those exit blocks.
1678693eedb1SChandler Carruth   // FIXME: We should teach SplitBlock to handle this and remove this
1679693eedb1SChandler Carruth   // restriction.
1680693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks)
1681693eedb1SChandler Carruth     if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI()))
1682693eedb1SChandler Carruth       return false;
1683693eedb1SChandler Carruth 
1684693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 4> ExitBlockSet(ExitBlocks.begin(),
1685693eedb1SChandler Carruth                                             ExitBlocks.end());
1686693eedb1SChandler Carruth 
1687693eedb1SChandler Carruth   // Compute the parent loop now before we start hacking on things.
1688693eedb1SChandler Carruth   Loop *ParentL = L.getParentLoop();
1689693eedb1SChandler Carruth 
1690693eedb1SChandler Carruth   // Compute the outer-most loop containing one of our exit blocks. This is the
1691693eedb1SChandler Carruth   // furthest up our loopnest which can be mutated, which we will use below to
1692693eedb1SChandler Carruth   // update things.
1693693eedb1SChandler Carruth   Loop *OuterExitL = &L;
1694693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks) {
1695693eedb1SChandler Carruth     Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1696693eedb1SChandler Carruth     if (!NewOuterExitL) {
1697693eedb1SChandler Carruth       // We exited the entire nest with this block, so we're done.
1698693eedb1SChandler Carruth       OuterExitL = nullptr;
1699693eedb1SChandler Carruth       break;
1700693eedb1SChandler Carruth     }
1701693eedb1SChandler Carruth     if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1702693eedb1SChandler Carruth       OuterExitL = NewOuterExitL;
1703693eedb1SChandler Carruth   }
1704693eedb1SChandler Carruth 
1705693eedb1SChandler Carruth   // If the edge we *aren't* cloning in the unswitch (the continuing edge)
1706693eedb1SChandler Carruth   // dominates its target, we can skip cloning the dominated region of the loop
1707693eedb1SChandler Carruth   // and its exits. We compute this as a set of nodes to be skipped.
1708693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 4> SkippedLoopAndExitBlocks;
1709693eedb1SChandler Carruth   if (ContinueSuccBB->getUniquePredecessor() ||
1710693eedb1SChandler Carruth       llvm::all_of(predecessors(ContinueSuccBB), [&](BasicBlock *PredBB) {
1711693eedb1SChandler Carruth         return PredBB == ParentBB || DT.dominates(ContinueSuccBB, PredBB);
1712693eedb1SChandler Carruth       })) {
1713693eedb1SChandler Carruth     visitDomSubTree(DT, ContinueSuccBB, [&](BasicBlock *BB) {
1714693eedb1SChandler Carruth       SkippedLoopAndExitBlocks.insert(BB);
1715693eedb1SChandler Carruth       return true;
1716693eedb1SChandler Carruth     });
1717693eedb1SChandler Carruth   }
1718693eedb1SChandler Carruth   // Similarly, if the edge we *are* cloning in the unswitch (the unswitched
1719693eedb1SChandler Carruth   // edge) dominates its target, we will end up with dead nodes in the original
1720693eedb1SChandler Carruth   // loop and its exits that will need to be deleted. Here, we just retain that
1721693eedb1SChandler Carruth   // the property holds and will compute the deleted set later.
1722693eedb1SChandler Carruth   bool DeleteUnswitchedSucc =
1723693eedb1SChandler Carruth       UnswitchedSuccBB->getUniquePredecessor() ||
1724693eedb1SChandler Carruth       llvm::all_of(predecessors(UnswitchedSuccBB), [&](BasicBlock *PredBB) {
1725693eedb1SChandler Carruth         return PredBB == ParentBB || DT.dominates(UnswitchedSuccBB, PredBB);
1726693eedb1SChandler Carruth       });
1727693eedb1SChandler Carruth 
1728693eedb1SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
1729693eedb1SChandler Carruth   // the conditional branch. We will change the preheader to have a conditional
1730693eedb1SChandler Carruth   // branch on LoopCond. The original preheader will become the split point
1731693eedb1SChandler Carruth   // between the unswitched versions, and we will have a new preheader for the
1732693eedb1SChandler Carruth   // original loop.
1733693eedb1SChandler Carruth   BasicBlock *SplitBB = L.getLoopPreheader();
1734693eedb1SChandler Carruth   BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI);
1735693eedb1SChandler Carruth 
1736693eedb1SChandler Carruth   // Keep a mapping for the cloned values.
1737693eedb1SChandler Carruth   ValueToValueMapTy VMap;
1738693eedb1SChandler Carruth 
1739693eedb1SChandler Carruth   // Build the cloned blocks from the loop.
1740693eedb1SChandler Carruth   auto *ClonedPH = buildClonedLoopBlocks(
1741693eedb1SChandler Carruth       L, LoopPH, SplitBB, ExitBlocks, ParentBB, UnswitchedSuccBB,
1742693eedb1SChandler Carruth       ContinueSuccBB, SkippedLoopAndExitBlocks, VMap, AC, DT, LI);
1743693eedb1SChandler Carruth 
1744693eedb1SChandler Carruth   // Build the cloned loop structure itself. This may be substantially
1745693eedb1SChandler Carruth   // different from the original structure due to the simplified CFG. This also
1746693eedb1SChandler Carruth   // handles inserting all the cloned blocks into the correct loops.
1747693eedb1SChandler Carruth   SmallVector<Loop *, 4> NonChildClonedLoops;
1748693eedb1SChandler Carruth   Loop *ClonedL =
1749693eedb1SChandler Carruth       buildClonedLoops(L, ExitBlocks, VMap, LI, NonChildClonedLoops);
1750693eedb1SChandler Carruth 
1751693eedb1SChandler Carruth   // Remove the parent as a predecessor of the unswitched successor.
1752693eedb1SChandler Carruth   UnswitchedSuccBB->removePredecessor(ParentBB, /*DontDeleteUselessPHIs*/ true);
1753693eedb1SChandler Carruth 
1754693eedb1SChandler Carruth   // Now splice the branch from the original loop and use it to select between
1755693eedb1SChandler Carruth   // the two loops.
1756693eedb1SChandler Carruth   SplitBB->getTerminator()->eraseFromParent();
1757693eedb1SChandler Carruth   SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), BI);
1758693eedb1SChandler Carruth   BI.setSuccessor(ClonedSucc, ClonedPH);
1759693eedb1SChandler Carruth   BI.setSuccessor(1 - ClonedSucc, LoopPH);
1760693eedb1SChandler Carruth 
1761693eedb1SChandler Carruth   // Create a new unconditional branch to the continuing block (as opposed to
1762693eedb1SChandler Carruth   // the one cloned).
1763693eedb1SChandler Carruth   BranchInst::Create(ContinueSuccBB, ParentBB);
1764693eedb1SChandler Carruth 
1765693eedb1SChandler Carruth   // Delete anything that was made dead in the original loop due to
1766693eedb1SChandler Carruth   // unswitching.
1767693eedb1SChandler Carruth   if (DeleteUnswitchedSucc)
1768693eedb1SChandler Carruth     deleteDeadBlocksFromLoop(L, UnswitchedSuccBB, ExitBlocks, DT, LI);
1769693eedb1SChandler Carruth 
1770693eedb1SChandler Carruth   SmallVector<Loop *, 4> HoistedLoops;
1771693eedb1SChandler Carruth   bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
1772693eedb1SChandler Carruth 
1773693eedb1SChandler Carruth   // This will have completely invalidated the dominator tree. We can't easily
1774693eedb1SChandler Carruth   // bound how much is invalid because in some cases we will refine the
1775693eedb1SChandler Carruth   // predecessor set of exit blocks of the loop which can move large unrelated
1776693eedb1SChandler Carruth   // regions of code into a new subtree.
1777693eedb1SChandler Carruth   //
1778693eedb1SChandler Carruth   // FIXME: Eventually, we should use an incremental update utility that
1779693eedb1SChandler Carruth   // leverages the existing information in the dominator tree (and potentially
1780693eedb1SChandler Carruth   // the nature of the change) to more efficiently update things.
1781693eedb1SChandler Carruth   DT.recalculate(*SplitBB->getParent());
1782693eedb1SChandler Carruth 
1783693eedb1SChandler Carruth   // We can change which blocks are exit blocks of all the cloned sibling
1784693eedb1SChandler Carruth   // loops, the current loop, and any parent loops which shared exit blocks
1785693eedb1SChandler Carruth   // with the current loop. As a consequence, we need to re-form LCSSA for
1786693eedb1SChandler Carruth   // them. But we shouldn't need to re-form LCSSA for any child loops.
1787693eedb1SChandler Carruth   // FIXME: This could be made more efficient by tracking which exit blocks are
1788693eedb1SChandler Carruth   // new, and focusing on them, but that isn't likely to be necessary.
1789693eedb1SChandler Carruth   //
1790693eedb1SChandler Carruth   // In order to reasonably rebuild LCSSA we need to walk inside-out across the
1791693eedb1SChandler Carruth   // loop nest and update every loop that could have had its exits changed. We
1792693eedb1SChandler Carruth   // also need to cover any intervening loops. We add all of these loops to
1793693eedb1SChandler Carruth   // a list and sort them by loop depth to achieve this without updating
1794693eedb1SChandler Carruth   // unnecessary loops.
1795693eedb1SChandler Carruth   auto UpdateLCSSA = [&](Loop &UpdateL) {
1796693eedb1SChandler Carruth #ifndef NDEBUG
1797693eedb1SChandler Carruth     for (Loop *ChildL : UpdateL)
1798693eedb1SChandler Carruth       assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
1799693eedb1SChandler Carruth              "Perturbed a child loop's LCSSA form!");
1800693eedb1SChandler Carruth #endif
1801693eedb1SChandler Carruth     formLCSSA(UpdateL, DT, &LI, nullptr);
1802693eedb1SChandler Carruth   };
1803693eedb1SChandler Carruth 
1804693eedb1SChandler Carruth   // For non-child cloned loops and hoisted loops, we just need to update LCSSA
1805693eedb1SChandler Carruth   // and we can do it in any order as they don't nest relative to each other.
1806693eedb1SChandler Carruth   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
1807693eedb1SChandler Carruth     UpdateLCSSA(*UpdatedL);
1808693eedb1SChandler Carruth 
1809693eedb1SChandler Carruth   // If the original loop had exit blocks, walk up through the outer most loop
1810693eedb1SChandler Carruth   // of those exit blocks to update LCSSA and form updated dedicated exits.
1811693eedb1SChandler Carruth   if (OuterExitL != &L) {
1812693eedb1SChandler Carruth     SmallVector<Loop *, 4> OuterLoops;
1813693eedb1SChandler Carruth     // We start with the cloned loop and the current loop if they are loops and
1814693eedb1SChandler Carruth     // move toward OuterExitL. Also, if either the cloned loop or the current
1815693eedb1SChandler Carruth     // loop have become top level loops we need to walk all the way out.
1816693eedb1SChandler Carruth     if (ClonedL) {
1817693eedb1SChandler Carruth       OuterLoops.push_back(ClonedL);
1818693eedb1SChandler Carruth       if (!ClonedL->getParentLoop())
1819693eedb1SChandler Carruth         OuterExitL = nullptr;
1820693eedb1SChandler Carruth     }
1821693eedb1SChandler Carruth     if (IsStillLoop) {
1822693eedb1SChandler Carruth       OuterLoops.push_back(&L);
1823693eedb1SChandler Carruth       if (!L.getParentLoop())
1824693eedb1SChandler Carruth         OuterExitL = nullptr;
1825693eedb1SChandler Carruth     }
1826693eedb1SChandler Carruth     // Grab all of the enclosing loops now.
1827693eedb1SChandler Carruth     for (Loop *OuterL = ParentL; OuterL != OuterExitL;
1828693eedb1SChandler Carruth          OuterL = OuterL->getParentLoop())
1829693eedb1SChandler Carruth       OuterLoops.push_back(OuterL);
1830693eedb1SChandler Carruth 
1831693eedb1SChandler Carruth     // Finally, update our list of outer loops. This is nicely ordered to work
1832693eedb1SChandler Carruth     // inside-out.
1833693eedb1SChandler Carruth     for (Loop *OuterL : OuterLoops) {
1834693eedb1SChandler Carruth       // First build LCSSA for this loop so that we can preserve it when
1835693eedb1SChandler Carruth       // forming dedicated exits. We don't want to perturb some other loop's
1836693eedb1SChandler Carruth       // LCSSA while doing that CFG edit.
1837693eedb1SChandler Carruth       UpdateLCSSA(*OuterL);
1838693eedb1SChandler Carruth 
1839693eedb1SChandler Carruth       // For loops reached by this loop's original exit blocks we may
1840693eedb1SChandler Carruth       // introduced new, non-dedicated exits. At least try to re-form dedicated
1841693eedb1SChandler Carruth       // exits for these loops. This may fail if they couldn't have dedicated
1842693eedb1SChandler Carruth       // exits to start with.
1843693eedb1SChandler Carruth       formDedicatedExitBlocks(OuterL, &DT, &LI, /*PreserveLCSSA*/ true);
1844693eedb1SChandler Carruth     }
1845693eedb1SChandler Carruth   }
1846693eedb1SChandler Carruth 
1847693eedb1SChandler Carruth #ifndef NDEBUG
1848693eedb1SChandler Carruth   // Verify the entire loop structure to catch any incorrect updates before we
1849693eedb1SChandler Carruth   // progress in the pass pipeline.
1850693eedb1SChandler Carruth   LI.verify(DT);
1851693eedb1SChandler Carruth #endif
1852693eedb1SChandler Carruth 
1853693eedb1SChandler Carruth   // Now that we've unswitched something, make callbacks to report the changes.
1854693eedb1SChandler Carruth   // For that we need to merge together the updated loops and the cloned loops
1855693eedb1SChandler Carruth   // and check whether the original loop survived.
1856693eedb1SChandler Carruth   SmallVector<Loop *, 4> SibLoops;
1857693eedb1SChandler Carruth   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
1858693eedb1SChandler Carruth     if (UpdatedL->getParentLoop() == ParentL)
1859693eedb1SChandler Carruth       SibLoops.push_back(UpdatedL);
1860693eedb1SChandler Carruth   NonTrivialUnswitchCB(IsStillLoop, SibLoops);
1861693eedb1SChandler Carruth 
1862693eedb1SChandler Carruth   ++NumBranches;
1863693eedb1SChandler Carruth   return true;
1864693eedb1SChandler Carruth }
1865693eedb1SChandler Carruth 
1866693eedb1SChandler Carruth /// Recursively compute the cost of a dominator subtree based on the per-block
1867693eedb1SChandler Carruth /// cost map provided.
1868693eedb1SChandler Carruth ///
1869693eedb1SChandler Carruth /// The recursive computation is memozied into the provided DT-indexed cost map
1870693eedb1SChandler Carruth /// to allow querying it for most nodes in the domtree without it becoming
1871693eedb1SChandler Carruth /// quadratic.
1872693eedb1SChandler Carruth static int
1873693eedb1SChandler Carruth computeDomSubtreeCost(DomTreeNode &N,
1874693eedb1SChandler Carruth                       const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
1875693eedb1SChandler Carruth                       SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
1876693eedb1SChandler Carruth   // Don't accumulate cost (or recurse through) blocks not in our block cost
1877693eedb1SChandler Carruth   // map and thus not part of the duplication cost being considered.
1878693eedb1SChandler Carruth   auto BBCostIt = BBCostMap.find(N.getBlock());
1879693eedb1SChandler Carruth   if (BBCostIt == BBCostMap.end())
1880693eedb1SChandler Carruth     return 0;
1881693eedb1SChandler Carruth 
1882693eedb1SChandler Carruth   // Lookup this node to see if we already computed its cost.
1883693eedb1SChandler Carruth   auto DTCostIt = DTCostMap.find(&N);
1884693eedb1SChandler Carruth   if (DTCostIt != DTCostMap.end())
1885693eedb1SChandler Carruth     return DTCostIt->second;
1886693eedb1SChandler Carruth 
1887693eedb1SChandler Carruth   // If not, we have to compute it. We can't use insert above and update
1888693eedb1SChandler Carruth   // because computing the cost may insert more things into the map.
1889693eedb1SChandler Carruth   int Cost = std::accumulate(
1890693eedb1SChandler Carruth       N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
1891693eedb1SChandler Carruth         return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
1892693eedb1SChandler Carruth       });
1893693eedb1SChandler Carruth   bool Inserted = DTCostMap.insert({&N, Cost}).second;
1894693eedb1SChandler Carruth   (void)Inserted;
1895693eedb1SChandler Carruth   assert(Inserted && "Should not insert a node while visiting children!");
1896693eedb1SChandler Carruth   return Cost;
1897693eedb1SChandler Carruth }
1898693eedb1SChandler Carruth 
18991353f9a4SChandler Carruth /// Unswitch control flow predicated on loop invariant conditions.
19001353f9a4SChandler Carruth ///
19011353f9a4SChandler Carruth /// This first hoists all branches or switches which are trivial (IE, do not
19021353f9a4SChandler Carruth /// require duplicating any part of the loop) out of the loop body. It then
19031353f9a4SChandler Carruth /// looks at other loop invariant control flows and tries to unswitch those as
19041353f9a4SChandler Carruth /// well by cloning the loop if the result is small enough.
1905693eedb1SChandler Carruth static bool
1906693eedb1SChandler Carruth unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
1907693eedb1SChandler Carruth              TargetTransformInfo &TTI, bool NonTrivial,
1908693eedb1SChandler Carruth              function_ref<void(bool, ArrayRef<Loop *>)> NonTrivialUnswitchCB) {
1909693eedb1SChandler Carruth   assert(L.isRecursivelyLCSSAForm(DT, LI) &&
19101353f9a4SChandler Carruth          "Loops must be in LCSSA form before unswitching.");
19111353f9a4SChandler Carruth   bool Changed = false;
19121353f9a4SChandler Carruth 
19131353f9a4SChandler Carruth   // Must be in loop simplified form: we need a preheader and dedicated exits.
19141353f9a4SChandler Carruth   if (!L.isLoopSimplifyForm())
19151353f9a4SChandler Carruth     return false;
19161353f9a4SChandler Carruth 
19171353f9a4SChandler Carruth   // Try trivial unswitch first before loop over other basic blocks in the loop.
19181353f9a4SChandler Carruth   Changed |= unswitchAllTrivialConditions(L, DT, LI);
19191353f9a4SChandler Carruth 
1920693eedb1SChandler Carruth   // If we're not doing non-trivial unswitching, we're done. We both accept
1921693eedb1SChandler Carruth   // a parameter but also check a local flag that can be used for testing
1922693eedb1SChandler Carruth   // a debugging.
1923693eedb1SChandler Carruth   if (!NonTrivial && !EnableNonTrivialUnswitch)
1924693eedb1SChandler Carruth     return Changed;
1925693eedb1SChandler Carruth 
1926693eedb1SChandler Carruth   // Collect all remaining invariant branch conditions within this loop (as
1927693eedb1SChandler Carruth   // opposed to an inner loop which would be handled when visiting that inner
1928693eedb1SChandler Carruth   // loop).
1929693eedb1SChandler Carruth   SmallVector<TerminatorInst *, 4> UnswitchCandidates;
1930693eedb1SChandler Carruth   for (auto *BB : L.blocks())
1931693eedb1SChandler Carruth     if (LI.getLoopFor(BB) == &L)
1932693eedb1SChandler Carruth       if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator()))
1933693eedb1SChandler Carruth         if (BI->isConditional() && L.isLoopInvariant(BI->getCondition()) &&
1934693eedb1SChandler Carruth             BI->getSuccessor(0) != BI->getSuccessor(1))
1935693eedb1SChandler Carruth           UnswitchCandidates.push_back(BI);
1936693eedb1SChandler Carruth 
1937693eedb1SChandler Carruth   // If we didn't find any candidates, we're done.
1938693eedb1SChandler Carruth   if (UnswitchCandidates.empty())
1939693eedb1SChandler Carruth     return Changed;
1940693eedb1SChandler Carruth 
1941693eedb1SChandler Carruth   DEBUG(dbgs() << "Considering " << UnswitchCandidates.size()
1942693eedb1SChandler Carruth                << " non-trivial loop invariant conditions for unswitching.\n");
1943693eedb1SChandler Carruth 
1944693eedb1SChandler Carruth   // Given that unswitching these terminators will require duplicating parts of
1945693eedb1SChandler Carruth   // the loop, so we need to be able to model that cost. Compute the ephemeral
1946693eedb1SChandler Carruth   // values and set up a data structure to hold per-BB costs. We cache each
1947693eedb1SChandler Carruth   // block's cost so that we don't recompute this when considering different
1948693eedb1SChandler Carruth   // subsets of the loop for duplication during unswitching.
1949693eedb1SChandler Carruth   SmallPtrSet<const Value *, 4> EphValues;
1950693eedb1SChandler Carruth   CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
1951693eedb1SChandler Carruth   SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
1952693eedb1SChandler Carruth 
1953693eedb1SChandler Carruth   // Compute the cost of each block, as well as the total loop cost. Also, bail
1954693eedb1SChandler Carruth   // out if we see instructions which are incompatible with loop unswitching
1955693eedb1SChandler Carruth   // (convergent, noduplicate, or cross-basic-block tokens).
1956693eedb1SChandler Carruth   // FIXME: We might be able to safely handle some of these in non-duplicated
1957693eedb1SChandler Carruth   // regions.
1958693eedb1SChandler Carruth   int LoopCost = 0;
1959693eedb1SChandler Carruth   for (auto *BB : L.blocks()) {
1960693eedb1SChandler Carruth     int Cost = 0;
1961693eedb1SChandler Carruth     for (auto &I : *BB) {
1962693eedb1SChandler Carruth       if (EphValues.count(&I))
1963693eedb1SChandler Carruth         continue;
1964693eedb1SChandler Carruth 
1965693eedb1SChandler Carruth       if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
1966693eedb1SChandler Carruth         return Changed;
1967693eedb1SChandler Carruth       if (auto CS = CallSite(&I))
1968693eedb1SChandler Carruth         if (CS.isConvergent() || CS.cannotDuplicate())
1969693eedb1SChandler Carruth           return Changed;
1970693eedb1SChandler Carruth 
1971693eedb1SChandler Carruth       Cost += TTI.getUserCost(&I);
1972693eedb1SChandler Carruth     }
1973693eedb1SChandler Carruth     assert(Cost >= 0 && "Must not have negative costs!");
1974693eedb1SChandler Carruth     LoopCost += Cost;
1975693eedb1SChandler Carruth     assert(LoopCost >= 0 && "Must not have negative loop costs!");
1976693eedb1SChandler Carruth     BBCostMap[BB] = Cost;
1977693eedb1SChandler Carruth   }
1978693eedb1SChandler Carruth   DEBUG(dbgs() << "  Total loop cost: " << LoopCost << "\n");
1979693eedb1SChandler Carruth 
1980693eedb1SChandler Carruth   // Now we find the best candidate by searching for the one with the following
1981693eedb1SChandler Carruth   // properties in order:
1982693eedb1SChandler Carruth   //
1983693eedb1SChandler Carruth   // 1) An unswitching cost below the threshold
1984693eedb1SChandler Carruth   // 2) The smallest number of duplicated unswitch candidates (to avoid
1985693eedb1SChandler Carruth   //    creating redundant subsequent unswitching)
1986693eedb1SChandler Carruth   // 3) The smallest cost after unswitching.
1987693eedb1SChandler Carruth   //
1988693eedb1SChandler Carruth   // We prioritize reducing fanout of unswitch candidates provided the cost
1989693eedb1SChandler Carruth   // remains below the threshold because this has a multiplicative effect.
1990693eedb1SChandler Carruth   //
1991693eedb1SChandler Carruth   // This requires memoizing each dominator subtree to avoid redundant work.
1992693eedb1SChandler Carruth   //
1993693eedb1SChandler Carruth   // FIXME: Need to actually do the number of candidates part above.
1994693eedb1SChandler Carruth   SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
1995693eedb1SChandler Carruth   // Given a terminator which might be unswitched, computes the non-duplicated
1996693eedb1SChandler Carruth   // cost for that terminator.
1997693eedb1SChandler Carruth   auto ComputeUnswitchedCost = [&](TerminatorInst *TI) {
1998693eedb1SChandler Carruth     BasicBlock &BB = *TI->getParent();
1999693eedb1SChandler Carruth     SmallPtrSet<BasicBlock *, 4> Visited;
2000693eedb1SChandler Carruth 
2001693eedb1SChandler Carruth     int Cost = LoopCost;
2002693eedb1SChandler Carruth     for (BasicBlock *SuccBB : successors(&BB)) {
2003693eedb1SChandler Carruth       // Don't count successors more than once.
2004693eedb1SChandler Carruth       if (!Visited.insert(SuccBB).second)
2005693eedb1SChandler Carruth         continue;
2006693eedb1SChandler Carruth 
2007693eedb1SChandler Carruth       // This successor's domtree will not need to be duplicated after
2008693eedb1SChandler Carruth       // unswitching if the edge to the successor dominates it (and thus the
2009693eedb1SChandler Carruth       // entire tree). This essentially means there is no other path into this
2010693eedb1SChandler Carruth       // subtree and so it will end up live in only one clone of the loop.
2011693eedb1SChandler Carruth       if (SuccBB->getUniquePredecessor() ||
2012693eedb1SChandler Carruth           llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2013693eedb1SChandler Carruth             return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2014693eedb1SChandler Carruth           })) {
2015693eedb1SChandler Carruth         Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2016693eedb1SChandler Carruth         assert(Cost >= 0 &&
2017693eedb1SChandler Carruth                "Non-duplicated cost should never exceed total loop cost!");
2018693eedb1SChandler Carruth       }
2019693eedb1SChandler Carruth     }
2020693eedb1SChandler Carruth 
2021693eedb1SChandler Carruth     // Now scale the cost by the number of unique successors minus one. We
2022693eedb1SChandler Carruth     // subtract one because there is already at least one copy of the entire
2023693eedb1SChandler Carruth     // loop. This is computing the new cost of unswitching a condition.
2024693eedb1SChandler Carruth     assert(Visited.size() > 1 &&
2025693eedb1SChandler Carruth            "Cannot unswitch a condition without multiple distinct successors!");
2026693eedb1SChandler Carruth     return Cost * (Visited.size() - 1);
2027693eedb1SChandler Carruth   };
2028693eedb1SChandler Carruth   TerminatorInst *BestUnswitchTI = nullptr;
2029693eedb1SChandler Carruth   int BestUnswitchCost;
2030693eedb1SChandler Carruth   for (TerminatorInst *CandidateTI : UnswitchCandidates) {
2031693eedb1SChandler Carruth     int CandidateCost = ComputeUnswitchedCost(CandidateTI);
2032693eedb1SChandler Carruth     DEBUG(dbgs() << "  Computed cost of " << CandidateCost
2033693eedb1SChandler Carruth                  << " for unswitch candidate: " << *CandidateTI << "\n");
2034693eedb1SChandler Carruth     if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2035693eedb1SChandler Carruth       BestUnswitchTI = CandidateTI;
2036693eedb1SChandler Carruth       BestUnswitchCost = CandidateCost;
2037693eedb1SChandler Carruth     }
2038693eedb1SChandler Carruth   }
2039693eedb1SChandler Carruth 
2040693eedb1SChandler Carruth   if (BestUnswitchCost < UnswitchThreshold) {
2041693eedb1SChandler Carruth     DEBUG(dbgs() << "  Trying to unswitch non-trivial (cost = "
2042693eedb1SChandler Carruth                  << BestUnswitchCost << ") branch: " << *BestUnswitchTI
2043693eedb1SChandler Carruth                  << "\n");
2044693eedb1SChandler Carruth     Changed |= unswitchInvariantBranch(L, cast<BranchInst>(*BestUnswitchTI), DT,
2045693eedb1SChandler Carruth                                        LI, AC, NonTrivialUnswitchCB);
2046693eedb1SChandler Carruth   } else {
2047693eedb1SChandler Carruth     DEBUG(dbgs() << "Cannot unswitch, lowest cost found: " << BestUnswitchCost
2048693eedb1SChandler Carruth                  << "\n");
2049693eedb1SChandler Carruth   }
20501353f9a4SChandler Carruth 
20511353f9a4SChandler Carruth   return Changed;
20521353f9a4SChandler Carruth }
20531353f9a4SChandler Carruth 
20541353f9a4SChandler Carruth PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
20551353f9a4SChandler Carruth                                               LoopStandardAnalysisResults &AR,
20561353f9a4SChandler Carruth                                               LPMUpdater &U) {
20571353f9a4SChandler Carruth   Function &F = *L.getHeader()->getParent();
20581353f9a4SChandler Carruth   (void)F;
20591353f9a4SChandler Carruth 
20601353f9a4SChandler Carruth   DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L << "\n");
20611353f9a4SChandler Carruth 
2062693eedb1SChandler Carruth   // Save the current loop name in a variable so that we can report it even
2063693eedb1SChandler Carruth   // after it has been deleted.
2064693eedb1SChandler Carruth   std::string LoopName = L.getName();
2065693eedb1SChandler Carruth 
2066693eedb1SChandler Carruth   auto NonTrivialUnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2067693eedb1SChandler Carruth                                                   ArrayRef<Loop *> NewLoops) {
2068693eedb1SChandler Carruth     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2069693eedb1SChandler Carruth     U.addSiblingLoops(NewLoops);
2070693eedb1SChandler Carruth 
2071693eedb1SChandler Carruth     // If the current loop remains valid, we should revisit it to catch any
2072693eedb1SChandler Carruth     // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2073693eedb1SChandler Carruth     if (CurrentLoopValid)
2074693eedb1SChandler Carruth       U.revisitCurrentLoop();
2075693eedb1SChandler Carruth     else
2076693eedb1SChandler Carruth       U.markLoopAsDeleted(L, LoopName);
2077693eedb1SChandler Carruth   };
2078693eedb1SChandler Carruth 
2079693eedb1SChandler Carruth   if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial,
2080693eedb1SChandler Carruth                     NonTrivialUnswitchCB))
20811353f9a4SChandler Carruth     return PreservedAnalyses::all();
20821353f9a4SChandler Carruth 
20831353f9a4SChandler Carruth   // Historically this pass has had issues with the dominator tree so verify it
20841353f9a4SChandler Carruth   // in asserts builds.
20857c35de12SDavid Green   assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
20861353f9a4SChandler Carruth   return getLoopPassPreservedAnalyses();
20871353f9a4SChandler Carruth }
20881353f9a4SChandler Carruth 
20891353f9a4SChandler Carruth namespace {
2090a369a457SEugene Zelenko 
20911353f9a4SChandler Carruth class SimpleLoopUnswitchLegacyPass : public LoopPass {
2092693eedb1SChandler Carruth   bool NonTrivial;
2093693eedb1SChandler Carruth 
20941353f9a4SChandler Carruth public:
20951353f9a4SChandler Carruth   static char ID; // Pass ID, replacement for typeid
2096a369a457SEugene Zelenko 
2097693eedb1SChandler Carruth   explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2098693eedb1SChandler Carruth       : LoopPass(ID), NonTrivial(NonTrivial) {
20991353f9a4SChandler Carruth     initializeSimpleLoopUnswitchLegacyPassPass(
21001353f9a4SChandler Carruth         *PassRegistry::getPassRegistry());
21011353f9a4SChandler Carruth   }
21021353f9a4SChandler Carruth 
21031353f9a4SChandler Carruth   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
21041353f9a4SChandler Carruth 
21051353f9a4SChandler Carruth   void getAnalysisUsage(AnalysisUsage &AU) const override {
21061353f9a4SChandler Carruth     AU.addRequired<AssumptionCacheTracker>();
2107693eedb1SChandler Carruth     AU.addRequired<TargetTransformInfoWrapperPass>();
21081353f9a4SChandler Carruth     getLoopAnalysisUsage(AU);
21091353f9a4SChandler Carruth   }
21101353f9a4SChandler Carruth };
2111a369a457SEugene Zelenko 
2112a369a457SEugene Zelenko } // end anonymous namespace
21131353f9a4SChandler Carruth 
21141353f9a4SChandler Carruth bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
21151353f9a4SChandler Carruth   if (skipLoop(L))
21161353f9a4SChandler Carruth     return false;
21171353f9a4SChandler Carruth 
21181353f9a4SChandler Carruth   Function &F = *L->getHeader()->getParent();
21191353f9a4SChandler Carruth 
21201353f9a4SChandler Carruth   DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L << "\n");
21211353f9a4SChandler Carruth 
21221353f9a4SChandler Carruth   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
21231353f9a4SChandler Carruth   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
21241353f9a4SChandler Carruth   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2125693eedb1SChandler Carruth   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
21261353f9a4SChandler Carruth 
2127693eedb1SChandler Carruth   auto NonTrivialUnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2128693eedb1SChandler Carruth                                          ArrayRef<Loop *> NewLoops) {
2129693eedb1SChandler Carruth     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2130693eedb1SChandler Carruth     for (auto *NewL : NewLoops)
2131693eedb1SChandler Carruth       LPM.addLoop(*NewL);
2132693eedb1SChandler Carruth 
2133693eedb1SChandler Carruth     // If the current loop remains valid, re-add it to the queue. This is
2134693eedb1SChandler Carruth     // a little wasteful as we'll finish processing the current loop as well,
2135693eedb1SChandler Carruth     // but it is the best we can do in the old PM.
2136693eedb1SChandler Carruth     if (CurrentLoopValid)
2137693eedb1SChandler Carruth       LPM.addLoop(*L);
2138693eedb1SChandler Carruth     else
2139693eedb1SChandler Carruth       LPM.markLoopAsDeleted(*L);
2140693eedb1SChandler Carruth   };
2141693eedb1SChandler Carruth 
2142693eedb1SChandler Carruth   bool Changed =
2143693eedb1SChandler Carruth       unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, NonTrivialUnswitchCB);
2144693eedb1SChandler Carruth 
2145693eedb1SChandler Carruth   // If anything was unswitched, also clear any cached information about this
2146693eedb1SChandler Carruth   // loop.
2147693eedb1SChandler Carruth   LPM.deleteSimpleAnalysisLoop(L);
21481353f9a4SChandler Carruth 
21491353f9a4SChandler Carruth   // Historically this pass has had issues with the dominator tree so verify it
21501353f9a4SChandler Carruth   // in asserts builds.
21517c35de12SDavid Green   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
21527c35de12SDavid Green 
21531353f9a4SChandler Carruth   return Changed;
21541353f9a4SChandler Carruth }
21551353f9a4SChandler Carruth 
21561353f9a4SChandler Carruth char SimpleLoopUnswitchLegacyPass::ID = 0;
21571353f9a4SChandler Carruth INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
21581353f9a4SChandler Carruth                       "Simple unswitch loops", false, false)
21591353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2160693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2161693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
21621353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopPass)
21631353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
21641353f9a4SChandler Carruth INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
21651353f9a4SChandler Carruth                     "Simple unswitch loops", false, false)
21661353f9a4SChandler Carruth 
2167693eedb1SChandler Carruth Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2168693eedb1SChandler Carruth   return new SimpleLoopUnswitchLegacyPass(NonTrivial);
21691353f9a4SChandler Carruth }
2170