1d8b0c8ceSChandler Carruth ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
21353f9a4SChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61353f9a4SChandler Carruth //
71353f9a4SChandler Carruth //===----------------------------------------------------------------------===//
81353f9a4SChandler Carruth 
96bda14b3SChandler Carruth #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
10a369a457SEugene Zelenko #include "llvm/ADT/DenseMap.h"
116bda14b3SChandler Carruth #include "llvm/ADT/STLExtras.h"
12a369a457SEugene Zelenko #include "llvm/ADT/Sequence.h"
13a369a457SEugene Zelenko #include "llvm/ADT/SetVector.h"
141353f9a4SChandler Carruth #include "llvm/ADT/SmallPtrSet.h"
15a369a457SEugene Zelenko #include "llvm/ADT/SmallVector.h"
161353f9a4SChandler Carruth #include "llvm/ADT/Statistic.h"
17a369a457SEugene Zelenko #include "llvm/ADT/Twine.h"
181353f9a4SChandler Carruth #include "llvm/Analysis/AssumptionCache.h"
1932e62f9cSChandler Carruth #include "llvm/Analysis/CFG.h"
20693eedb1SChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
21619a8346SMax Kazantsev #include "llvm/Analysis/GuardUtils.h"
224da3331dSChandler Carruth #include "llvm/Analysis/InstructionSimplify.h"
23a369a457SEugene Zelenko #include "llvm/Analysis/LoopAnalysisManager.h"
241353f9a4SChandler Carruth #include "llvm/Analysis/LoopInfo.h"
2532e62f9cSChandler Carruth #include "llvm/Analysis/LoopIterator.h"
261353f9a4SChandler Carruth #include "llvm/Analysis/LoopPass.h"
27a2eebb82SAlina Sbirlea #include "llvm/Analysis/MemorySSA.h"
28a2eebb82SAlina Sbirlea #include "llvm/Analysis/MemorySSAUpdater.h"
29a369a457SEugene Zelenko #include "llvm/IR/BasicBlock.h"
30a369a457SEugene Zelenko #include "llvm/IR/Constant.h"
311353f9a4SChandler Carruth #include "llvm/IR/Constants.h"
321353f9a4SChandler Carruth #include "llvm/IR/Dominators.h"
331353f9a4SChandler Carruth #include "llvm/IR/Function.h"
34a369a457SEugene Zelenko #include "llvm/IR/InstrTypes.h"
35a369a457SEugene Zelenko #include "llvm/IR/Instruction.h"
361353f9a4SChandler Carruth #include "llvm/IR/Instructions.h"
37693eedb1SChandler Carruth #include "llvm/IR/IntrinsicInst.h"
381055e9e3SNikita Popov #include "llvm/IR/IRBuilder.h"
39a369a457SEugene Zelenko #include "llvm/IR/Use.h"
40a369a457SEugene Zelenko #include "llvm/IR/Value.h"
4105da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
42a369a457SEugene Zelenko #include "llvm/Pass.h"
43a369a457SEugene Zelenko #include "llvm/Support/Casting.h"
444c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
451353f9a4SChandler Carruth #include "llvm/Support/Debug.h"
46a369a457SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
47a369a457SEugene Zelenko #include "llvm/Support/GenericDomTree.h"
481353f9a4SChandler Carruth #include "llvm/Support/raw_ostream.h"
49693eedb1SChandler Carruth #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
501353f9a4SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
51693eedb1SChandler Carruth #include "llvm/Transforms/Utils/Cloning.h"
521353f9a4SChandler Carruth #include "llvm/Transforms/Utils/LoopUtils.h"
53693eedb1SChandler Carruth #include "llvm/Transforms/Utils/ValueMapper.h"
54a369a457SEugene Zelenko #include <algorithm>
55a369a457SEugene Zelenko #include <cassert>
56a369a457SEugene Zelenko #include <iterator>
57693eedb1SChandler Carruth #include <numeric>
58a369a457SEugene Zelenko #include <utility>
591353f9a4SChandler Carruth 
601353f9a4SChandler Carruth #define DEBUG_TYPE "simple-loop-unswitch"
611353f9a4SChandler Carruth 
621353f9a4SChandler Carruth using namespace llvm;
631353f9a4SChandler Carruth 
641353f9a4SChandler Carruth STATISTIC(NumBranches, "Number of branches unswitched");
651353f9a4SChandler Carruth STATISTIC(NumSwitches, "Number of switches unswitched");
66619a8346SMax Kazantsev STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
671353f9a4SChandler Carruth STATISTIC(NumTrivial, "Number of unswitches that are trivial");
682e3e224eSFedor Sergeev STATISTIC(
692e3e224eSFedor Sergeev     NumCostMultiplierSkipped,
702e3e224eSFedor Sergeev     "Number of unswitch candidates that had their cost multiplier skipped");
711353f9a4SChandler Carruth 
72693eedb1SChandler Carruth static cl::opt<bool> EnableNonTrivialUnswitch(
73693eedb1SChandler Carruth     "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
74693eedb1SChandler Carruth     cl::desc("Forcibly enables non-trivial loop unswitching rather than "
75693eedb1SChandler Carruth              "following the configuration passed into the pass."));
76693eedb1SChandler Carruth 
77693eedb1SChandler Carruth static cl::opt<int>
78693eedb1SChandler Carruth     UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
79693eedb1SChandler Carruth                       cl::desc("The cost threshold for unswitching a loop."));
80693eedb1SChandler Carruth 
812e3e224eSFedor Sergeev static cl::opt<bool> EnableUnswitchCostMultiplier(
822e3e224eSFedor Sergeev     "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
832e3e224eSFedor Sergeev     cl::desc("Enable unswitch cost multiplier that prohibits exponential "
842e3e224eSFedor Sergeev              "explosion in nontrivial unswitch."));
852e3e224eSFedor Sergeev static cl::opt<int> UnswitchSiblingsToplevelDiv(
862e3e224eSFedor Sergeev     "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
872e3e224eSFedor Sergeev     cl::desc("Toplevel siblings divisor for cost multiplier."));
882e3e224eSFedor Sergeev static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
892e3e224eSFedor Sergeev     "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
902e3e224eSFedor Sergeev     cl::desc("Number of unswitch candidates that are ignored when calculating "
912e3e224eSFedor Sergeev              "cost multiplier."));
92619a8346SMax Kazantsev static cl::opt<bool> UnswitchGuards(
93619a8346SMax Kazantsev     "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
94619a8346SMax Kazantsev     cl::desc("If enabled, simple loop unswitching will also consider "
95619a8346SMax Kazantsev              "llvm.experimental.guard intrinsics as unswitch candidates."));
96619a8346SMax Kazantsev 
974da3331dSChandler Carruth /// Collect all of the loop invariant input values transitively used by the
984da3331dSChandler Carruth /// homogeneous instruction graph from a given root.
994da3331dSChandler Carruth ///
1004da3331dSChandler Carruth /// This essentially walks from a root recursively through loop variant operands
1014da3331dSChandler Carruth /// which have the exact same opcode and finds all inputs which are loop
1024da3331dSChandler Carruth /// invariant. For some operations these can be re-associated and unswitched out
1034da3331dSChandler Carruth /// of the loop entirely.
104d1dab0c3SChandler Carruth static TinyPtrVector<Value *>
1054da3331dSChandler Carruth collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
1064da3331dSChandler Carruth                                          LoopInfo &LI) {
1074da3331dSChandler Carruth   assert(!L.isLoopInvariant(&Root) &&
1084da3331dSChandler Carruth          "Only need to walk the graph if root itself is not invariant.");
109d1dab0c3SChandler Carruth   TinyPtrVector<Value *> Invariants;
1104da3331dSChandler Carruth 
1114da3331dSChandler Carruth   // Build a worklist and recurse through operators collecting invariants.
1124da3331dSChandler Carruth   SmallVector<Instruction *, 4> Worklist;
1134da3331dSChandler Carruth   SmallPtrSet<Instruction *, 8> Visited;
1144da3331dSChandler Carruth   Worklist.push_back(&Root);
1154da3331dSChandler Carruth   Visited.insert(&Root);
1164da3331dSChandler Carruth   do {
1174da3331dSChandler Carruth     Instruction &I = *Worklist.pop_back_val();
1184da3331dSChandler Carruth     for (Value *OpV : I.operand_values()) {
1194da3331dSChandler Carruth       // Skip constants as unswitching isn't interesting for them.
1204da3331dSChandler Carruth       if (isa<Constant>(OpV))
1214da3331dSChandler Carruth         continue;
1224da3331dSChandler Carruth 
1234da3331dSChandler Carruth       // Add it to our result if loop invariant.
1244da3331dSChandler Carruth       if (L.isLoopInvariant(OpV)) {
1254da3331dSChandler Carruth         Invariants.push_back(OpV);
1264da3331dSChandler Carruth         continue;
1274da3331dSChandler Carruth       }
1284da3331dSChandler Carruth 
1294da3331dSChandler Carruth       // If not an instruction with the same opcode, nothing we can do.
1304da3331dSChandler Carruth       Instruction *OpI = dyn_cast<Instruction>(OpV);
1314da3331dSChandler Carruth       if (!OpI || OpI->getOpcode() != Root.getOpcode())
1324da3331dSChandler Carruth         continue;
1334da3331dSChandler Carruth 
1344da3331dSChandler Carruth       // Visit this operand.
1354da3331dSChandler Carruth       if (Visited.insert(OpI).second)
1364da3331dSChandler Carruth         Worklist.push_back(OpI);
1374da3331dSChandler Carruth     }
1384da3331dSChandler Carruth   } while (!Worklist.empty());
1394da3331dSChandler Carruth 
1404da3331dSChandler Carruth   return Invariants;
1414da3331dSChandler Carruth }
1424da3331dSChandler Carruth 
1434da3331dSChandler Carruth static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
1441353f9a4SChandler Carruth                                      Constant &Replacement) {
1454da3331dSChandler Carruth   assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
1461353f9a4SChandler Carruth 
1471353f9a4SChandler Carruth   // Replace uses of LIC in the loop with the given constant.
1484da3331dSChandler Carruth   for (auto UI = Invariant->use_begin(), UE = Invariant->use_end(); UI != UE;) {
1491353f9a4SChandler Carruth     // Grab the use and walk past it so we can clobber it in the use list.
1501353f9a4SChandler Carruth     Use *U = &*UI++;
1511353f9a4SChandler Carruth     Instruction *UserI = dyn_cast<Instruction>(U->getUser());
1521353f9a4SChandler Carruth 
1531353f9a4SChandler Carruth     // Replace this use within the loop body.
1544da3331dSChandler Carruth     if (UserI && L.contains(UserI))
1554da3331dSChandler Carruth       U->set(&Replacement);
1561353f9a4SChandler Carruth   }
1571353f9a4SChandler Carruth }
1581353f9a4SChandler Carruth 
159d869b188SChandler Carruth /// Check that all the LCSSA PHI nodes in the loop exit block have trivial
160d869b188SChandler Carruth /// incoming values along this edge.
161d869b188SChandler Carruth static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
162d869b188SChandler Carruth                                          BasicBlock &ExitBB) {
163d869b188SChandler Carruth   for (Instruction &I : ExitBB) {
164d869b188SChandler Carruth     auto *PN = dyn_cast<PHINode>(&I);
165d869b188SChandler Carruth     if (!PN)
166d869b188SChandler Carruth       // No more PHIs to check.
167d869b188SChandler Carruth       return true;
168d869b188SChandler Carruth 
169d869b188SChandler Carruth     // If the incoming value for this edge isn't loop invariant the unswitch
170d869b188SChandler Carruth     // won't be trivial.
171d869b188SChandler Carruth     if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
172d869b188SChandler Carruth       return false;
173d869b188SChandler Carruth   }
174d869b188SChandler Carruth   llvm_unreachable("Basic blocks should never be empty!");
175d869b188SChandler Carruth }
176d869b188SChandler Carruth 
177d1dab0c3SChandler Carruth /// Insert code to test a set of loop invariant values, and conditionally branch
178d1dab0c3SChandler Carruth /// on them.
179d1dab0c3SChandler Carruth static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
180d1dab0c3SChandler Carruth                                                   ArrayRef<Value *> Invariants,
181d1dab0c3SChandler Carruth                                                   bool Direction,
182d1dab0c3SChandler Carruth                                                   BasicBlock &UnswitchedSucc,
1832b5a8976SJuneyoung Lee                                                   BasicBlock &NormalSucc) {
184d1dab0c3SChandler Carruth   IRBuilder<> IRB(&BB);
185d1dab0c3SChandler Carruth 
1869e62c864SPhilip Reames   Value *Cond = Direction ? IRB.CreateOr(Invariants) :
1879e62c864SPhilip Reames     IRB.CreateAnd(Invariants);
188d1dab0c3SChandler Carruth   IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
189d1dab0c3SChandler Carruth                    Direction ? &NormalSucc : &UnswitchedSucc);
190d1dab0c3SChandler Carruth }
191d1dab0c3SChandler Carruth 
192d869b188SChandler Carruth /// Rewrite the PHI nodes in an unswitched loop exit basic block.
193d869b188SChandler Carruth ///
194d869b188SChandler Carruth /// Requires that the loop exit and unswitched basic block are the same, and
195d869b188SChandler Carruth /// that the exiting block was a unique predecessor of that block. Rewrites the
196d869b188SChandler Carruth /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
197d869b188SChandler Carruth /// PHI nodes from the old preheader that now contains the unswitched
198d869b188SChandler Carruth /// terminator.
199d869b188SChandler Carruth static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
200d869b188SChandler Carruth                                                   BasicBlock &OldExitingBB,
201d869b188SChandler Carruth                                                   BasicBlock &OldPH) {
202c7fc81e6SBenjamin Kramer   for (PHINode &PN : UnswitchedBB.phis()) {
203d869b188SChandler Carruth     // When the loop exit is directly unswitched we just need to update the
204d869b188SChandler Carruth     // incoming basic block. We loop to handle weird cases with repeated
205d869b188SChandler Carruth     // incoming blocks, but expect to typically only have one operand here.
206c7fc81e6SBenjamin Kramer     for (auto i : seq<int>(0, PN.getNumOperands())) {
207c7fc81e6SBenjamin Kramer       assert(PN.getIncomingBlock(i) == &OldExitingBB &&
208d869b188SChandler Carruth              "Found incoming block different from unique predecessor!");
209c7fc81e6SBenjamin Kramer       PN.setIncomingBlock(i, &OldPH);
210d869b188SChandler Carruth     }
211d869b188SChandler Carruth   }
212d869b188SChandler Carruth }
213d869b188SChandler Carruth 
214d869b188SChandler Carruth /// Rewrite the PHI nodes in the loop exit basic block and the split off
215d869b188SChandler Carruth /// unswitched block.
216d869b188SChandler Carruth ///
217d869b188SChandler Carruth /// Because the exit block remains an exit from the loop, this rewrites the
218d869b188SChandler Carruth /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
219d869b188SChandler Carruth /// nodes into the unswitched basic block to select between the value in the
220d869b188SChandler Carruth /// old preheader and the loop exit.
221d869b188SChandler Carruth static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
222d869b188SChandler Carruth                                                       BasicBlock &UnswitchedBB,
223d869b188SChandler Carruth                                                       BasicBlock &OldExitingBB,
2244da3331dSChandler Carruth                                                       BasicBlock &OldPH,
2254da3331dSChandler Carruth                                                       bool FullUnswitch) {
226d869b188SChandler Carruth   assert(&ExitBB != &UnswitchedBB &&
227d869b188SChandler Carruth          "Must have different loop exit and unswitched blocks!");
228d869b188SChandler Carruth   Instruction *InsertPt = &*UnswitchedBB.begin();
229c7fc81e6SBenjamin Kramer   for (PHINode &PN : ExitBB.phis()) {
230c7fc81e6SBenjamin Kramer     auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
231c7fc81e6SBenjamin Kramer                                   PN.getName() + ".split", InsertPt);
232d869b188SChandler Carruth 
233d869b188SChandler Carruth     // Walk backwards over the old PHI node's inputs to minimize the cost of
234d869b188SChandler Carruth     // removing each one. We have to do this weird loop manually so that we
235d869b188SChandler Carruth     // create the same number of new incoming edges in the new PHI as we expect
236d869b188SChandler Carruth     // each case-based edge to be included in the unswitched switch in some
237d869b188SChandler Carruth     // cases.
238d869b188SChandler Carruth     // FIXME: This is really, really gross. It would be much cleaner if LLVM
239d869b188SChandler Carruth     // allowed us to create a single entry for a predecessor block without
240d869b188SChandler Carruth     // having separate entries for each "edge" even though these edges are
241d869b188SChandler Carruth     // required to produce identical results.
242c7fc81e6SBenjamin Kramer     for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
243c7fc81e6SBenjamin Kramer       if (PN.getIncomingBlock(i) != &OldExitingBB)
244d869b188SChandler Carruth         continue;
245d869b188SChandler Carruth 
2464da3331dSChandler Carruth       Value *Incoming = PN.getIncomingValue(i);
2474da3331dSChandler Carruth       if (FullUnswitch)
2484da3331dSChandler Carruth         // No more edge from the old exiting block to the exit block.
2494da3331dSChandler Carruth         PN.removeIncomingValue(i);
2504da3331dSChandler Carruth 
251d869b188SChandler Carruth       NewPN->addIncoming(Incoming, &OldPH);
252d869b188SChandler Carruth     }
253d869b188SChandler Carruth 
254d869b188SChandler Carruth     // Now replace the old PHI with the new one and wire the old one in as an
255d869b188SChandler Carruth     // input to the new one.
256c7fc81e6SBenjamin Kramer     PN.replaceAllUsesWith(NewPN);
257c7fc81e6SBenjamin Kramer     NewPN->addIncoming(&PN, &ExitBB);
258d869b188SChandler Carruth   }
259d869b188SChandler Carruth }
260d869b188SChandler Carruth 
261d8b0c8ceSChandler Carruth /// Hoist the current loop up to the innermost loop containing a remaining exit.
262d8b0c8ceSChandler Carruth ///
263d8b0c8ceSChandler Carruth /// Because we've removed an exit from the loop, we may have changed the set of
264d8b0c8ceSChandler Carruth /// loops reachable and need to move the current loop up the loop nest or even
265d8b0c8ceSChandler Carruth /// to an entirely separate nest.
266d8b0c8ceSChandler Carruth static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
26797468e92SAlina Sbirlea                                  DominatorTree &DT, LoopInfo &LI,
268c4d8c631SDaniil Suchkov                                  MemorySSAUpdater *MSSAU, ScalarEvolution *SE) {
269d8b0c8ceSChandler Carruth   // If the loop is already at the top level, we can't hoist it anywhere.
270d8b0c8ceSChandler Carruth   Loop *OldParentL = L.getParentLoop();
271d8b0c8ceSChandler Carruth   if (!OldParentL)
272d8b0c8ceSChandler Carruth     return;
273d8b0c8ceSChandler Carruth 
274d8b0c8ceSChandler Carruth   SmallVector<BasicBlock *, 4> Exits;
275d8b0c8ceSChandler Carruth   L.getExitBlocks(Exits);
276d8b0c8ceSChandler Carruth   Loop *NewParentL = nullptr;
277d8b0c8ceSChandler Carruth   for (auto *ExitBB : Exits)
278d8b0c8ceSChandler Carruth     if (Loop *ExitL = LI.getLoopFor(ExitBB))
279d8b0c8ceSChandler Carruth       if (!NewParentL || NewParentL->contains(ExitL))
280d8b0c8ceSChandler Carruth         NewParentL = ExitL;
281d8b0c8ceSChandler Carruth 
282d8b0c8ceSChandler Carruth   if (NewParentL == OldParentL)
283d8b0c8ceSChandler Carruth     return;
284d8b0c8ceSChandler Carruth 
285d8b0c8ceSChandler Carruth   // The new parent loop (if different) should always contain the old one.
286d8b0c8ceSChandler Carruth   if (NewParentL)
287d8b0c8ceSChandler Carruth     assert(NewParentL->contains(OldParentL) &&
288d8b0c8ceSChandler Carruth            "Can only hoist this loop up the nest!");
289d8b0c8ceSChandler Carruth 
290d8b0c8ceSChandler Carruth   // The preheader will need to move with the body of this loop. However,
291d8b0c8ceSChandler Carruth   // because it isn't in this loop we also need to update the primary loop map.
292d8b0c8ceSChandler Carruth   assert(OldParentL == LI.getLoopFor(&Preheader) &&
293d8b0c8ceSChandler Carruth          "Parent loop of this loop should contain this loop's preheader!");
294d8b0c8ceSChandler Carruth   LI.changeLoopFor(&Preheader, NewParentL);
295d8b0c8ceSChandler Carruth 
296d8b0c8ceSChandler Carruth   // Remove this loop from its old parent.
297d8b0c8ceSChandler Carruth   OldParentL->removeChildLoop(&L);
298d8b0c8ceSChandler Carruth 
299d8b0c8ceSChandler Carruth   // Add the loop either to the new parent or as a top-level loop.
300d8b0c8ceSChandler Carruth   if (NewParentL)
301d8b0c8ceSChandler Carruth     NewParentL->addChildLoop(&L);
302d8b0c8ceSChandler Carruth   else
303d8b0c8ceSChandler Carruth     LI.addTopLevelLoop(&L);
304d8b0c8ceSChandler Carruth 
305d8b0c8ceSChandler Carruth   // Remove this loops blocks from the old parent and every other loop up the
306d8b0c8ceSChandler Carruth   // nest until reaching the new parent. Also update all of these
307d8b0c8ceSChandler Carruth   // no-longer-containing loops to reflect the nesting change.
308d8b0c8ceSChandler Carruth   for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
309d8b0c8ceSChandler Carruth        OldContainingL = OldContainingL->getParentLoop()) {
310d8b0c8ceSChandler Carruth     llvm::erase_if(OldContainingL->getBlocksVector(),
311d8b0c8ceSChandler Carruth                    [&](const BasicBlock *BB) {
312d8b0c8ceSChandler Carruth                      return BB == &Preheader || L.contains(BB);
313d8b0c8ceSChandler Carruth                    });
314d8b0c8ceSChandler Carruth 
315d8b0c8ceSChandler Carruth     OldContainingL->getBlocksSet().erase(&Preheader);
316d8b0c8ceSChandler Carruth     for (BasicBlock *BB : L.blocks())
317d8b0c8ceSChandler Carruth       OldContainingL->getBlocksSet().erase(BB);
318d8b0c8ceSChandler Carruth 
319d8b0c8ceSChandler Carruth     // Because we just hoisted a loop out of this one, we have essentially
320d8b0c8ceSChandler Carruth     // created new exit paths from it. That means we need to form LCSSA PHI
321d8b0c8ceSChandler Carruth     // nodes for values used in the no-longer-nested loop.
322c4d8c631SDaniil Suchkov     formLCSSA(*OldContainingL, DT, &LI, SE);
323d8b0c8ceSChandler Carruth 
324d8b0c8ceSChandler Carruth     // We shouldn't need to form dedicated exits because the exit introduced
32552e97a28SAlina Sbirlea     // here is the (just split by unswitching) preheader. However, after trivial
32652e97a28SAlina Sbirlea     // unswitching it is possible to get new non-dedicated exits out of parent
32752e97a28SAlina Sbirlea     // loop so let's conservatively form dedicated exit blocks and figure out
32852e97a28SAlina Sbirlea     // if we can optimize later.
32997468e92SAlina Sbirlea     formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
33097468e92SAlina Sbirlea                             /*PreserveLCSSA*/ true);
331d8b0c8ceSChandler Carruth   }
332d8b0c8ceSChandler Carruth }
333d8b0c8ceSChandler Carruth 
3344a9cde5aSFlorian Hahn // Return the top-most loop containing ExitBB and having ExitBB as exiting block
3354a9cde5aSFlorian Hahn // or the loop containing ExitBB, if there is no parent loop containing ExitBB
3364a9cde5aSFlorian Hahn // as exiting block.
3374a9cde5aSFlorian Hahn static Loop *getTopMostExitingLoop(BasicBlock *ExitBB, LoopInfo &LI) {
3384a9cde5aSFlorian Hahn   Loop *TopMost = LI.getLoopFor(ExitBB);
3394a9cde5aSFlorian Hahn   Loop *Current = TopMost;
3404a9cde5aSFlorian Hahn   while (Current) {
3414a9cde5aSFlorian Hahn     if (Current->isLoopExiting(ExitBB))
3424a9cde5aSFlorian Hahn       TopMost = Current;
3434a9cde5aSFlorian Hahn     Current = Current->getParentLoop();
3444a9cde5aSFlorian Hahn   }
3454a9cde5aSFlorian Hahn   return TopMost;
3464a9cde5aSFlorian Hahn }
3474a9cde5aSFlorian Hahn 
3481353f9a4SChandler Carruth /// Unswitch a trivial branch if the condition is loop invariant.
3491353f9a4SChandler Carruth ///
3501353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the branch has
3511353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the
3521353f9a4SChandler Carruth /// condition is invariant and one of the successors is a loop exit. This
3531353f9a4SChandler Carruth /// allows us to unswitch without duplicating the loop, making it trivial.
3541353f9a4SChandler Carruth ///
3551353f9a4SChandler Carruth /// If this routine fails to unswitch the branch it returns false.
3561353f9a4SChandler Carruth ///
3571353f9a4SChandler Carruth /// If the branch can be unswitched, this routine splits the preheader and
3581353f9a4SChandler Carruth /// hoists the branch above that split. Preserves loop simplified form
3591353f9a4SChandler Carruth /// (splitting the exit block as necessary). It simplifies the branch within
3601353f9a4SChandler Carruth /// the loop to an unconditional branch but doesn't remove it entirely. Further
3611353f9a4SChandler Carruth /// cleanup can be done with some simplify-cfg like pass.
3623897ded6SChandler Carruth ///
3633897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
3643897ded6SChandler Carruth /// invalidated by this.
3651353f9a4SChandler Carruth static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
366a2eebb82SAlina Sbirlea                                   LoopInfo &LI, ScalarEvolution *SE,
367a2eebb82SAlina Sbirlea                                   MemorySSAUpdater *MSSAU) {
3681353f9a4SChandler Carruth   assert(BI.isConditional() && "Can only unswitch a conditional branch!");
369d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Trying to unswitch branch: " << BI << "\n");
3701353f9a4SChandler Carruth 
3714da3331dSChandler Carruth   // The loop invariant values that we want to unswitch.
372d1dab0c3SChandler Carruth   TinyPtrVector<Value *> Invariants;
3731353f9a4SChandler Carruth 
3744da3331dSChandler Carruth   // When true, we're fully unswitching the branch rather than just unswitching
3754da3331dSChandler Carruth   // some input conditions to the branch.
3764da3331dSChandler Carruth   bool FullUnswitch = false;
3774da3331dSChandler Carruth 
3784da3331dSChandler Carruth   if (L.isLoopInvariant(BI.getCondition())) {
3794da3331dSChandler Carruth     Invariants.push_back(BI.getCondition());
3804da3331dSChandler Carruth     FullUnswitch = true;
3814da3331dSChandler Carruth   } else {
3824da3331dSChandler Carruth     if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
3834da3331dSChandler Carruth       Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
3844da3331dSChandler Carruth     if (Invariants.empty())
3854da3331dSChandler Carruth       // Couldn't find invariant inputs!
3861353f9a4SChandler Carruth       return false;
3874da3331dSChandler Carruth   }
3881353f9a4SChandler Carruth 
3894da3331dSChandler Carruth   // Check that one of the branch's successors exits, and which one.
3904da3331dSChandler Carruth   bool ExitDirection = true;
3911353f9a4SChandler Carruth   int LoopExitSuccIdx = 0;
3921353f9a4SChandler Carruth   auto *LoopExitBB = BI.getSuccessor(0);
393baf045fbSChandler Carruth   if (L.contains(LoopExitBB)) {
3944da3331dSChandler Carruth     ExitDirection = false;
3951353f9a4SChandler Carruth     LoopExitSuccIdx = 1;
3961353f9a4SChandler Carruth     LoopExitBB = BI.getSuccessor(1);
397baf045fbSChandler Carruth     if (L.contains(LoopExitBB))
3981353f9a4SChandler Carruth       return false;
3991353f9a4SChandler Carruth   }
4001353f9a4SChandler Carruth   auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
401d869b188SChandler Carruth   auto *ParentBB = BI.getParent();
402d869b188SChandler Carruth   if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
4031353f9a4SChandler Carruth     return false;
4041353f9a4SChandler Carruth 
4054da3331dSChandler Carruth   // When unswitching only part of the branch's condition, we need the exit
4064da3331dSChandler Carruth   // block to be reached directly from the partially unswitched input. This can
4074da3331dSChandler Carruth   // be done when the exit block is along the true edge and the branch condition
4084da3331dSChandler Carruth   // is a graph of `or` operations, or the exit block is along the false edge
4094da3331dSChandler Carruth   // and the condition is a graph of `and` operations.
4104da3331dSChandler Carruth   if (!FullUnswitch) {
4114da3331dSChandler Carruth     if (ExitDirection) {
4124da3331dSChandler Carruth       if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or)
4134da3331dSChandler Carruth         return false;
4144da3331dSChandler Carruth     } else {
4154da3331dSChandler Carruth       if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And)
4164da3331dSChandler Carruth         return false;
4174da3331dSChandler Carruth     }
4184da3331dSChandler Carruth   }
4194da3331dSChandler Carruth 
4204da3331dSChandler Carruth   LLVM_DEBUG({
4214da3331dSChandler Carruth     dbgs() << "    unswitching trivial invariant conditions for: " << BI
4224da3331dSChandler Carruth            << "\n";
4234da3331dSChandler Carruth     for (Value *Invariant : Invariants) {
4244da3331dSChandler Carruth       dbgs() << "      " << *Invariant << " == true";
4254da3331dSChandler Carruth       if (Invariant != Invariants.back())
4264da3331dSChandler Carruth         dbgs() << " ||";
4274da3331dSChandler Carruth       dbgs() << "\n";
4284da3331dSChandler Carruth     }
4294da3331dSChandler Carruth   });
4301353f9a4SChandler Carruth 
4313897ded6SChandler Carruth   // If we have scalar evolutions, we need to invalidate them including this
4324a9cde5aSFlorian Hahn   // loop, the loop containing the exit block and the topmost parent loop
4334a9cde5aSFlorian Hahn   // exiting via LoopExitBB.
4343897ded6SChandler Carruth   if (SE) {
4354a9cde5aSFlorian Hahn     if (Loop *ExitL = getTopMostExitingLoop(LoopExitBB, LI))
4363897ded6SChandler Carruth       SE->forgetLoop(ExitL);
4373897ded6SChandler Carruth     else
4383897ded6SChandler Carruth       // Forget the entire nest as this exits the entire nest.
4393897ded6SChandler Carruth       SE->forgetTopmostLoop(&L);
4403897ded6SChandler Carruth   }
4413897ded6SChandler Carruth 
442a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
443a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
444a2eebb82SAlina Sbirlea 
4451353f9a4SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
4461353f9a4SChandler Carruth   // the conditional branch. We will change the preheader to have a conditional
4471353f9a4SChandler Carruth   // branch on LoopCond.
4481353f9a4SChandler Carruth   BasicBlock *OldPH = L.getLoopPreheader();
449a2eebb82SAlina Sbirlea   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
4501353f9a4SChandler Carruth 
4511353f9a4SChandler Carruth   // Now that we have a place to insert the conditional branch, create a place
4521353f9a4SChandler Carruth   // to branch to: this is the exit block out of the loop that we are
4531353f9a4SChandler Carruth   // unswitching. We need to split this if there are other loop predecessors.
4541353f9a4SChandler Carruth   // Because the loop is in simplified form, *any* other predecessor is enough.
4551353f9a4SChandler Carruth   BasicBlock *UnswitchedBB;
4564da3331dSChandler Carruth   if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
4574da3331dSChandler Carruth     assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
458d869b188SChandler Carruth            "A branch's parent isn't a predecessor!");
4591353f9a4SChandler Carruth     UnswitchedBB = LoopExitBB;
4601353f9a4SChandler Carruth   } else {
461a2eebb82SAlina Sbirlea     UnswitchedBB =
462a2eebb82SAlina Sbirlea         SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
4631353f9a4SChandler Carruth   }
4641353f9a4SChandler Carruth 
465a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
466a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
467a2eebb82SAlina Sbirlea 
4684da3331dSChandler Carruth   // Actually move the invariant uses into the unswitched position. If possible,
4694da3331dSChandler Carruth   // we do this by moving the instructions, but when doing partial unswitching
4704da3331dSChandler Carruth   // we do it by building a new merge of the values in the unswitched position.
4711353f9a4SChandler Carruth   OldPH->getTerminator()->eraseFromParent();
4724da3331dSChandler Carruth   if (FullUnswitch) {
4734da3331dSChandler Carruth     // If fully unswitching, we can use the existing branch instruction.
4744da3331dSChandler Carruth     // Splice it into the old PH to gate reaching the new preheader and re-point
4754da3331dSChandler Carruth     // its successors.
4764da3331dSChandler Carruth     OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
4774da3331dSChandler Carruth                                 BI);
478a2eebb82SAlina Sbirlea     if (MSSAU) {
479a2eebb82SAlina Sbirlea       // Temporarily clone the terminator, to make MSSA update cheaper by
480a2eebb82SAlina Sbirlea       // separating "insert edge" updates from "remove edge" ones.
481a2eebb82SAlina Sbirlea       ParentBB->getInstList().push_back(BI.clone());
482a2eebb82SAlina Sbirlea     } else {
4831353f9a4SChandler Carruth       // Create a new unconditional branch that will continue the loop as a new
4841353f9a4SChandler Carruth       // terminator.
4851353f9a4SChandler Carruth       BranchInst::Create(ContinueBB, ParentBB);
486a2eebb82SAlina Sbirlea     }
487a2eebb82SAlina Sbirlea     BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
488a2eebb82SAlina Sbirlea     BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
4894da3331dSChandler Carruth   } else {
4904da3331dSChandler Carruth     // Only unswitching a subset of inputs to the condition, so we will need to
4914da3331dSChandler Carruth     // build a new branch that merges the invariant inputs.
4924da3331dSChandler Carruth     if (ExitDirection)
4934da3331dSChandler Carruth       assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
4944da3331dSChandler Carruth                  Instruction::Or &&
4954da3331dSChandler Carruth              "Must have an `or` of `i1`s for the condition!");
4964da3331dSChandler Carruth     else
4974da3331dSChandler Carruth       assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
4984da3331dSChandler Carruth                  Instruction::And &&
4994da3331dSChandler Carruth              "Must have an `and` of `i1`s for the condition!");
500d1dab0c3SChandler Carruth     buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
5012b5a8976SJuneyoung Lee                                           *UnswitchedBB, *NewPH);
5024da3331dSChandler Carruth   }
5031353f9a4SChandler Carruth 
504a2eebb82SAlina Sbirlea   // Update the dominator tree with the added edge.
505a2eebb82SAlina Sbirlea   DT.insertEdge(OldPH, UnswitchedBB);
506a2eebb82SAlina Sbirlea 
507a2eebb82SAlina Sbirlea   // After the dominator tree was updated with the added edge, update MemorySSA
508a2eebb82SAlina Sbirlea   // if available.
509a2eebb82SAlina Sbirlea   if (MSSAU) {
510a2eebb82SAlina Sbirlea     SmallVector<CFGUpdate, 1> Updates;
511a2eebb82SAlina Sbirlea     Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
512a2eebb82SAlina Sbirlea     MSSAU->applyInsertUpdates(Updates, DT);
513a2eebb82SAlina Sbirlea   }
514a2eebb82SAlina Sbirlea 
515a2eebb82SAlina Sbirlea   // Finish updating dominator tree and memory ssa for full unswitch.
516a2eebb82SAlina Sbirlea   if (FullUnswitch) {
517a2eebb82SAlina Sbirlea     if (MSSAU) {
518a2eebb82SAlina Sbirlea       // Remove the cloned branch instruction.
519a2eebb82SAlina Sbirlea       ParentBB->getTerminator()->eraseFromParent();
520a2eebb82SAlina Sbirlea       // Create unconditional branch now.
521a2eebb82SAlina Sbirlea       BranchInst::Create(ContinueBB, ParentBB);
522a2eebb82SAlina Sbirlea       MSSAU->removeEdge(ParentBB, LoopExitBB);
523a2eebb82SAlina Sbirlea     }
524a2eebb82SAlina Sbirlea     DT.deleteEdge(ParentBB, LoopExitBB);
525a2eebb82SAlina Sbirlea   }
526a2eebb82SAlina Sbirlea 
527a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
528a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
529a2eebb82SAlina Sbirlea 
530d869b188SChandler Carruth   // Rewrite the relevant PHI nodes.
531d869b188SChandler Carruth   if (UnswitchedBB == LoopExitBB)
532d869b188SChandler Carruth     rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
533d869b188SChandler Carruth   else
534d869b188SChandler Carruth     rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
5354da3331dSChandler Carruth                                               *ParentBB, *OldPH, FullUnswitch);
536d869b188SChandler Carruth 
5374da3331dSChandler Carruth   // The constant we can replace all of our invariants with inside the loop
5384da3331dSChandler Carruth   // body. If any of the invariants have a value other than this the loop won't
5394da3331dSChandler Carruth   // be entered.
5404da3331dSChandler Carruth   ConstantInt *Replacement = ExitDirection
5414da3331dSChandler Carruth                                  ? ConstantInt::getFalse(BI.getContext())
5424da3331dSChandler Carruth                                  : ConstantInt::getTrue(BI.getContext());
5431353f9a4SChandler Carruth 
5441353f9a4SChandler Carruth   // Since this is an i1 condition we can also trivially replace uses of it
5451353f9a4SChandler Carruth   // within the loop with a constant.
5464da3331dSChandler Carruth   for (Value *Invariant : Invariants)
5474da3331dSChandler Carruth     replaceLoopInvariantUses(L, Invariant, *Replacement);
5481353f9a4SChandler Carruth 
549d8b0c8ceSChandler Carruth   // If this was full unswitching, we may have changed the nesting relationship
550d8b0c8ceSChandler Carruth   // for this loop so hoist it to its correct parent if needed.
551d8b0c8ceSChandler Carruth   if (FullUnswitch)
552c4d8c631SDaniil Suchkov     hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
55397468e92SAlina Sbirlea 
55497468e92SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
55597468e92SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
556d8b0c8ceSChandler Carruth 
55752e97a28SAlina Sbirlea   LLVM_DEBUG(dbgs() << "    done: unswitching trivial branch...\n");
5581353f9a4SChandler Carruth   ++NumTrivial;
5591353f9a4SChandler Carruth   ++NumBranches;
5601353f9a4SChandler Carruth   return true;
5611353f9a4SChandler Carruth }
5621353f9a4SChandler Carruth 
5631353f9a4SChandler Carruth /// Unswitch a trivial switch if the condition is loop invariant.
5641353f9a4SChandler Carruth ///
5651353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the switch has
5661353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the
5671353f9a4SChandler Carruth /// condition is invariant and that at least one of the successors is a loop
5681353f9a4SChandler Carruth /// exit. This allows us to unswitch without duplicating the loop, making it
5691353f9a4SChandler Carruth /// trivial.
5701353f9a4SChandler Carruth ///
5711353f9a4SChandler Carruth /// If this routine fails to unswitch the switch it returns false.
5721353f9a4SChandler Carruth ///
5731353f9a4SChandler Carruth /// If the switch can be unswitched, this routine splits the preheader and
5741353f9a4SChandler Carruth /// copies the switch above that split. If the default case is one of the
5751353f9a4SChandler Carruth /// exiting cases, it copies the non-exiting cases and points them at the new
5761353f9a4SChandler Carruth /// preheader. If the default case is not exiting, it copies the exiting cases
5771353f9a4SChandler Carruth /// and points the default at the preheader. It preserves loop simplified form
5781353f9a4SChandler Carruth /// (splitting the exit blocks as necessary). It simplifies the switch within
5791353f9a4SChandler Carruth /// the loop by removing now-dead cases. If the default case is one of those
5801353f9a4SChandler Carruth /// unswitched, it replaces its destination with a new basic block containing
5811353f9a4SChandler Carruth /// only unreachable. Such basic blocks, while technically loop exits, are not
5821353f9a4SChandler Carruth /// considered for unswitching so this is a stable transform and the same
5831353f9a4SChandler Carruth /// switch will not be revisited. If after unswitching there is only a single
5841353f9a4SChandler Carruth /// in-loop successor, the switch is further simplified to an unconditional
5851353f9a4SChandler Carruth /// branch. Still more cleanup can be done with some simplify-cfg like pass.
5863897ded6SChandler Carruth ///
5873897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
5883897ded6SChandler Carruth /// invalidated by this.
5891353f9a4SChandler Carruth static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
590a2eebb82SAlina Sbirlea                                   LoopInfo &LI, ScalarEvolution *SE,
591a2eebb82SAlina Sbirlea                                   MemorySSAUpdater *MSSAU) {
592d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Trying to unswitch switch: " << SI << "\n");
5931353f9a4SChandler Carruth   Value *LoopCond = SI.getCondition();
5941353f9a4SChandler Carruth 
5951353f9a4SChandler Carruth   // If this isn't switching on an invariant condition, we can't unswitch it.
5961353f9a4SChandler Carruth   if (!L.isLoopInvariant(LoopCond))
5971353f9a4SChandler Carruth     return false;
5981353f9a4SChandler Carruth 
599d869b188SChandler Carruth   auto *ParentBB = SI.getParent();
600d869b188SChandler Carruth 
601*db04ff4bSAlina Sbirlea   // The same check must be used both for the default and the exit cases. We
602*db04ff4bSAlina Sbirlea   // should never leave edges from the switch instruction to a basic block that
603*db04ff4bSAlina Sbirlea   // we are unswitching, hence the condition used to determine the default case
604*db04ff4bSAlina Sbirlea   // needs to also be used to populate ExitCaseIndices, which is then used to
605*db04ff4bSAlina Sbirlea   // remove cases from the switch.
6066227f021SAlina Sbirlea   auto IsTriviallyUnswitchableExitBlock = [&](BasicBlock &BBToCheck) {
6076227f021SAlina Sbirlea     // BBToCheck is not an exit block if it is inside loop L.
6086227f021SAlina Sbirlea     if (L.contains(&BBToCheck))
6096227f021SAlina Sbirlea       return false;
6106227f021SAlina Sbirlea     // BBToCheck is not trivial to unswitch if its phis aren't loop invariant.
6116227f021SAlina Sbirlea     if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, BBToCheck))
6126227f021SAlina Sbirlea       return false;
6136227f021SAlina Sbirlea     // We do not unswitch a block that only has an unreachable statement, as
6146227f021SAlina Sbirlea     // it's possible this is a previously unswitched block. Only unswitch if
6156227f021SAlina Sbirlea     // either the terminator is not unreachable, or, if it is, it's not the only
6166227f021SAlina Sbirlea     // instruction in the block.
6176227f021SAlina Sbirlea     auto *TI = BBToCheck.getTerminator();
6186227f021SAlina Sbirlea     bool isUnreachable = isa<UnreachableInst>(TI);
6196227f021SAlina Sbirlea     return !isUnreachable ||
6206227f021SAlina Sbirlea            (isUnreachable && (BBToCheck.getFirstNonPHIOrDbg() != TI));
6216227f021SAlina Sbirlea   };
6226227f021SAlina Sbirlea 
6231353f9a4SChandler Carruth   SmallVector<int, 4> ExitCaseIndices;
624*db04ff4bSAlina Sbirlea   for (auto Case : SI.cases())
625*db04ff4bSAlina Sbirlea     if (IsTriviallyUnswitchableExitBlock(*Case.getCaseSuccessor()))
6261353f9a4SChandler Carruth       ExitCaseIndices.push_back(Case.getCaseIndex());
6271353f9a4SChandler Carruth   BasicBlock *DefaultExitBB = nullptr;
628d4097b4aSYevgeny Rouban   SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight =
629d4097b4aSYevgeny Rouban       SwitchInstProfUpdateWrapper::getSuccessorWeight(SI, 0);
6306227f021SAlina Sbirlea   if (IsTriviallyUnswitchableExitBlock(*SI.getDefaultDest())) {
6311353f9a4SChandler Carruth     DefaultExitBB = SI.getDefaultDest();
632d4097b4aSYevgeny Rouban   } else if (ExitCaseIndices.empty())
6331353f9a4SChandler Carruth     return false;
6341353f9a4SChandler Carruth 
63552e97a28SAlina Sbirlea   LLVM_DEBUG(dbgs() << "    unswitching trivial switch...\n");
6361353f9a4SChandler Carruth 
637a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
638a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
639a2eebb82SAlina Sbirlea 
6403897ded6SChandler Carruth   // We may need to invalidate SCEVs for the outermost loop reached by any of
6413897ded6SChandler Carruth   // the exits.
6423897ded6SChandler Carruth   Loop *OuterL = &L;
6433897ded6SChandler Carruth 
64447dc3a34SChandler Carruth   if (DefaultExitBB) {
64547dc3a34SChandler Carruth     // Clear out the default destination temporarily to allow accurate
64647dc3a34SChandler Carruth     // predecessor lists to be examined below.
64747dc3a34SChandler Carruth     SI.setDefaultDest(nullptr);
64847dc3a34SChandler Carruth     // Check the loop containing this exit.
64947dc3a34SChandler Carruth     Loop *ExitL = LI.getLoopFor(DefaultExitBB);
65047dc3a34SChandler Carruth     if (!ExitL || ExitL->contains(OuterL))
65147dc3a34SChandler Carruth       OuterL = ExitL;
65247dc3a34SChandler Carruth   }
65347dc3a34SChandler Carruth 
65447dc3a34SChandler Carruth   // Store the exit cases into a separate data structure and remove them from
65547dc3a34SChandler Carruth   // the switch.
656d4097b4aSYevgeny Rouban   SmallVector<std::tuple<ConstantInt *, BasicBlock *,
657d4097b4aSYevgeny Rouban                          SwitchInstProfUpdateWrapper::CaseWeightOpt>,
658d4097b4aSYevgeny Rouban               4> ExitCases;
6591353f9a4SChandler Carruth   ExitCases.reserve(ExitCaseIndices.size());
660d4097b4aSYevgeny Rouban   SwitchInstProfUpdateWrapper SIW(SI);
6611353f9a4SChandler Carruth   // We walk the case indices backwards so that we remove the last case first
6621353f9a4SChandler Carruth   // and don't disrupt the earlier indices.
6631353f9a4SChandler Carruth   for (unsigned Index : reverse(ExitCaseIndices)) {
6641353f9a4SChandler Carruth     auto CaseI = SI.case_begin() + Index;
6653897ded6SChandler Carruth     // Compute the outer loop from this exit.
6663897ded6SChandler Carruth     Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
6673897ded6SChandler Carruth     if (!ExitL || ExitL->contains(OuterL))
6683897ded6SChandler Carruth       OuterL = ExitL;
6691353f9a4SChandler Carruth     // Save the value of this case.
670d4097b4aSYevgeny Rouban     auto W = SIW.getSuccessorWeight(CaseI->getSuccessorIndex());
671d4097b4aSYevgeny Rouban     ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W);
6721353f9a4SChandler Carruth     // Delete the unswitched cases.
673d4097b4aSYevgeny Rouban     SIW.removeCase(CaseI);
6741353f9a4SChandler Carruth   }
6751353f9a4SChandler Carruth 
6763897ded6SChandler Carruth   if (SE) {
6773897ded6SChandler Carruth     if (OuterL)
6783897ded6SChandler Carruth       SE->forgetLoop(OuterL);
6793897ded6SChandler Carruth     else
6803897ded6SChandler Carruth       SE->forgetTopmostLoop(&L);
6813897ded6SChandler Carruth   }
6823897ded6SChandler Carruth 
6831353f9a4SChandler Carruth   // Check if after this all of the remaining cases point at the same
6841353f9a4SChandler Carruth   // successor.
6851353f9a4SChandler Carruth   BasicBlock *CommonSuccBB = nullptr;
6861353f9a4SChandler Carruth   if (SI.getNumCases() > 0 &&
6871353f9a4SChandler Carruth       std::all_of(std::next(SI.case_begin()), SI.case_end(),
6881353f9a4SChandler Carruth                   [&SI](const SwitchInst::CaseHandle &Case) {
6891353f9a4SChandler Carruth                     return Case.getCaseSuccessor() ==
6901353f9a4SChandler Carruth                            SI.case_begin()->getCaseSuccessor();
6911353f9a4SChandler Carruth                   }))
6921353f9a4SChandler Carruth     CommonSuccBB = SI.case_begin()->getCaseSuccessor();
69347dc3a34SChandler Carruth   if (!DefaultExitBB) {
6941353f9a4SChandler Carruth     // If we're not unswitching the default, we need it to match any cases to
6951353f9a4SChandler Carruth     // have a common successor or if we have no cases it is the common
6961353f9a4SChandler Carruth     // successor.
6971353f9a4SChandler Carruth     if (SI.getNumCases() == 0)
6981353f9a4SChandler Carruth       CommonSuccBB = SI.getDefaultDest();
6991353f9a4SChandler Carruth     else if (SI.getDefaultDest() != CommonSuccBB)
7001353f9a4SChandler Carruth       CommonSuccBB = nullptr;
7011353f9a4SChandler Carruth   }
7021353f9a4SChandler Carruth 
7031353f9a4SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
7041353f9a4SChandler Carruth   // the switch.
7051353f9a4SChandler Carruth   BasicBlock *OldPH = L.getLoopPreheader();
706a2eebb82SAlina Sbirlea   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
7071353f9a4SChandler Carruth   OldPH->getTerminator()->eraseFromParent();
7081353f9a4SChandler Carruth 
7091353f9a4SChandler Carruth   // Now add the unswitched switch.
7101353f9a4SChandler Carruth   auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
711d4097b4aSYevgeny Rouban   SwitchInstProfUpdateWrapper NewSIW(*NewSI);
7121353f9a4SChandler Carruth 
713d869b188SChandler Carruth   // Rewrite the IR for the unswitched basic blocks. This requires two steps.
714d869b188SChandler Carruth   // First, we split any exit blocks with remaining in-loop predecessors. Then
715d869b188SChandler Carruth   // we update the PHIs in one of two ways depending on if there was a split.
716d869b188SChandler Carruth   // We walk in reverse so that we split in the same order as the cases
717d869b188SChandler Carruth   // appeared. This is purely for convenience of reading the resulting IR, but
718d869b188SChandler Carruth   // it doesn't cost anything really.
719d869b188SChandler Carruth   SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
7201353f9a4SChandler Carruth   SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
7211353f9a4SChandler Carruth   // Handle the default exit if necessary.
7221353f9a4SChandler Carruth   // FIXME: It'd be great if we could merge this with the loop below but LLVM's
7231353f9a4SChandler Carruth   // ranges aren't quite powerful enough yet.
724d869b188SChandler Carruth   if (DefaultExitBB) {
725d869b188SChandler Carruth     if (pred_empty(DefaultExitBB)) {
726d869b188SChandler Carruth       UnswitchedExitBBs.insert(DefaultExitBB);
727d869b188SChandler Carruth       rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
728d869b188SChandler Carruth     } else {
7291353f9a4SChandler Carruth       auto *SplitBB =
730a2eebb82SAlina Sbirlea           SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
731a2eebb82SAlina Sbirlea       rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
732a2eebb82SAlina Sbirlea                                                 *ParentBB, *OldPH,
733a2eebb82SAlina Sbirlea                                                 /*FullUnswitch*/ true);
7341353f9a4SChandler Carruth       DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
7351353f9a4SChandler Carruth     }
736d869b188SChandler Carruth   }
7371353f9a4SChandler Carruth   // Note that we must use a reference in the for loop so that we update the
7381353f9a4SChandler Carruth   // container.
739d4097b4aSYevgeny Rouban   for (auto &ExitCase : reverse(ExitCases)) {
7401353f9a4SChandler Carruth     // Grab a reference to the exit block in the pair so that we can update it.
741d4097b4aSYevgeny Rouban     BasicBlock *ExitBB = std::get<1>(ExitCase);
7421353f9a4SChandler Carruth 
7431353f9a4SChandler Carruth     // If this case is the last edge into the exit block, we can simply reuse it
7441353f9a4SChandler Carruth     // as it will no longer be a loop exit. No mapping necessary.
745d869b188SChandler Carruth     if (pred_empty(ExitBB)) {
746d869b188SChandler Carruth       // Only rewrite once.
747d869b188SChandler Carruth       if (UnswitchedExitBBs.insert(ExitBB).second)
748d869b188SChandler Carruth         rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
7491353f9a4SChandler Carruth       continue;
750d869b188SChandler Carruth     }
7511353f9a4SChandler Carruth 
7521353f9a4SChandler Carruth     // Otherwise we need to split the exit block so that we retain an exit
7531353f9a4SChandler Carruth     // block from the loop and a target for the unswitched condition.
7541353f9a4SChandler Carruth     BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
7551353f9a4SChandler Carruth     if (!SplitExitBB) {
7561353f9a4SChandler Carruth       // If this is the first time we see this, do the split and remember it.
757a2eebb82SAlina Sbirlea       SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
758a2eebb82SAlina Sbirlea       rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
759a2eebb82SAlina Sbirlea                                                 *ParentBB, *OldPH,
760a2eebb82SAlina Sbirlea                                                 /*FullUnswitch*/ true);
7611353f9a4SChandler Carruth     }
762d869b188SChandler Carruth     // Update the case pair to point to the split block.
763d4097b4aSYevgeny Rouban     std::get<1>(ExitCase) = SplitExitBB;
7641353f9a4SChandler Carruth   }
7651353f9a4SChandler Carruth 
7661353f9a4SChandler Carruth   // Now add the unswitched cases. We do this in reverse order as we built them
7671353f9a4SChandler Carruth   // in reverse order.
768d4097b4aSYevgeny Rouban   for (auto &ExitCase : reverse(ExitCases)) {
769d4097b4aSYevgeny Rouban     ConstantInt *CaseVal = std::get<0>(ExitCase);
770d4097b4aSYevgeny Rouban     BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
7711353f9a4SChandler Carruth 
772d4097b4aSYevgeny Rouban     NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
7731353f9a4SChandler Carruth   }
7741353f9a4SChandler Carruth 
7751353f9a4SChandler Carruth   // If the default was unswitched, re-point it and add explicit cases for
7761353f9a4SChandler Carruth   // entering the loop.
7771353f9a4SChandler Carruth   if (DefaultExitBB) {
778d4097b4aSYevgeny Rouban     NewSIW->setDefaultDest(DefaultExitBB);
779d4097b4aSYevgeny Rouban     NewSIW.setSuccessorWeight(0, DefaultCaseWeight);
7801353f9a4SChandler Carruth 
7811353f9a4SChandler Carruth     // We removed all the exit cases, so we just copy the cases to the
7821353f9a4SChandler Carruth     // unswitched switch.
783d4097b4aSYevgeny Rouban     for (const auto &Case : SI.cases())
784d4097b4aSYevgeny Rouban       NewSIW.addCase(Case.getCaseValue(), NewPH,
785d4097b4aSYevgeny Rouban                      SIW.getSuccessorWeight(Case.getSuccessorIndex()));
786d4097b4aSYevgeny Rouban   } else if (DefaultCaseWeight) {
787d4097b4aSYevgeny Rouban     // We have to set branch weight of the default case.
788d4097b4aSYevgeny Rouban     uint64_t SW = *DefaultCaseWeight;
789d4097b4aSYevgeny Rouban     for (const auto &Case : SI.cases()) {
790d4097b4aSYevgeny Rouban       auto W = SIW.getSuccessorWeight(Case.getSuccessorIndex());
791d4097b4aSYevgeny Rouban       assert(W &&
792d4097b4aSYevgeny Rouban              "case weight must be defined as default case weight is defined");
793d4097b4aSYevgeny Rouban       SW += *W;
794d4097b4aSYevgeny Rouban     }
795d4097b4aSYevgeny Rouban     NewSIW.setSuccessorWeight(0, SW);
7961353f9a4SChandler Carruth   }
7971353f9a4SChandler Carruth 
7981353f9a4SChandler Carruth   // If we ended up with a common successor for every path through the switch
7991353f9a4SChandler Carruth   // after unswitching, rewrite it to an unconditional branch to make it easy
8001353f9a4SChandler Carruth   // to recognize. Otherwise we potentially have to recognize the default case
8011353f9a4SChandler Carruth   // pointing at unreachable and other complexity.
8021353f9a4SChandler Carruth   if (CommonSuccBB) {
8031353f9a4SChandler Carruth     BasicBlock *BB = SI.getParent();
80447dc3a34SChandler Carruth     // We may have had multiple edges to this common successor block, so remove
80547dc3a34SChandler Carruth     // them as predecessors. We skip the first one, either the default or the
80647dc3a34SChandler Carruth     // actual first case.
80747dc3a34SChandler Carruth     bool SkippedFirst = DefaultExitBB == nullptr;
80847dc3a34SChandler Carruth     for (auto Case : SI.cases()) {
80947dc3a34SChandler Carruth       assert(Case.getCaseSuccessor() == CommonSuccBB &&
81047dc3a34SChandler Carruth              "Non-common successor!");
811148861f5SChandler Carruth       (void)Case;
81247dc3a34SChandler Carruth       if (!SkippedFirst) {
81347dc3a34SChandler Carruth         SkippedFirst = true;
81447dc3a34SChandler Carruth         continue;
81547dc3a34SChandler Carruth       }
81647dc3a34SChandler Carruth       CommonSuccBB->removePredecessor(BB,
81720b91899SMax Kazantsev                                       /*KeepOneInputPHIs*/ true);
81847dc3a34SChandler Carruth     }
81947dc3a34SChandler Carruth     // Now nuke the switch and replace it with a direct branch.
820d4097b4aSYevgeny Rouban     SIW.eraseFromParent();
8211353f9a4SChandler Carruth     BranchInst::Create(CommonSuccBB, BB);
82247dc3a34SChandler Carruth   } else if (DefaultExitBB) {
82347dc3a34SChandler Carruth     assert(SI.getNumCases() > 0 &&
82447dc3a34SChandler Carruth            "If we had no cases we'd have a common successor!");
82547dc3a34SChandler Carruth     // Move the last case to the default successor. This is valid as if the
82647dc3a34SChandler Carruth     // default got unswitched it cannot be reached. This has the advantage of
82747dc3a34SChandler Carruth     // being simple and keeping the number of edges from this switch to
82847dc3a34SChandler Carruth     // successors the same, and avoiding any PHI update complexity.
82947dc3a34SChandler Carruth     auto LastCaseI = std::prev(SI.case_end());
830d4097b4aSYevgeny Rouban 
83147dc3a34SChandler Carruth     SI.setDefaultDest(LastCaseI->getCaseSuccessor());
832d4097b4aSYevgeny Rouban     SIW.setSuccessorWeight(
833d4097b4aSYevgeny Rouban         0, SIW.getSuccessorWeight(LastCaseI->getSuccessorIndex()));
834d4097b4aSYevgeny Rouban     SIW.removeCase(LastCaseI);
8351353f9a4SChandler Carruth   }
8361353f9a4SChandler Carruth 
8372c85a231SChandler Carruth   // Walk the unswitched exit blocks and the unswitched split blocks and update
8382c85a231SChandler Carruth   // the dominator tree based on the CFG edits. While we are walking unordered
8392c85a231SChandler Carruth   // containers here, the API for applyUpdates takes an unordered list of
8402c85a231SChandler Carruth   // updates and requires them to not contain duplicates.
8412c85a231SChandler Carruth   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
8422c85a231SChandler Carruth   for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
8432c85a231SChandler Carruth     DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
8442c85a231SChandler Carruth     DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
8452c85a231SChandler Carruth   }
8462c85a231SChandler Carruth   for (auto SplitUnswitchedPair : SplitExitBBMap) {
84790d2e3a1SAlina Sbirlea     DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first});
84890d2e3a1SAlina Sbirlea     DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second});
8492c85a231SChandler Carruth   }
8502c85a231SChandler Carruth   DT.applyUpdates(DTUpdates);
851a2eebb82SAlina Sbirlea 
852a2eebb82SAlina Sbirlea   if (MSSAU) {
853a2eebb82SAlina Sbirlea     MSSAU->applyUpdates(DTUpdates, DT);
854a2eebb82SAlina Sbirlea     if (VerifyMemorySSA)
855a2eebb82SAlina Sbirlea       MSSAU->getMemorySSA()->verifyMemorySSA();
856a2eebb82SAlina Sbirlea   }
857a2eebb82SAlina Sbirlea 
8587c35de12SDavid Green   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
859d8b0c8ceSChandler Carruth 
860d8b0c8ceSChandler Carruth   // We may have changed the nesting relationship for this loop so hoist it to
861d8b0c8ceSChandler Carruth   // its correct parent if needed.
862c4d8c631SDaniil Suchkov   hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
86397468e92SAlina Sbirlea 
86497468e92SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
86597468e92SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
866d8b0c8ceSChandler Carruth 
8671353f9a4SChandler Carruth   ++NumTrivial;
8681353f9a4SChandler Carruth   ++NumSwitches;
86952e97a28SAlina Sbirlea   LLVM_DEBUG(dbgs() << "    done: unswitching trivial switch...\n");
8701353f9a4SChandler Carruth   return true;
8711353f9a4SChandler Carruth }
8721353f9a4SChandler Carruth 
8731353f9a4SChandler Carruth /// This routine scans the loop to find a branch or switch which occurs before
8741353f9a4SChandler Carruth /// any side effects occur. These can potentially be unswitched without
8751353f9a4SChandler Carruth /// duplicating the loop. If a branch or switch is successfully unswitched the
8761353f9a4SChandler Carruth /// scanning continues to see if subsequent branches or switches have become
8771353f9a4SChandler Carruth /// trivial. Once all trivial candidates have been unswitched, this routine
8781353f9a4SChandler Carruth /// returns.
8791353f9a4SChandler Carruth ///
8801353f9a4SChandler Carruth /// The return value indicates whether anything was unswitched (and therefore
8811353f9a4SChandler Carruth /// changed).
8823897ded6SChandler Carruth ///
8833897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
8843897ded6SChandler Carruth /// invalidated by this.
8851353f9a4SChandler Carruth static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
886a2eebb82SAlina Sbirlea                                          LoopInfo &LI, ScalarEvolution *SE,
887a2eebb82SAlina Sbirlea                                          MemorySSAUpdater *MSSAU) {
8881353f9a4SChandler Carruth   bool Changed = false;
8891353f9a4SChandler Carruth 
8901353f9a4SChandler Carruth   // If loop header has only one reachable successor we should keep looking for
8911353f9a4SChandler Carruth   // trivial condition candidates in the successor as well. An alternative is
8921353f9a4SChandler Carruth   // to constant fold conditions and merge successors into loop header (then we
8931353f9a4SChandler Carruth   // only need to check header's terminator). The reason for not doing this in
8941353f9a4SChandler Carruth   // LoopUnswitch pass is that it could potentially break LoopPassManager's
8951353f9a4SChandler Carruth   // invariants. Folding dead branches could either eliminate the current loop
8961353f9a4SChandler Carruth   // or make other loops unreachable. LCSSA form might also not be preserved
8971353f9a4SChandler Carruth   // after deleting branches. The following code keeps traversing loop header's
8981353f9a4SChandler Carruth   // successors until it finds the trivial condition candidate (condition that
8991353f9a4SChandler Carruth   // is not a constant). Since unswitching generates branches with constant
9001353f9a4SChandler Carruth   // conditions, this scenario could be very common in practice.
9011353f9a4SChandler Carruth   BasicBlock *CurrentBB = L.getHeader();
9021353f9a4SChandler Carruth   SmallPtrSet<BasicBlock *, 8> Visited;
9031353f9a4SChandler Carruth   Visited.insert(CurrentBB);
9041353f9a4SChandler Carruth   do {
9051353f9a4SChandler Carruth     // Check if there are any side-effecting instructions (e.g. stores, calls,
9061353f9a4SChandler Carruth     // volatile loads) in the part of the loop that the code *would* execute
9071353f9a4SChandler Carruth     // without unswitching.
90893210870SAlina Sbirlea     if (MSSAU) // Possible early exit with MSSA
90993210870SAlina Sbirlea       if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
91093210870SAlina Sbirlea         if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
91193210870SAlina Sbirlea           return Changed;
9121353f9a4SChandler Carruth     if (llvm::any_of(*CurrentBB,
9131353f9a4SChandler Carruth                      [](Instruction &I) { return I.mayHaveSideEffects(); }))
9141353f9a4SChandler Carruth       return Changed;
9151353f9a4SChandler Carruth 
916edb12a83SChandler Carruth     Instruction *CurrentTerm = CurrentBB->getTerminator();
9171353f9a4SChandler Carruth 
9181353f9a4SChandler Carruth     if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
9191353f9a4SChandler Carruth       // Don't bother trying to unswitch past a switch with a constant
9201353f9a4SChandler Carruth       // condition. This should be removed prior to running this pass by
9211353f9a4SChandler Carruth       // simplify-cfg.
9221353f9a4SChandler Carruth       if (isa<Constant>(SI->getCondition()))
9231353f9a4SChandler Carruth         return Changed;
9241353f9a4SChandler Carruth 
925a2eebb82SAlina Sbirlea       if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
926f209649dSHiroshi Inoue         // Couldn't unswitch this one so we're done.
9271353f9a4SChandler Carruth         return Changed;
9281353f9a4SChandler Carruth 
9291353f9a4SChandler Carruth       // Mark that we managed to unswitch something.
9301353f9a4SChandler Carruth       Changed = true;
9311353f9a4SChandler Carruth 
9321353f9a4SChandler Carruth       // If unswitching turned the terminator into an unconditional branch then
9331353f9a4SChandler Carruth       // we can continue. The unswitching logic specifically works to fold any
9341353f9a4SChandler Carruth       // cases it can into an unconditional branch to make it easier to
9351353f9a4SChandler Carruth       // recognize here.
9361353f9a4SChandler Carruth       auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
9371353f9a4SChandler Carruth       if (!BI || BI->isConditional())
9381353f9a4SChandler Carruth         return Changed;
9391353f9a4SChandler Carruth 
9401353f9a4SChandler Carruth       CurrentBB = BI->getSuccessor(0);
9411353f9a4SChandler Carruth       continue;
9421353f9a4SChandler Carruth     }
9431353f9a4SChandler Carruth 
9441353f9a4SChandler Carruth     auto *BI = dyn_cast<BranchInst>(CurrentTerm);
9451353f9a4SChandler Carruth     if (!BI)
9461353f9a4SChandler Carruth       // We do not understand other terminator instructions.
9471353f9a4SChandler Carruth       return Changed;
9481353f9a4SChandler Carruth 
9491353f9a4SChandler Carruth     // Don't bother trying to unswitch past an unconditional branch or a branch
9501353f9a4SChandler Carruth     // with a constant value. These should be removed by simplify-cfg prior to
9511353f9a4SChandler Carruth     // running this pass.
9521353f9a4SChandler Carruth     if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
9531353f9a4SChandler Carruth       return Changed;
9541353f9a4SChandler Carruth 
9551353f9a4SChandler Carruth     // Found a trivial condition candidate: non-foldable conditional branch. If
9561353f9a4SChandler Carruth     // we fail to unswitch this, we can't do anything else that is trivial.
957a2eebb82SAlina Sbirlea     if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
9581353f9a4SChandler Carruth       return Changed;
9591353f9a4SChandler Carruth 
9601353f9a4SChandler Carruth     // Mark that we managed to unswitch something.
9611353f9a4SChandler Carruth     Changed = true;
9621353f9a4SChandler Carruth 
9634da3331dSChandler Carruth     // If we only unswitched some of the conditions feeding the branch, we won't
9644da3331dSChandler Carruth     // have collapsed it to a single successor.
9651353f9a4SChandler Carruth     BI = cast<BranchInst>(CurrentBB->getTerminator());
9664da3331dSChandler Carruth     if (BI->isConditional())
9674da3331dSChandler Carruth       return Changed;
9684da3331dSChandler Carruth 
9694da3331dSChandler Carruth     // Follow the newly unconditional branch into its successor.
9701353f9a4SChandler Carruth     CurrentBB = BI->getSuccessor(0);
9711353f9a4SChandler Carruth 
9721353f9a4SChandler Carruth     // When continuing, if we exit the loop or reach a previous visited block,
9731353f9a4SChandler Carruth     // then we can not reach any trivial condition candidates (unfoldable
9741353f9a4SChandler Carruth     // branch instructions or switch instructions) and no unswitch can happen.
9751353f9a4SChandler Carruth   } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
9761353f9a4SChandler Carruth 
9771353f9a4SChandler Carruth   return Changed;
9781353f9a4SChandler Carruth }
9791353f9a4SChandler Carruth 
980693eedb1SChandler Carruth /// Build the cloned blocks for an unswitched copy of the given loop.
981693eedb1SChandler Carruth ///
982693eedb1SChandler Carruth /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
983693eedb1SChandler Carruth /// after the split block (`SplitBB`) that will be used to select between the
984693eedb1SChandler Carruth /// cloned and original loop.
985693eedb1SChandler Carruth ///
986693eedb1SChandler Carruth /// This routine handles cloning all of the necessary loop blocks and exit
987693eedb1SChandler Carruth /// blocks including rewriting their instructions and the relevant PHI nodes.
9881652996fSChandler Carruth /// Any loop blocks or exit blocks which are dominated by a different successor
9891652996fSChandler Carruth /// than the one for this clone of the loop blocks can be trivially skipped. We
9901652996fSChandler Carruth /// use the `DominatingSucc` map to determine whether a block satisfies that
9911652996fSChandler Carruth /// property with a simple map lookup.
9921652996fSChandler Carruth ///
9931652996fSChandler Carruth /// It also correctly creates the unconditional branch in the cloned
994693eedb1SChandler Carruth /// unswitched parent block to only point at the unswitched successor.
995693eedb1SChandler Carruth ///
996693eedb1SChandler Carruth /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
997693eedb1SChandler Carruth /// block splitting is correctly reflected in `LoopInfo`, essentially all of
998693eedb1SChandler Carruth /// the cloned blocks (and their loops) are left without full `LoopInfo`
999693eedb1SChandler Carruth /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
1000693eedb1SChandler Carruth /// blocks to them but doesn't create the cloned `DominatorTree` structure and
1001693eedb1SChandler Carruth /// instead the caller must recompute an accurate DT. It *does* correctly
1002693eedb1SChandler Carruth /// update the `AssumptionCache` provided in `AC`.
1003693eedb1SChandler Carruth static BasicBlock *buildClonedLoopBlocks(
1004693eedb1SChandler Carruth     Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
1005693eedb1SChandler Carruth     ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
1006693eedb1SChandler Carruth     BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
10071652996fSChandler Carruth     const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
100869e68f84SChandler Carruth     ValueToValueMapTy &VMap,
100969e68f84SChandler Carruth     SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
1010a2eebb82SAlina Sbirlea     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
1011693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> NewBlocks;
1012693eedb1SChandler Carruth   NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
1013693eedb1SChandler Carruth 
1014693eedb1SChandler Carruth   // We will need to clone a bunch of blocks, wrap up the clone operation in
1015693eedb1SChandler Carruth   // a helper.
1016693eedb1SChandler Carruth   auto CloneBlock = [&](BasicBlock *OldBB) {
1017693eedb1SChandler Carruth     // Clone the basic block and insert it before the new preheader.
1018693eedb1SChandler Carruth     BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
1019693eedb1SChandler Carruth     NewBB->moveBefore(LoopPH);
1020693eedb1SChandler Carruth 
1021693eedb1SChandler Carruth     // Record this block and the mapping.
1022693eedb1SChandler Carruth     NewBlocks.push_back(NewBB);
1023693eedb1SChandler Carruth     VMap[OldBB] = NewBB;
1024693eedb1SChandler Carruth 
1025693eedb1SChandler Carruth     return NewBB;
1026693eedb1SChandler Carruth   };
1027693eedb1SChandler Carruth 
10281652996fSChandler Carruth   // We skip cloning blocks when they have a dominating succ that is not the
10291652996fSChandler Carruth   // succ we are cloning for.
10301652996fSChandler Carruth   auto SkipBlock = [&](BasicBlock *BB) {
10311652996fSChandler Carruth     auto It = DominatingSucc.find(BB);
10321652996fSChandler Carruth     return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
10331652996fSChandler Carruth   };
10341652996fSChandler Carruth 
1035693eedb1SChandler Carruth   // First, clone the preheader.
1036693eedb1SChandler Carruth   auto *ClonedPH = CloneBlock(LoopPH);
1037693eedb1SChandler Carruth 
1038693eedb1SChandler Carruth   // Then clone all the loop blocks, skipping the ones that aren't necessary.
1039693eedb1SChandler Carruth   for (auto *LoopBB : L.blocks())
10401652996fSChandler Carruth     if (!SkipBlock(LoopBB))
1041693eedb1SChandler Carruth       CloneBlock(LoopBB);
1042693eedb1SChandler Carruth 
1043693eedb1SChandler Carruth   // Split all the loop exit edges so that when we clone the exit blocks, if
1044693eedb1SChandler Carruth   // any of the exit blocks are *also* a preheader for some other loop, we
1045693eedb1SChandler Carruth   // don't create multiple predecessors entering the loop header.
1046693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks) {
10471652996fSChandler Carruth     if (SkipBlock(ExitBB))
1048693eedb1SChandler Carruth       continue;
1049693eedb1SChandler Carruth 
1050693eedb1SChandler Carruth     // When we are going to clone an exit, we don't need to clone all the
1051693eedb1SChandler Carruth     // instructions in the exit block and we want to ensure we have an easy
1052693eedb1SChandler Carruth     // place to merge the CFG, so split the exit first. This is always safe to
1053693eedb1SChandler Carruth     // do because there cannot be any non-loop predecessors of a loop exit in
1054693eedb1SChandler Carruth     // loop simplified form.
1055a2eebb82SAlina Sbirlea     auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
1056693eedb1SChandler Carruth 
1057693eedb1SChandler Carruth     // Rearrange the names to make it easier to write test cases by having the
1058693eedb1SChandler Carruth     // exit block carry the suffix rather than the merge block carrying the
1059693eedb1SChandler Carruth     // suffix.
1060693eedb1SChandler Carruth     MergeBB->takeName(ExitBB);
1061693eedb1SChandler Carruth     ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1062693eedb1SChandler Carruth 
1063693eedb1SChandler Carruth     // Now clone the original exit block.
1064693eedb1SChandler Carruth     auto *ClonedExitBB = CloneBlock(ExitBB);
1065693eedb1SChandler Carruth     assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1066693eedb1SChandler Carruth            "Exit block should have been split to have one successor!");
1067693eedb1SChandler Carruth     assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1068693eedb1SChandler Carruth            "Cloned exit block has the wrong successor!");
1069693eedb1SChandler Carruth 
1070693eedb1SChandler Carruth     // Remap any cloned instructions and create a merge phi node for them.
1071693eedb1SChandler Carruth     for (auto ZippedInsts : llvm::zip_first(
1072693eedb1SChandler Carruth              llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1073693eedb1SChandler Carruth              llvm::make_range(ClonedExitBB->begin(),
1074693eedb1SChandler Carruth                               std::prev(ClonedExitBB->end())))) {
1075693eedb1SChandler Carruth       Instruction &I = std::get<0>(ZippedInsts);
1076693eedb1SChandler Carruth       Instruction &ClonedI = std::get<1>(ZippedInsts);
1077693eedb1SChandler Carruth 
1078693eedb1SChandler Carruth       // The only instructions in the exit block should be PHI nodes and
1079693eedb1SChandler Carruth       // potentially a landing pad.
1080693eedb1SChandler Carruth       assert(
1081693eedb1SChandler Carruth           (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1082693eedb1SChandler Carruth           "Bad instruction in exit block!");
1083693eedb1SChandler Carruth       // We should have a value map between the instruction and its clone.
1084693eedb1SChandler Carruth       assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1085693eedb1SChandler Carruth 
1086693eedb1SChandler Carruth       auto *MergePN =
1087693eedb1SChandler Carruth           PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1088693eedb1SChandler Carruth                           &*MergeBB->getFirstInsertionPt());
1089693eedb1SChandler Carruth       I.replaceAllUsesWith(MergePN);
1090693eedb1SChandler Carruth       MergePN->addIncoming(&I, ExitBB);
1091693eedb1SChandler Carruth       MergePN->addIncoming(&ClonedI, ClonedExitBB);
1092693eedb1SChandler Carruth     }
1093693eedb1SChandler Carruth   }
1094693eedb1SChandler Carruth 
1095693eedb1SChandler Carruth   // Rewrite the instructions in the cloned blocks to refer to the instructions
1096693eedb1SChandler Carruth   // in the cloned blocks. We have to do this as a second pass so that we have
1097693eedb1SChandler Carruth   // everything available. Also, we have inserted new instructions which may
1098693eedb1SChandler Carruth   // include assume intrinsics, so we update the assumption cache while
1099693eedb1SChandler Carruth   // processing this.
1100693eedb1SChandler Carruth   for (auto *ClonedBB : NewBlocks)
1101693eedb1SChandler Carruth     for (Instruction &I : *ClonedBB) {
1102693eedb1SChandler Carruth       RemapInstruction(&I, VMap,
1103693eedb1SChandler Carruth                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1104693eedb1SChandler Carruth       if (auto *II = dyn_cast<IntrinsicInst>(&I))
1105693eedb1SChandler Carruth         if (II->getIntrinsicID() == Intrinsic::assume)
1106693eedb1SChandler Carruth           AC.registerAssumption(II);
1107693eedb1SChandler Carruth     }
1108693eedb1SChandler Carruth 
1109693eedb1SChandler Carruth   // Update any PHI nodes in the cloned successors of the skipped blocks to not
1110693eedb1SChandler Carruth   // have spurious incoming values.
1111693eedb1SChandler Carruth   for (auto *LoopBB : L.blocks())
11121652996fSChandler Carruth     if (SkipBlock(LoopBB))
1113693eedb1SChandler Carruth       for (auto *SuccBB : successors(LoopBB))
1114693eedb1SChandler Carruth         if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1115693eedb1SChandler Carruth           for (PHINode &PN : ClonedSuccBB->phis())
1116693eedb1SChandler Carruth             PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1117693eedb1SChandler Carruth 
1118ed296543SChandler Carruth   // Remove the cloned parent as a predecessor of any successor we ended up
1119ed296543SChandler Carruth   // cloning other than the unswitched one.
1120ed296543SChandler Carruth   auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1121ed296543SChandler Carruth   for (auto *SuccBB : successors(ParentBB)) {
1122ed296543SChandler Carruth     if (SuccBB == UnswitchedSuccBB)
1123ed296543SChandler Carruth       continue;
1124ed296543SChandler Carruth 
1125ed296543SChandler Carruth     auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1126ed296543SChandler Carruth     if (!ClonedSuccBB)
1127ed296543SChandler Carruth       continue;
1128ed296543SChandler Carruth 
1129ed296543SChandler Carruth     ClonedSuccBB->removePredecessor(ClonedParentBB,
113020b91899SMax Kazantsev                                     /*KeepOneInputPHIs*/ true);
1131ed296543SChandler Carruth   }
1132ed296543SChandler Carruth 
1133ed296543SChandler Carruth   // Replace the cloned branch with an unconditional branch to the cloned
1134ed296543SChandler Carruth   // unswitched successor.
1135ed296543SChandler Carruth   auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1136ed296543SChandler Carruth   ClonedParentBB->getTerminator()->eraseFromParent();
1137ed296543SChandler Carruth   BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1138ed296543SChandler Carruth 
1139ed296543SChandler Carruth   // If there are duplicate entries in the PHI nodes because of multiple edges
1140ed296543SChandler Carruth   // to the unswitched successor, we need to nuke all but one as we replaced it
1141ed296543SChandler Carruth   // with a direct branch.
1142ed296543SChandler Carruth   for (PHINode &PN : ClonedSuccBB->phis()) {
1143ed296543SChandler Carruth     bool Found = false;
1144ed296543SChandler Carruth     // Loop over the incoming operands backwards so we can easily delete as we
1145ed296543SChandler Carruth     // go without invalidating the index.
1146ed296543SChandler Carruth     for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1147ed296543SChandler Carruth       if (PN.getIncomingBlock(i) != ClonedParentBB)
1148ed296543SChandler Carruth         continue;
1149ed296543SChandler Carruth       if (!Found) {
1150ed296543SChandler Carruth         Found = true;
1151ed296543SChandler Carruth         continue;
1152ed296543SChandler Carruth       }
1153ed296543SChandler Carruth       PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1154ed296543SChandler Carruth     }
1155ed296543SChandler Carruth   }
1156ed296543SChandler Carruth 
115769e68f84SChandler Carruth   // Record the domtree updates for the new blocks.
115844aab925SChandler Carruth   SmallPtrSet<BasicBlock *, 4> SuccSet;
115944aab925SChandler Carruth   for (auto *ClonedBB : NewBlocks) {
116069e68f84SChandler Carruth     for (auto *SuccBB : successors(ClonedBB))
116144aab925SChandler Carruth       if (SuccSet.insert(SuccBB).second)
116269e68f84SChandler Carruth         DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
116344aab925SChandler Carruth     SuccSet.clear();
116444aab925SChandler Carruth   }
116569e68f84SChandler Carruth 
1166693eedb1SChandler Carruth   return ClonedPH;
1167693eedb1SChandler Carruth }
1168693eedb1SChandler Carruth 
1169693eedb1SChandler Carruth /// Recursively clone the specified loop and all of its children.
1170693eedb1SChandler Carruth ///
1171693eedb1SChandler Carruth /// The target parent loop for the clone should be provided, or can be null if
1172693eedb1SChandler Carruth /// the clone is a top-level loop. While cloning, all the blocks are mapped
1173693eedb1SChandler Carruth /// with the provided value map. The entire original loop must be present in
1174693eedb1SChandler Carruth /// the value map. The cloned loop is returned.
1175693eedb1SChandler Carruth static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1176693eedb1SChandler Carruth                            const ValueToValueMapTy &VMap, LoopInfo &LI) {
1177693eedb1SChandler Carruth   auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1178693eedb1SChandler Carruth     assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1179693eedb1SChandler Carruth     ClonedL.reserveBlocks(OrigL.getNumBlocks());
1180693eedb1SChandler Carruth     for (auto *BB : OrigL.blocks()) {
1181693eedb1SChandler Carruth       auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1182693eedb1SChandler Carruth       ClonedL.addBlockEntry(ClonedBB);
11830ace148cSChandler Carruth       if (LI.getLoopFor(BB) == &OrigL)
1184693eedb1SChandler Carruth         LI.changeLoopFor(ClonedBB, &ClonedL);
1185693eedb1SChandler Carruth     }
1186693eedb1SChandler Carruth   };
1187693eedb1SChandler Carruth 
1188693eedb1SChandler Carruth   // We specially handle the first loop because it may get cloned into
1189693eedb1SChandler Carruth   // a different parent and because we most commonly are cloning leaf loops.
1190693eedb1SChandler Carruth   Loop *ClonedRootL = LI.AllocateLoop();
1191693eedb1SChandler Carruth   if (RootParentL)
1192693eedb1SChandler Carruth     RootParentL->addChildLoop(ClonedRootL);
1193693eedb1SChandler Carruth   else
1194693eedb1SChandler Carruth     LI.addTopLevelLoop(ClonedRootL);
1195693eedb1SChandler Carruth   AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1196693eedb1SChandler Carruth 
1197693eedb1SChandler Carruth   if (OrigRootL.empty())
1198693eedb1SChandler Carruth     return ClonedRootL;
1199693eedb1SChandler Carruth 
1200693eedb1SChandler Carruth   // If we have a nest, we can quickly clone the entire loop nest using an
1201693eedb1SChandler Carruth   // iterative approach because it is a tree. We keep the cloned parent in the
1202693eedb1SChandler Carruth   // data structure to avoid repeatedly querying through a map to find it.
1203693eedb1SChandler Carruth   SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1204693eedb1SChandler Carruth   // Build up the loops to clone in reverse order as we'll clone them from the
1205693eedb1SChandler Carruth   // back.
1206693eedb1SChandler Carruth   for (Loop *ChildL : llvm::reverse(OrigRootL))
1207693eedb1SChandler Carruth     LoopsToClone.push_back({ClonedRootL, ChildL});
1208693eedb1SChandler Carruth   do {
1209693eedb1SChandler Carruth     Loop *ClonedParentL, *L;
1210693eedb1SChandler Carruth     std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1211693eedb1SChandler Carruth     Loop *ClonedL = LI.AllocateLoop();
1212693eedb1SChandler Carruth     ClonedParentL->addChildLoop(ClonedL);
1213693eedb1SChandler Carruth     AddClonedBlocksToLoop(*L, *ClonedL);
1214693eedb1SChandler Carruth     for (Loop *ChildL : llvm::reverse(*L))
1215693eedb1SChandler Carruth       LoopsToClone.push_back({ClonedL, ChildL});
1216693eedb1SChandler Carruth   } while (!LoopsToClone.empty());
1217693eedb1SChandler Carruth 
1218693eedb1SChandler Carruth   return ClonedRootL;
1219693eedb1SChandler Carruth }
1220693eedb1SChandler Carruth 
1221693eedb1SChandler Carruth /// Build the cloned loops of an original loop from unswitching.
1222693eedb1SChandler Carruth ///
1223693eedb1SChandler Carruth /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1224693eedb1SChandler Carruth /// operation. We need to re-verify that there even is a loop (as the backedge
1225693eedb1SChandler Carruth /// may not have been cloned), and even if there are remaining backedges the
1226693eedb1SChandler Carruth /// backedge set may be different. However, we know that each child loop is
1227693eedb1SChandler Carruth /// undisturbed, we only need to find where to place each child loop within
1228693eedb1SChandler Carruth /// either any parent loop or within a cloned version of the original loop.
1229693eedb1SChandler Carruth ///
1230693eedb1SChandler Carruth /// Because child loops may end up cloned outside of any cloned version of the
1231693eedb1SChandler Carruth /// original loop, multiple cloned sibling loops may be created. All of them
1232693eedb1SChandler Carruth /// are returned so that the newly introduced loop nest roots can be
1233693eedb1SChandler Carruth /// identified.
12349281503eSChandler Carruth static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1235693eedb1SChandler Carruth                              const ValueToValueMapTy &VMap, LoopInfo &LI,
1236693eedb1SChandler Carruth                              SmallVectorImpl<Loop *> &NonChildClonedLoops) {
1237693eedb1SChandler Carruth   Loop *ClonedL = nullptr;
1238693eedb1SChandler Carruth 
1239693eedb1SChandler Carruth   auto *OrigPH = OrigL.getLoopPreheader();
1240693eedb1SChandler Carruth   auto *OrigHeader = OrigL.getHeader();
1241693eedb1SChandler Carruth 
1242693eedb1SChandler Carruth   auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1243693eedb1SChandler Carruth   auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1244693eedb1SChandler Carruth 
1245693eedb1SChandler Carruth   // We need to know the loops of the cloned exit blocks to even compute the
1246693eedb1SChandler Carruth   // accurate parent loop. If we only clone exits to some parent of the
1247693eedb1SChandler Carruth   // original parent, we want to clone into that outer loop. We also keep track
1248693eedb1SChandler Carruth   // of the loops that our cloned exit blocks participate in.
1249693eedb1SChandler Carruth   Loop *ParentL = nullptr;
1250693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1251693eedb1SChandler Carruth   SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1252693eedb1SChandler Carruth   ClonedExitsInLoops.reserve(ExitBlocks.size());
1253693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks)
1254693eedb1SChandler Carruth     if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1255693eedb1SChandler Carruth       if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1256693eedb1SChandler Carruth         ExitLoopMap[ClonedExitBB] = ExitL;
1257693eedb1SChandler Carruth         ClonedExitsInLoops.push_back(ClonedExitBB);
1258693eedb1SChandler Carruth         if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1259693eedb1SChandler Carruth           ParentL = ExitL;
1260693eedb1SChandler Carruth       }
1261693eedb1SChandler Carruth   assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1262693eedb1SChandler Carruth           ParentL->contains(OrigL.getParentLoop())) &&
1263693eedb1SChandler Carruth          "The computed parent loop should always contain (or be) the parent of "
1264693eedb1SChandler Carruth          "the original loop.");
1265693eedb1SChandler Carruth 
1266693eedb1SChandler Carruth   // We build the set of blocks dominated by the cloned header from the set of
1267693eedb1SChandler Carruth   // cloned blocks out of the original loop. While not all of these will
1268693eedb1SChandler Carruth   // necessarily be in the cloned loop, it is enough to establish that they
1269693eedb1SChandler Carruth   // aren't in unreachable cycles, etc.
1270693eedb1SChandler Carruth   SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1271693eedb1SChandler Carruth   for (auto *BB : OrigL.blocks())
1272693eedb1SChandler Carruth     if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1273693eedb1SChandler Carruth       ClonedLoopBlocks.insert(ClonedBB);
1274693eedb1SChandler Carruth 
1275693eedb1SChandler Carruth   // Rebuild the set of blocks that will end up in the cloned loop. We may have
1276693eedb1SChandler Carruth   // skipped cloning some region of this loop which can in turn skip some of
1277693eedb1SChandler Carruth   // the backedges so we have to rebuild the blocks in the loop based on the
1278693eedb1SChandler Carruth   // backedges that remain after cloning.
1279693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1280693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1281693eedb1SChandler Carruth   for (auto *Pred : predecessors(ClonedHeader)) {
1282693eedb1SChandler Carruth     // The only possible non-loop header predecessor is the preheader because
1283693eedb1SChandler Carruth     // we know we cloned the loop in simplified form.
1284693eedb1SChandler Carruth     if (Pred == ClonedPH)
1285693eedb1SChandler Carruth       continue;
1286693eedb1SChandler Carruth 
1287693eedb1SChandler Carruth     // Because the loop was in simplified form, the only non-loop predecessor
1288693eedb1SChandler Carruth     // should be the preheader.
1289693eedb1SChandler Carruth     assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1290693eedb1SChandler Carruth                                            "header other than the preheader "
1291693eedb1SChandler Carruth                                            "that is not part of the loop!");
1292693eedb1SChandler Carruth 
1293693eedb1SChandler Carruth     // Insert this block into the loop set and on the first visit (and if it
1294693eedb1SChandler Carruth     // isn't the header we're currently walking) put it into the worklist to
1295693eedb1SChandler Carruth     // recurse through.
1296693eedb1SChandler Carruth     if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1297693eedb1SChandler Carruth       Worklist.push_back(Pred);
1298693eedb1SChandler Carruth   }
1299693eedb1SChandler Carruth 
1300693eedb1SChandler Carruth   // If we had any backedges then there *is* a cloned loop. Put the header into
1301693eedb1SChandler Carruth   // the loop set and then walk the worklist backwards to find all the blocks
1302693eedb1SChandler Carruth   // that remain within the loop after cloning.
1303693eedb1SChandler Carruth   if (!BlocksInClonedLoop.empty()) {
1304693eedb1SChandler Carruth     BlocksInClonedLoop.insert(ClonedHeader);
1305693eedb1SChandler Carruth 
1306693eedb1SChandler Carruth     while (!Worklist.empty()) {
1307693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1308693eedb1SChandler Carruth       assert(BlocksInClonedLoop.count(BB) &&
1309693eedb1SChandler Carruth              "Didn't put block into the loop set!");
1310693eedb1SChandler Carruth 
1311693eedb1SChandler Carruth       // Insert any predecessors that are in the possible set into the cloned
1312693eedb1SChandler Carruth       // set, and if the insert is successful, add them to the worklist. Note
1313693eedb1SChandler Carruth       // that we filter on the blocks that are definitely reachable via the
1314693eedb1SChandler Carruth       // backedge to the loop header so we may prune out dead code within the
1315693eedb1SChandler Carruth       // cloned loop.
1316693eedb1SChandler Carruth       for (auto *Pred : predecessors(BB))
1317693eedb1SChandler Carruth         if (ClonedLoopBlocks.count(Pred) &&
1318693eedb1SChandler Carruth             BlocksInClonedLoop.insert(Pred).second)
1319693eedb1SChandler Carruth           Worklist.push_back(Pred);
1320693eedb1SChandler Carruth     }
1321693eedb1SChandler Carruth 
1322693eedb1SChandler Carruth     ClonedL = LI.AllocateLoop();
1323693eedb1SChandler Carruth     if (ParentL) {
1324693eedb1SChandler Carruth       ParentL->addBasicBlockToLoop(ClonedPH, LI);
1325693eedb1SChandler Carruth       ParentL->addChildLoop(ClonedL);
1326693eedb1SChandler Carruth     } else {
1327693eedb1SChandler Carruth       LI.addTopLevelLoop(ClonedL);
1328693eedb1SChandler Carruth     }
13299281503eSChandler Carruth     NonChildClonedLoops.push_back(ClonedL);
1330693eedb1SChandler Carruth 
1331693eedb1SChandler Carruth     ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1332693eedb1SChandler Carruth     // We don't want to just add the cloned loop blocks based on how we
1333693eedb1SChandler Carruth     // discovered them. The original order of blocks was carefully built in
1334693eedb1SChandler Carruth     // a way that doesn't rely on predecessor ordering. Rather than re-invent
1335693eedb1SChandler Carruth     // that logic, we just re-walk the original blocks (and those of the child
1336693eedb1SChandler Carruth     // loops) and filter them as we add them into the cloned loop.
1337693eedb1SChandler Carruth     for (auto *BB : OrigL.blocks()) {
1338693eedb1SChandler Carruth       auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1339693eedb1SChandler Carruth       if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1340693eedb1SChandler Carruth         continue;
1341693eedb1SChandler Carruth 
1342693eedb1SChandler Carruth       // Directly add the blocks that are only in this loop.
1343693eedb1SChandler Carruth       if (LI.getLoopFor(BB) == &OrigL) {
1344693eedb1SChandler Carruth         ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1345693eedb1SChandler Carruth         continue;
1346693eedb1SChandler Carruth       }
1347693eedb1SChandler Carruth 
1348693eedb1SChandler Carruth       // We want to manually add it to this loop and parents.
1349693eedb1SChandler Carruth       // Registering it with LoopInfo will happen when we clone the top
1350693eedb1SChandler Carruth       // loop for this block.
1351693eedb1SChandler Carruth       for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1352693eedb1SChandler Carruth         PL->addBlockEntry(ClonedBB);
1353693eedb1SChandler Carruth     }
1354693eedb1SChandler Carruth 
1355693eedb1SChandler Carruth     // Now add each child loop whose header remains within the cloned loop. All
1356693eedb1SChandler Carruth     // of the blocks within the loop must satisfy the same constraints as the
1357693eedb1SChandler Carruth     // header so once we pass the header checks we can just clone the entire
1358693eedb1SChandler Carruth     // child loop nest.
1359693eedb1SChandler Carruth     for (Loop *ChildL : OrigL) {
1360693eedb1SChandler Carruth       auto *ClonedChildHeader =
1361693eedb1SChandler Carruth           cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1362693eedb1SChandler Carruth       if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1363693eedb1SChandler Carruth         continue;
1364693eedb1SChandler Carruth 
1365693eedb1SChandler Carruth #ifndef NDEBUG
1366693eedb1SChandler Carruth       // We should never have a cloned child loop header but fail to have
1367693eedb1SChandler Carruth       // all of the blocks for that child loop.
1368693eedb1SChandler Carruth       for (auto *ChildLoopBB : ChildL->blocks())
1369693eedb1SChandler Carruth         assert(BlocksInClonedLoop.count(
1370693eedb1SChandler Carruth                    cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1371693eedb1SChandler Carruth                "Child cloned loop has a header within the cloned outer "
1372693eedb1SChandler Carruth                "loop but not all of its blocks!");
1373693eedb1SChandler Carruth #endif
1374693eedb1SChandler Carruth 
1375693eedb1SChandler Carruth       cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1376693eedb1SChandler Carruth     }
1377693eedb1SChandler Carruth   }
1378693eedb1SChandler Carruth 
1379693eedb1SChandler Carruth   // Now that we've handled all the components of the original loop that were
1380693eedb1SChandler Carruth   // cloned into a new loop, we still need to handle anything from the original
1381693eedb1SChandler Carruth   // loop that wasn't in a cloned loop.
1382693eedb1SChandler Carruth 
1383693eedb1SChandler Carruth   // Figure out what blocks are left to place within any loop nest containing
1384693eedb1SChandler Carruth   // the unswitched loop. If we never formed a loop, the cloned PH is one of
1385693eedb1SChandler Carruth   // them.
1386693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1387693eedb1SChandler Carruth   if (BlocksInClonedLoop.empty())
1388693eedb1SChandler Carruth     UnloopedBlockSet.insert(ClonedPH);
1389693eedb1SChandler Carruth   for (auto *ClonedBB : ClonedLoopBlocks)
1390693eedb1SChandler Carruth     if (!BlocksInClonedLoop.count(ClonedBB))
1391693eedb1SChandler Carruth       UnloopedBlockSet.insert(ClonedBB);
1392693eedb1SChandler Carruth 
1393693eedb1SChandler Carruth   // Copy the cloned exits and sort them in ascending loop depth, we'll work
1394693eedb1SChandler Carruth   // backwards across these to process them inside out. The order shouldn't
1395693eedb1SChandler Carruth   // matter as we're just trying to build up the map from inside-out; we use
1396693eedb1SChandler Carruth   // the map in a more stably ordered way below.
1397693eedb1SChandler Carruth   auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
13980cac726aSFangrui Song   llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1399693eedb1SChandler Carruth     return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1400693eedb1SChandler Carruth            ExitLoopMap.lookup(RHS)->getLoopDepth();
1401693eedb1SChandler Carruth   });
1402693eedb1SChandler Carruth 
1403693eedb1SChandler Carruth   // Populate the existing ExitLoopMap with everything reachable from each
1404693eedb1SChandler Carruth   // exit, starting from the inner most exit.
1405693eedb1SChandler Carruth   while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1406693eedb1SChandler Carruth     assert(Worklist.empty() && "Didn't clear worklist!");
1407693eedb1SChandler Carruth 
1408693eedb1SChandler Carruth     BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1409693eedb1SChandler Carruth     Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1410693eedb1SChandler Carruth 
1411693eedb1SChandler Carruth     // Walk the CFG back until we hit the cloned PH adding everything reachable
1412693eedb1SChandler Carruth     // and in the unlooped set to this exit block's loop.
1413693eedb1SChandler Carruth     Worklist.push_back(ExitBB);
1414693eedb1SChandler Carruth     do {
1415693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1416693eedb1SChandler Carruth       // We can stop recursing at the cloned preheader (if we get there).
1417693eedb1SChandler Carruth       if (BB == ClonedPH)
1418693eedb1SChandler Carruth         continue;
1419693eedb1SChandler Carruth 
1420693eedb1SChandler Carruth       for (BasicBlock *PredBB : predecessors(BB)) {
1421693eedb1SChandler Carruth         // If this pred has already been moved to our set or is part of some
1422693eedb1SChandler Carruth         // (inner) loop, no update needed.
1423693eedb1SChandler Carruth         if (!UnloopedBlockSet.erase(PredBB)) {
1424693eedb1SChandler Carruth           assert(
1425693eedb1SChandler Carruth               (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1426693eedb1SChandler Carruth               "Predecessor not mapped to a loop!");
1427693eedb1SChandler Carruth           continue;
1428693eedb1SChandler Carruth         }
1429693eedb1SChandler Carruth 
1430693eedb1SChandler Carruth         // We just insert into the loop set here. We'll add these blocks to the
1431693eedb1SChandler Carruth         // exit loop after we build up the set in an order that doesn't rely on
1432693eedb1SChandler Carruth         // predecessor order (which in turn relies on use list order).
1433693eedb1SChandler Carruth         bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1434693eedb1SChandler Carruth         (void)Inserted;
1435693eedb1SChandler Carruth         assert(Inserted && "Should only visit an unlooped block once!");
1436693eedb1SChandler Carruth 
1437693eedb1SChandler Carruth         // And recurse through to its predecessors.
1438693eedb1SChandler Carruth         Worklist.push_back(PredBB);
1439693eedb1SChandler Carruth       }
1440693eedb1SChandler Carruth     } while (!Worklist.empty());
1441693eedb1SChandler Carruth   }
1442693eedb1SChandler Carruth 
1443693eedb1SChandler Carruth   // Now that the ExitLoopMap gives as  mapping for all the non-looping cloned
1444693eedb1SChandler Carruth   // blocks to their outer loops, walk the cloned blocks and the cloned exits
1445693eedb1SChandler Carruth   // in their original order adding them to the correct loop.
1446693eedb1SChandler Carruth 
1447693eedb1SChandler Carruth   // We need a stable insertion order. We use the order of the original loop
1448693eedb1SChandler Carruth   // order and map into the correct parent loop.
1449693eedb1SChandler Carruth   for (auto *BB : llvm::concat<BasicBlock *const>(
1450693eedb1SChandler Carruth            makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1451693eedb1SChandler Carruth     if (Loop *OuterL = ExitLoopMap.lookup(BB))
1452693eedb1SChandler Carruth       OuterL->addBasicBlockToLoop(BB, LI);
1453693eedb1SChandler Carruth 
1454693eedb1SChandler Carruth #ifndef NDEBUG
1455693eedb1SChandler Carruth   for (auto &BBAndL : ExitLoopMap) {
1456693eedb1SChandler Carruth     auto *BB = BBAndL.first;
1457693eedb1SChandler Carruth     auto *OuterL = BBAndL.second;
1458693eedb1SChandler Carruth     assert(LI.getLoopFor(BB) == OuterL &&
1459693eedb1SChandler Carruth            "Failed to put all blocks into outer loops!");
1460693eedb1SChandler Carruth   }
1461693eedb1SChandler Carruth #endif
1462693eedb1SChandler Carruth 
1463693eedb1SChandler Carruth   // Now that all the blocks are placed into the correct containing loop in the
1464693eedb1SChandler Carruth   // absence of child loops, find all the potentially cloned child loops and
1465693eedb1SChandler Carruth   // clone them into whatever outer loop we placed their header into.
1466693eedb1SChandler Carruth   for (Loop *ChildL : OrigL) {
1467693eedb1SChandler Carruth     auto *ClonedChildHeader =
1468693eedb1SChandler Carruth         cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1469693eedb1SChandler Carruth     if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1470693eedb1SChandler Carruth       continue;
1471693eedb1SChandler Carruth 
1472693eedb1SChandler Carruth #ifndef NDEBUG
1473693eedb1SChandler Carruth     for (auto *ChildLoopBB : ChildL->blocks())
1474693eedb1SChandler Carruth       assert(VMap.count(ChildLoopBB) &&
1475693eedb1SChandler Carruth              "Cloned a child loop header but not all of that loops blocks!");
1476693eedb1SChandler Carruth #endif
1477693eedb1SChandler Carruth 
1478693eedb1SChandler Carruth     NonChildClonedLoops.push_back(cloneLoopNest(
1479693eedb1SChandler Carruth         *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1480693eedb1SChandler Carruth   }
1481693eedb1SChandler Carruth }
1482693eedb1SChandler Carruth 
148369e68f84SChandler Carruth static void
14841652996fSChandler Carruth deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
14851652996fSChandler Carruth                        ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1486a2eebb82SAlina Sbirlea                        DominatorTree &DT, MemorySSAUpdater *MSSAU) {
14871652996fSChandler Carruth   // Find all the dead clones, and remove them from their successors.
14881652996fSChandler Carruth   SmallVector<BasicBlock *, 16> DeadBlocks;
14891652996fSChandler Carruth   for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
14901652996fSChandler Carruth     for (auto &VMap : VMaps)
14911652996fSChandler Carruth       if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
14921652996fSChandler Carruth         if (!DT.isReachableFromEntry(ClonedBB)) {
14931652996fSChandler Carruth           for (BasicBlock *SuccBB : successors(ClonedBB))
14941652996fSChandler Carruth             SuccBB->removePredecessor(ClonedBB);
14951652996fSChandler Carruth           DeadBlocks.push_back(ClonedBB);
14961652996fSChandler Carruth         }
14971652996fSChandler Carruth 
1498a2eebb82SAlina Sbirlea   // Remove all MemorySSA in the dead blocks
1499a2eebb82SAlina Sbirlea   if (MSSAU) {
1500db101864SAlina Sbirlea     SmallSetVector<BasicBlock *, 8> DeadBlockSet(DeadBlocks.begin(),
1501a2eebb82SAlina Sbirlea                                                  DeadBlocks.end());
1502a2eebb82SAlina Sbirlea     MSSAU->removeBlocks(DeadBlockSet);
1503a2eebb82SAlina Sbirlea   }
1504a2eebb82SAlina Sbirlea 
15051652996fSChandler Carruth   // Drop any remaining references to break cycles.
15061652996fSChandler Carruth   for (BasicBlock *BB : DeadBlocks)
15071652996fSChandler Carruth     BB->dropAllReferences();
15081652996fSChandler Carruth   // Erase them from the IR.
15091652996fSChandler Carruth   for (BasicBlock *BB : DeadBlocks)
15101652996fSChandler Carruth     BB->eraseFromParent();
15111652996fSChandler Carruth }
15121652996fSChandler Carruth 
1513a2eebb82SAlina Sbirlea static void deleteDeadBlocksFromLoop(Loop &L,
1514693eedb1SChandler Carruth                                      SmallVectorImpl<BasicBlock *> &ExitBlocks,
1515a2eebb82SAlina Sbirlea                                      DominatorTree &DT, LoopInfo &LI,
1516a2eebb82SAlina Sbirlea                                      MemorySSAUpdater *MSSAU) {
15178b6effd9SFedor Sergeev   // Find all the dead blocks tied to this loop, and remove them from their
15188b6effd9SFedor Sergeev   // successors.
1519db101864SAlina Sbirlea   SmallSetVector<BasicBlock *, 8> DeadBlockSet;
15207b49aa03SFedor Sergeev 
15218b6effd9SFedor Sergeev   // Start with loop/exit blocks and get a transitive closure of reachable dead
15228b6effd9SFedor Sergeev   // blocks.
15238b6effd9SFedor Sergeev   SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
15248b6effd9SFedor Sergeev                                                 ExitBlocks.end());
15258b6effd9SFedor Sergeev   DeathCandidates.append(L.blocks().begin(), L.blocks().end());
15268b6effd9SFedor Sergeev   while (!DeathCandidates.empty()) {
15278b6effd9SFedor Sergeev     auto *BB = DeathCandidates.pop_back_val();
15288b6effd9SFedor Sergeev     if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
15298b6effd9SFedor Sergeev       for (BasicBlock *SuccBB : successors(BB)) {
15301652996fSChandler Carruth         SuccBB->removePredecessor(BB);
15318b6effd9SFedor Sergeev         DeathCandidates.push_back(SuccBB);
15321652996fSChandler Carruth       }
15338b6effd9SFedor Sergeev       DeadBlockSet.insert(BB);
15348b6effd9SFedor Sergeev     }
15358b6effd9SFedor Sergeev   }
1536693eedb1SChandler Carruth 
1537a2eebb82SAlina Sbirlea   // Remove all MemorySSA in the dead blocks
1538a2eebb82SAlina Sbirlea   if (MSSAU)
1539a2eebb82SAlina Sbirlea     MSSAU->removeBlocks(DeadBlockSet);
1540a2eebb82SAlina Sbirlea 
1541693eedb1SChandler Carruth   // Filter out the dead blocks from the exit blocks list so that it can be
1542693eedb1SChandler Carruth   // used in the caller.
1543693eedb1SChandler Carruth   llvm::erase_if(ExitBlocks,
154469e68f84SChandler Carruth                  [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1545693eedb1SChandler Carruth 
1546693eedb1SChandler Carruth   // Walk from this loop up through its parents removing all of the dead blocks.
1547693eedb1SChandler Carruth   for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
15488b6effd9SFedor Sergeev     for (auto *BB : DeadBlockSet)
1549693eedb1SChandler Carruth       ParentL->getBlocksSet().erase(BB);
1550693eedb1SChandler Carruth     llvm::erase_if(ParentL->getBlocksVector(),
155169e68f84SChandler Carruth                    [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1552693eedb1SChandler Carruth   }
1553693eedb1SChandler Carruth 
1554693eedb1SChandler Carruth   // Now delete the dead child loops. This raw delete will clear them
1555693eedb1SChandler Carruth   // recursively.
1556693eedb1SChandler Carruth   llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
155769e68f84SChandler Carruth     if (!DeadBlockSet.count(ChildL->getHeader()))
1558693eedb1SChandler Carruth       return false;
1559693eedb1SChandler Carruth 
1560693eedb1SChandler Carruth     assert(llvm::all_of(ChildL->blocks(),
1561693eedb1SChandler Carruth                         [&](BasicBlock *ChildBB) {
156269e68f84SChandler Carruth                           return DeadBlockSet.count(ChildBB);
1563693eedb1SChandler Carruth                         }) &&
1564693eedb1SChandler Carruth            "If the child loop header is dead all blocks in the child loop must "
1565693eedb1SChandler Carruth            "be dead as well!");
1566693eedb1SChandler Carruth     LI.destroy(ChildL);
1567693eedb1SChandler Carruth     return true;
1568693eedb1SChandler Carruth   });
1569693eedb1SChandler Carruth 
157069e68f84SChandler Carruth   // Remove the loop mappings for the dead blocks and drop all the references
157169e68f84SChandler Carruth   // from these blocks to others to handle cyclic references as we start
157269e68f84SChandler Carruth   // deleting the blocks themselves.
15738b6effd9SFedor Sergeev   for (auto *BB : DeadBlockSet) {
157469e68f84SChandler Carruth     // Check that the dominator tree has already been updated.
157569e68f84SChandler Carruth     assert(!DT.getNode(BB) && "Should already have cleared domtree!");
1576693eedb1SChandler Carruth     LI.changeLoopFor(BB, nullptr);
1577693eedb1SChandler Carruth     BB->dropAllReferences();
1578693eedb1SChandler Carruth   }
157969e68f84SChandler Carruth 
158069e68f84SChandler Carruth   // Actually delete the blocks now that they've been fully unhooked from the
158169e68f84SChandler Carruth   // IR.
15827b49aa03SFedor Sergeev   for (auto *BB : DeadBlockSet)
158369e68f84SChandler Carruth     BB->eraseFromParent();
1584693eedb1SChandler Carruth }
1585693eedb1SChandler Carruth 
1586693eedb1SChandler Carruth /// Recompute the set of blocks in a loop after unswitching.
1587693eedb1SChandler Carruth ///
1588693eedb1SChandler Carruth /// This walks from the original headers predecessors to rebuild the loop. We
1589693eedb1SChandler Carruth /// take advantage of the fact that new blocks can't have been added, and so we
1590693eedb1SChandler Carruth /// filter by the original loop's blocks. This also handles potentially
1591693eedb1SChandler Carruth /// unreachable code that we don't want to explore but might be found examining
1592693eedb1SChandler Carruth /// the predecessors of the header.
1593693eedb1SChandler Carruth ///
1594693eedb1SChandler Carruth /// If the original loop is no longer a loop, this will return an empty set. If
1595693eedb1SChandler Carruth /// it remains a loop, all the blocks within it will be added to the set
1596693eedb1SChandler Carruth /// (including those blocks in inner loops).
1597693eedb1SChandler Carruth static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1598693eedb1SChandler Carruth                                                                  LoopInfo &LI) {
1599693eedb1SChandler Carruth   SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1600693eedb1SChandler Carruth 
1601693eedb1SChandler Carruth   auto *PH = L.getLoopPreheader();
1602693eedb1SChandler Carruth   auto *Header = L.getHeader();
1603693eedb1SChandler Carruth 
1604693eedb1SChandler Carruth   // A worklist to use while walking backwards from the header.
1605693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1606693eedb1SChandler Carruth 
1607693eedb1SChandler Carruth   // First walk the predecessors of the header to find the backedges. This will
1608693eedb1SChandler Carruth   // form the basis of our walk.
1609693eedb1SChandler Carruth   for (auto *Pred : predecessors(Header)) {
1610693eedb1SChandler Carruth     // Skip the preheader.
1611693eedb1SChandler Carruth     if (Pred == PH)
1612693eedb1SChandler Carruth       continue;
1613693eedb1SChandler Carruth 
1614693eedb1SChandler Carruth     // Because the loop was in simplified form, the only non-loop predecessor
1615693eedb1SChandler Carruth     // is the preheader.
1616693eedb1SChandler Carruth     assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1617693eedb1SChandler Carruth                                "than the preheader that is not part of the "
1618693eedb1SChandler Carruth                                "loop!");
1619693eedb1SChandler Carruth 
1620693eedb1SChandler Carruth     // Insert this block into the loop set and on the first visit and, if it
1621693eedb1SChandler Carruth     // isn't the header we're currently walking, put it into the worklist to
1622693eedb1SChandler Carruth     // recurse through.
1623693eedb1SChandler Carruth     if (LoopBlockSet.insert(Pred).second && Pred != Header)
1624693eedb1SChandler Carruth       Worklist.push_back(Pred);
1625693eedb1SChandler Carruth   }
1626693eedb1SChandler Carruth 
1627693eedb1SChandler Carruth   // If no backedges were found, we're done.
1628693eedb1SChandler Carruth   if (LoopBlockSet.empty())
1629693eedb1SChandler Carruth     return LoopBlockSet;
1630693eedb1SChandler Carruth 
1631693eedb1SChandler Carruth   // We found backedges, recurse through them to identify the loop blocks.
1632693eedb1SChandler Carruth   while (!Worklist.empty()) {
1633693eedb1SChandler Carruth     BasicBlock *BB = Worklist.pop_back_val();
1634693eedb1SChandler Carruth     assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1635693eedb1SChandler Carruth 
163643acdb35SChandler Carruth     // No need to walk past the header.
163743acdb35SChandler Carruth     if (BB == Header)
163843acdb35SChandler Carruth       continue;
163943acdb35SChandler Carruth 
1640693eedb1SChandler Carruth     // Because we know the inner loop structure remains valid we can use the
1641693eedb1SChandler Carruth     // loop structure to jump immediately across the entire nested loop.
1642693eedb1SChandler Carruth     // Further, because it is in loop simplified form, we can directly jump
1643693eedb1SChandler Carruth     // to its preheader afterward.
1644693eedb1SChandler Carruth     if (Loop *InnerL = LI.getLoopFor(BB))
1645693eedb1SChandler Carruth       if (InnerL != &L) {
1646693eedb1SChandler Carruth         assert(L.contains(InnerL) &&
1647693eedb1SChandler Carruth                "Should not reach a loop *outside* this loop!");
1648693eedb1SChandler Carruth         // The preheader is the only possible predecessor of the loop so
1649693eedb1SChandler Carruth         // insert it into the set and check whether it was already handled.
1650693eedb1SChandler Carruth         auto *InnerPH = InnerL->getLoopPreheader();
1651693eedb1SChandler Carruth         assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1652693eedb1SChandler Carruth                                       "but not contain the inner loop "
1653693eedb1SChandler Carruth                                       "preheader!");
1654693eedb1SChandler Carruth         if (!LoopBlockSet.insert(InnerPH).second)
1655693eedb1SChandler Carruth           // The only way to reach the preheader is through the loop body
1656693eedb1SChandler Carruth           // itself so if it has been visited the loop is already handled.
1657693eedb1SChandler Carruth           continue;
1658693eedb1SChandler Carruth 
1659693eedb1SChandler Carruth         // Insert all of the blocks (other than those already present) into
1660bf7190a1SChandler Carruth         // the loop set. We expect at least the block that led us to find the
1661bf7190a1SChandler Carruth         // inner loop to be in the block set, but we may also have other loop
1662bf7190a1SChandler Carruth         // blocks if they were already enqueued as predecessors of some other
1663bf7190a1SChandler Carruth         // outer loop block.
1664693eedb1SChandler Carruth         for (auto *InnerBB : InnerL->blocks()) {
1665693eedb1SChandler Carruth           if (InnerBB == BB) {
1666693eedb1SChandler Carruth             assert(LoopBlockSet.count(InnerBB) &&
1667693eedb1SChandler Carruth                    "Block should already be in the set!");
1668693eedb1SChandler Carruth             continue;
1669693eedb1SChandler Carruth           }
1670693eedb1SChandler Carruth 
1671bf7190a1SChandler Carruth           LoopBlockSet.insert(InnerBB);
1672693eedb1SChandler Carruth         }
1673693eedb1SChandler Carruth 
1674693eedb1SChandler Carruth         // Add the preheader to the worklist so we will continue past the
1675693eedb1SChandler Carruth         // loop body.
1676693eedb1SChandler Carruth         Worklist.push_back(InnerPH);
1677693eedb1SChandler Carruth         continue;
1678693eedb1SChandler Carruth       }
1679693eedb1SChandler Carruth 
1680693eedb1SChandler Carruth     // Insert any predecessors that were in the original loop into the new
1681693eedb1SChandler Carruth     // set, and if the insert is successful, add them to the worklist.
1682693eedb1SChandler Carruth     for (auto *Pred : predecessors(BB))
1683693eedb1SChandler Carruth       if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1684693eedb1SChandler Carruth         Worklist.push_back(Pred);
1685693eedb1SChandler Carruth   }
1686693eedb1SChandler Carruth 
168743acdb35SChandler Carruth   assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
168843acdb35SChandler Carruth 
1689693eedb1SChandler Carruth   // We've found all the blocks participating in the loop, return our completed
1690693eedb1SChandler Carruth   // set.
1691693eedb1SChandler Carruth   return LoopBlockSet;
1692693eedb1SChandler Carruth }
1693693eedb1SChandler Carruth 
1694693eedb1SChandler Carruth /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1695693eedb1SChandler Carruth ///
1696693eedb1SChandler Carruth /// The removal may have removed some child loops entirely but cannot have
1697693eedb1SChandler Carruth /// disturbed any remaining child loops. However, they may need to be hoisted
1698693eedb1SChandler Carruth /// to the parent loop (or to be top-level loops). The original loop may be
1699693eedb1SChandler Carruth /// completely removed.
1700693eedb1SChandler Carruth ///
1701693eedb1SChandler Carruth /// The sibling loops resulting from this update are returned. If the original
1702693eedb1SChandler Carruth /// loop remains a valid loop, it will be the first entry in this list with all
1703693eedb1SChandler Carruth /// of the newly sibling loops following it.
1704693eedb1SChandler Carruth ///
1705693eedb1SChandler Carruth /// Returns true if the loop remains a loop after unswitching, and false if it
1706693eedb1SChandler Carruth /// is no longer a loop after unswitching (and should not continue to be
1707693eedb1SChandler Carruth /// referenced).
1708693eedb1SChandler Carruth static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1709693eedb1SChandler Carruth                                      LoopInfo &LI,
1710693eedb1SChandler Carruth                                      SmallVectorImpl<Loop *> &HoistedLoops) {
1711693eedb1SChandler Carruth   auto *PH = L.getLoopPreheader();
1712693eedb1SChandler Carruth 
1713693eedb1SChandler Carruth   // Compute the actual parent loop from the exit blocks. Because we may have
1714693eedb1SChandler Carruth   // pruned some exits the loop may be different from the original parent.
1715693eedb1SChandler Carruth   Loop *ParentL = nullptr;
1716693eedb1SChandler Carruth   SmallVector<Loop *, 4> ExitLoops;
1717693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> ExitsInLoops;
1718693eedb1SChandler Carruth   ExitsInLoops.reserve(ExitBlocks.size());
1719693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks)
1720693eedb1SChandler Carruth     if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1721693eedb1SChandler Carruth       ExitLoops.push_back(ExitL);
1722693eedb1SChandler Carruth       ExitsInLoops.push_back(ExitBB);
1723693eedb1SChandler Carruth       if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1724693eedb1SChandler Carruth         ParentL = ExitL;
1725693eedb1SChandler Carruth     }
1726693eedb1SChandler Carruth 
1727693eedb1SChandler Carruth   // Recompute the blocks participating in this loop. This may be empty if it
1728693eedb1SChandler Carruth   // is no longer a loop.
1729693eedb1SChandler Carruth   auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1730693eedb1SChandler Carruth 
1731693eedb1SChandler Carruth   // If we still have a loop, we need to re-set the loop's parent as the exit
1732693eedb1SChandler Carruth   // block set changing may have moved it within the loop nest. Note that this
1733693eedb1SChandler Carruth   // can only happen when this loop has a parent as it can only hoist the loop
1734693eedb1SChandler Carruth   // *up* the nest.
1735693eedb1SChandler Carruth   if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1736693eedb1SChandler Carruth     // Remove this loop's (original) blocks from all of the intervening loops.
1737693eedb1SChandler Carruth     for (Loop *IL = L.getParentLoop(); IL != ParentL;
1738693eedb1SChandler Carruth          IL = IL->getParentLoop()) {
1739693eedb1SChandler Carruth       IL->getBlocksSet().erase(PH);
1740693eedb1SChandler Carruth       for (auto *BB : L.blocks())
1741693eedb1SChandler Carruth         IL->getBlocksSet().erase(BB);
1742693eedb1SChandler Carruth       llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1743693eedb1SChandler Carruth         return BB == PH || L.contains(BB);
1744693eedb1SChandler Carruth       });
1745693eedb1SChandler Carruth     }
1746693eedb1SChandler Carruth 
1747693eedb1SChandler Carruth     LI.changeLoopFor(PH, ParentL);
1748693eedb1SChandler Carruth     L.getParentLoop()->removeChildLoop(&L);
1749693eedb1SChandler Carruth     if (ParentL)
1750693eedb1SChandler Carruth       ParentL->addChildLoop(&L);
1751693eedb1SChandler Carruth     else
1752693eedb1SChandler Carruth       LI.addTopLevelLoop(&L);
1753693eedb1SChandler Carruth   }
1754693eedb1SChandler Carruth 
1755693eedb1SChandler Carruth   // Now we update all the blocks which are no longer within the loop.
1756693eedb1SChandler Carruth   auto &Blocks = L.getBlocksVector();
1757693eedb1SChandler Carruth   auto BlocksSplitI =
1758693eedb1SChandler Carruth       LoopBlockSet.empty()
1759693eedb1SChandler Carruth           ? Blocks.begin()
1760693eedb1SChandler Carruth           : std::stable_partition(
1761693eedb1SChandler Carruth                 Blocks.begin(), Blocks.end(),
1762693eedb1SChandler Carruth                 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1763693eedb1SChandler Carruth 
1764693eedb1SChandler Carruth   // Before we erase the list of unlooped blocks, build a set of them.
1765693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1766693eedb1SChandler Carruth   if (LoopBlockSet.empty())
1767693eedb1SChandler Carruth     UnloopedBlocks.insert(PH);
1768693eedb1SChandler Carruth 
1769693eedb1SChandler Carruth   // Now erase these blocks from the loop.
1770693eedb1SChandler Carruth   for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1771693eedb1SChandler Carruth     L.getBlocksSet().erase(BB);
1772693eedb1SChandler Carruth   Blocks.erase(BlocksSplitI, Blocks.end());
1773693eedb1SChandler Carruth 
1774693eedb1SChandler Carruth   // Sort the exits in ascending loop depth, we'll work backwards across these
1775693eedb1SChandler Carruth   // to process them inside out.
1776efd94c56SFangrui Song   llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1777693eedb1SChandler Carruth     return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1778693eedb1SChandler Carruth   });
1779693eedb1SChandler Carruth 
1780693eedb1SChandler Carruth   // We'll build up a set for each exit loop.
1781693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1782693eedb1SChandler Carruth   Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1783693eedb1SChandler Carruth 
1784693eedb1SChandler Carruth   auto RemoveUnloopedBlocksFromLoop =
1785693eedb1SChandler Carruth       [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1786693eedb1SChandler Carruth         for (auto *BB : UnloopedBlocks)
1787693eedb1SChandler Carruth           L.getBlocksSet().erase(BB);
1788693eedb1SChandler Carruth         llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1789693eedb1SChandler Carruth           return UnloopedBlocks.count(BB);
1790693eedb1SChandler Carruth         });
1791693eedb1SChandler Carruth       };
1792693eedb1SChandler Carruth 
1793693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1794693eedb1SChandler Carruth   while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1795693eedb1SChandler Carruth     assert(Worklist.empty() && "Didn't clear worklist!");
1796693eedb1SChandler Carruth     assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1797693eedb1SChandler Carruth 
1798693eedb1SChandler Carruth     // Grab the next exit block, in decreasing loop depth order.
1799693eedb1SChandler Carruth     BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1800693eedb1SChandler Carruth     Loop &ExitL = *LI.getLoopFor(ExitBB);
1801693eedb1SChandler Carruth     assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1802693eedb1SChandler Carruth 
1803693eedb1SChandler Carruth     // Erase all of the unlooped blocks from the loops between the previous
1804693eedb1SChandler Carruth     // exit loop and this exit loop. This works because the ExitInLoops list is
1805693eedb1SChandler Carruth     // sorted in increasing order of loop depth and thus we visit loops in
1806693eedb1SChandler Carruth     // decreasing order of loop depth.
1807693eedb1SChandler Carruth     for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1808693eedb1SChandler Carruth       RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1809693eedb1SChandler Carruth 
1810693eedb1SChandler Carruth     // Walk the CFG back until we hit the cloned PH adding everything reachable
1811693eedb1SChandler Carruth     // and in the unlooped set to this exit block's loop.
1812693eedb1SChandler Carruth     Worklist.push_back(ExitBB);
1813693eedb1SChandler Carruth     do {
1814693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1815693eedb1SChandler Carruth       // We can stop recursing at the cloned preheader (if we get there).
1816693eedb1SChandler Carruth       if (BB == PH)
1817693eedb1SChandler Carruth         continue;
1818693eedb1SChandler Carruth 
1819693eedb1SChandler Carruth       for (BasicBlock *PredBB : predecessors(BB)) {
1820693eedb1SChandler Carruth         // If this pred has already been moved to our set or is part of some
1821693eedb1SChandler Carruth         // (inner) loop, no update needed.
1822693eedb1SChandler Carruth         if (!UnloopedBlocks.erase(PredBB)) {
1823693eedb1SChandler Carruth           assert((NewExitLoopBlocks.count(PredBB) ||
1824693eedb1SChandler Carruth                   ExitL.contains(LI.getLoopFor(PredBB))) &&
1825693eedb1SChandler Carruth                  "Predecessor not in a nested loop (or already visited)!");
1826693eedb1SChandler Carruth           continue;
1827693eedb1SChandler Carruth         }
1828693eedb1SChandler Carruth 
1829693eedb1SChandler Carruth         // We just insert into the loop set here. We'll add these blocks to the
1830693eedb1SChandler Carruth         // exit loop after we build up the set in a deterministic order rather
1831693eedb1SChandler Carruth         // than the predecessor-influenced visit order.
1832693eedb1SChandler Carruth         bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1833693eedb1SChandler Carruth         (void)Inserted;
1834693eedb1SChandler Carruth         assert(Inserted && "Should only visit an unlooped block once!");
1835693eedb1SChandler Carruth 
1836693eedb1SChandler Carruth         // And recurse through to its predecessors.
1837693eedb1SChandler Carruth         Worklist.push_back(PredBB);
1838693eedb1SChandler Carruth       }
1839693eedb1SChandler Carruth     } while (!Worklist.empty());
1840693eedb1SChandler Carruth 
1841693eedb1SChandler Carruth     // If blocks in this exit loop were directly part of the original loop (as
1842693eedb1SChandler Carruth     // opposed to a child loop) update the map to point to this exit loop. This
1843693eedb1SChandler Carruth     // just updates a map and so the fact that the order is unstable is fine.
1844693eedb1SChandler Carruth     for (auto *BB : NewExitLoopBlocks)
1845693eedb1SChandler Carruth       if (Loop *BBL = LI.getLoopFor(BB))
1846693eedb1SChandler Carruth         if (BBL == &L || !L.contains(BBL))
1847693eedb1SChandler Carruth           LI.changeLoopFor(BB, &ExitL);
1848693eedb1SChandler Carruth 
1849693eedb1SChandler Carruth     // We will remove the remaining unlooped blocks from this loop in the next
1850693eedb1SChandler Carruth     // iteration or below.
1851693eedb1SChandler Carruth     NewExitLoopBlocks.clear();
1852693eedb1SChandler Carruth   }
1853693eedb1SChandler Carruth 
1854693eedb1SChandler Carruth   // Any remaining unlooped blocks are no longer part of any loop unless they
1855693eedb1SChandler Carruth   // are part of some child loop.
1856693eedb1SChandler Carruth   for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1857693eedb1SChandler Carruth     RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1858693eedb1SChandler Carruth   for (auto *BB : UnloopedBlocks)
1859693eedb1SChandler Carruth     if (Loop *BBL = LI.getLoopFor(BB))
1860693eedb1SChandler Carruth       if (BBL == &L || !L.contains(BBL))
1861693eedb1SChandler Carruth         LI.changeLoopFor(BB, nullptr);
1862693eedb1SChandler Carruth 
1863693eedb1SChandler Carruth   // Sink all the child loops whose headers are no longer in the loop set to
1864693eedb1SChandler Carruth   // the parent (or to be top level loops). We reach into the loop and directly
1865693eedb1SChandler Carruth   // update its subloop vector to make this batch update efficient.
1866693eedb1SChandler Carruth   auto &SubLoops = L.getSubLoopsVector();
1867693eedb1SChandler Carruth   auto SubLoopsSplitI =
1868693eedb1SChandler Carruth       LoopBlockSet.empty()
1869693eedb1SChandler Carruth           ? SubLoops.begin()
1870693eedb1SChandler Carruth           : std::stable_partition(
1871693eedb1SChandler Carruth                 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1872693eedb1SChandler Carruth                   return LoopBlockSet.count(SubL->getHeader());
1873693eedb1SChandler Carruth                 });
1874693eedb1SChandler Carruth   for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1875693eedb1SChandler Carruth     HoistedLoops.push_back(HoistedL);
1876693eedb1SChandler Carruth     HoistedL->setParentLoop(nullptr);
1877693eedb1SChandler Carruth 
1878693eedb1SChandler Carruth     // To compute the new parent of this hoisted loop we look at where we
1879693eedb1SChandler Carruth     // placed the preheader above. We can't lookup the header itself because we
1880693eedb1SChandler Carruth     // retained the mapping from the header to the hoisted loop. But the
1881693eedb1SChandler Carruth     // preheader and header should have the exact same new parent computed
1882693eedb1SChandler Carruth     // based on the set of exit blocks from the original loop as the preheader
1883693eedb1SChandler Carruth     // is a predecessor of the header and so reached in the reverse walk. And
1884693eedb1SChandler Carruth     // because the loops were all in simplified form the preheader of the
1885693eedb1SChandler Carruth     // hoisted loop can't be part of some *other* loop.
1886693eedb1SChandler Carruth     if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1887693eedb1SChandler Carruth       NewParentL->addChildLoop(HoistedL);
1888693eedb1SChandler Carruth     else
1889693eedb1SChandler Carruth       LI.addTopLevelLoop(HoistedL);
1890693eedb1SChandler Carruth   }
1891693eedb1SChandler Carruth   SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1892693eedb1SChandler Carruth 
1893693eedb1SChandler Carruth   // Actually delete the loop if nothing remained within it.
1894693eedb1SChandler Carruth   if (Blocks.empty()) {
1895693eedb1SChandler Carruth     assert(SubLoops.empty() &&
1896693eedb1SChandler Carruth            "Failed to remove all subloops from the original loop!");
1897693eedb1SChandler Carruth     if (Loop *ParentL = L.getParentLoop())
1898693eedb1SChandler Carruth       ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1899693eedb1SChandler Carruth     else
1900693eedb1SChandler Carruth       LI.removeLoop(llvm::find(LI, &L));
1901693eedb1SChandler Carruth     LI.destroy(&L);
1902693eedb1SChandler Carruth     return false;
1903693eedb1SChandler Carruth   }
1904693eedb1SChandler Carruth 
1905693eedb1SChandler Carruth   return true;
1906693eedb1SChandler Carruth }
1907693eedb1SChandler Carruth 
1908693eedb1SChandler Carruth /// Helper to visit a dominator subtree, invoking a callable on each node.
1909693eedb1SChandler Carruth ///
1910693eedb1SChandler Carruth /// Returning false at any point will stop walking past that node of the tree.
1911693eedb1SChandler Carruth template <typename CallableT>
1912693eedb1SChandler Carruth void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1913693eedb1SChandler Carruth   SmallVector<DomTreeNode *, 4> DomWorklist;
1914693eedb1SChandler Carruth   DomWorklist.push_back(DT[BB]);
1915693eedb1SChandler Carruth #ifndef NDEBUG
1916693eedb1SChandler Carruth   SmallPtrSet<DomTreeNode *, 4> Visited;
1917693eedb1SChandler Carruth   Visited.insert(DT[BB]);
1918693eedb1SChandler Carruth #endif
1919693eedb1SChandler Carruth   do {
1920693eedb1SChandler Carruth     DomTreeNode *N = DomWorklist.pop_back_val();
1921693eedb1SChandler Carruth 
1922693eedb1SChandler Carruth     // Visit this node.
1923693eedb1SChandler Carruth     if (!Callable(N->getBlock()))
1924693eedb1SChandler Carruth       continue;
1925693eedb1SChandler Carruth 
1926693eedb1SChandler Carruth     // Accumulate the child nodes.
1927693eedb1SChandler Carruth     for (DomTreeNode *ChildN : *N) {
1928693eedb1SChandler Carruth       assert(Visited.insert(ChildN).second &&
1929693eedb1SChandler Carruth              "Cannot visit a node twice when walking a tree!");
1930693eedb1SChandler Carruth       DomWorklist.push_back(ChildN);
1931693eedb1SChandler Carruth     }
1932693eedb1SChandler Carruth   } while (!DomWorklist.empty());
1933693eedb1SChandler Carruth }
1934693eedb1SChandler Carruth 
1935bde31000SMax Kazantsev static void unswitchNontrivialInvariants(
193660b2e054SChandler Carruth     Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
1937bde31000SMax Kazantsev     SmallVectorImpl<BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI,
1938bde31000SMax Kazantsev     AssumptionCache &AC, function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
1939a2eebb82SAlina Sbirlea     ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
19401652996fSChandler Carruth   auto *ParentBB = TI.getParent();
19411652996fSChandler Carruth   BranchInst *BI = dyn_cast<BranchInst>(&TI);
19421652996fSChandler Carruth   SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
1943d1dab0c3SChandler Carruth 
19441652996fSChandler Carruth   // We can only unswitch switches, conditional branches with an invariant
19451652996fSChandler Carruth   // condition, or combining invariant conditions with an instruction.
1946c598ef7fSSimon Pilgrim   assert((SI || (BI && BI->isConditional())) &&
19471652996fSChandler Carruth          "Can only unswitch switches and conditional branch!");
19481652996fSChandler Carruth   bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
1949d1dab0c3SChandler Carruth   if (FullUnswitch)
1950d1dab0c3SChandler Carruth     assert(Invariants.size() == 1 &&
1951d1dab0c3SChandler Carruth            "Cannot have other invariants with full unswitching!");
1952d1dab0c3SChandler Carruth   else
19531652996fSChandler Carruth     assert(isa<Instruction>(BI->getCondition()) &&
1954d1dab0c3SChandler Carruth            "Partial unswitching requires an instruction as the condition!");
1955d1dab0c3SChandler Carruth 
1956a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
1957a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
1958a2eebb82SAlina Sbirlea 
1959d1dab0c3SChandler Carruth   // Constant and BBs tracking the cloned and continuing successor. When we are
1960d1dab0c3SChandler Carruth   // unswitching the entire condition, this can just be trivially chosen to
1961d1dab0c3SChandler Carruth   // unswitch towards `true`. However, when we are unswitching a set of
1962d1dab0c3SChandler Carruth   // invariants combined with `and` or `or`, the combining operation determines
1963d1dab0c3SChandler Carruth   // the best direction to unswitch: we want to unswitch the direction that will
1964d1dab0c3SChandler Carruth   // collapse the branch.
1965d1dab0c3SChandler Carruth   bool Direction = true;
1966d1dab0c3SChandler Carruth   int ClonedSucc = 0;
1967d1dab0c3SChandler Carruth   if (!FullUnswitch) {
19681652996fSChandler Carruth     if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
19691652996fSChandler Carruth       assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
19701652996fSChandler Carruth                  Instruction::And &&
19711652996fSChandler Carruth              "Only `or` and `and` instructions can combine invariants being "
19721652996fSChandler Carruth              "unswitched.");
1973d1dab0c3SChandler Carruth       Direction = false;
1974d1dab0c3SChandler Carruth       ClonedSucc = 1;
1975d1dab0c3SChandler Carruth     }
1976d1dab0c3SChandler Carruth   }
1977693eedb1SChandler Carruth 
19781652996fSChandler Carruth   BasicBlock *RetainedSuccBB =
19791652996fSChandler Carruth       BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
19801652996fSChandler Carruth   SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
19811652996fSChandler Carruth   if (BI)
19821652996fSChandler Carruth     UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
19831652996fSChandler Carruth   else
19841652996fSChandler Carruth     for (auto Case : SI->cases())
1985ed296543SChandler Carruth       if (Case.getCaseSuccessor() != RetainedSuccBB)
19861652996fSChandler Carruth         UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
19871652996fSChandler Carruth 
19881652996fSChandler Carruth   assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
19891652996fSChandler Carruth          "Should not unswitch the same successor we are retaining!");
1990693eedb1SChandler Carruth 
1991693eedb1SChandler Carruth   // The branch should be in this exact loop. Any inner loop's invariant branch
1992693eedb1SChandler Carruth   // should be handled by unswitching that inner loop. The caller of this
1993693eedb1SChandler Carruth   // routine should filter out any candidates that remain (but were skipped for
1994693eedb1SChandler Carruth   // whatever reason).
1995693eedb1SChandler Carruth   assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1996693eedb1SChandler Carruth 
1997693eedb1SChandler Carruth   // Compute the parent loop now before we start hacking on things.
1998693eedb1SChandler Carruth   Loop *ParentL = L.getParentLoop();
1999a2eebb82SAlina Sbirlea   // Get blocks in RPO order for MSSA update, before changing the CFG.
2000a2eebb82SAlina Sbirlea   LoopBlocksRPO LBRPO(&L);
2001a2eebb82SAlina Sbirlea   if (MSSAU)
2002a2eebb82SAlina Sbirlea     LBRPO.perform(&LI);
2003693eedb1SChandler Carruth 
2004693eedb1SChandler Carruth   // Compute the outer-most loop containing one of our exit blocks. This is the
2005693eedb1SChandler Carruth   // furthest up our loopnest which can be mutated, which we will use below to
2006693eedb1SChandler Carruth   // update things.
2007693eedb1SChandler Carruth   Loop *OuterExitL = &L;
2008693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks) {
2009693eedb1SChandler Carruth     Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
2010693eedb1SChandler Carruth     if (!NewOuterExitL) {
2011693eedb1SChandler Carruth       // We exited the entire nest with this block, so we're done.
2012693eedb1SChandler Carruth       OuterExitL = nullptr;
2013693eedb1SChandler Carruth       break;
2014693eedb1SChandler Carruth     }
2015693eedb1SChandler Carruth     if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
2016693eedb1SChandler Carruth       OuterExitL = NewOuterExitL;
2017693eedb1SChandler Carruth   }
2018693eedb1SChandler Carruth 
20193897ded6SChandler Carruth   // At this point, we're definitely going to unswitch something so invalidate
20203897ded6SChandler Carruth   // any cached information in ScalarEvolution for the outer most loop
20213897ded6SChandler Carruth   // containing an exit block and all nested loops.
20223897ded6SChandler Carruth   if (SE) {
20233897ded6SChandler Carruth     if (OuterExitL)
20243897ded6SChandler Carruth       SE->forgetLoop(OuterExitL);
20253897ded6SChandler Carruth     else
20263897ded6SChandler Carruth       SE->forgetTopmostLoop(&L);
20273897ded6SChandler Carruth   }
20283897ded6SChandler Carruth 
20291652996fSChandler Carruth   // If the edge from this terminator to a successor dominates that successor,
20301652996fSChandler Carruth   // store a map from each block in its dominator subtree to it. This lets us
20311652996fSChandler Carruth   // tell when cloning for a particular successor if a block is dominated by
20321652996fSChandler Carruth   // some *other* successor with a single data structure. We use this to
20331652996fSChandler Carruth   // significantly reduce cloning.
20341652996fSChandler Carruth   SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
20351652996fSChandler Carruth   for (auto *SuccBB : llvm::concat<BasicBlock *const>(
20361652996fSChandler Carruth            makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
20371652996fSChandler Carruth     if (SuccBB->getUniquePredecessor() ||
20381652996fSChandler Carruth         llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
20391652996fSChandler Carruth           return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
20401652996fSChandler Carruth         }))
20411652996fSChandler Carruth       visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
20421652996fSChandler Carruth         DominatingSucc[BB] = SuccBB;
2043693eedb1SChandler Carruth         return true;
2044693eedb1SChandler Carruth       });
2045693eedb1SChandler Carruth 
2046693eedb1SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
2047693eedb1SChandler Carruth   // the conditional branch. We will change the preheader to have a conditional
2048693eedb1SChandler Carruth   // branch on LoopCond. The original preheader will become the split point
2049693eedb1SChandler Carruth   // between the unswitched versions, and we will have a new preheader for the
2050693eedb1SChandler Carruth   // original loop.
2051693eedb1SChandler Carruth   BasicBlock *SplitBB = L.getLoopPreheader();
2052a2eebb82SAlina Sbirlea   BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
2053693eedb1SChandler Carruth 
205469e68f84SChandler Carruth   // Keep track of the dominator tree updates needed.
205569e68f84SChandler Carruth   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
205669e68f84SChandler Carruth 
20571652996fSChandler Carruth   // Clone the loop for each unswitched successor.
20581652996fSChandler Carruth   SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
20591652996fSChandler Carruth   VMaps.reserve(UnswitchedSuccBBs.size());
20601652996fSChandler Carruth   SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
20611652996fSChandler Carruth   for (auto *SuccBB : UnswitchedSuccBBs) {
20621652996fSChandler Carruth     VMaps.emplace_back(new ValueToValueMapTy());
20631652996fSChandler Carruth     ClonedPHs[SuccBB] = buildClonedLoopBlocks(
20641652996fSChandler Carruth         L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2065a2eebb82SAlina Sbirlea         DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
20661652996fSChandler Carruth   }
2067693eedb1SChandler Carruth 
2068d1dab0c3SChandler Carruth   // The stitching of the branched code back together depends on whether we're
2069d1dab0c3SChandler Carruth   // doing full unswitching or not with the exception that we always want to
2070d1dab0c3SChandler Carruth   // nuke the initial terminator placed in the split block.
2071d1dab0c3SChandler Carruth   SplitBB->getTerminator()->eraseFromParent();
2072d1dab0c3SChandler Carruth   if (FullUnswitch) {
2073a2eebb82SAlina Sbirlea     // Splice the terminator from the original loop and rewrite its
2074a2eebb82SAlina Sbirlea     // successors.
2075a2eebb82SAlina Sbirlea     SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2076a2eebb82SAlina Sbirlea 
2077a2eebb82SAlina Sbirlea     // Keep a clone of the terminator for MSSA updates.
2078a2eebb82SAlina Sbirlea     Instruction *NewTI = TI.clone();
2079a2eebb82SAlina Sbirlea     ParentBB->getInstList().push_back(NewTI);
2080a2eebb82SAlina Sbirlea 
2081a2eebb82SAlina Sbirlea     // First wire up the moved terminator to the preheaders.
2082a2eebb82SAlina Sbirlea     if (BI) {
2083a2eebb82SAlina Sbirlea       BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2084a2eebb82SAlina Sbirlea       BI->setSuccessor(ClonedSucc, ClonedPH);
2085a2eebb82SAlina Sbirlea       BI->setSuccessor(1 - ClonedSucc, LoopPH);
2086a2eebb82SAlina Sbirlea       DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2087a2eebb82SAlina Sbirlea     } else {
2088a2eebb82SAlina Sbirlea       assert(SI && "Must either be a branch or switch!");
2089a2eebb82SAlina Sbirlea 
2090a2eebb82SAlina Sbirlea       // Walk the cases and directly update their successors.
2091a2eebb82SAlina Sbirlea       assert(SI->getDefaultDest() == RetainedSuccBB &&
2092a2eebb82SAlina Sbirlea              "Not retaining default successor!");
2093a2eebb82SAlina Sbirlea       SI->setDefaultDest(LoopPH);
2094a2eebb82SAlina Sbirlea       for (auto &Case : SI->cases())
2095a2eebb82SAlina Sbirlea         if (Case.getCaseSuccessor() == RetainedSuccBB)
2096a2eebb82SAlina Sbirlea           Case.setSuccessor(LoopPH);
2097a2eebb82SAlina Sbirlea         else
2098a2eebb82SAlina Sbirlea           Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2099a2eebb82SAlina Sbirlea 
2100a2eebb82SAlina Sbirlea       // We need to use the set to populate domtree updates as even when there
2101a2eebb82SAlina Sbirlea       // are multiple cases pointing at the same successor we only want to
2102a2eebb82SAlina Sbirlea       // remove and insert one edge in the domtree.
2103a2eebb82SAlina Sbirlea       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2104a2eebb82SAlina Sbirlea         DTUpdates.push_back(
2105a2eebb82SAlina Sbirlea             {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2106a2eebb82SAlina Sbirlea     }
2107a2eebb82SAlina Sbirlea 
2108a2eebb82SAlina Sbirlea     if (MSSAU) {
2109a2eebb82SAlina Sbirlea       DT.applyUpdates(DTUpdates);
2110a2eebb82SAlina Sbirlea       DTUpdates.clear();
2111a2eebb82SAlina Sbirlea 
2112a2eebb82SAlina Sbirlea       // Remove all but one edge to the retained block and all unswitched
2113a2eebb82SAlina Sbirlea       // blocks. This is to avoid having duplicate entries in the cloned Phis,
2114a2eebb82SAlina Sbirlea       // when we know we only keep a single edge for each case.
2115a2eebb82SAlina Sbirlea       MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2116a2eebb82SAlina Sbirlea       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2117a2eebb82SAlina Sbirlea         MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2118a2eebb82SAlina Sbirlea 
2119a2eebb82SAlina Sbirlea       for (auto &VMap : VMaps)
2120a2eebb82SAlina Sbirlea         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2121a2eebb82SAlina Sbirlea                                    /*IgnoreIncomingWithNoClones=*/true);
2122a2eebb82SAlina Sbirlea       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2123a2eebb82SAlina Sbirlea 
2124a2eebb82SAlina Sbirlea       // Remove all edges to unswitched blocks.
2125a2eebb82SAlina Sbirlea       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2126a2eebb82SAlina Sbirlea         MSSAU->removeEdge(ParentBB, SuccBB);
2127a2eebb82SAlina Sbirlea     }
2128a2eebb82SAlina Sbirlea 
2129a2eebb82SAlina Sbirlea     // Now unhook the successor relationship as we'll be replacing
2130ed296543SChandler Carruth     // the terminator with a direct branch. This is much simpler for branches
2131ed296543SChandler Carruth     // than switches so we handle those first.
2132ed296543SChandler Carruth     if (BI) {
21331652996fSChandler Carruth       // Remove the parent as a predecessor of the unswitched successor.
2134ed296543SChandler Carruth       assert(UnswitchedSuccBBs.size() == 1 &&
2135ed296543SChandler Carruth              "Only one possible unswitched block for a branch!");
2136ed296543SChandler Carruth       BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2137ed296543SChandler Carruth       UnswitchedSuccBB->removePredecessor(ParentBB,
213820b91899SMax Kazantsev                                           /*KeepOneInputPHIs*/ true);
2139ed296543SChandler Carruth       DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2140ed296543SChandler Carruth     } else {
2141ed296543SChandler Carruth       // Note that we actually want to remove the parent block as a predecessor
2142ed296543SChandler Carruth       // of *every* case successor. The case successor is either unswitched,
2143ed296543SChandler Carruth       // completely eliminating an edge from the parent to that successor, or it
2144ed296543SChandler Carruth       // is a duplicate edge to the retained successor as the retained successor
2145ed296543SChandler Carruth       // is always the default successor and as we'll replace this with a direct
2146ed296543SChandler Carruth       // branch we no longer need the duplicate entries in the PHI nodes.
2147a2eebb82SAlina Sbirlea       SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2148a2eebb82SAlina Sbirlea       assert(NewSI->getDefaultDest() == RetainedSuccBB &&
2149ed296543SChandler Carruth              "Not retaining default successor!");
2150a2eebb82SAlina Sbirlea       for (auto &Case : NewSI->cases())
2151ed296543SChandler Carruth         Case.getCaseSuccessor()->removePredecessor(
2152ed296543SChandler Carruth             ParentBB,
215320b91899SMax Kazantsev             /*KeepOneInputPHIs*/ true);
2154ed296543SChandler Carruth 
2155ed296543SChandler Carruth       // We need to use the set to populate domtree updates as even when there
2156ed296543SChandler Carruth       // are multiple cases pointing at the same successor we only want to
2157ed296543SChandler Carruth       // remove and insert one edge in the domtree.
2158ed296543SChandler Carruth       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
21591652996fSChandler Carruth         DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
21601652996fSChandler Carruth     }
2161693eedb1SChandler Carruth 
2162a2eebb82SAlina Sbirlea     // After MSSAU update, remove the cloned terminator instruction NewTI.
2163a2eebb82SAlina Sbirlea     ParentBB->getTerminator()->eraseFromParent();
2164693eedb1SChandler Carruth 
2165693eedb1SChandler Carruth     // Create a new unconditional branch to the continuing block (as opposed to
2166693eedb1SChandler Carruth     // the one cloned).
21671652996fSChandler Carruth     BranchInst::Create(RetainedSuccBB, ParentBB);
2168d1dab0c3SChandler Carruth   } else {
21691652996fSChandler Carruth     assert(BI && "Only branches have partial unswitching.");
21701652996fSChandler Carruth     assert(UnswitchedSuccBBs.size() == 1 &&
21711652996fSChandler Carruth            "Only one possible unswitched block for a branch!");
21721652996fSChandler Carruth     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2173d1dab0c3SChandler Carruth     // When doing a partial unswitch, we have to do a bit more work to build up
2174d1dab0c3SChandler Carruth     // the branch in the split block.
2175d1dab0c3SChandler Carruth     buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
21762b5a8976SJuneyoung Lee                                           *ClonedPH, *LoopPH);
217735c8af18SAlina Sbirlea     DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
217835c8af18SAlina Sbirlea 
2179b7a33530SAlina Sbirlea     if (MSSAU) {
218035c8af18SAlina Sbirlea       DT.applyUpdates(DTUpdates);
218135c8af18SAlina Sbirlea       DTUpdates.clear();
218235c8af18SAlina Sbirlea 
2183b7a33530SAlina Sbirlea       // Perform MSSA cloning updates.
2184b7a33530SAlina Sbirlea       for (auto &VMap : VMaps)
2185b7a33530SAlina Sbirlea         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2186b7a33530SAlina Sbirlea                                    /*IgnoreIncomingWithNoClones=*/true);
2187b7a33530SAlina Sbirlea       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2188b7a33530SAlina Sbirlea     }
21891652996fSChandler Carruth   }
21901652996fSChandler Carruth 
21911652996fSChandler Carruth   // Apply the updates accumulated above to get an up-to-date dominator tree.
219269e68f84SChandler Carruth   DT.applyUpdates(DTUpdates);
219369e68f84SChandler Carruth 
21941652996fSChandler Carruth   // Now that we have an accurate dominator tree, first delete the dead cloned
21951652996fSChandler Carruth   // blocks so that we can accurately build any cloned loops. It is important to
21961652996fSChandler Carruth   // not delete the blocks from the original loop yet because we still want to
21971652996fSChandler Carruth   // reference the original loop to understand the cloned loop's structure.
2198a2eebb82SAlina Sbirlea   deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
21991652996fSChandler Carruth 
220069e68f84SChandler Carruth   // Build the cloned loop structure itself. This may be substantially
220169e68f84SChandler Carruth   // different from the original structure due to the simplified CFG. This also
220269e68f84SChandler Carruth   // handles inserting all the cloned blocks into the correct loops.
220369e68f84SChandler Carruth   SmallVector<Loop *, 4> NonChildClonedLoops;
22041652996fSChandler Carruth   for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
22051652996fSChandler Carruth     buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
220669e68f84SChandler Carruth 
22071652996fSChandler Carruth   // Now that our cloned loops have been built, we can update the original loop.
22081652996fSChandler Carruth   // First we delete the dead blocks from it and then we rebuild the loop
22091652996fSChandler Carruth   // structure taking these deletions into account.
2210a2eebb82SAlina Sbirlea   deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU);
2211a2eebb82SAlina Sbirlea 
2212a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
2213a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
2214a2eebb82SAlina Sbirlea 
2215693eedb1SChandler Carruth   SmallVector<Loop *, 4> HoistedLoops;
2216693eedb1SChandler Carruth   bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2217693eedb1SChandler Carruth 
2218a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
2219a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
2220a2eebb82SAlina Sbirlea 
222169e68f84SChandler Carruth   // This transformation has a high risk of corrupting the dominator tree, and
222269e68f84SChandler Carruth   // the below steps to rebuild loop structures will result in hard to debug
222369e68f84SChandler Carruth   // errors in that case so verify that the dominator tree is sane first.
222469e68f84SChandler Carruth   // FIXME: Remove this when the bugs stop showing up and rely on existing
222569e68f84SChandler Carruth   // verification steps.
222669e68f84SChandler Carruth   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2227693eedb1SChandler Carruth 
22281652996fSChandler Carruth   if (BI) {
22291652996fSChandler Carruth     // If we unswitched a branch which collapses the condition to a known
22301652996fSChandler Carruth     // constant we want to replace all the uses of the invariants within both
22311652996fSChandler Carruth     // the original and cloned blocks. We do this here so that we can use the
22321652996fSChandler Carruth     // now updated dominator tree to identify which side the users are on.
22331652996fSChandler Carruth     assert(UnswitchedSuccBBs.size() == 1 &&
22341652996fSChandler Carruth            "Only one possible unswitched block for a branch!");
22351652996fSChandler Carruth     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2236f9a02a70SFedor Sergeev 
2237f9a02a70SFedor Sergeev     // When considering multiple partially-unswitched invariants
2238f9a02a70SFedor Sergeev     // we cant just go replace them with constants in both branches.
2239f9a02a70SFedor Sergeev     //
2240f9a02a70SFedor Sergeev     // For 'AND' we infer that true branch ("continue") means true
2241f9a02a70SFedor Sergeev     // for each invariant operand.
2242f9a02a70SFedor Sergeev     // For 'OR' we can infer that false branch ("continue") means false
2243f9a02a70SFedor Sergeev     // for each invariant operand.
2244f9a02a70SFedor Sergeev     // So it happens that for multiple-partial case we dont replace
2245f9a02a70SFedor Sergeev     // in the unswitched branch.
2246f9a02a70SFedor Sergeev     bool ReplaceUnswitched = FullUnswitch || (Invariants.size() == 1);
2247f9a02a70SFedor Sergeev 
2248d1dab0c3SChandler Carruth     ConstantInt *UnswitchedReplacement =
22491652996fSChandler Carruth         Direction ? ConstantInt::getTrue(BI->getContext())
22501652996fSChandler Carruth                   : ConstantInt::getFalse(BI->getContext());
2251d1dab0c3SChandler Carruth     ConstantInt *ContinueReplacement =
22521652996fSChandler Carruth         Direction ? ConstantInt::getFalse(BI->getContext())
22531652996fSChandler Carruth                   : ConstantInt::getTrue(BI->getContext());
2254d1dab0c3SChandler Carruth     for (Value *Invariant : Invariants)
2255d1dab0c3SChandler Carruth       for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2256d1dab0c3SChandler Carruth            UI != UE;) {
2257d1dab0c3SChandler Carruth         // Grab the use and walk past it so we can clobber it in the use list.
2258d1dab0c3SChandler Carruth         Use *U = &*UI++;
2259d1dab0c3SChandler Carruth         Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2260d1dab0c3SChandler Carruth         if (!UserI)
2261d1dab0c3SChandler Carruth           continue;
2262d1dab0c3SChandler Carruth 
2263d1dab0c3SChandler Carruth         // Replace it with the 'continue' side if in the main loop body, and the
2264d1dab0c3SChandler Carruth         // unswitched if in the cloned blocks.
2265d1dab0c3SChandler Carruth         if (DT.dominates(LoopPH, UserI->getParent()))
2266d1dab0c3SChandler Carruth           U->set(ContinueReplacement);
2267f9a02a70SFedor Sergeev         else if (ReplaceUnswitched &&
2268f9a02a70SFedor Sergeev                  DT.dominates(ClonedPH, UserI->getParent()))
2269d1dab0c3SChandler Carruth           U->set(UnswitchedReplacement);
2270d1dab0c3SChandler Carruth       }
22711652996fSChandler Carruth   }
2272d1dab0c3SChandler Carruth 
2273693eedb1SChandler Carruth   // We can change which blocks are exit blocks of all the cloned sibling
2274693eedb1SChandler Carruth   // loops, the current loop, and any parent loops which shared exit blocks
2275693eedb1SChandler Carruth   // with the current loop. As a consequence, we need to re-form LCSSA for
2276693eedb1SChandler Carruth   // them. But we shouldn't need to re-form LCSSA for any child loops.
2277693eedb1SChandler Carruth   // FIXME: This could be made more efficient by tracking which exit blocks are
2278693eedb1SChandler Carruth   // new, and focusing on them, but that isn't likely to be necessary.
2279693eedb1SChandler Carruth   //
2280693eedb1SChandler Carruth   // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2281693eedb1SChandler Carruth   // loop nest and update every loop that could have had its exits changed. We
2282693eedb1SChandler Carruth   // also need to cover any intervening loops. We add all of these loops to
2283693eedb1SChandler Carruth   // a list and sort them by loop depth to achieve this without updating
2284693eedb1SChandler Carruth   // unnecessary loops.
22859281503eSChandler Carruth   auto UpdateLoop = [&](Loop &UpdateL) {
2286693eedb1SChandler Carruth #ifndef NDEBUG
228743acdb35SChandler Carruth     UpdateL.verifyLoop();
228843acdb35SChandler Carruth     for (Loop *ChildL : UpdateL) {
228943acdb35SChandler Carruth       ChildL->verifyLoop();
2290693eedb1SChandler Carruth       assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2291693eedb1SChandler Carruth              "Perturbed a child loop's LCSSA form!");
229243acdb35SChandler Carruth     }
2293693eedb1SChandler Carruth #endif
2294693eedb1SChandler Carruth     // First build LCSSA for this loop so that we can preserve it when
2295693eedb1SChandler Carruth     // forming dedicated exits. We don't want to perturb some other loop's
2296693eedb1SChandler Carruth     // LCSSA while doing that CFG edit.
2297c4d8c631SDaniil Suchkov     formLCSSA(UpdateL, DT, &LI, SE);
2298693eedb1SChandler Carruth 
2299693eedb1SChandler Carruth     // For loops reached by this loop's original exit blocks we may
2300693eedb1SChandler Carruth     // introduced new, non-dedicated exits. At least try to re-form dedicated
2301693eedb1SChandler Carruth     // exits for these loops. This may fail if they couldn't have dedicated
2302693eedb1SChandler Carruth     // exits to start with.
230397468e92SAlina Sbirlea     formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
23049281503eSChandler Carruth   };
23059281503eSChandler Carruth 
23069281503eSChandler Carruth   // For non-child cloned loops and hoisted loops, we just need to update LCSSA
23079281503eSChandler Carruth   // and we can do it in any order as they don't nest relative to each other.
23089281503eSChandler Carruth   //
23099281503eSChandler Carruth   // Also check if any of the loops we have updated have become top-level loops
23109281503eSChandler Carruth   // as that will necessitate widening the outer loop scope.
23119281503eSChandler Carruth   for (Loop *UpdatedL :
23129281503eSChandler Carruth        llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
23139281503eSChandler Carruth     UpdateLoop(*UpdatedL);
23149281503eSChandler Carruth     if (!UpdatedL->getParentLoop())
23159281503eSChandler Carruth       OuterExitL = nullptr;
2316693eedb1SChandler Carruth   }
23179281503eSChandler Carruth   if (IsStillLoop) {
23189281503eSChandler Carruth     UpdateLoop(L);
23199281503eSChandler Carruth     if (!L.getParentLoop())
23209281503eSChandler Carruth       OuterExitL = nullptr;
2321693eedb1SChandler Carruth   }
2322693eedb1SChandler Carruth 
23239281503eSChandler Carruth   // If the original loop had exit blocks, walk up through the outer most loop
23249281503eSChandler Carruth   // of those exit blocks to update LCSSA and form updated dedicated exits.
23259281503eSChandler Carruth   if (OuterExitL != &L)
23269281503eSChandler Carruth     for (Loop *OuterL = ParentL; OuterL != OuterExitL;
23279281503eSChandler Carruth          OuterL = OuterL->getParentLoop())
23289281503eSChandler Carruth       UpdateLoop(*OuterL);
23299281503eSChandler Carruth 
2330693eedb1SChandler Carruth #ifndef NDEBUG
2331693eedb1SChandler Carruth   // Verify the entire loop structure to catch any incorrect updates before we
2332693eedb1SChandler Carruth   // progress in the pass pipeline.
2333693eedb1SChandler Carruth   LI.verify(DT);
2334693eedb1SChandler Carruth #endif
2335693eedb1SChandler Carruth 
2336693eedb1SChandler Carruth   // Now that we've unswitched something, make callbacks to report the changes.
2337693eedb1SChandler Carruth   // For that we need to merge together the updated loops and the cloned loops
2338693eedb1SChandler Carruth   // and check whether the original loop survived.
2339693eedb1SChandler Carruth   SmallVector<Loop *, 4> SibLoops;
2340693eedb1SChandler Carruth   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2341693eedb1SChandler Carruth     if (UpdatedL->getParentLoop() == ParentL)
2342693eedb1SChandler Carruth       SibLoops.push_back(UpdatedL);
234371fd2704SChandler Carruth   UnswitchCB(IsStillLoop, SibLoops);
2344693eedb1SChandler Carruth 
2345a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
2346a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
2347a2eebb82SAlina Sbirlea 
2348b7dff9c9SZaara Syeda   if (BI)
2349693eedb1SChandler Carruth     ++NumBranches;
2350b7dff9c9SZaara Syeda   else
2351b7dff9c9SZaara Syeda     ++NumSwitches;
2352693eedb1SChandler Carruth }
2353693eedb1SChandler Carruth 
2354693eedb1SChandler Carruth /// Recursively compute the cost of a dominator subtree based on the per-block
2355693eedb1SChandler Carruth /// cost map provided.
2356693eedb1SChandler Carruth ///
2357693eedb1SChandler Carruth /// The recursive computation is memozied into the provided DT-indexed cost map
2358693eedb1SChandler Carruth /// to allow querying it for most nodes in the domtree without it becoming
2359693eedb1SChandler Carruth /// quadratic.
2360693eedb1SChandler Carruth static int
2361693eedb1SChandler Carruth computeDomSubtreeCost(DomTreeNode &N,
2362693eedb1SChandler Carruth                       const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2363693eedb1SChandler Carruth                       SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2364693eedb1SChandler Carruth   // Don't accumulate cost (or recurse through) blocks not in our block cost
2365693eedb1SChandler Carruth   // map and thus not part of the duplication cost being considered.
2366693eedb1SChandler Carruth   auto BBCostIt = BBCostMap.find(N.getBlock());
2367693eedb1SChandler Carruth   if (BBCostIt == BBCostMap.end())
2368693eedb1SChandler Carruth     return 0;
2369693eedb1SChandler Carruth 
2370693eedb1SChandler Carruth   // Lookup this node to see if we already computed its cost.
2371693eedb1SChandler Carruth   auto DTCostIt = DTCostMap.find(&N);
2372693eedb1SChandler Carruth   if (DTCostIt != DTCostMap.end())
2373693eedb1SChandler Carruth     return DTCostIt->second;
2374693eedb1SChandler Carruth 
2375693eedb1SChandler Carruth   // If not, we have to compute it. We can't use insert above and update
2376693eedb1SChandler Carruth   // because computing the cost may insert more things into the map.
2377693eedb1SChandler Carruth   int Cost = std::accumulate(
2378693eedb1SChandler Carruth       N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2379693eedb1SChandler Carruth         return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2380693eedb1SChandler Carruth       });
2381693eedb1SChandler Carruth   bool Inserted = DTCostMap.insert({&N, Cost}).second;
2382693eedb1SChandler Carruth   (void)Inserted;
2383693eedb1SChandler Carruth   assert(Inserted && "Should not insert a node while visiting children!");
2384693eedb1SChandler Carruth   return Cost;
2385693eedb1SChandler Carruth }
2386693eedb1SChandler Carruth 
2387619a8346SMax Kazantsev /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2388619a8346SMax Kazantsev /// making the following replacement:
2389619a8346SMax Kazantsev ///
2390a132016dSSimon Pilgrim ///   --code before guard--
2391619a8346SMax Kazantsev ///   call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
2392a132016dSSimon Pilgrim ///   --code after guard--
2393619a8346SMax Kazantsev ///
2394619a8346SMax Kazantsev /// into
2395619a8346SMax Kazantsev ///
2396a132016dSSimon Pilgrim ///   --code before guard--
2397619a8346SMax Kazantsev ///   br i1 %cond, label %guarded, label %deopt
2398619a8346SMax Kazantsev ///
2399619a8346SMax Kazantsev /// guarded:
2400a132016dSSimon Pilgrim ///   --code after guard--
2401619a8346SMax Kazantsev ///
2402619a8346SMax Kazantsev /// deopt:
2403619a8346SMax Kazantsev ///   call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2404619a8346SMax Kazantsev ///   unreachable
2405619a8346SMax Kazantsev ///
2406619a8346SMax Kazantsev /// It also makes all relevant DT and LI updates, so that all structures are in
2407619a8346SMax Kazantsev /// valid state after this transform.
2408619a8346SMax Kazantsev static BranchInst *
2409619a8346SMax Kazantsev turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2410619a8346SMax Kazantsev                     SmallVectorImpl<BasicBlock *> &ExitBlocks,
2411a2eebb82SAlina Sbirlea                     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
2412619a8346SMax Kazantsev   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2413619a8346SMax Kazantsev   LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2414619a8346SMax Kazantsev   BasicBlock *CheckBB = GI->getParent();
2415619a8346SMax Kazantsev 
2416797935f4SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
2417a2eebb82SAlina Sbirlea      MSSAU->getMemorySSA()->verifyMemorySSA();
2418a2eebb82SAlina Sbirlea 
2419619a8346SMax Kazantsev   // Remove all CheckBB's successors from DomTree. A block can be seen among
2420619a8346SMax Kazantsev   // successors more than once, but for DomTree it should be added only once.
2421619a8346SMax Kazantsev   SmallPtrSet<BasicBlock *, 4> Successors;
2422619a8346SMax Kazantsev   for (auto *Succ : successors(CheckBB))
2423619a8346SMax Kazantsev     if (Successors.insert(Succ).second)
2424619a8346SMax Kazantsev       DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2425619a8346SMax Kazantsev 
2426619a8346SMax Kazantsev   Instruction *DeoptBlockTerm =
2427619a8346SMax Kazantsev       SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2428619a8346SMax Kazantsev   BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2429619a8346SMax Kazantsev   // SplitBlockAndInsertIfThen inserts control flow that branches to
2430619a8346SMax Kazantsev   // DeoptBlockTerm if the condition is true.  We want the opposite.
2431619a8346SMax Kazantsev   CheckBI->swapSuccessors();
2432619a8346SMax Kazantsev 
2433619a8346SMax Kazantsev   BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2434619a8346SMax Kazantsev   GuardedBlock->setName("guarded");
2435619a8346SMax Kazantsev   CheckBI->getSuccessor(1)->setName("deopt");
2436a2eebb82SAlina Sbirlea   BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
2437619a8346SMax Kazantsev 
2438619a8346SMax Kazantsev   // We now have a new exit block.
2439619a8346SMax Kazantsev   ExitBlocks.push_back(CheckBI->getSuccessor(1));
2440619a8346SMax Kazantsev 
2441a2eebb82SAlina Sbirlea   if (MSSAU)
2442a2eebb82SAlina Sbirlea     MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2443a2eebb82SAlina Sbirlea 
2444619a8346SMax Kazantsev   GI->moveBefore(DeoptBlockTerm);
2445619a8346SMax Kazantsev   GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2446619a8346SMax Kazantsev 
2447619a8346SMax Kazantsev   // Add new successors of CheckBB into DomTree.
2448619a8346SMax Kazantsev   for (auto *Succ : successors(CheckBB))
2449619a8346SMax Kazantsev     DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2450619a8346SMax Kazantsev 
2451619a8346SMax Kazantsev   // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2452619a8346SMax Kazantsev   // successors.
2453619a8346SMax Kazantsev   for (auto *Succ : Successors)
2454619a8346SMax Kazantsev     DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2455619a8346SMax Kazantsev 
2456619a8346SMax Kazantsev   // Make proper changes to DT.
2457619a8346SMax Kazantsev   DT.applyUpdates(DTUpdates);
2458619a8346SMax Kazantsev   // Inform LI of a new loop block.
2459619a8346SMax Kazantsev   L.addBasicBlockToLoop(GuardedBlock, LI);
2460619a8346SMax Kazantsev 
2461a2eebb82SAlina Sbirlea   if (MSSAU) {
2462a2eebb82SAlina Sbirlea     MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
24635c5cf899SAlina Sbirlea     MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::BeforeTerminator);
2464a2eebb82SAlina Sbirlea     if (VerifyMemorySSA)
2465a2eebb82SAlina Sbirlea       MSSAU->getMemorySSA()->verifyMemorySSA();
2466a2eebb82SAlina Sbirlea   }
2467a2eebb82SAlina Sbirlea 
2468619a8346SMax Kazantsev   ++NumGuards;
2469619a8346SMax Kazantsev   return CheckBI;
2470619a8346SMax Kazantsev }
2471619a8346SMax Kazantsev 
24722e3e224eSFedor Sergeev /// Cost multiplier is a way to limit potentially exponential behavior
24732e3e224eSFedor Sergeev /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
24742e3e224eSFedor Sergeev /// candidates available. Also accounting for the number of "sibling" loops with
24752e3e224eSFedor Sergeev /// the idea to account for previous unswitches that already happened on this
24762e3e224eSFedor Sergeev /// cluster of loops. There was an attempt to keep this formula simple,
24772e3e224eSFedor Sergeev /// just enough to limit the worst case behavior. Even if it is not that simple
24782e3e224eSFedor Sergeev /// now it is still not an attempt to provide a detailed heuristic size
24792e3e224eSFedor Sergeev /// prediction.
24802e3e224eSFedor Sergeev ///
24812e3e224eSFedor Sergeev /// TODO: Make a proper accounting of "explosion" effect for all kinds of
24822e3e224eSFedor Sergeev /// unswitch candidates, making adequate predictions instead of wild guesses.
24832e3e224eSFedor Sergeev /// That requires knowing not just the number of "remaining" candidates but
24842e3e224eSFedor Sergeev /// also costs of unswitching for each of these candidates.
24851c03cc5aSAlina Sbirlea static int CalculateUnswitchCostMultiplier(
24862e3e224eSFedor Sergeev     Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
24872e3e224eSFedor Sergeev     ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
24882e3e224eSFedor Sergeev         UnswitchCandidates) {
24892e3e224eSFedor Sergeev 
24902e3e224eSFedor Sergeev   // Guards and other exiting conditions do not contribute to exponential
24912e3e224eSFedor Sergeev   // explosion as soon as they dominate the latch (otherwise there might be
24922e3e224eSFedor Sergeev   // another path to the latch remaining that does not allow to eliminate the
24932e3e224eSFedor Sergeev   // loop copy on unswitch).
24942e3e224eSFedor Sergeev   BasicBlock *Latch = L.getLoopLatch();
24952e3e224eSFedor Sergeev   BasicBlock *CondBlock = TI.getParent();
24962e3e224eSFedor Sergeev   if (DT.dominates(CondBlock, Latch) &&
24972e3e224eSFedor Sergeev       (isGuard(&TI) ||
24982e3e224eSFedor Sergeev        llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
24992e3e224eSFedor Sergeev          return L.contains(SuccBB);
25002e3e224eSFedor Sergeev        }) <= 1)) {
25012e3e224eSFedor Sergeev     NumCostMultiplierSkipped++;
25022e3e224eSFedor Sergeev     return 1;
25032e3e224eSFedor Sergeev   }
25042e3e224eSFedor Sergeev 
25052e3e224eSFedor Sergeev   auto *ParentL = L.getParentLoop();
25062e3e224eSFedor Sergeev   int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
25072e3e224eSFedor Sergeev                                : std::distance(LI.begin(), LI.end()));
25082e3e224eSFedor Sergeev   // Count amount of clones that all the candidates might cause during
25092e3e224eSFedor Sergeev   // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
25102e3e224eSFedor Sergeev   int UnswitchedClones = 0;
25112e3e224eSFedor Sergeev   for (auto Candidate : UnswitchCandidates) {
25122e3e224eSFedor Sergeev     Instruction *CI = Candidate.first;
25132e3e224eSFedor Sergeev     BasicBlock *CondBlock = CI->getParent();
25142e3e224eSFedor Sergeev     bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
25152e3e224eSFedor Sergeev     if (isGuard(CI)) {
25162e3e224eSFedor Sergeev       if (!SkipExitingSuccessors)
25172e3e224eSFedor Sergeev         UnswitchedClones++;
25182e3e224eSFedor Sergeev       continue;
25192e3e224eSFedor Sergeev     }
25202e3e224eSFedor Sergeev     int NonExitingSuccessors = llvm::count_if(
25212e3e224eSFedor Sergeev         successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
25222e3e224eSFedor Sergeev           return !SkipExitingSuccessors || L.contains(SuccBB);
25232e3e224eSFedor Sergeev         });
25242e3e224eSFedor Sergeev     UnswitchedClones += Log2_32(NonExitingSuccessors);
25252e3e224eSFedor Sergeev   }
25262e3e224eSFedor Sergeev 
25272e3e224eSFedor Sergeev   // Ignore up to the "unscaled candidates" number of unswitch candidates
25282e3e224eSFedor Sergeev   // when calculating the power-of-two scaling of the cost. The main idea
25292e3e224eSFedor Sergeev   // with this control is to allow a small number of unswitches to happen
25302e3e224eSFedor Sergeev   // and rely more on siblings multiplier (see below) when the number
25312e3e224eSFedor Sergeev   // of candidates is small.
25322e3e224eSFedor Sergeev   unsigned ClonesPower =
25332e3e224eSFedor Sergeev       std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
25342e3e224eSFedor Sergeev 
25352e3e224eSFedor Sergeev   // Allowing top-level loops to spread a bit more than nested ones.
25362e3e224eSFedor Sergeev   int SiblingsMultiplier =
25372e3e224eSFedor Sergeev       std::max((ParentL ? SiblingsCount
25382e3e224eSFedor Sergeev                         : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
25392e3e224eSFedor Sergeev                1);
25402e3e224eSFedor Sergeev   // Compute the cost multiplier in a way that won't overflow by saturating
25412e3e224eSFedor Sergeev   // at an upper bound.
25422e3e224eSFedor Sergeev   int CostMultiplier;
25432e3e224eSFedor Sergeev   if (ClonesPower > Log2_32(UnswitchThreshold) ||
25442e3e224eSFedor Sergeev       SiblingsMultiplier > UnswitchThreshold)
25452e3e224eSFedor Sergeev     CostMultiplier = UnswitchThreshold;
25462e3e224eSFedor Sergeev   else
25472e3e224eSFedor Sergeev     CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
25482e3e224eSFedor Sergeev                               (int)UnswitchThreshold);
25492e3e224eSFedor Sergeev 
25502e3e224eSFedor Sergeev   LLVM_DEBUG(dbgs() << "  Computed multiplier  " << CostMultiplier
25512e3e224eSFedor Sergeev                     << " (siblings " << SiblingsMultiplier << " * clones "
25522e3e224eSFedor Sergeev                     << (1 << ClonesPower) << ")"
25532e3e224eSFedor Sergeev                     << " for unswitch candidate: " << TI << "\n");
25542e3e224eSFedor Sergeev   return CostMultiplier;
25552e3e224eSFedor Sergeev }
25562e3e224eSFedor Sergeev 
25573897ded6SChandler Carruth static bool
25583897ded6SChandler Carruth unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
25593897ded6SChandler Carruth                       AssumptionCache &AC, TargetTransformInfo &TTI,
25603897ded6SChandler Carruth                       function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2561a2eebb82SAlina Sbirlea                       ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
2562d1dab0c3SChandler Carruth   // Collect all invariant conditions within this loop (as opposed to an inner
2563d1dab0c3SChandler Carruth   // loop which would be handled when visiting that inner loop).
256460b2e054SChandler Carruth   SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
2565d1dab0c3SChandler Carruth       UnswitchCandidates;
2566619a8346SMax Kazantsev 
2567619a8346SMax Kazantsev   // Whether or not we should also collect guards in the loop.
2568619a8346SMax Kazantsev   bool CollectGuards = false;
2569619a8346SMax Kazantsev   if (UnswitchGuards) {
2570619a8346SMax Kazantsev     auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2571619a8346SMax Kazantsev         Intrinsic::getName(Intrinsic::experimental_guard));
2572619a8346SMax Kazantsev     if (GuardDecl && !GuardDecl->use_empty())
2573619a8346SMax Kazantsev       CollectGuards = true;
2574619a8346SMax Kazantsev   }
2575619a8346SMax Kazantsev 
2576d1dab0c3SChandler Carruth   for (auto *BB : L.blocks()) {
2577d1dab0c3SChandler Carruth     if (LI.getLoopFor(BB) != &L)
2578d1dab0c3SChandler Carruth       continue;
25791353f9a4SChandler Carruth 
2580619a8346SMax Kazantsev     if (CollectGuards)
2581619a8346SMax Kazantsev       for (auto &I : *BB)
2582619a8346SMax Kazantsev         if (isGuard(&I)) {
2583619a8346SMax Kazantsev           auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2584619a8346SMax Kazantsev           // TODO: Support AND, OR conditions and partial unswitching.
2585619a8346SMax Kazantsev           if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2586619a8346SMax Kazantsev             UnswitchCandidates.push_back({&I, {Cond}});
2587619a8346SMax Kazantsev         }
2588619a8346SMax Kazantsev 
25891652996fSChandler Carruth     if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
25901652996fSChandler Carruth       // We can only consider fully loop-invariant switch conditions as we need
25911652996fSChandler Carruth       // to completely eliminate the switch after unswitching.
25921652996fSChandler Carruth       if (!isa<Constant>(SI->getCondition()) &&
2593d000f8b6SSerguei Katkov           L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor())
25941652996fSChandler Carruth         UnswitchCandidates.push_back({SI, {SI->getCondition()}});
25951652996fSChandler Carruth       continue;
25961652996fSChandler Carruth     }
25971652996fSChandler Carruth 
2598d1dab0c3SChandler Carruth     auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2599d1dab0c3SChandler Carruth     if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2600d1dab0c3SChandler Carruth         BI->getSuccessor(0) == BI->getSuccessor(1))
2601d1dab0c3SChandler Carruth       continue;
26021353f9a4SChandler Carruth 
2603d1dab0c3SChandler Carruth     if (L.isLoopInvariant(BI->getCondition())) {
2604d1dab0c3SChandler Carruth       UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2605d1dab0c3SChandler Carruth       continue;
260671fd2704SChandler Carruth     }
26071353f9a4SChandler Carruth 
2608d1dab0c3SChandler Carruth     Instruction &CondI = *cast<Instruction>(BI->getCondition());
2609d1dab0c3SChandler Carruth     if (CondI.getOpcode() != Instruction::And &&
2610d1dab0c3SChandler Carruth       CondI.getOpcode() != Instruction::Or)
2611d1dab0c3SChandler Carruth       continue;
2612693eedb1SChandler Carruth 
2613d1dab0c3SChandler Carruth     TinyPtrVector<Value *> Invariants =
2614d1dab0c3SChandler Carruth         collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2615d1dab0c3SChandler Carruth     if (Invariants.empty())
2616d1dab0c3SChandler Carruth       continue;
2617d1dab0c3SChandler Carruth 
2618d1dab0c3SChandler Carruth     UnswitchCandidates.push_back({BI, std::move(Invariants)});
2619d1dab0c3SChandler Carruth   }
2620693eedb1SChandler Carruth 
2621693eedb1SChandler Carruth   // If we didn't find any candidates, we're done.
2622693eedb1SChandler Carruth   if (UnswitchCandidates.empty())
262371fd2704SChandler Carruth     return false;
2624693eedb1SChandler Carruth 
262532e62f9cSChandler Carruth   // Check if there are irreducible CFG cycles in this loop. If so, we cannot
262632e62f9cSChandler Carruth   // easily unswitch non-trivial edges out of the loop. Doing so might turn the
262732e62f9cSChandler Carruth   // irreducible control flow into reducible control flow and introduce new
262832e62f9cSChandler Carruth   // loops "out of thin air". If we ever discover important use cases for doing
262932e62f9cSChandler Carruth   // this, we can add support to loop unswitch, but it is a lot of complexity
2630f209649dSHiroshi Inoue   // for what seems little or no real world benefit.
263132e62f9cSChandler Carruth   LoopBlocksRPO RPOT(&L);
263232e62f9cSChandler Carruth   RPOT.perform(&LI);
263332e62f9cSChandler Carruth   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
263471fd2704SChandler Carruth     return false;
263532e62f9cSChandler Carruth 
2636bde31000SMax Kazantsev   SmallVector<BasicBlock *, 4> ExitBlocks;
2637bde31000SMax Kazantsev   L.getUniqueExitBlocks(ExitBlocks);
2638bde31000SMax Kazantsev 
2639bde31000SMax Kazantsev   // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
2640bde31000SMax Kazantsev   // don't know how to split those exit blocks.
2641bde31000SMax Kazantsev   // FIXME: We should teach SplitBlock to handle this and remove this
2642bde31000SMax Kazantsev   // restriction.
2643bde31000SMax Kazantsev   for (auto *ExitBB : ExitBlocks)
2644bde31000SMax Kazantsev     if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) {
2645bde31000SMax Kazantsev       dbgs() << "Cannot unswitch because of cleanuppad in exit block\n";
2646bde31000SMax Kazantsev       return false;
2647bde31000SMax Kazantsev     }
2648bde31000SMax Kazantsev 
2649d34e60caSNicola Zaghen   LLVM_DEBUG(
2650d34e60caSNicola Zaghen       dbgs() << "Considering " << UnswitchCandidates.size()
2651693eedb1SChandler Carruth              << " non-trivial loop invariant conditions for unswitching.\n");
2652693eedb1SChandler Carruth 
2653693eedb1SChandler Carruth   // Given that unswitching these terminators will require duplicating parts of
2654693eedb1SChandler Carruth   // the loop, so we need to be able to model that cost. Compute the ephemeral
2655693eedb1SChandler Carruth   // values and set up a data structure to hold per-BB costs. We cache each
2656693eedb1SChandler Carruth   // block's cost so that we don't recompute this when considering different
2657693eedb1SChandler Carruth   // subsets of the loop for duplication during unswitching.
2658693eedb1SChandler Carruth   SmallPtrSet<const Value *, 4> EphValues;
2659693eedb1SChandler Carruth   CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2660693eedb1SChandler Carruth   SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2661693eedb1SChandler Carruth 
2662693eedb1SChandler Carruth   // Compute the cost of each block, as well as the total loop cost. Also, bail
2663693eedb1SChandler Carruth   // out if we see instructions which are incompatible with loop unswitching
2664693eedb1SChandler Carruth   // (convergent, noduplicate, or cross-basic-block tokens).
2665693eedb1SChandler Carruth   // FIXME: We might be able to safely handle some of these in non-duplicated
2666693eedb1SChandler Carruth   // regions.
2667693eedb1SChandler Carruth   int LoopCost = 0;
2668693eedb1SChandler Carruth   for (auto *BB : L.blocks()) {
2669693eedb1SChandler Carruth     int Cost = 0;
2670693eedb1SChandler Carruth     for (auto &I : *BB) {
2671693eedb1SChandler Carruth       if (EphValues.count(&I))
2672693eedb1SChandler Carruth         continue;
2673693eedb1SChandler Carruth 
2674693eedb1SChandler Carruth       if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
267571fd2704SChandler Carruth         return false;
2676592d8e7dSCraig Topper       if (auto *CB = dyn_cast<CallBase>(&I))
2677592d8e7dSCraig Topper         if (CB->isConvergent() || CB->cannotDuplicate())
267871fd2704SChandler Carruth           return false;
2679693eedb1SChandler Carruth 
2680e9c9329aSSam Parker       Cost += TTI.getUserCost(&I, TargetTransformInfo::TCK_CodeSize);
2681693eedb1SChandler Carruth     }
2682693eedb1SChandler Carruth     assert(Cost >= 0 && "Must not have negative costs!");
2683693eedb1SChandler Carruth     LoopCost += Cost;
2684693eedb1SChandler Carruth     assert(LoopCost >= 0 && "Must not have negative loop costs!");
2685693eedb1SChandler Carruth     BBCostMap[BB] = Cost;
2686693eedb1SChandler Carruth   }
2687d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Total loop cost: " << LoopCost << "\n");
2688693eedb1SChandler Carruth 
2689693eedb1SChandler Carruth   // Now we find the best candidate by searching for the one with the following
2690693eedb1SChandler Carruth   // properties in order:
2691693eedb1SChandler Carruth   //
2692693eedb1SChandler Carruth   // 1) An unswitching cost below the threshold
2693693eedb1SChandler Carruth   // 2) The smallest number of duplicated unswitch candidates (to avoid
2694693eedb1SChandler Carruth   //    creating redundant subsequent unswitching)
2695693eedb1SChandler Carruth   // 3) The smallest cost after unswitching.
2696693eedb1SChandler Carruth   //
2697693eedb1SChandler Carruth   // We prioritize reducing fanout of unswitch candidates provided the cost
2698693eedb1SChandler Carruth   // remains below the threshold because this has a multiplicative effect.
2699693eedb1SChandler Carruth   //
2700693eedb1SChandler Carruth   // This requires memoizing each dominator subtree to avoid redundant work.
2701693eedb1SChandler Carruth   //
2702693eedb1SChandler Carruth   // FIXME: Need to actually do the number of candidates part above.
2703693eedb1SChandler Carruth   SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2704693eedb1SChandler Carruth   // Given a terminator which might be unswitched, computes the non-duplicated
2705693eedb1SChandler Carruth   // cost for that terminator.
270660b2e054SChandler Carruth   auto ComputeUnswitchedCost = [&](Instruction &TI, bool FullUnswitch) {
2707d1dab0c3SChandler Carruth     BasicBlock &BB = *TI.getParent();
2708693eedb1SChandler Carruth     SmallPtrSet<BasicBlock *, 4> Visited;
2709693eedb1SChandler Carruth 
2710693eedb1SChandler Carruth     int Cost = LoopCost;
2711693eedb1SChandler Carruth     for (BasicBlock *SuccBB : successors(&BB)) {
2712693eedb1SChandler Carruth       // Don't count successors more than once.
2713693eedb1SChandler Carruth       if (!Visited.insert(SuccBB).second)
2714693eedb1SChandler Carruth         continue;
2715693eedb1SChandler Carruth 
2716d1dab0c3SChandler Carruth       // If this is a partial unswitch candidate, then it must be a conditional
2717d1dab0c3SChandler Carruth       // branch with a condition of either `or` or `and`. In that case, one of
2718d1dab0c3SChandler Carruth       // the successors is necessarily duplicated, so don't even try to remove
2719d1dab0c3SChandler Carruth       // its cost.
2720d1dab0c3SChandler Carruth       if (!FullUnswitch) {
2721d1dab0c3SChandler Carruth         auto &BI = cast<BranchInst>(TI);
2722d1dab0c3SChandler Carruth         if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2723d1dab0c3SChandler Carruth             Instruction::And) {
2724d1dab0c3SChandler Carruth           if (SuccBB == BI.getSuccessor(1))
2725d1dab0c3SChandler Carruth             continue;
2726d1dab0c3SChandler Carruth         } else {
2727d1dab0c3SChandler Carruth           assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2728d1dab0c3SChandler Carruth                      Instruction::Or &&
2729d1dab0c3SChandler Carruth                  "Only `and` and `or` conditions can result in a partial "
2730d1dab0c3SChandler Carruth                  "unswitch!");
2731d1dab0c3SChandler Carruth           if (SuccBB == BI.getSuccessor(0))
2732d1dab0c3SChandler Carruth             continue;
2733d1dab0c3SChandler Carruth         }
2734d1dab0c3SChandler Carruth       }
2735d1dab0c3SChandler Carruth 
2736693eedb1SChandler Carruth       // This successor's domtree will not need to be duplicated after
2737693eedb1SChandler Carruth       // unswitching if the edge to the successor dominates it (and thus the
2738693eedb1SChandler Carruth       // entire tree). This essentially means there is no other path into this
2739693eedb1SChandler Carruth       // subtree and so it will end up live in only one clone of the loop.
2740693eedb1SChandler Carruth       if (SuccBB->getUniquePredecessor() ||
2741693eedb1SChandler Carruth           llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2742693eedb1SChandler Carruth             return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2743693eedb1SChandler Carruth           })) {
2744693eedb1SChandler Carruth         Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2745693eedb1SChandler Carruth         assert(Cost >= 0 &&
2746693eedb1SChandler Carruth                "Non-duplicated cost should never exceed total loop cost!");
2747693eedb1SChandler Carruth       }
2748693eedb1SChandler Carruth     }
2749693eedb1SChandler Carruth 
2750693eedb1SChandler Carruth     // Now scale the cost by the number of unique successors minus one. We
2751693eedb1SChandler Carruth     // subtract one because there is already at least one copy of the entire
2752693eedb1SChandler Carruth     // loop. This is computing the new cost of unswitching a condition.
2753619a8346SMax Kazantsev     // Note that guards always have 2 unique successors that are implicit and
2754619a8346SMax Kazantsev     // will be materialized if we decide to unswitch it.
2755619a8346SMax Kazantsev     int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2756619a8346SMax Kazantsev     assert(SuccessorsCount > 1 &&
2757693eedb1SChandler Carruth            "Cannot unswitch a condition without multiple distinct successors!");
2758619a8346SMax Kazantsev     return Cost * (SuccessorsCount - 1);
2759693eedb1SChandler Carruth   };
276060b2e054SChandler Carruth   Instruction *BestUnswitchTI = nullptr;
2761c598ef7fSSimon Pilgrim   int BestUnswitchCost = 0;
2762d1dab0c3SChandler Carruth   ArrayRef<Value *> BestUnswitchInvariants;
2763d1dab0c3SChandler Carruth   for (auto &TerminatorAndInvariants : UnswitchCandidates) {
276460b2e054SChandler Carruth     Instruction &TI = *TerminatorAndInvariants.first;
2765d1dab0c3SChandler Carruth     ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2766d1dab0c3SChandler Carruth     BranchInst *BI = dyn_cast<BranchInst>(&TI);
27671652996fSChandler Carruth     int CandidateCost = ComputeUnswitchedCost(
27681652996fSChandler Carruth         TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
27691652996fSChandler Carruth                                      Invariants[0] == BI->getCondition()));
27702e3e224eSFedor Sergeev     // Calculate cost multiplier which is a tool to limit potentially
27712e3e224eSFedor Sergeev     // exponential behavior of loop-unswitch.
27722e3e224eSFedor Sergeev     if (EnableUnswitchCostMultiplier) {
27732e3e224eSFedor Sergeev       int CostMultiplier =
27741c03cc5aSAlina Sbirlea           CalculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
27752e3e224eSFedor Sergeev       assert(
27762e3e224eSFedor Sergeev           (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
27772e3e224eSFedor Sergeev           "cost multiplier needs to be in the range of 1..UnswitchThreshold");
27782e3e224eSFedor Sergeev       CandidateCost *= CostMultiplier;
27792e3e224eSFedor Sergeev       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
27802e3e224eSFedor Sergeev                         << " (multiplier: " << CostMultiplier << ")"
27812e3e224eSFedor Sergeev                         << " for unswitch candidate: " << TI << "\n");
27822e3e224eSFedor Sergeev     } else {
2783d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
2784d1dab0c3SChandler Carruth                         << " for unswitch candidate: " << TI << "\n");
27852e3e224eSFedor Sergeev     }
27862e3e224eSFedor Sergeev 
2787693eedb1SChandler Carruth     if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2788d1dab0c3SChandler Carruth       BestUnswitchTI = &TI;
2789693eedb1SChandler Carruth       BestUnswitchCost = CandidateCost;
2790d1dab0c3SChandler Carruth       BestUnswitchInvariants = Invariants;
2791693eedb1SChandler Carruth     }
2792693eedb1SChandler Carruth   }
2793c598ef7fSSimon Pilgrim   assert(BestUnswitchTI && "Failed to find loop unswitch candidate");
2794693eedb1SChandler Carruth 
279571fd2704SChandler Carruth   if (BestUnswitchCost >= UnswitchThreshold) {
279671fd2704SChandler Carruth     LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
279771fd2704SChandler Carruth                       << BestUnswitchCost << "\n");
279871fd2704SChandler Carruth     return false;
279971fd2704SChandler Carruth   }
280071fd2704SChandler Carruth 
2801619a8346SMax Kazantsev   // If the best candidate is a guard, turn it into a branch.
2802619a8346SMax Kazantsev   if (isGuard(BestUnswitchTI))
2803619a8346SMax Kazantsev     BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
2804a2eebb82SAlina Sbirlea                                          ExitBlocks, DT, LI, MSSAU);
2805619a8346SMax Kazantsev 
2806bde31000SMax Kazantsev   LLVM_DEBUG(dbgs() << "  Unswitching non-trivial (cost = "
28071652996fSChandler Carruth                     << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
28081652996fSChandler Carruth                     << "\n");
2809bde31000SMax Kazantsev   unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
2810a2eebb82SAlina Sbirlea                                ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU);
2811bde31000SMax Kazantsev   return true;
28121353f9a4SChandler Carruth }
28131353f9a4SChandler Carruth 
2814d1dab0c3SChandler Carruth /// Unswitch control flow predicated on loop invariant conditions.
2815d1dab0c3SChandler Carruth ///
2816d1dab0c3SChandler Carruth /// This first hoists all branches or switches which are trivial (IE, do not
2817d1dab0c3SChandler Carruth /// require duplicating any part of the loop) out of the loop body. It then
2818d1dab0c3SChandler Carruth /// looks at other loop invariant control flows and tries to unswitch those as
2819d1dab0c3SChandler Carruth /// well by cloning the loop if the result is small enough.
28203897ded6SChandler Carruth ///
28213897ded6SChandler Carruth /// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
28223897ded6SChandler Carruth /// updated based on the unswitch.
2823a2eebb82SAlina Sbirlea /// The `MSSA` analysis is also updated if valid (i.e. its use is enabled).
28243897ded6SChandler Carruth ///
28253897ded6SChandler Carruth /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
28263897ded6SChandler Carruth /// true, we will attempt to do non-trivial unswitching as well as trivial
28273897ded6SChandler Carruth /// unswitching.
28283897ded6SChandler Carruth ///
28293897ded6SChandler Carruth /// The `UnswitchCB` callback provided will be run after unswitching is
28303897ded6SChandler Carruth /// complete, with the first parameter set to `true` if the provided loop
28313897ded6SChandler Carruth /// remains a loop, and a list of new sibling loops created.
28323897ded6SChandler Carruth ///
28333897ded6SChandler Carruth /// If `SE` is non-null, we will update that analysis based on the unswitching
28343897ded6SChandler Carruth /// done.
28353897ded6SChandler Carruth static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
28363897ded6SChandler Carruth                          AssumptionCache &AC, TargetTransformInfo &TTI,
28373897ded6SChandler Carruth                          bool NonTrivial,
28383897ded6SChandler Carruth                          function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2839a2eebb82SAlina Sbirlea                          ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
2840d1dab0c3SChandler Carruth   assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2841d1dab0c3SChandler Carruth          "Loops must be in LCSSA form before unswitching.");
2842d1dab0c3SChandler Carruth   bool Changed = false;
2843d1dab0c3SChandler Carruth 
2844d1dab0c3SChandler Carruth   // Must be in loop simplified form: we need a preheader and dedicated exits.
2845d1dab0c3SChandler Carruth   if (!L.isLoopSimplifyForm())
2846d1dab0c3SChandler Carruth     return false;
2847d1dab0c3SChandler Carruth 
2848d1dab0c3SChandler Carruth   // Try trivial unswitch first before loop over other basic blocks in the loop.
2849a2eebb82SAlina Sbirlea   if (unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
2850d1dab0c3SChandler Carruth     // If we unswitched successfully we will want to clean up the loop before
2851d1dab0c3SChandler Carruth     // processing it further so just mark it as unswitched and return.
2852d1dab0c3SChandler Carruth     UnswitchCB(/*CurrentLoopValid*/ true, {});
2853d1dab0c3SChandler Carruth     return true;
2854d1dab0c3SChandler Carruth   }
2855d1dab0c3SChandler Carruth 
2856d1dab0c3SChandler Carruth   // If we're not doing non-trivial unswitching, we're done. We both accept
2857d1dab0c3SChandler Carruth   // a parameter but also check a local flag that can be used for testing
2858d1dab0c3SChandler Carruth   // a debugging.
2859d1dab0c3SChandler Carruth   if (!NonTrivial && !EnableNonTrivialUnswitch)
2860d1dab0c3SChandler Carruth     return false;
2861d1dab0c3SChandler Carruth 
2862d1dab0c3SChandler Carruth   // For non-trivial unswitching, because it often creates new loops, we rely on
2863d1dab0c3SChandler Carruth   // the pass manager to iterate on the loops rather than trying to immediately
2864d1dab0c3SChandler Carruth   // reach a fixed point. There is no substantial advantage to iterating
2865d1dab0c3SChandler Carruth   // internally, and if any of the new loops are simplified enough to contain
2866d1dab0c3SChandler Carruth   // trivial unswitching we want to prefer those.
2867d1dab0c3SChandler Carruth 
2868d1dab0c3SChandler Carruth   // Try to unswitch the best invariant condition. We prefer this full unswitch to
2869d1dab0c3SChandler Carruth   // a partial unswitch when possible below the threshold.
2870a2eebb82SAlina Sbirlea   if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE, MSSAU))
2871d1dab0c3SChandler Carruth     return true;
2872d1dab0c3SChandler Carruth 
2873d1dab0c3SChandler Carruth   // No other opportunities to unswitch.
2874d1dab0c3SChandler Carruth   return Changed;
2875d1dab0c3SChandler Carruth }
2876d1dab0c3SChandler Carruth 
28771353f9a4SChandler Carruth PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
28781353f9a4SChandler Carruth                                               LoopStandardAnalysisResults &AR,
28791353f9a4SChandler Carruth                                               LPMUpdater &U) {
28801353f9a4SChandler Carruth   Function &F = *L.getHeader()->getParent();
28811353f9a4SChandler Carruth   (void)F;
28821353f9a4SChandler Carruth 
2883d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2884d34e60caSNicola Zaghen                     << "\n");
28851353f9a4SChandler Carruth 
2886693eedb1SChandler Carruth   // Save the current loop name in a variable so that we can report it even
2887693eedb1SChandler Carruth   // after it has been deleted.
2888adcd0268SBenjamin Kramer   std::string LoopName = std::string(L.getName());
2889693eedb1SChandler Carruth 
289071fd2704SChandler Carruth   auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2891693eedb1SChandler Carruth                                         ArrayRef<Loop *> NewLoops) {
2892693eedb1SChandler Carruth     // If we did a non-trivial unswitch, we have added new (cloned) loops.
289371fd2704SChandler Carruth     if (!NewLoops.empty())
2894693eedb1SChandler Carruth       U.addSiblingLoops(NewLoops);
2895693eedb1SChandler Carruth 
2896693eedb1SChandler Carruth     // If the current loop remains valid, we should revisit it to catch any
2897693eedb1SChandler Carruth     // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2898693eedb1SChandler Carruth     if (CurrentLoopValid)
2899693eedb1SChandler Carruth       U.revisitCurrentLoop();
2900693eedb1SChandler Carruth     else
2901693eedb1SChandler Carruth       U.markLoopAsDeleted(L, LoopName);
2902693eedb1SChandler Carruth   };
2903693eedb1SChandler Carruth 
2904a2eebb82SAlina Sbirlea   Optional<MemorySSAUpdater> MSSAU;
2905a2eebb82SAlina Sbirlea   if (AR.MSSA) {
2906a2eebb82SAlina Sbirlea     MSSAU = MemorySSAUpdater(AR.MSSA);
2907a2eebb82SAlina Sbirlea     if (VerifyMemorySSA)
2908a2eebb82SAlina Sbirlea       AR.MSSA->verifyMemorySSA();
2909a2eebb82SAlina Sbirlea   }
29103897ded6SChandler Carruth   if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
2911a2eebb82SAlina Sbirlea                     &AR.SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
29121353f9a4SChandler Carruth     return PreservedAnalyses::all();
29131353f9a4SChandler Carruth 
2914a2eebb82SAlina Sbirlea   if (AR.MSSA && VerifyMemorySSA)
2915a2eebb82SAlina Sbirlea     AR.MSSA->verifyMemorySSA();
2916a2eebb82SAlina Sbirlea 
29171353f9a4SChandler Carruth   // Historically this pass has had issues with the dominator tree so verify it
29181353f9a4SChandler Carruth   // in asserts builds.
29197c35de12SDavid Green   assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
29203cef1f7dSAlina Sbirlea 
29213cef1f7dSAlina Sbirlea   auto PA = getLoopPassPreservedAnalyses();
2922f92109dcSAlina Sbirlea   if (AR.MSSA)
29233cef1f7dSAlina Sbirlea     PA.preserve<MemorySSAAnalysis>();
29243cef1f7dSAlina Sbirlea   return PA;
29251353f9a4SChandler Carruth }
29261353f9a4SChandler Carruth 
29271353f9a4SChandler Carruth namespace {
2928a369a457SEugene Zelenko 
29291353f9a4SChandler Carruth class SimpleLoopUnswitchLegacyPass : public LoopPass {
2930693eedb1SChandler Carruth   bool NonTrivial;
2931693eedb1SChandler Carruth 
29321353f9a4SChandler Carruth public:
29331353f9a4SChandler Carruth   static char ID; // Pass ID, replacement for typeid
2934a369a457SEugene Zelenko 
2935693eedb1SChandler Carruth   explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2936693eedb1SChandler Carruth       : LoopPass(ID), NonTrivial(NonTrivial) {
29371353f9a4SChandler Carruth     initializeSimpleLoopUnswitchLegacyPassPass(
29381353f9a4SChandler Carruth         *PassRegistry::getPassRegistry());
29391353f9a4SChandler Carruth   }
29401353f9a4SChandler Carruth 
29411353f9a4SChandler Carruth   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
29421353f9a4SChandler Carruth 
29431353f9a4SChandler Carruth   void getAnalysisUsage(AnalysisUsage &AU) const override {
29441353f9a4SChandler Carruth     AU.addRequired<AssumptionCacheTracker>();
2945693eedb1SChandler Carruth     AU.addRequired<TargetTransformInfoWrapperPass>();
2946a2eebb82SAlina Sbirlea     if (EnableMSSALoopDependency) {
2947a2eebb82SAlina Sbirlea       AU.addRequired<MemorySSAWrapperPass>();
2948a2eebb82SAlina Sbirlea       AU.addPreserved<MemorySSAWrapperPass>();
2949a2eebb82SAlina Sbirlea     }
29501353f9a4SChandler Carruth     getLoopAnalysisUsage(AU);
29511353f9a4SChandler Carruth   }
29521353f9a4SChandler Carruth };
2953a369a457SEugene Zelenko 
2954a369a457SEugene Zelenko } // end anonymous namespace
29551353f9a4SChandler Carruth 
29561353f9a4SChandler Carruth bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
29571353f9a4SChandler Carruth   if (skipLoop(L))
29581353f9a4SChandler Carruth     return false;
29591353f9a4SChandler Carruth 
29601353f9a4SChandler Carruth   Function &F = *L->getHeader()->getParent();
29611353f9a4SChandler Carruth 
2962d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2963d34e60caSNicola Zaghen                     << "\n");
29641353f9a4SChandler Carruth 
29651353f9a4SChandler Carruth   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
29661353f9a4SChandler Carruth   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
29671353f9a4SChandler Carruth   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2968693eedb1SChandler Carruth   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2969a2eebb82SAlina Sbirlea   MemorySSA *MSSA = nullptr;
2970a2eebb82SAlina Sbirlea   Optional<MemorySSAUpdater> MSSAU;
2971a2eebb82SAlina Sbirlea   if (EnableMSSALoopDependency) {
2972a2eebb82SAlina Sbirlea     MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
2973a2eebb82SAlina Sbirlea     MSSAU = MemorySSAUpdater(MSSA);
2974a2eebb82SAlina Sbirlea   }
29751353f9a4SChandler Carruth 
29763897ded6SChandler Carruth   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
29773897ded6SChandler Carruth   auto *SE = SEWP ? &SEWP->getSE() : nullptr;
29783897ded6SChandler Carruth 
297971fd2704SChandler Carruth   auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2980693eedb1SChandler Carruth                                ArrayRef<Loop *> NewLoops) {
2981693eedb1SChandler Carruth     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2982693eedb1SChandler Carruth     for (auto *NewL : NewLoops)
2983693eedb1SChandler Carruth       LPM.addLoop(*NewL);
2984693eedb1SChandler Carruth 
2985693eedb1SChandler Carruth     // If the current loop remains valid, re-add it to the queue. This is
2986693eedb1SChandler Carruth     // a little wasteful as we'll finish processing the current loop as well,
2987693eedb1SChandler Carruth     // but it is the best we can do in the old PM.
2988693eedb1SChandler Carruth     if (CurrentLoopValid)
2989693eedb1SChandler Carruth       LPM.addLoop(*L);
2990693eedb1SChandler Carruth     else
2991693eedb1SChandler Carruth       LPM.markLoopAsDeleted(*L);
2992693eedb1SChandler Carruth   };
2993693eedb1SChandler Carruth 
2994a2eebb82SAlina Sbirlea   if (MSSA && VerifyMemorySSA)
2995a2eebb82SAlina Sbirlea     MSSA->verifyMemorySSA();
2996a2eebb82SAlina Sbirlea 
2997a2eebb82SAlina Sbirlea   bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE,
2998a2eebb82SAlina Sbirlea                               MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
2999a2eebb82SAlina Sbirlea 
3000a2eebb82SAlina Sbirlea   if (MSSA && VerifyMemorySSA)
3001a2eebb82SAlina Sbirlea     MSSA->verifyMemorySSA();
3002693eedb1SChandler Carruth 
30031353f9a4SChandler Carruth   // Historically this pass has had issues with the dominator tree so verify it
30041353f9a4SChandler Carruth   // in asserts builds.
30057c35de12SDavid Green   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
30067c35de12SDavid Green 
30071353f9a4SChandler Carruth   return Changed;
30081353f9a4SChandler Carruth }
30091353f9a4SChandler Carruth 
30101353f9a4SChandler Carruth char SimpleLoopUnswitchLegacyPass::ID = 0;
30111353f9a4SChandler Carruth INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
30121353f9a4SChandler Carruth                       "Simple unswitch loops", false, false)
30131353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3014693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3015693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
30161353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopPass)
3017a2eebb82SAlina Sbirlea INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
30181353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
30191353f9a4SChandler Carruth INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
30201353f9a4SChandler Carruth                     "Simple unswitch loops", false, false)
30211353f9a4SChandler Carruth 
3022693eedb1SChandler Carruth Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
3023693eedb1SChandler Carruth   return new SimpleLoopUnswitchLegacyPass(NonTrivial);
30241353f9a4SChandler Carruth }
3025