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"
298aaeee5fSMax Kazantsev #include "llvm/Analysis/MustExecute.h"
309ed8e0caSdfukalov #include "llvm/Analysis/ScalarEvolution.h"
31a369a457SEugene Zelenko #include "llvm/IR/BasicBlock.h"
32a369a457SEugene Zelenko #include "llvm/IR/Constant.h"
331353f9a4SChandler Carruth #include "llvm/IR/Constants.h"
341353f9a4SChandler Carruth #include "llvm/IR/Dominators.h"
351353f9a4SChandler Carruth #include "llvm/IR/Function.h"
369ed8e0caSdfukalov #include "llvm/IR/IRBuilder.h"
37a369a457SEugene Zelenko #include "llvm/IR/InstrTypes.h"
38a369a457SEugene Zelenko #include "llvm/IR/Instruction.h"
391353f9a4SChandler Carruth #include "llvm/IR/Instructions.h"
40693eedb1SChandler Carruth #include "llvm/IR/IntrinsicInst.h"
415bb38e84SJuneyoung Lee #include "llvm/IR/PatternMatch.h"
42a369a457SEugene Zelenko #include "llvm/IR/Use.h"
43a369a457SEugene Zelenko #include "llvm/IR/Value.h"
4405da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
45a369a457SEugene Zelenko #include "llvm/Pass.h"
46a369a457SEugene Zelenko #include "llvm/Support/Casting.h"
474c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
481353f9a4SChandler Carruth #include "llvm/Support/Debug.h"
49a369a457SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
50a369a457SEugene Zelenko #include "llvm/Support/GenericDomTree.h"
511353f9a4SChandler Carruth #include "llvm/Support/raw_ostream.h"
52693eedb1SChandler Carruth #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
531353f9a4SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
54693eedb1SChandler Carruth #include "llvm/Transforms/Utils/Cloning.h"
555502cfa0SSerguei Katkov #include "llvm/Transforms/Utils/Local.h"
561353f9a4SChandler Carruth #include "llvm/Transforms/Utils/LoopUtils.h"
57693eedb1SChandler Carruth #include "llvm/Transforms/Utils/ValueMapper.h"
58a369a457SEugene Zelenko #include <algorithm>
59a369a457SEugene Zelenko #include <cassert>
60a369a457SEugene Zelenko #include <iterator>
61693eedb1SChandler Carruth #include <numeric>
62a369a457SEugene Zelenko #include <utility>
631353f9a4SChandler Carruth 
641353f9a4SChandler Carruth #define DEBUG_TYPE "simple-loop-unswitch"
651353f9a4SChandler Carruth 
661353f9a4SChandler Carruth using namespace llvm;
675bb38e84SJuneyoung Lee using namespace llvm::PatternMatch;
681353f9a4SChandler Carruth 
691353f9a4SChandler Carruth STATISTIC(NumBranches, "Number of branches unswitched");
701353f9a4SChandler Carruth STATISTIC(NumSwitches, "Number of switches unswitched");
71619a8346SMax Kazantsev STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
721353f9a4SChandler Carruth STATISTIC(NumTrivial, "Number of unswitches that are trivial");
732e3e224eSFedor Sergeev STATISTIC(
742e3e224eSFedor Sergeev     NumCostMultiplierSkipped,
752e3e224eSFedor Sergeev     "Number of unswitch candidates that had their cost multiplier skipped");
761353f9a4SChandler Carruth 
77693eedb1SChandler Carruth static cl::opt<bool> EnableNonTrivialUnswitch(
78693eedb1SChandler Carruth     "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
79693eedb1SChandler Carruth     cl::desc("Forcibly enables non-trivial loop unswitching rather than "
80693eedb1SChandler Carruth              "following the configuration passed into the pass."));
81693eedb1SChandler Carruth 
82693eedb1SChandler Carruth static cl::opt<int>
83693eedb1SChandler Carruth     UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
84*df1f0328SChristopher Tetreault                       cl::ZeroOrMore,
85693eedb1SChandler Carruth                       cl::desc("The cost threshold for unswitching a loop."));
86693eedb1SChandler Carruth 
872e3e224eSFedor Sergeev static cl::opt<bool> EnableUnswitchCostMultiplier(
882e3e224eSFedor Sergeev     "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
892e3e224eSFedor Sergeev     cl::desc("Enable unswitch cost multiplier that prohibits exponential "
902e3e224eSFedor Sergeev              "explosion in nontrivial unswitch."));
912e3e224eSFedor Sergeev static cl::opt<int> UnswitchSiblingsToplevelDiv(
922e3e224eSFedor Sergeev     "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
932e3e224eSFedor Sergeev     cl::desc("Toplevel siblings divisor for cost multiplier."));
942e3e224eSFedor Sergeev static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
952e3e224eSFedor Sergeev     "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
962e3e224eSFedor Sergeev     cl::desc("Number of unswitch candidates that are ignored when calculating "
972e3e224eSFedor Sergeev              "cost multiplier."));
98619a8346SMax Kazantsev static cl::opt<bool> UnswitchGuards(
99619a8346SMax Kazantsev     "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
100619a8346SMax Kazantsev     cl::desc("If enabled, simple loop unswitching will also consider "
101619a8346SMax Kazantsev              "llvm.experimental.guard intrinsics as unswitch candidates."));
1027647c271SMax Kazantsev static cl::opt<bool> DropNonTrivialImplicitNullChecks(
1037647c271SMax Kazantsev     "simple-loop-unswitch-drop-non-trivial-implicit-null-checks",
1047647c271SMax Kazantsev     cl::init(false), cl::Hidden,
1057647c271SMax Kazantsev     cl::desc("If enabled, drop make.implicit metadata in unswitched implicit "
1067647c271SMax Kazantsev              "null checks to save time analyzing if we can keep it."));
107f3a27511SJingu Kang static cl::opt<unsigned>
108f3a27511SJingu Kang     MSSAThreshold("simple-loop-unswitch-memoryssa-threshold",
109f3a27511SJingu Kang                   cl::desc("Max number of memory uses to explore during "
110f3a27511SJingu Kang                            "partial unswitching analysis"),
111f3a27511SJingu Kang                   cl::init(100), cl::Hidden);
112619a8346SMax Kazantsev 
1134da3331dSChandler Carruth /// Collect all of the loop invariant input values transitively used by the
1144da3331dSChandler Carruth /// homogeneous instruction graph from a given root.
1154da3331dSChandler Carruth ///
1164da3331dSChandler Carruth /// This essentially walks from a root recursively through loop variant operands
1174da3331dSChandler Carruth /// which have the exact same opcode and finds all inputs which are loop
1184da3331dSChandler Carruth /// invariant. For some operations these can be re-associated and unswitched out
1194da3331dSChandler Carruth /// of the loop entirely.
120d1dab0c3SChandler Carruth static TinyPtrVector<Value *>
1214da3331dSChandler Carruth collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
1224da3331dSChandler Carruth                                          LoopInfo &LI) {
1234da3331dSChandler Carruth   assert(!L.isLoopInvariant(&Root) &&
1244da3331dSChandler Carruth          "Only need to walk the graph if root itself is not invariant.");
125d1dab0c3SChandler Carruth   TinyPtrVector<Value *> Invariants;
1264da3331dSChandler Carruth 
1275bb38e84SJuneyoung Lee   bool IsRootAnd = match(&Root, m_LogicalAnd());
1285bb38e84SJuneyoung Lee   bool IsRootOr  = match(&Root, m_LogicalOr());
1295bb38e84SJuneyoung Lee 
1304da3331dSChandler Carruth   // Build a worklist and recurse through operators collecting invariants.
1314da3331dSChandler Carruth   SmallVector<Instruction *, 4> Worklist;
1324da3331dSChandler Carruth   SmallPtrSet<Instruction *, 8> Visited;
1334da3331dSChandler Carruth   Worklist.push_back(&Root);
1344da3331dSChandler Carruth   Visited.insert(&Root);
1354da3331dSChandler Carruth   do {
1364da3331dSChandler Carruth     Instruction &I = *Worklist.pop_back_val();
1374da3331dSChandler Carruth     for (Value *OpV : I.operand_values()) {
1384da3331dSChandler Carruth       // Skip constants as unswitching isn't interesting for them.
1394da3331dSChandler Carruth       if (isa<Constant>(OpV))
1404da3331dSChandler Carruth         continue;
1414da3331dSChandler Carruth 
1424da3331dSChandler Carruth       // Add it to our result if loop invariant.
1434da3331dSChandler Carruth       if (L.isLoopInvariant(OpV)) {
1444da3331dSChandler Carruth         Invariants.push_back(OpV);
1454da3331dSChandler Carruth         continue;
1464da3331dSChandler Carruth       }
1474da3331dSChandler Carruth 
1484da3331dSChandler Carruth       // If not an instruction with the same opcode, nothing we can do.
1494da3331dSChandler Carruth       Instruction *OpI = dyn_cast<Instruction>(OpV);
1504da3331dSChandler Carruth 
1515bb38e84SJuneyoung Lee       if (OpI && ((IsRootAnd && match(OpI, m_LogicalAnd())) ||
1525bb38e84SJuneyoung Lee                   (IsRootOr  && match(OpI, m_LogicalOr())))) {
1534da3331dSChandler Carruth         // Visit this operand.
1544da3331dSChandler Carruth         if (Visited.insert(OpI).second)
1554da3331dSChandler Carruth           Worklist.push_back(OpI);
1564da3331dSChandler Carruth       }
1575bb38e84SJuneyoung Lee     }
1584da3331dSChandler Carruth   } while (!Worklist.empty());
1594da3331dSChandler Carruth 
1604da3331dSChandler Carruth   return Invariants;
1614da3331dSChandler Carruth }
1624da3331dSChandler Carruth 
1634da3331dSChandler Carruth static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
1641353f9a4SChandler Carruth                                      Constant &Replacement) {
1654da3331dSChandler Carruth   assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
1661353f9a4SChandler Carruth 
1671353f9a4SChandler Carruth   // Replace uses of LIC in the loop with the given constant.
1685fc9e309SKazu Hirata   // We use make_early_inc_range as set invalidates the iterator.
1695fc9e309SKazu Hirata   for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
1705fc9e309SKazu Hirata     Instruction *UserI = dyn_cast<Instruction>(U.getUser());
1711353f9a4SChandler Carruth 
1721353f9a4SChandler Carruth     // Replace this use within the loop body.
1734da3331dSChandler Carruth     if (UserI && L.contains(UserI))
1745fc9e309SKazu Hirata       U.set(&Replacement);
1751353f9a4SChandler Carruth   }
1761353f9a4SChandler Carruth }
1771353f9a4SChandler Carruth 
178d869b188SChandler Carruth /// Check that all the LCSSA PHI nodes in the loop exit block have trivial
179d869b188SChandler Carruth /// incoming values along this edge.
180d869b188SChandler Carruth static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
181d869b188SChandler Carruth                                          BasicBlock &ExitBB) {
182d869b188SChandler Carruth   for (Instruction &I : ExitBB) {
183d869b188SChandler Carruth     auto *PN = dyn_cast<PHINode>(&I);
184d869b188SChandler Carruth     if (!PN)
185d869b188SChandler Carruth       // No more PHIs to check.
186d869b188SChandler Carruth       return true;
187d869b188SChandler Carruth 
188d869b188SChandler Carruth     // If the incoming value for this edge isn't loop invariant the unswitch
189d869b188SChandler Carruth     // won't be trivial.
190d869b188SChandler Carruth     if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
191d869b188SChandler Carruth       return false;
192d869b188SChandler Carruth   }
193d869b188SChandler Carruth   llvm_unreachable("Basic blocks should never be empty!");
194d869b188SChandler Carruth }
195d869b188SChandler Carruth 
196f3a27511SJingu Kang /// Copy a set of loop invariant values \p ToDuplicate and insert them at the
197f3a27511SJingu Kang /// end of \p BB and conditionally branch on the copied condition. We only
198f3a27511SJingu Kang /// branch on a single value.
199d1dab0c3SChandler Carruth static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
200d1dab0c3SChandler Carruth                                                   ArrayRef<Value *> Invariants,
201d1dab0c3SChandler Carruth                                                   bool Direction,
202d1dab0c3SChandler Carruth                                                   BasicBlock &UnswitchedSucc,
2032b5a8976SJuneyoung Lee                                                   BasicBlock &NormalSucc) {
204d1dab0c3SChandler Carruth   IRBuilder<> IRB(&BB);
205d1dab0c3SChandler Carruth 
2069e62c864SPhilip Reames   Value *Cond = Direction ? IRB.CreateOr(Invariants) :
2079e62c864SPhilip Reames     IRB.CreateAnd(Invariants);
208d1dab0c3SChandler Carruth   IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
209d1dab0c3SChandler Carruth                    Direction ? &NormalSucc : &UnswitchedSucc);
210d1dab0c3SChandler Carruth }
211d1dab0c3SChandler Carruth 
212f3a27511SJingu Kang /// Copy a set of loop invariant values, and conditionally branch on them.
213f3a27511SJingu Kang static void buildPartialInvariantUnswitchConditionalBranch(
214f3a27511SJingu Kang     BasicBlock &BB, ArrayRef<Value *> ToDuplicate, bool Direction,
215f3a27511SJingu Kang     BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, Loop &L,
216f3a27511SJingu Kang     MemorySSAUpdater *MSSAU) {
217f3a27511SJingu Kang   ValueToValueMapTy VMap;
218f3a27511SJingu Kang   for (auto *Val : reverse(ToDuplicate)) {
219f3a27511SJingu Kang     Instruction *Inst = cast<Instruction>(Val);
220f3a27511SJingu Kang     Instruction *NewInst = Inst->clone();
221f3a27511SJingu Kang     BB.getInstList().insert(BB.end(), NewInst);
222f3a27511SJingu Kang     RemapInstruction(NewInst, VMap,
223f3a27511SJingu Kang                      RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
224f3a27511SJingu Kang     VMap[Val] = NewInst;
225f3a27511SJingu Kang 
226f3a27511SJingu Kang     if (!MSSAU)
227f3a27511SJingu Kang       continue;
228f3a27511SJingu Kang 
229f3a27511SJingu Kang     MemorySSA *MSSA = MSSAU->getMemorySSA();
230f3a27511SJingu Kang     if (auto *MemUse =
231f3a27511SJingu Kang             dyn_cast_or_null<MemoryUse>(MSSA->getMemoryAccess(Inst))) {
232f3a27511SJingu Kang       auto *DefiningAccess = MemUse->getDefiningAccess();
233f3a27511SJingu Kang       // Get the first defining access before the loop.
234f3a27511SJingu Kang       while (L.contains(DefiningAccess->getBlock())) {
235f3a27511SJingu Kang         // If the defining access is a MemoryPhi, get the incoming
236f3a27511SJingu Kang         // value for the pre-header as defining access.
237f3a27511SJingu Kang         if (auto *MemPhi = dyn_cast<MemoryPhi>(DefiningAccess))
238f3a27511SJingu Kang           DefiningAccess =
239f3a27511SJingu Kang               MemPhi->getIncomingValueForBlock(L.getLoopPreheader());
240f3a27511SJingu Kang         else
241f3a27511SJingu Kang           DefiningAccess = cast<MemoryDef>(DefiningAccess)->getDefiningAccess();
242f3a27511SJingu Kang       }
243f3a27511SJingu Kang       MSSAU->createMemoryAccessInBB(NewInst, DefiningAccess,
244f3a27511SJingu Kang                                     NewInst->getParent(),
245f3a27511SJingu Kang                                     MemorySSA::BeforeTerminator);
246f3a27511SJingu Kang     }
247f3a27511SJingu Kang   }
248f3a27511SJingu Kang 
249f3a27511SJingu Kang   IRBuilder<> IRB(&BB);
250f3a27511SJingu Kang   Value *Cond = VMap[ToDuplicate[0]];
251f3a27511SJingu Kang   IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
252f3a27511SJingu Kang                    Direction ? &NormalSucc : &UnswitchedSucc);
253f3a27511SJingu Kang }
254f3a27511SJingu Kang 
255d869b188SChandler Carruth /// Rewrite the PHI nodes in an unswitched loop exit basic block.
256d869b188SChandler Carruth ///
257d869b188SChandler Carruth /// Requires that the loop exit and unswitched basic block are the same, and
258d869b188SChandler Carruth /// that the exiting block was a unique predecessor of that block. Rewrites the
259d869b188SChandler Carruth /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
260d869b188SChandler Carruth /// PHI nodes from the old preheader that now contains the unswitched
261d869b188SChandler Carruth /// terminator.
262d869b188SChandler Carruth static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
263d869b188SChandler Carruth                                                   BasicBlock &OldExitingBB,
264d869b188SChandler Carruth                                                   BasicBlock &OldPH) {
265c7fc81e6SBenjamin Kramer   for (PHINode &PN : UnswitchedBB.phis()) {
266d869b188SChandler Carruth     // When the loop exit is directly unswitched we just need to update the
267d869b188SChandler Carruth     // incoming basic block. We loop to handle weird cases with repeated
268d869b188SChandler Carruth     // incoming blocks, but expect to typically only have one operand here.
269c7fc81e6SBenjamin Kramer     for (auto i : seq<int>(0, PN.getNumOperands())) {
270c7fc81e6SBenjamin Kramer       assert(PN.getIncomingBlock(i) == &OldExitingBB &&
271d869b188SChandler Carruth              "Found incoming block different from unique predecessor!");
272c7fc81e6SBenjamin Kramer       PN.setIncomingBlock(i, &OldPH);
273d869b188SChandler Carruth     }
274d869b188SChandler Carruth   }
275d869b188SChandler Carruth }
276d869b188SChandler Carruth 
277d869b188SChandler Carruth /// Rewrite the PHI nodes in the loop exit basic block and the split off
278d869b188SChandler Carruth /// unswitched block.
279d869b188SChandler Carruth ///
280d869b188SChandler Carruth /// Because the exit block remains an exit from the loop, this rewrites the
281d869b188SChandler Carruth /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
282d869b188SChandler Carruth /// nodes into the unswitched basic block to select between the value in the
283d869b188SChandler Carruth /// old preheader and the loop exit.
284d869b188SChandler Carruth static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
285d869b188SChandler Carruth                                                       BasicBlock &UnswitchedBB,
286d869b188SChandler Carruth                                                       BasicBlock &OldExitingBB,
2874da3331dSChandler Carruth                                                       BasicBlock &OldPH,
2884da3331dSChandler Carruth                                                       bool FullUnswitch) {
289d869b188SChandler Carruth   assert(&ExitBB != &UnswitchedBB &&
290d869b188SChandler Carruth          "Must have different loop exit and unswitched blocks!");
291d869b188SChandler Carruth   Instruction *InsertPt = &*UnswitchedBB.begin();
292c7fc81e6SBenjamin Kramer   for (PHINode &PN : ExitBB.phis()) {
293c7fc81e6SBenjamin Kramer     auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
294c7fc81e6SBenjamin Kramer                                   PN.getName() + ".split", InsertPt);
295d869b188SChandler Carruth 
296d869b188SChandler Carruth     // Walk backwards over the old PHI node's inputs to minimize the cost of
297d869b188SChandler Carruth     // removing each one. We have to do this weird loop manually so that we
298d869b188SChandler Carruth     // create the same number of new incoming edges in the new PHI as we expect
299d869b188SChandler Carruth     // each case-based edge to be included in the unswitched switch in some
300d869b188SChandler Carruth     // cases.
301d869b188SChandler Carruth     // FIXME: This is really, really gross. It would be much cleaner if LLVM
302d869b188SChandler Carruth     // allowed us to create a single entry for a predecessor block without
303d869b188SChandler Carruth     // having separate entries for each "edge" even though these edges are
304d869b188SChandler Carruth     // required to produce identical results.
305c7fc81e6SBenjamin Kramer     for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
306c7fc81e6SBenjamin Kramer       if (PN.getIncomingBlock(i) != &OldExitingBB)
307d869b188SChandler Carruth         continue;
308d869b188SChandler Carruth 
3094da3331dSChandler Carruth       Value *Incoming = PN.getIncomingValue(i);
3104da3331dSChandler Carruth       if (FullUnswitch)
3114da3331dSChandler Carruth         // No more edge from the old exiting block to the exit block.
3124da3331dSChandler Carruth         PN.removeIncomingValue(i);
3134da3331dSChandler Carruth 
314d869b188SChandler Carruth       NewPN->addIncoming(Incoming, &OldPH);
315d869b188SChandler Carruth     }
316d869b188SChandler Carruth 
317d869b188SChandler Carruth     // Now replace the old PHI with the new one and wire the old one in as an
318d869b188SChandler Carruth     // input to the new one.
319c7fc81e6SBenjamin Kramer     PN.replaceAllUsesWith(NewPN);
320c7fc81e6SBenjamin Kramer     NewPN->addIncoming(&PN, &ExitBB);
321d869b188SChandler Carruth   }
322d869b188SChandler Carruth }
323d869b188SChandler Carruth 
324d8b0c8ceSChandler Carruth /// Hoist the current loop up to the innermost loop containing a remaining exit.
325d8b0c8ceSChandler Carruth ///
326d8b0c8ceSChandler Carruth /// Because we've removed an exit from the loop, we may have changed the set of
327d8b0c8ceSChandler Carruth /// loops reachable and need to move the current loop up the loop nest or even
328d8b0c8ceSChandler Carruth /// to an entirely separate nest.
329d8b0c8ceSChandler Carruth static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
33097468e92SAlina Sbirlea                                  DominatorTree &DT, LoopInfo &LI,
331c4d8c631SDaniil Suchkov                                  MemorySSAUpdater *MSSAU, ScalarEvolution *SE) {
332d8b0c8ceSChandler Carruth   // If the loop is already at the top level, we can't hoist it anywhere.
333d8b0c8ceSChandler Carruth   Loop *OldParentL = L.getParentLoop();
334d8b0c8ceSChandler Carruth   if (!OldParentL)
335d8b0c8ceSChandler Carruth     return;
336d8b0c8ceSChandler Carruth 
337d8b0c8ceSChandler Carruth   SmallVector<BasicBlock *, 4> Exits;
338d8b0c8ceSChandler Carruth   L.getExitBlocks(Exits);
339d8b0c8ceSChandler Carruth   Loop *NewParentL = nullptr;
340d8b0c8ceSChandler Carruth   for (auto *ExitBB : Exits)
341d8b0c8ceSChandler Carruth     if (Loop *ExitL = LI.getLoopFor(ExitBB))
342d8b0c8ceSChandler Carruth       if (!NewParentL || NewParentL->contains(ExitL))
343d8b0c8ceSChandler Carruth         NewParentL = ExitL;
344d8b0c8ceSChandler Carruth 
345d8b0c8ceSChandler Carruth   if (NewParentL == OldParentL)
346d8b0c8ceSChandler Carruth     return;
347d8b0c8ceSChandler Carruth 
348d8b0c8ceSChandler Carruth   // The new parent loop (if different) should always contain the old one.
349d8b0c8ceSChandler Carruth   if (NewParentL)
350d8b0c8ceSChandler Carruth     assert(NewParentL->contains(OldParentL) &&
351d8b0c8ceSChandler Carruth            "Can only hoist this loop up the nest!");
352d8b0c8ceSChandler Carruth 
353d8b0c8ceSChandler Carruth   // The preheader will need to move with the body of this loop. However,
354d8b0c8ceSChandler Carruth   // because it isn't in this loop we also need to update the primary loop map.
355d8b0c8ceSChandler Carruth   assert(OldParentL == LI.getLoopFor(&Preheader) &&
356d8b0c8ceSChandler Carruth          "Parent loop of this loop should contain this loop's preheader!");
357d8b0c8ceSChandler Carruth   LI.changeLoopFor(&Preheader, NewParentL);
358d8b0c8ceSChandler Carruth 
359d8b0c8ceSChandler Carruth   // Remove this loop from its old parent.
360d8b0c8ceSChandler Carruth   OldParentL->removeChildLoop(&L);
361d8b0c8ceSChandler Carruth 
362d8b0c8ceSChandler Carruth   // Add the loop either to the new parent or as a top-level loop.
363d8b0c8ceSChandler Carruth   if (NewParentL)
364d8b0c8ceSChandler Carruth     NewParentL->addChildLoop(&L);
365d8b0c8ceSChandler Carruth   else
366d8b0c8ceSChandler Carruth     LI.addTopLevelLoop(&L);
367d8b0c8ceSChandler Carruth 
368d8b0c8ceSChandler Carruth   // Remove this loops blocks from the old parent and every other loop up the
369d8b0c8ceSChandler Carruth   // nest until reaching the new parent. Also update all of these
370d8b0c8ceSChandler Carruth   // no-longer-containing loops to reflect the nesting change.
371d8b0c8ceSChandler Carruth   for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
372d8b0c8ceSChandler Carruth        OldContainingL = OldContainingL->getParentLoop()) {
373d8b0c8ceSChandler Carruth     llvm::erase_if(OldContainingL->getBlocksVector(),
374d8b0c8ceSChandler Carruth                    [&](const BasicBlock *BB) {
375d8b0c8ceSChandler Carruth                      return BB == &Preheader || L.contains(BB);
376d8b0c8ceSChandler Carruth                    });
377d8b0c8ceSChandler Carruth 
378d8b0c8ceSChandler Carruth     OldContainingL->getBlocksSet().erase(&Preheader);
379d8b0c8ceSChandler Carruth     for (BasicBlock *BB : L.blocks())
380d8b0c8ceSChandler Carruth       OldContainingL->getBlocksSet().erase(BB);
381d8b0c8ceSChandler Carruth 
382d8b0c8ceSChandler Carruth     // Because we just hoisted a loop out of this one, we have essentially
383d8b0c8ceSChandler Carruth     // created new exit paths from it. That means we need to form LCSSA PHI
384d8b0c8ceSChandler Carruth     // nodes for values used in the no-longer-nested loop.
385c4d8c631SDaniil Suchkov     formLCSSA(*OldContainingL, DT, &LI, SE);
386d8b0c8ceSChandler Carruth 
387d8b0c8ceSChandler Carruth     // We shouldn't need to form dedicated exits because the exit introduced
38852e97a28SAlina Sbirlea     // here is the (just split by unswitching) preheader. However, after trivial
38952e97a28SAlina Sbirlea     // unswitching it is possible to get new non-dedicated exits out of parent
39052e97a28SAlina Sbirlea     // loop so let's conservatively form dedicated exit blocks and figure out
39152e97a28SAlina Sbirlea     // if we can optimize later.
39297468e92SAlina Sbirlea     formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
39397468e92SAlina Sbirlea                             /*PreserveLCSSA*/ true);
394d8b0c8ceSChandler Carruth   }
395d8b0c8ceSChandler Carruth }
396d8b0c8ceSChandler Carruth 
3974a9cde5aSFlorian Hahn // Return the top-most loop containing ExitBB and having ExitBB as exiting block
3984a9cde5aSFlorian Hahn // or the loop containing ExitBB, if there is no parent loop containing ExitBB
3994a9cde5aSFlorian Hahn // as exiting block.
4004a9cde5aSFlorian Hahn static Loop *getTopMostExitingLoop(BasicBlock *ExitBB, LoopInfo &LI) {
4014a9cde5aSFlorian Hahn   Loop *TopMost = LI.getLoopFor(ExitBB);
4024a9cde5aSFlorian Hahn   Loop *Current = TopMost;
4034a9cde5aSFlorian Hahn   while (Current) {
4044a9cde5aSFlorian Hahn     if (Current->isLoopExiting(ExitBB))
4054a9cde5aSFlorian Hahn       TopMost = Current;
4064a9cde5aSFlorian Hahn     Current = Current->getParentLoop();
4074a9cde5aSFlorian Hahn   }
4084a9cde5aSFlorian Hahn   return TopMost;
4094a9cde5aSFlorian Hahn }
4104a9cde5aSFlorian Hahn 
4111353f9a4SChandler Carruth /// Unswitch a trivial branch if the condition is loop invariant.
4121353f9a4SChandler Carruth ///
4131353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the branch has
4141353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the
4151353f9a4SChandler Carruth /// condition is invariant and one of the successors is a loop exit. This
4161353f9a4SChandler Carruth /// allows us to unswitch without duplicating the loop, making it trivial.
4171353f9a4SChandler Carruth ///
4181353f9a4SChandler Carruth /// If this routine fails to unswitch the branch it returns false.
4191353f9a4SChandler Carruth ///
4201353f9a4SChandler Carruth /// If the branch can be unswitched, this routine splits the preheader and
4211353f9a4SChandler Carruth /// hoists the branch above that split. Preserves loop simplified form
4221353f9a4SChandler Carruth /// (splitting the exit block as necessary). It simplifies the branch within
4231353f9a4SChandler Carruth /// the loop to an unconditional branch but doesn't remove it entirely. Further
424472462c4SBjorn Pettersson /// cleanup can be done with some simplifycfg like pass.
4253897ded6SChandler Carruth ///
4263897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
4273897ded6SChandler Carruth /// invalidated by this.
4281353f9a4SChandler Carruth static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
429a2eebb82SAlina Sbirlea                                   LoopInfo &LI, ScalarEvolution *SE,
430a2eebb82SAlina Sbirlea                                   MemorySSAUpdater *MSSAU) {
4311353f9a4SChandler Carruth   assert(BI.isConditional() && "Can only unswitch a conditional branch!");
432d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Trying to unswitch branch: " << BI << "\n");
4331353f9a4SChandler Carruth 
4344da3331dSChandler Carruth   // The loop invariant values that we want to unswitch.
435d1dab0c3SChandler Carruth   TinyPtrVector<Value *> Invariants;
4361353f9a4SChandler Carruth 
4374da3331dSChandler Carruth   // When true, we're fully unswitching the branch rather than just unswitching
4384da3331dSChandler Carruth   // some input conditions to the branch.
4394da3331dSChandler Carruth   bool FullUnswitch = false;
4404da3331dSChandler Carruth 
4414da3331dSChandler Carruth   if (L.isLoopInvariant(BI.getCondition())) {
4424da3331dSChandler Carruth     Invariants.push_back(BI.getCondition());
4434da3331dSChandler Carruth     FullUnswitch = true;
4444da3331dSChandler Carruth   } else {
4454da3331dSChandler Carruth     if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
4464da3331dSChandler Carruth       Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
44784eeb828SRoman Lebedev     if (Invariants.empty()) {
44884eeb828SRoman Lebedev       LLVM_DEBUG(dbgs() << "   Couldn't find invariant inputs!\n");
4491353f9a4SChandler Carruth       return false;
4504da3331dSChandler Carruth     }
45184eeb828SRoman Lebedev   }
4521353f9a4SChandler Carruth 
4534da3331dSChandler Carruth   // Check that one of the branch's successors exits, and which one.
4544da3331dSChandler Carruth   bool ExitDirection = true;
4551353f9a4SChandler Carruth   int LoopExitSuccIdx = 0;
4561353f9a4SChandler Carruth   auto *LoopExitBB = BI.getSuccessor(0);
457baf045fbSChandler Carruth   if (L.contains(LoopExitBB)) {
4584da3331dSChandler Carruth     ExitDirection = false;
4591353f9a4SChandler Carruth     LoopExitSuccIdx = 1;
4601353f9a4SChandler Carruth     LoopExitBB = BI.getSuccessor(1);
46184eeb828SRoman Lebedev     if (L.contains(LoopExitBB)) {
46284eeb828SRoman Lebedev       LLVM_DEBUG(dbgs() << "   Branch doesn't exit the loop!\n");
4631353f9a4SChandler Carruth       return false;
4641353f9a4SChandler Carruth     }
46584eeb828SRoman Lebedev   }
4661353f9a4SChandler Carruth   auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
467d869b188SChandler Carruth   auto *ParentBB = BI.getParent();
46884eeb828SRoman Lebedev   if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) {
46984eeb828SRoman Lebedev     LLVM_DEBUG(dbgs() << "   Loop exit PHI's aren't loop-invariant!\n");
4701353f9a4SChandler Carruth     return false;
47184eeb828SRoman Lebedev   }
4721353f9a4SChandler Carruth 
4734da3331dSChandler Carruth   // When unswitching only part of the branch's condition, we need the exit
4744da3331dSChandler Carruth   // block to be reached directly from the partially unswitched input. This can
4754da3331dSChandler Carruth   // be done when the exit block is along the true edge and the branch condition
4764da3331dSChandler Carruth   // is a graph of `or` operations, or the exit block is along the false edge
4774da3331dSChandler Carruth   // and the condition is a graph of `and` operations.
4784da3331dSChandler Carruth   if (!FullUnswitch) {
47984eeb828SRoman Lebedev     if (ExitDirection ? !match(BI.getCondition(), m_LogicalOr())
48084eeb828SRoman Lebedev                       : !match(BI.getCondition(), m_LogicalAnd())) {
48184eeb828SRoman Lebedev       LLVM_DEBUG(dbgs() << "   Branch condition is in improper form for "
48284eeb828SRoman Lebedev                            "non-full unswitch!\n");
4834da3331dSChandler Carruth       return false;
4844da3331dSChandler Carruth     }
4854da3331dSChandler Carruth   }
4864da3331dSChandler Carruth 
4874da3331dSChandler Carruth   LLVM_DEBUG({
4884da3331dSChandler Carruth     dbgs() << "    unswitching trivial invariant conditions for: " << BI
4894da3331dSChandler Carruth            << "\n";
4904da3331dSChandler Carruth     for (Value *Invariant : Invariants) {
4914da3331dSChandler Carruth       dbgs() << "      " << *Invariant << " == true";
4924da3331dSChandler Carruth       if (Invariant != Invariants.back())
4934da3331dSChandler Carruth         dbgs() << " ||";
4944da3331dSChandler Carruth       dbgs() << "\n";
4954da3331dSChandler Carruth     }
4964da3331dSChandler Carruth   });
4971353f9a4SChandler Carruth 
4983897ded6SChandler Carruth   // If we have scalar evolutions, we need to invalidate them including this
4994a9cde5aSFlorian Hahn   // loop, the loop containing the exit block and the topmost parent loop
5004a9cde5aSFlorian Hahn   // exiting via LoopExitBB.
5013897ded6SChandler Carruth   if (SE) {
5024a9cde5aSFlorian Hahn     if (Loop *ExitL = getTopMostExitingLoop(LoopExitBB, LI))
5033897ded6SChandler Carruth       SE->forgetLoop(ExitL);
5043897ded6SChandler Carruth     else
5053897ded6SChandler Carruth       // Forget the entire nest as this exits the entire nest.
5063897ded6SChandler Carruth       SE->forgetTopmostLoop(&L);
5073897ded6SChandler Carruth   }
5083897ded6SChandler Carruth 
509a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
510a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
511a2eebb82SAlina Sbirlea 
5121353f9a4SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
5131353f9a4SChandler Carruth   // the conditional branch. We will change the preheader to have a conditional
5141353f9a4SChandler Carruth   // branch on LoopCond.
5151353f9a4SChandler Carruth   BasicBlock *OldPH = L.getLoopPreheader();
516a2eebb82SAlina Sbirlea   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
5171353f9a4SChandler Carruth 
5181353f9a4SChandler Carruth   // Now that we have a place to insert the conditional branch, create a place
5191353f9a4SChandler Carruth   // to branch to: this is the exit block out of the loop that we are
5201353f9a4SChandler Carruth   // unswitching. We need to split this if there are other loop predecessors.
5211353f9a4SChandler Carruth   // Because the loop is in simplified form, *any* other predecessor is enough.
5221353f9a4SChandler Carruth   BasicBlock *UnswitchedBB;
5234da3331dSChandler Carruth   if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
5244da3331dSChandler Carruth     assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
525d869b188SChandler Carruth            "A branch's parent isn't a predecessor!");
5261353f9a4SChandler Carruth     UnswitchedBB = LoopExitBB;
5271353f9a4SChandler Carruth   } else {
528a2eebb82SAlina Sbirlea     UnswitchedBB =
529a2eebb82SAlina Sbirlea         SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
5301353f9a4SChandler Carruth   }
5311353f9a4SChandler Carruth 
532a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
533a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
534a2eebb82SAlina Sbirlea 
5354da3331dSChandler Carruth   // Actually move the invariant uses into the unswitched position. If possible,
5364da3331dSChandler Carruth   // we do this by moving the instructions, but when doing partial unswitching
5374da3331dSChandler Carruth   // we do it by building a new merge of the values in the unswitched position.
5381353f9a4SChandler Carruth   OldPH->getTerminator()->eraseFromParent();
5394da3331dSChandler Carruth   if (FullUnswitch) {
5404da3331dSChandler Carruth     // If fully unswitching, we can use the existing branch instruction.
5414da3331dSChandler Carruth     // Splice it into the old PH to gate reaching the new preheader and re-point
5424da3331dSChandler Carruth     // its successors.
5434da3331dSChandler Carruth     OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
5444da3331dSChandler Carruth                                 BI);
545a2eebb82SAlina Sbirlea     if (MSSAU) {
546a2eebb82SAlina Sbirlea       // Temporarily clone the terminator, to make MSSA update cheaper by
547a2eebb82SAlina Sbirlea       // separating "insert edge" updates from "remove edge" ones.
548a2eebb82SAlina Sbirlea       ParentBB->getInstList().push_back(BI.clone());
549a2eebb82SAlina Sbirlea     } else {
5501353f9a4SChandler Carruth       // Create a new unconditional branch that will continue the loop as a new
5511353f9a4SChandler Carruth       // terminator.
5521353f9a4SChandler Carruth       BranchInst::Create(ContinueBB, ParentBB);
553a2eebb82SAlina Sbirlea     }
554a2eebb82SAlina Sbirlea     BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
555a2eebb82SAlina Sbirlea     BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
5564da3331dSChandler Carruth   } else {
5574da3331dSChandler Carruth     // Only unswitching a subset of inputs to the condition, so we will need to
5584da3331dSChandler Carruth     // build a new branch that merges the invariant inputs.
5594da3331dSChandler Carruth     if (ExitDirection)
5605bb38e84SJuneyoung Lee       assert(match(BI.getCondition(), m_LogicalOr()) &&
5615bb38e84SJuneyoung Lee              "Must have an `or` of `i1`s or `select i1 X, true, Y`s for the "
5625bb38e84SJuneyoung Lee              "condition!");
5634da3331dSChandler Carruth     else
5645bb38e84SJuneyoung Lee       assert(match(BI.getCondition(), m_LogicalAnd()) &&
5655bb38e84SJuneyoung Lee              "Must have an `and` of `i1`s or `select i1 X, Y, false`s for the"
5665bb38e84SJuneyoung Lee              " condition!");
567d1dab0c3SChandler Carruth     buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
5682b5a8976SJuneyoung Lee                                           *UnswitchedBB, *NewPH);
5694da3331dSChandler Carruth   }
5701353f9a4SChandler Carruth 
571a2eebb82SAlina Sbirlea   // Update the dominator tree with the added edge.
572a2eebb82SAlina Sbirlea   DT.insertEdge(OldPH, UnswitchedBB);
573a2eebb82SAlina Sbirlea 
574a2eebb82SAlina Sbirlea   // After the dominator tree was updated with the added edge, update MemorySSA
575a2eebb82SAlina Sbirlea   // if available.
576a2eebb82SAlina Sbirlea   if (MSSAU) {
577a2eebb82SAlina Sbirlea     SmallVector<CFGUpdate, 1> Updates;
578a2eebb82SAlina Sbirlea     Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
579a2eebb82SAlina Sbirlea     MSSAU->applyInsertUpdates(Updates, DT);
580a2eebb82SAlina Sbirlea   }
581a2eebb82SAlina Sbirlea 
582a2eebb82SAlina Sbirlea   // Finish updating dominator tree and memory ssa for full unswitch.
583a2eebb82SAlina Sbirlea   if (FullUnswitch) {
584a2eebb82SAlina Sbirlea     if (MSSAU) {
585a2eebb82SAlina Sbirlea       // Remove the cloned branch instruction.
586a2eebb82SAlina Sbirlea       ParentBB->getTerminator()->eraseFromParent();
587a2eebb82SAlina Sbirlea       // Create unconditional branch now.
588a2eebb82SAlina Sbirlea       BranchInst::Create(ContinueBB, ParentBB);
589a2eebb82SAlina Sbirlea       MSSAU->removeEdge(ParentBB, LoopExitBB);
590a2eebb82SAlina Sbirlea     }
591a2eebb82SAlina Sbirlea     DT.deleteEdge(ParentBB, LoopExitBB);
592a2eebb82SAlina Sbirlea   }
593a2eebb82SAlina Sbirlea 
594a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
595a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
596a2eebb82SAlina Sbirlea 
597d869b188SChandler Carruth   // Rewrite the relevant PHI nodes.
598d869b188SChandler Carruth   if (UnswitchedBB == LoopExitBB)
599d869b188SChandler Carruth     rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
600d869b188SChandler Carruth   else
601d869b188SChandler Carruth     rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
6024da3331dSChandler Carruth                                               *ParentBB, *OldPH, FullUnswitch);
603d869b188SChandler Carruth 
6044da3331dSChandler Carruth   // The constant we can replace all of our invariants with inside the loop
6054da3331dSChandler Carruth   // body. If any of the invariants have a value other than this the loop won't
6064da3331dSChandler Carruth   // be entered.
6074da3331dSChandler Carruth   ConstantInt *Replacement = ExitDirection
6084da3331dSChandler Carruth                                  ? ConstantInt::getFalse(BI.getContext())
6094da3331dSChandler Carruth                                  : ConstantInt::getTrue(BI.getContext());
6101353f9a4SChandler Carruth 
6111353f9a4SChandler Carruth   // Since this is an i1 condition we can also trivially replace uses of it
6121353f9a4SChandler Carruth   // within the loop with a constant.
6134da3331dSChandler Carruth   for (Value *Invariant : Invariants)
6144da3331dSChandler Carruth     replaceLoopInvariantUses(L, Invariant, *Replacement);
6151353f9a4SChandler Carruth 
616d8b0c8ceSChandler Carruth   // If this was full unswitching, we may have changed the nesting relationship
617d8b0c8ceSChandler Carruth   // for this loop so hoist it to its correct parent if needed.
618d8b0c8ceSChandler Carruth   if (FullUnswitch)
619c4d8c631SDaniil Suchkov     hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
62097468e92SAlina Sbirlea 
62197468e92SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
62297468e92SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
623d8b0c8ceSChandler Carruth 
62452e97a28SAlina Sbirlea   LLVM_DEBUG(dbgs() << "    done: unswitching trivial branch...\n");
6251353f9a4SChandler Carruth   ++NumTrivial;
6261353f9a4SChandler Carruth   ++NumBranches;
6271353f9a4SChandler Carruth   return true;
6281353f9a4SChandler Carruth }
6291353f9a4SChandler Carruth 
6301353f9a4SChandler Carruth /// Unswitch a trivial switch if the condition is loop invariant.
6311353f9a4SChandler Carruth ///
6321353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the switch has
6331353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the
6341353f9a4SChandler Carruth /// condition is invariant and that at least one of the successors is a loop
6351353f9a4SChandler Carruth /// exit. This allows us to unswitch without duplicating the loop, making it
6361353f9a4SChandler Carruth /// trivial.
6371353f9a4SChandler Carruth ///
6381353f9a4SChandler Carruth /// If this routine fails to unswitch the switch it returns false.
6391353f9a4SChandler Carruth ///
6401353f9a4SChandler Carruth /// If the switch can be unswitched, this routine splits the preheader and
6411353f9a4SChandler Carruth /// copies the switch above that split. If the default case is one of the
6421353f9a4SChandler Carruth /// exiting cases, it copies the non-exiting cases and points them at the new
6431353f9a4SChandler Carruth /// preheader. If the default case is not exiting, it copies the exiting cases
6441353f9a4SChandler Carruth /// and points the default at the preheader. It preserves loop simplified form
6451353f9a4SChandler Carruth /// (splitting the exit blocks as necessary). It simplifies the switch within
6461353f9a4SChandler Carruth /// the loop by removing now-dead cases. If the default case is one of those
6471353f9a4SChandler Carruth /// unswitched, it replaces its destination with a new basic block containing
6481353f9a4SChandler Carruth /// only unreachable. Such basic blocks, while technically loop exits, are not
6491353f9a4SChandler Carruth /// considered for unswitching so this is a stable transform and the same
6501353f9a4SChandler Carruth /// switch will not be revisited. If after unswitching there is only a single
6511353f9a4SChandler Carruth /// in-loop successor, the switch is further simplified to an unconditional
652472462c4SBjorn Pettersson /// branch. Still more cleanup can be done with some simplifycfg like pass.
6533897ded6SChandler Carruth ///
6543897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
6553897ded6SChandler Carruth /// invalidated by this.
6561353f9a4SChandler Carruth static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
657a2eebb82SAlina Sbirlea                                   LoopInfo &LI, ScalarEvolution *SE,
658a2eebb82SAlina Sbirlea                                   MemorySSAUpdater *MSSAU) {
659d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Trying to unswitch switch: " << SI << "\n");
6601353f9a4SChandler Carruth   Value *LoopCond = SI.getCondition();
6611353f9a4SChandler Carruth 
6621353f9a4SChandler Carruth   // If this isn't switching on an invariant condition, we can't unswitch it.
6631353f9a4SChandler Carruth   if (!L.isLoopInvariant(LoopCond))
6641353f9a4SChandler Carruth     return false;
6651353f9a4SChandler Carruth 
666d869b188SChandler Carruth   auto *ParentBB = SI.getParent();
667d869b188SChandler Carruth 
668db04ff4bSAlina Sbirlea   // The same check must be used both for the default and the exit cases. We
669db04ff4bSAlina Sbirlea   // should never leave edges from the switch instruction to a basic block that
670db04ff4bSAlina Sbirlea   // we are unswitching, hence the condition used to determine the default case
671db04ff4bSAlina Sbirlea   // needs to also be used to populate ExitCaseIndices, which is then used to
672db04ff4bSAlina Sbirlea   // remove cases from the switch.
6736227f021SAlina Sbirlea   auto IsTriviallyUnswitchableExitBlock = [&](BasicBlock &BBToCheck) {
6746227f021SAlina Sbirlea     // BBToCheck is not an exit block if it is inside loop L.
6756227f021SAlina Sbirlea     if (L.contains(&BBToCheck))
6766227f021SAlina Sbirlea       return false;
6776227f021SAlina Sbirlea     // BBToCheck is not trivial to unswitch if its phis aren't loop invariant.
6786227f021SAlina Sbirlea     if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, BBToCheck))
6796227f021SAlina Sbirlea       return false;
6806227f021SAlina Sbirlea     // We do not unswitch a block that only has an unreachable statement, as
6816227f021SAlina Sbirlea     // it's possible this is a previously unswitched block. Only unswitch if
6826227f021SAlina Sbirlea     // either the terminator is not unreachable, or, if it is, it's not the only
6836227f021SAlina Sbirlea     // instruction in the block.
6846227f021SAlina Sbirlea     auto *TI = BBToCheck.getTerminator();
6856227f021SAlina Sbirlea     bool isUnreachable = isa<UnreachableInst>(TI);
6866227f021SAlina Sbirlea     return !isUnreachable ||
6876227f021SAlina Sbirlea            (isUnreachable && (BBToCheck.getFirstNonPHIOrDbg() != TI));
6886227f021SAlina Sbirlea   };
6896227f021SAlina Sbirlea 
6901353f9a4SChandler Carruth   SmallVector<int, 4> ExitCaseIndices;
691db04ff4bSAlina Sbirlea   for (auto Case : SI.cases())
692db04ff4bSAlina Sbirlea     if (IsTriviallyUnswitchableExitBlock(*Case.getCaseSuccessor()))
6931353f9a4SChandler Carruth       ExitCaseIndices.push_back(Case.getCaseIndex());
6941353f9a4SChandler Carruth   BasicBlock *DefaultExitBB = nullptr;
695d4097b4aSYevgeny Rouban   SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight =
696d4097b4aSYevgeny Rouban       SwitchInstProfUpdateWrapper::getSuccessorWeight(SI, 0);
6976227f021SAlina Sbirlea   if (IsTriviallyUnswitchableExitBlock(*SI.getDefaultDest())) {
6981353f9a4SChandler Carruth     DefaultExitBB = SI.getDefaultDest();
699d4097b4aSYevgeny Rouban   } else if (ExitCaseIndices.empty())
7001353f9a4SChandler Carruth     return false;
7011353f9a4SChandler Carruth 
70252e97a28SAlina Sbirlea   LLVM_DEBUG(dbgs() << "    unswitching trivial switch...\n");
7031353f9a4SChandler Carruth 
704a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
705a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
706a2eebb82SAlina Sbirlea 
7073897ded6SChandler Carruth   // We may need to invalidate SCEVs for the outermost loop reached by any of
7083897ded6SChandler Carruth   // the exits.
7093897ded6SChandler Carruth   Loop *OuterL = &L;
7103897ded6SChandler Carruth 
71147dc3a34SChandler Carruth   if (DefaultExitBB) {
71247dc3a34SChandler Carruth     // Clear out the default destination temporarily to allow accurate
71347dc3a34SChandler Carruth     // predecessor lists to be examined below.
71447dc3a34SChandler Carruth     SI.setDefaultDest(nullptr);
71547dc3a34SChandler Carruth     // Check the loop containing this exit.
71647dc3a34SChandler Carruth     Loop *ExitL = LI.getLoopFor(DefaultExitBB);
71747dc3a34SChandler Carruth     if (!ExitL || ExitL->contains(OuterL))
71847dc3a34SChandler Carruth       OuterL = ExitL;
71947dc3a34SChandler Carruth   }
72047dc3a34SChandler Carruth 
72147dc3a34SChandler Carruth   // Store the exit cases into a separate data structure and remove them from
72247dc3a34SChandler Carruth   // the switch.
723d4097b4aSYevgeny Rouban   SmallVector<std::tuple<ConstantInt *, BasicBlock *,
724d4097b4aSYevgeny Rouban                          SwitchInstProfUpdateWrapper::CaseWeightOpt>,
725d4097b4aSYevgeny Rouban               4> ExitCases;
7261353f9a4SChandler Carruth   ExitCases.reserve(ExitCaseIndices.size());
727d4097b4aSYevgeny Rouban   SwitchInstProfUpdateWrapper SIW(SI);
7281353f9a4SChandler Carruth   // We walk the case indices backwards so that we remove the last case first
7291353f9a4SChandler Carruth   // and don't disrupt the earlier indices.
7301353f9a4SChandler Carruth   for (unsigned Index : reverse(ExitCaseIndices)) {
7311353f9a4SChandler Carruth     auto CaseI = SI.case_begin() + Index;
7323897ded6SChandler Carruth     // Compute the outer loop from this exit.
7333897ded6SChandler Carruth     Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
7343897ded6SChandler Carruth     if (!ExitL || ExitL->contains(OuterL))
7353897ded6SChandler Carruth       OuterL = ExitL;
7361353f9a4SChandler Carruth     // Save the value of this case.
737d4097b4aSYevgeny Rouban     auto W = SIW.getSuccessorWeight(CaseI->getSuccessorIndex());
738d4097b4aSYevgeny Rouban     ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W);
7391353f9a4SChandler Carruth     // Delete the unswitched cases.
740d4097b4aSYevgeny Rouban     SIW.removeCase(CaseI);
7411353f9a4SChandler Carruth   }
7421353f9a4SChandler Carruth 
7433897ded6SChandler Carruth   if (SE) {
7443897ded6SChandler Carruth     if (OuterL)
7453897ded6SChandler Carruth       SE->forgetLoop(OuterL);
7463897ded6SChandler Carruth     else
7473897ded6SChandler Carruth       SE->forgetTopmostLoop(&L);
7483897ded6SChandler Carruth   }
7493897ded6SChandler Carruth 
7501353f9a4SChandler Carruth   // Check if after this all of the remaining cases point at the same
7511353f9a4SChandler Carruth   // successor.
7521353f9a4SChandler Carruth   BasicBlock *CommonSuccBB = nullptr;
7531353f9a4SChandler Carruth   if (SI.getNumCases() > 0 &&
754b023cdeaSKazu Hirata       all_of(drop_begin(SI.cases()), [&SI](const SwitchInst::CaseHandle &Case) {
755b023cdeaSKazu Hirata         return Case.getCaseSuccessor() == SI.case_begin()->getCaseSuccessor();
7561353f9a4SChandler Carruth       }))
7571353f9a4SChandler Carruth     CommonSuccBB = SI.case_begin()->getCaseSuccessor();
75847dc3a34SChandler Carruth   if (!DefaultExitBB) {
7591353f9a4SChandler Carruth     // If we're not unswitching the default, we need it to match any cases to
7601353f9a4SChandler Carruth     // have a common successor or if we have no cases it is the common
7611353f9a4SChandler Carruth     // successor.
7621353f9a4SChandler Carruth     if (SI.getNumCases() == 0)
7631353f9a4SChandler Carruth       CommonSuccBB = SI.getDefaultDest();
7641353f9a4SChandler Carruth     else if (SI.getDefaultDest() != CommonSuccBB)
7651353f9a4SChandler Carruth       CommonSuccBB = nullptr;
7661353f9a4SChandler Carruth   }
7671353f9a4SChandler Carruth 
7681353f9a4SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
7691353f9a4SChandler Carruth   // the switch.
7701353f9a4SChandler Carruth   BasicBlock *OldPH = L.getLoopPreheader();
771a2eebb82SAlina Sbirlea   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
7721353f9a4SChandler Carruth   OldPH->getTerminator()->eraseFromParent();
7731353f9a4SChandler Carruth 
7741353f9a4SChandler Carruth   // Now add the unswitched switch.
7751353f9a4SChandler Carruth   auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
776d4097b4aSYevgeny Rouban   SwitchInstProfUpdateWrapper NewSIW(*NewSI);
7771353f9a4SChandler Carruth 
778d869b188SChandler Carruth   // Rewrite the IR for the unswitched basic blocks. This requires two steps.
779d869b188SChandler Carruth   // First, we split any exit blocks with remaining in-loop predecessors. Then
780d869b188SChandler Carruth   // we update the PHIs in one of two ways depending on if there was a split.
781d869b188SChandler Carruth   // We walk in reverse so that we split in the same order as the cases
782d869b188SChandler Carruth   // appeared. This is purely for convenience of reading the resulting IR, but
783d869b188SChandler Carruth   // it doesn't cost anything really.
784d869b188SChandler Carruth   SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
7851353f9a4SChandler Carruth   SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
7861353f9a4SChandler Carruth   // Handle the default exit if necessary.
7871353f9a4SChandler Carruth   // FIXME: It'd be great if we could merge this with the loop below but LLVM's
7881353f9a4SChandler Carruth   // ranges aren't quite powerful enough yet.
789d869b188SChandler Carruth   if (DefaultExitBB) {
790d869b188SChandler Carruth     if (pred_empty(DefaultExitBB)) {
791d869b188SChandler Carruth       UnswitchedExitBBs.insert(DefaultExitBB);
792d869b188SChandler Carruth       rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
793d869b188SChandler Carruth     } else {
7941353f9a4SChandler Carruth       auto *SplitBB =
795a2eebb82SAlina Sbirlea           SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
796a2eebb82SAlina Sbirlea       rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
797a2eebb82SAlina Sbirlea                                                 *ParentBB, *OldPH,
798a2eebb82SAlina Sbirlea                                                 /*FullUnswitch*/ true);
7991353f9a4SChandler Carruth       DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
8001353f9a4SChandler Carruth     }
801d869b188SChandler Carruth   }
8021353f9a4SChandler Carruth   // Note that we must use a reference in the for loop so that we update the
8031353f9a4SChandler Carruth   // container.
804d4097b4aSYevgeny Rouban   for (auto &ExitCase : reverse(ExitCases)) {
8051353f9a4SChandler Carruth     // Grab a reference to the exit block in the pair so that we can update it.
806d4097b4aSYevgeny Rouban     BasicBlock *ExitBB = std::get<1>(ExitCase);
8071353f9a4SChandler Carruth 
8081353f9a4SChandler Carruth     // If this case is the last edge into the exit block, we can simply reuse it
8091353f9a4SChandler Carruth     // as it will no longer be a loop exit. No mapping necessary.
810d869b188SChandler Carruth     if (pred_empty(ExitBB)) {
811d869b188SChandler Carruth       // Only rewrite once.
812d869b188SChandler Carruth       if (UnswitchedExitBBs.insert(ExitBB).second)
813d869b188SChandler Carruth         rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
8141353f9a4SChandler Carruth       continue;
815d869b188SChandler Carruth     }
8161353f9a4SChandler Carruth 
8171353f9a4SChandler Carruth     // Otherwise we need to split the exit block so that we retain an exit
8181353f9a4SChandler Carruth     // block from the loop and a target for the unswitched condition.
8191353f9a4SChandler Carruth     BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
8201353f9a4SChandler Carruth     if (!SplitExitBB) {
8211353f9a4SChandler Carruth       // If this is the first time we see this, do the split and remember it.
822a2eebb82SAlina Sbirlea       SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
823a2eebb82SAlina Sbirlea       rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
824a2eebb82SAlina Sbirlea                                                 *ParentBB, *OldPH,
825a2eebb82SAlina Sbirlea                                                 /*FullUnswitch*/ true);
8261353f9a4SChandler Carruth     }
827d869b188SChandler Carruth     // Update the case pair to point to the split block.
828d4097b4aSYevgeny Rouban     std::get<1>(ExitCase) = SplitExitBB;
8291353f9a4SChandler Carruth   }
8301353f9a4SChandler Carruth 
8311353f9a4SChandler Carruth   // Now add the unswitched cases. We do this in reverse order as we built them
8321353f9a4SChandler Carruth   // in reverse order.
833d4097b4aSYevgeny Rouban   for (auto &ExitCase : reverse(ExitCases)) {
834d4097b4aSYevgeny Rouban     ConstantInt *CaseVal = std::get<0>(ExitCase);
835d4097b4aSYevgeny Rouban     BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
8361353f9a4SChandler Carruth 
837d4097b4aSYevgeny Rouban     NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
8381353f9a4SChandler Carruth   }
8391353f9a4SChandler Carruth 
8401353f9a4SChandler Carruth   // If the default was unswitched, re-point it and add explicit cases for
8411353f9a4SChandler Carruth   // entering the loop.
8421353f9a4SChandler Carruth   if (DefaultExitBB) {
843d4097b4aSYevgeny Rouban     NewSIW->setDefaultDest(DefaultExitBB);
844d4097b4aSYevgeny Rouban     NewSIW.setSuccessorWeight(0, DefaultCaseWeight);
8451353f9a4SChandler Carruth 
8461353f9a4SChandler Carruth     // We removed all the exit cases, so we just copy the cases to the
8471353f9a4SChandler Carruth     // unswitched switch.
848d4097b4aSYevgeny Rouban     for (const auto &Case : SI.cases())
849d4097b4aSYevgeny Rouban       NewSIW.addCase(Case.getCaseValue(), NewPH,
850d4097b4aSYevgeny Rouban                      SIW.getSuccessorWeight(Case.getSuccessorIndex()));
851d4097b4aSYevgeny Rouban   } else if (DefaultCaseWeight) {
852d4097b4aSYevgeny Rouban     // We have to set branch weight of the default case.
853d4097b4aSYevgeny Rouban     uint64_t SW = *DefaultCaseWeight;
854d4097b4aSYevgeny Rouban     for (const auto &Case : SI.cases()) {
855d4097b4aSYevgeny Rouban       auto W = SIW.getSuccessorWeight(Case.getSuccessorIndex());
856d4097b4aSYevgeny Rouban       assert(W &&
857d4097b4aSYevgeny Rouban              "case weight must be defined as default case weight is defined");
858d4097b4aSYevgeny Rouban       SW += *W;
859d4097b4aSYevgeny Rouban     }
860d4097b4aSYevgeny Rouban     NewSIW.setSuccessorWeight(0, SW);
8611353f9a4SChandler Carruth   }
8621353f9a4SChandler Carruth 
8631353f9a4SChandler Carruth   // If we ended up with a common successor for every path through the switch
8641353f9a4SChandler Carruth   // after unswitching, rewrite it to an unconditional branch to make it easy
8651353f9a4SChandler Carruth   // to recognize. Otherwise we potentially have to recognize the default case
8661353f9a4SChandler Carruth   // pointing at unreachable and other complexity.
8671353f9a4SChandler Carruth   if (CommonSuccBB) {
8681353f9a4SChandler Carruth     BasicBlock *BB = SI.getParent();
86947dc3a34SChandler Carruth     // We may have had multiple edges to this common successor block, so remove
87047dc3a34SChandler Carruth     // them as predecessors. We skip the first one, either the default or the
87147dc3a34SChandler Carruth     // actual first case.
87247dc3a34SChandler Carruth     bool SkippedFirst = DefaultExitBB == nullptr;
87347dc3a34SChandler Carruth     for (auto Case : SI.cases()) {
87447dc3a34SChandler Carruth       assert(Case.getCaseSuccessor() == CommonSuccBB &&
87547dc3a34SChandler Carruth              "Non-common successor!");
876148861f5SChandler Carruth       (void)Case;
87747dc3a34SChandler Carruth       if (!SkippedFirst) {
87847dc3a34SChandler Carruth         SkippedFirst = true;
87947dc3a34SChandler Carruth         continue;
88047dc3a34SChandler Carruth       }
88147dc3a34SChandler Carruth       CommonSuccBB->removePredecessor(BB,
88220b91899SMax Kazantsev                                       /*KeepOneInputPHIs*/ true);
88347dc3a34SChandler Carruth     }
88447dc3a34SChandler Carruth     // Now nuke the switch and replace it with a direct branch.
885d4097b4aSYevgeny Rouban     SIW.eraseFromParent();
8861353f9a4SChandler Carruth     BranchInst::Create(CommonSuccBB, BB);
88747dc3a34SChandler Carruth   } else if (DefaultExitBB) {
88847dc3a34SChandler Carruth     assert(SI.getNumCases() > 0 &&
88947dc3a34SChandler Carruth            "If we had no cases we'd have a common successor!");
89047dc3a34SChandler Carruth     // Move the last case to the default successor. This is valid as if the
89147dc3a34SChandler Carruth     // default got unswitched it cannot be reached. This has the advantage of
89247dc3a34SChandler Carruth     // being simple and keeping the number of edges from this switch to
89347dc3a34SChandler Carruth     // successors the same, and avoiding any PHI update complexity.
89447dc3a34SChandler Carruth     auto LastCaseI = std::prev(SI.case_end());
895d4097b4aSYevgeny Rouban 
89647dc3a34SChandler Carruth     SI.setDefaultDest(LastCaseI->getCaseSuccessor());
897d4097b4aSYevgeny Rouban     SIW.setSuccessorWeight(
898d4097b4aSYevgeny Rouban         0, SIW.getSuccessorWeight(LastCaseI->getSuccessorIndex()));
899d4097b4aSYevgeny Rouban     SIW.removeCase(LastCaseI);
9001353f9a4SChandler Carruth   }
9011353f9a4SChandler Carruth 
9022c85a231SChandler Carruth   // Walk the unswitched exit blocks and the unswitched split blocks and update
9032c85a231SChandler Carruth   // the dominator tree based on the CFG edits. While we are walking unordered
9042c85a231SChandler Carruth   // containers here, the API for applyUpdates takes an unordered list of
9052c85a231SChandler Carruth   // updates and requires them to not contain duplicates.
9062c85a231SChandler Carruth   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
9072c85a231SChandler Carruth   for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
9082c85a231SChandler Carruth     DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
9092c85a231SChandler Carruth     DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
9102c85a231SChandler Carruth   }
9112c85a231SChandler Carruth   for (auto SplitUnswitchedPair : SplitExitBBMap) {
91290d2e3a1SAlina Sbirlea     DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first});
91390d2e3a1SAlina Sbirlea     DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second});
9142c85a231SChandler Carruth   }
915a2eebb82SAlina Sbirlea 
916a2eebb82SAlina Sbirlea   if (MSSAU) {
91763aeaf75SAlina Sbirlea     MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
918a2eebb82SAlina Sbirlea     if (VerifyMemorySSA)
919a2eebb82SAlina Sbirlea       MSSAU->getMemorySSA()->verifyMemorySSA();
92063aeaf75SAlina Sbirlea   } else {
92163aeaf75SAlina Sbirlea     DT.applyUpdates(DTUpdates);
922a2eebb82SAlina Sbirlea   }
923a2eebb82SAlina Sbirlea 
9247c35de12SDavid Green   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
925d8b0c8ceSChandler Carruth 
926d8b0c8ceSChandler Carruth   // We may have changed the nesting relationship for this loop so hoist it to
927d8b0c8ceSChandler Carruth   // its correct parent if needed.
928c4d8c631SDaniil Suchkov   hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
92997468e92SAlina Sbirlea 
93097468e92SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
93197468e92SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
932d8b0c8ceSChandler Carruth 
9331353f9a4SChandler Carruth   ++NumTrivial;
9341353f9a4SChandler Carruth   ++NumSwitches;
93552e97a28SAlina Sbirlea   LLVM_DEBUG(dbgs() << "    done: unswitching trivial switch...\n");
9361353f9a4SChandler Carruth   return true;
9371353f9a4SChandler Carruth }
9381353f9a4SChandler Carruth 
9391353f9a4SChandler Carruth /// This routine scans the loop to find a branch or switch which occurs before
9401353f9a4SChandler Carruth /// any side effects occur. These can potentially be unswitched without
9411353f9a4SChandler Carruth /// duplicating the loop. If a branch or switch is successfully unswitched the
9421353f9a4SChandler Carruth /// scanning continues to see if subsequent branches or switches have become
9431353f9a4SChandler Carruth /// trivial. Once all trivial candidates have been unswitched, this routine
9441353f9a4SChandler Carruth /// returns.
9451353f9a4SChandler Carruth ///
9461353f9a4SChandler Carruth /// The return value indicates whether anything was unswitched (and therefore
9471353f9a4SChandler Carruth /// changed).
9483897ded6SChandler Carruth ///
9493897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
9503897ded6SChandler Carruth /// invalidated by this.
9511353f9a4SChandler Carruth static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
952a2eebb82SAlina Sbirlea                                          LoopInfo &LI, ScalarEvolution *SE,
953a2eebb82SAlina Sbirlea                                          MemorySSAUpdater *MSSAU) {
9541353f9a4SChandler Carruth   bool Changed = false;
9551353f9a4SChandler Carruth 
9561353f9a4SChandler Carruth   // If loop header has only one reachable successor we should keep looking for
9571353f9a4SChandler Carruth   // trivial condition candidates in the successor as well. An alternative is
9581353f9a4SChandler Carruth   // to constant fold conditions and merge successors into loop header (then we
9591353f9a4SChandler Carruth   // only need to check header's terminator). The reason for not doing this in
9601353f9a4SChandler Carruth   // LoopUnswitch pass is that it could potentially break LoopPassManager's
9611353f9a4SChandler Carruth   // invariants. Folding dead branches could either eliminate the current loop
9621353f9a4SChandler Carruth   // or make other loops unreachable. LCSSA form might also not be preserved
9631353f9a4SChandler Carruth   // after deleting branches. The following code keeps traversing loop header's
9641353f9a4SChandler Carruth   // successors until it finds the trivial condition candidate (condition that
9651353f9a4SChandler Carruth   // is not a constant). Since unswitching generates branches with constant
9661353f9a4SChandler Carruth   // conditions, this scenario could be very common in practice.
9671353f9a4SChandler Carruth   BasicBlock *CurrentBB = L.getHeader();
9681353f9a4SChandler Carruth   SmallPtrSet<BasicBlock *, 8> Visited;
9691353f9a4SChandler Carruth   Visited.insert(CurrentBB);
9701353f9a4SChandler Carruth   do {
9711353f9a4SChandler Carruth     // Check if there are any side-effecting instructions (e.g. stores, calls,
9721353f9a4SChandler Carruth     // volatile loads) in the part of the loop that the code *would* execute
9731353f9a4SChandler Carruth     // without unswitching.
97493210870SAlina Sbirlea     if (MSSAU) // Possible early exit with MSSA
97593210870SAlina Sbirlea       if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
97693210870SAlina Sbirlea         if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
97793210870SAlina Sbirlea           return Changed;
9781353f9a4SChandler Carruth     if (llvm::any_of(*CurrentBB,
9791353f9a4SChandler Carruth                      [](Instruction &I) { return I.mayHaveSideEffects(); }))
9801353f9a4SChandler Carruth       return Changed;
9811353f9a4SChandler Carruth 
982edb12a83SChandler Carruth     Instruction *CurrentTerm = CurrentBB->getTerminator();
9831353f9a4SChandler Carruth 
9841353f9a4SChandler Carruth     if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
9851353f9a4SChandler Carruth       // Don't bother trying to unswitch past a switch with a constant
9861353f9a4SChandler Carruth       // condition. This should be removed prior to running this pass by
987472462c4SBjorn Pettersson       // simplifycfg.
9881353f9a4SChandler Carruth       if (isa<Constant>(SI->getCondition()))
9891353f9a4SChandler Carruth         return Changed;
9901353f9a4SChandler Carruth 
991a2eebb82SAlina Sbirlea       if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
992f209649dSHiroshi Inoue         // Couldn't unswitch this one so we're done.
9931353f9a4SChandler Carruth         return Changed;
9941353f9a4SChandler Carruth 
9951353f9a4SChandler Carruth       // Mark that we managed to unswitch something.
9961353f9a4SChandler Carruth       Changed = true;
9971353f9a4SChandler Carruth 
9981353f9a4SChandler Carruth       // If unswitching turned the terminator into an unconditional branch then
9991353f9a4SChandler Carruth       // we can continue. The unswitching logic specifically works to fold any
10001353f9a4SChandler Carruth       // cases it can into an unconditional branch to make it easier to
10011353f9a4SChandler Carruth       // recognize here.
10021353f9a4SChandler Carruth       auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
10031353f9a4SChandler Carruth       if (!BI || BI->isConditional())
10041353f9a4SChandler Carruth         return Changed;
10051353f9a4SChandler Carruth 
10061353f9a4SChandler Carruth       CurrentBB = BI->getSuccessor(0);
10071353f9a4SChandler Carruth       continue;
10081353f9a4SChandler Carruth     }
10091353f9a4SChandler Carruth 
10101353f9a4SChandler Carruth     auto *BI = dyn_cast<BranchInst>(CurrentTerm);
10111353f9a4SChandler Carruth     if (!BI)
10121353f9a4SChandler Carruth       // We do not understand other terminator instructions.
10131353f9a4SChandler Carruth       return Changed;
10141353f9a4SChandler Carruth 
10151353f9a4SChandler Carruth     // Don't bother trying to unswitch past an unconditional branch or a branch
1016472462c4SBjorn Pettersson     // with a constant value. These should be removed by simplifycfg prior to
10171353f9a4SChandler Carruth     // running this pass.
10181353f9a4SChandler Carruth     if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
10191353f9a4SChandler Carruth       return Changed;
10201353f9a4SChandler Carruth 
10211353f9a4SChandler Carruth     // Found a trivial condition candidate: non-foldable conditional branch. If
10221353f9a4SChandler Carruth     // we fail to unswitch this, we can't do anything else that is trivial.
1023a2eebb82SAlina Sbirlea     if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
10241353f9a4SChandler Carruth       return Changed;
10251353f9a4SChandler Carruth 
10261353f9a4SChandler Carruth     // Mark that we managed to unswitch something.
10271353f9a4SChandler Carruth     Changed = true;
10281353f9a4SChandler Carruth 
10294da3331dSChandler Carruth     // If we only unswitched some of the conditions feeding the branch, we won't
10304da3331dSChandler Carruth     // have collapsed it to a single successor.
10311353f9a4SChandler Carruth     BI = cast<BranchInst>(CurrentBB->getTerminator());
10324da3331dSChandler Carruth     if (BI->isConditional())
10334da3331dSChandler Carruth       return Changed;
10344da3331dSChandler Carruth 
10354da3331dSChandler Carruth     // Follow the newly unconditional branch into its successor.
10361353f9a4SChandler Carruth     CurrentBB = BI->getSuccessor(0);
10371353f9a4SChandler Carruth 
10381353f9a4SChandler Carruth     // When continuing, if we exit the loop or reach a previous visited block,
10391353f9a4SChandler Carruth     // then we can not reach any trivial condition candidates (unfoldable
10401353f9a4SChandler Carruth     // branch instructions or switch instructions) and no unswitch can happen.
10411353f9a4SChandler Carruth   } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
10421353f9a4SChandler Carruth 
10431353f9a4SChandler Carruth   return Changed;
10441353f9a4SChandler Carruth }
10451353f9a4SChandler Carruth 
1046693eedb1SChandler Carruth /// Build the cloned blocks for an unswitched copy of the given loop.
1047693eedb1SChandler Carruth ///
1048693eedb1SChandler Carruth /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
1049693eedb1SChandler Carruth /// after the split block (`SplitBB`) that will be used to select between the
1050693eedb1SChandler Carruth /// cloned and original loop.
1051693eedb1SChandler Carruth ///
1052693eedb1SChandler Carruth /// This routine handles cloning all of the necessary loop blocks and exit
1053693eedb1SChandler Carruth /// blocks including rewriting their instructions and the relevant PHI nodes.
10541652996fSChandler Carruth /// Any loop blocks or exit blocks which are dominated by a different successor
10551652996fSChandler Carruth /// than the one for this clone of the loop blocks can be trivially skipped. We
10561652996fSChandler Carruth /// use the `DominatingSucc` map to determine whether a block satisfies that
10571652996fSChandler Carruth /// property with a simple map lookup.
10581652996fSChandler Carruth ///
10591652996fSChandler Carruth /// It also correctly creates the unconditional branch in the cloned
1060693eedb1SChandler Carruth /// unswitched parent block to only point at the unswitched successor.
1061693eedb1SChandler Carruth ///
1062693eedb1SChandler Carruth /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
1063693eedb1SChandler Carruth /// block splitting is correctly reflected in `LoopInfo`, essentially all of
1064693eedb1SChandler Carruth /// the cloned blocks (and their loops) are left without full `LoopInfo`
1065693eedb1SChandler Carruth /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
1066693eedb1SChandler Carruth /// blocks to them but doesn't create the cloned `DominatorTree` structure and
1067693eedb1SChandler Carruth /// instead the caller must recompute an accurate DT. It *does* correctly
1068693eedb1SChandler Carruth /// update the `AssumptionCache` provided in `AC`.
1069693eedb1SChandler Carruth static BasicBlock *buildClonedLoopBlocks(
1070693eedb1SChandler Carruth     Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
1071693eedb1SChandler Carruth     ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
1072693eedb1SChandler Carruth     BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
10731652996fSChandler Carruth     const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
107469e68f84SChandler Carruth     ValueToValueMapTy &VMap,
107569e68f84SChandler Carruth     SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
1076a2eebb82SAlina Sbirlea     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
1077693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> NewBlocks;
1078693eedb1SChandler Carruth   NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
1079693eedb1SChandler Carruth 
1080693eedb1SChandler Carruth   // We will need to clone a bunch of blocks, wrap up the clone operation in
1081693eedb1SChandler Carruth   // a helper.
1082693eedb1SChandler Carruth   auto CloneBlock = [&](BasicBlock *OldBB) {
1083693eedb1SChandler Carruth     // Clone the basic block and insert it before the new preheader.
1084693eedb1SChandler Carruth     BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
1085693eedb1SChandler Carruth     NewBB->moveBefore(LoopPH);
1086693eedb1SChandler Carruth 
1087693eedb1SChandler Carruth     // Record this block and the mapping.
1088693eedb1SChandler Carruth     NewBlocks.push_back(NewBB);
1089693eedb1SChandler Carruth     VMap[OldBB] = NewBB;
1090693eedb1SChandler Carruth 
1091693eedb1SChandler Carruth     return NewBB;
1092693eedb1SChandler Carruth   };
1093693eedb1SChandler Carruth 
10941652996fSChandler Carruth   // We skip cloning blocks when they have a dominating succ that is not the
10951652996fSChandler Carruth   // succ we are cloning for.
10961652996fSChandler Carruth   auto SkipBlock = [&](BasicBlock *BB) {
10971652996fSChandler Carruth     auto It = DominatingSucc.find(BB);
10981652996fSChandler Carruth     return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
10991652996fSChandler Carruth   };
11001652996fSChandler Carruth 
1101693eedb1SChandler Carruth   // First, clone the preheader.
1102693eedb1SChandler Carruth   auto *ClonedPH = CloneBlock(LoopPH);
1103693eedb1SChandler Carruth 
1104693eedb1SChandler Carruth   // Then clone all the loop blocks, skipping the ones that aren't necessary.
1105693eedb1SChandler Carruth   for (auto *LoopBB : L.blocks())
11061652996fSChandler Carruth     if (!SkipBlock(LoopBB))
1107693eedb1SChandler Carruth       CloneBlock(LoopBB);
1108693eedb1SChandler Carruth 
1109693eedb1SChandler Carruth   // Split all the loop exit edges so that when we clone the exit blocks, if
1110693eedb1SChandler Carruth   // any of the exit blocks are *also* a preheader for some other loop, we
1111693eedb1SChandler Carruth   // don't create multiple predecessors entering the loop header.
1112693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks) {
11131652996fSChandler Carruth     if (SkipBlock(ExitBB))
1114693eedb1SChandler Carruth       continue;
1115693eedb1SChandler Carruth 
1116693eedb1SChandler Carruth     // When we are going to clone an exit, we don't need to clone all the
1117693eedb1SChandler Carruth     // instructions in the exit block and we want to ensure we have an easy
1118693eedb1SChandler Carruth     // place to merge the CFG, so split the exit first. This is always safe to
1119693eedb1SChandler Carruth     // do because there cannot be any non-loop predecessors of a loop exit in
1120693eedb1SChandler Carruth     // loop simplified form.
1121a2eebb82SAlina Sbirlea     auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
1122693eedb1SChandler Carruth 
1123693eedb1SChandler Carruth     // Rearrange the names to make it easier to write test cases by having the
1124693eedb1SChandler Carruth     // exit block carry the suffix rather than the merge block carrying the
1125693eedb1SChandler Carruth     // suffix.
1126693eedb1SChandler Carruth     MergeBB->takeName(ExitBB);
1127693eedb1SChandler Carruth     ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1128693eedb1SChandler Carruth 
1129693eedb1SChandler Carruth     // Now clone the original exit block.
1130693eedb1SChandler Carruth     auto *ClonedExitBB = CloneBlock(ExitBB);
1131693eedb1SChandler Carruth     assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1132693eedb1SChandler Carruth            "Exit block should have been split to have one successor!");
1133693eedb1SChandler Carruth     assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1134693eedb1SChandler Carruth            "Cloned exit block has the wrong successor!");
1135693eedb1SChandler Carruth 
1136693eedb1SChandler Carruth     // Remap any cloned instructions and create a merge phi node for them.
1137693eedb1SChandler Carruth     for (auto ZippedInsts : llvm::zip_first(
1138693eedb1SChandler Carruth              llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1139693eedb1SChandler Carruth              llvm::make_range(ClonedExitBB->begin(),
1140693eedb1SChandler Carruth                               std::prev(ClonedExitBB->end())))) {
1141693eedb1SChandler Carruth       Instruction &I = std::get<0>(ZippedInsts);
1142693eedb1SChandler Carruth       Instruction &ClonedI = std::get<1>(ZippedInsts);
1143693eedb1SChandler Carruth 
1144693eedb1SChandler Carruth       // The only instructions in the exit block should be PHI nodes and
1145693eedb1SChandler Carruth       // potentially a landing pad.
1146693eedb1SChandler Carruth       assert(
1147693eedb1SChandler Carruth           (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1148693eedb1SChandler Carruth           "Bad instruction in exit block!");
1149693eedb1SChandler Carruth       // We should have a value map between the instruction and its clone.
1150693eedb1SChandler Carruth       assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1151693eedb1SChandler Carruth 
1152693eedb1SChandler Carruth       auto *MergePN =
1153693eedb1SChandler Carruth           PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1154693eedb1SChandler Carruth                           &*MergeBB->getFirstInsertionPt());
1155693eedb1SChandler Carruth       I.replaceAllUsesWith(MergePN);
1156693eedb1SChandler Carruth       MergePN->addIncoming(&I, ExitBB);
1157693eedb1SChandler Carruth       MergePN->addIncoming(&ClonedI, ClonedExitBB);
1158693eedb1SChandler Carruth     }
1159693eedb1SChandler Carruth   }
1160693eedb1SChandler Carruth 
1161693eedb1SChandler Carruth   // Rewrite the instructions in the cloned blocks to refer to the instructions
1162693eedb1SChandler Carruth   // in the cloned blocks. We have to do this as a second pass so that we have
1163693eedb1SChandler Carruth   // everything available. Also, we have inserted new instructions which may
1164693eedb1SChandler Carruth   // include assume intrinsics, so we update the assumption cache while
1165693eedb1SChandler Carruth   // processing this.
1166693eedb1SChandler Carruth   for (auto *ClonedBB : NewBlocks)
1167693eedb1SChandler Carruth     for (Instruction &I : *ClonedBB) {
1168693eedb1SChandler Carruth       RemapInstruction(&I, VMap,
1169693eedb1SChandler Carruth                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1170a6d2a8d6SPhilip Reames       if (auto *II = dyn_cast<AssumeInst>(&I))
1171693eedb1SChandler Carruth         AC.registerAssumption(II);
1172693eedb1SChandler Carruth     }
1173693eedb1SChandler Carruth 
1174693eedb1SChandler Carruth   // Update any PHI nodes in the cloned successors of the skipped blocks to not
1175693eedb1SChandler Carruth   // have spurious incoming values.
1176693eedb1SChandler Carruth   for (auto *LoopBB : L.blocks())
11771652996fSChandler Carruth     if (SkipBlock(LoopBB))
1178693eedb1SChandler Carruth       for (auto *SuccBB : successors(LoopBB))
1179693eedb1SChandler Carruth         if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1180693eedb1SChandler Carruth           for (PHINode &PN : ClonedSuccBB->phis())
1181693eedb1SChandler Carruth             PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1182693eedb1SChandler Carruth 
1183ed296543SChandler Carruth   // Remove the cloned parent as a predecessor of any successor we ended up
1184ed296543SChandler Carruth   // cloning other than the unswitched one.
1185ed296543SChandler Carruth   auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1186ed296543SChandler Carruth   for (auto *SuccBB : successors(ParentBB)) {
1187ed296543SChandler Carruth     if (SuccBB == UnswitchedSuccBB)
1188ed296543SChandler Carruth       continue;
1189ed296543SChandler Carruth 
1190ed296543SChandler Carruth     auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1191ed296543SChandler Carruth     if (!ClonedSuccBB)
1192ed296543SChandler Carruth       continue;
1193ed296543SChandler Carruth 
1194ed296543SChandler Carruth     ClonedSuccBB->removePredecessor(ClonedParentBB,
119520b91899SMax Kazantsev                                     /*KeepOneInputPHIs*/ true);
1196ed296543SChandler Carruth   }
1197ed296543SChandler Carruth 
1198ed296543SChandler Carruth   // Replace the cloned branch with an unconditional branch to the cloned
1199ed296543SChandler Carruth   // unswitched successor.
1200ed296543SChandler Carruth   auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
12015502cfa0SSerguei Katkov   Instruction *ClonedTerminator = ClonedParentBB->getTerminator();
12025502cfa0SSerguei Katkov   // Trivial Simplification. If Terminator is a conditional branch and
12035502cfa0SSerguei Katkov   // condition becomes dead - erase it.
12045502cfa0SSerguei Katkov   Value *ClonedConditionToErase = nullptr;
12055502cfa0SSerguei Katkov   if (auto *BI = dyn_cast<BranchInst>(ClonedTerminator))
12065502cfa0SSerguei Katkov     ClonedConditionToErase = BI->getCondition();
12075502cfa0SSerguei Katkov   else if (auto *SI = dyn_cast<SwitchInst>(ClonedTerminator))
12085502cfa0SSerguei Katkov     ClonedConditionToErase = SI->getCondition();
12095502cfa0SSerguei Katkov 
12105502cfa0SSerguei Katkov   ClonedTerminator->eraseFromParent();
1211ed296543SChandler Carruth   BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1212ed296543SChandler Carruth 
12135502cfa0SSerguei Katkov   if (ClonedConditionToErase)
12145502cfa0SSerguei Katkov     RecursivelyDeleteTriviallyDeadInstructions(ClonedConditionToErase, nullptr,
12155502cfa0SSerguei Katkov                                                MSSAU);
12165502cfa0SSerguei Katkov 
1217ed296543SChandler Carruth   // If there are duplicate entries in the PHI nodes because of multiple edges
1218ed296543SChandler Carruth   // to the unswitched successor, we need to nuke all but one as we replaced it
1219ed296543SChandler Carruth   // with a direct branch.
1220ed296543SChandler Carruth   for (PHINode &PN : ClonedSuccBB->phis()) {
1221ed296543SChandler Carruth     bool Found = false;
1222ed296543SChandler Carruth     // Loop over the incoming operands backwards so we can easily delete as we
1223ed296543SChandler Carruth     // go without invalidating the index.
1224ed296543SChandler Carruth     for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1225ed296543SChandler Carruth       if (PN.getIncomingBlock(i) != ClonedParentBB)
1226ed296543SChandler Carruth         continue;
1227ed296543SChandler Carruth       if (!Found) {
1228ed296543SChandler Carruth         Found = true;
1229ed296543SChandler Carruth         continue;
1230ed296543SChandler Carruth       }
1231ed296543SChandler Carruth       PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1232ed296543SChandler Carruth     }
1233ed296543SChandler Carruth   }
1234ed296543SChandler Carruth 
123569e68f84SChandler Carruth   // Record the domtree updates for the new blocks.
123644aab925SChandler Carruth   SmallPtrSet<BasicBlock *, 4> SuccSet;
123744aab925SChandler Carruth   for (auto *ClonedBB : NewBlocks) {
123869e68f84SChandler Carruth     for (auto *SuccBB : successors(ClonedBB))
123944aab925SChandler Carruth       if (SuccSet.insert(SuccBB).second)
124069e68f84SChandler Carruth         DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
124144aab925SChandler Carruth     SuccSet.clear();
124244aab925SChandler Carruth   }
124369e68f84SChandler Carruth 
1244693eedb1SChandler Carruth   return ClonedPH;
1245693eedb1SChandler Carruth }
1246693eedb1SChandler Carruth 
1247693eedb1SChandler Carruth /// Recursively clone the specified loop and all of its children.
1248693eedb1SChandler Carruth ///
1249693eedb1SChandler Carruth /// The target parent loop for the clone should be provided, or can be null if
1250693eedb1SChandler Carruth /// the clone is a top-level loop. While cloning, all the blocks are mapped
1251693eedb1SChandler Carruth /// with the provided value map. The entire original loop must be present in
1252693eedb1SChandler Carruth /// the value map. The cloned loop is returned.
1253693eedb1SChandler Carruth static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1254693eedb1SChandler Carruth                            const ValueToValueMapTy &VMap, LoopInfo &LI) {
1255693eedb1SChandler Carruth   auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1256693eedb1SChandler Carruth     assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1257693eedb1SChandler Carruth     ClonedL.reserveBlocks(OrigL.getNumBlocks());
1258693eedb1SChandler Carruth     for (auto *BB : OrigL.blocks()) {
1259693eedb1SChandler Carruth       auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1260693eedb1SChandler Carruth       ClonedL.addBlockEntry(ClonedBB);
12610ace148cSChandler Carruth       if (LI.getLoopFor(BB) == &OrigL)
1262693eedb1SChandler Carruth         LI.changeLoopFor(ClonedBB, &ClonedL);
1263693eedb1SChandler Carruth     }
1264693eedb1SChandler Carruth   };
1265693eedb1SChandler Carruth 
1266693eedb1SChandler Carruth   // We specially handle the first loop because it may get cloned into
1267693eedb1SChandler Carruth   // a different parent and because we most commonly are cloning leaf loops.
1268693eedb1SChandler Carruth   Loop *ClonedRootL = LI.AllocateLoop();
1269693eedb1SChandler Carruth   if (RootParentL)
1270693eedb1SChandler Carruth     RootParentL->addChildLoop(ClonedRootL);
1271693eedb1SChandler Carruth   else
1272693eedb1SChandler Carruth     LI.addTopLevelLoop(ClonedRootL);
1273693eedb1SChandler Carruth   AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1274693eedb1SChandler Carruth 
127589c1e35fSStefanos Baziotis   if (OrigRootL.isInnermost())
1276693eedb1SChandler Carruth     return ClonedRootL;
1277693eedb1SChandler Carruth 
1278693eedb1SChandler Carruth   // If we have a nest, we can quickly clone the entire loop nest using an
1279693eedb1SChandler Carruth   // iterative approach because it is a tree. We keep the cloned parent in the
1280693eedb1SChandler Carruth   // data structure to avoid repeatedly querying through a map to find it.
1281693eedb1SChandler Carruth   SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1282693eedb1SChandler Carruth   // Build up the loops to clone in reverse order as we'll clone them from the
1283693eedb1SChandler Carruth   // back.
1284693eedb1SChandler Carruth   for (Loop *ChildL : llvm::reverse(OrigRootL))
1285693eedb1SChandler Carruth     LoopsToClone.push_back({ClonedRootL, ChildL});
1286693eedb1SChandler Carruth   do {
1287693eedb1SChandler Carruth     Loop *ClonedParentL, *L;
1288693eedb1SChandler Carruth     std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1289693eedb1SChandler Carruth     Loop *ClonedL = LI.AllocateLoop();
1290693eedb1SChandler Carruth     ClonedParentL->addChildLoop(ClonedL);
1291693eedb1SChandler Carruth     AddClonedBlocksToLoop(*L, *ClonedL);
1292693eedb1SChandler Carruth     for (Loop *ChildL : llvm::reverse(*L))
1293693eedb1SChandler Carruth       LoopsToClone.push_back({ClonedL, ChildL});
1294693eedb1SChandler Carruth   } while (!LoopsToClone.empty());
1295693eedb1SChandler Carruth 
1296693eedb1SChandler Carruth   return ClonedRootL;
1297693eedb1SChandler Carruth }
1298693eedb1SChandler Carruth 
1299693eedb1SChandler Carruth /// Build the cloned loops of an original loop from unswitching.
1300693eedb1SChandler Carruth ///
1301693eedb1SChandler Carruth /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1302693eedb1SChandler Carruth /// operation. We need to re-verify that there even is a loop (as the backedge
1303693eedb1SChandler Carruth /// may not have been cloned), and even if there are remaining backedges the
1304693eedb1SChandler Carruth /// backedge set may be different. However, we know that each child loop is
1305693eedb1SChandler Carruth /// undisturbed, we only need to find where to place each child loop within
1306693eedb1SChandler Carruth /// either any parent loop or within a cloned version of the original loop.
1307693eedb1SChandler Carruth ///
1308693eedb1SChandler Carruth /// Because child loops may end up cloned outside of any cloned version of the
1309693eedb1SChandler Carruth /// original loop, multiple cloned sibling loops may be created. All of them
1310693eedb1SChandler Carruth /// are returned so that the newly introduced loop nest roots can be
1311693eedb1SChandler Carruth /// identified.
13129281503eSChandler Carruth static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1313693eedb1SChandler Carruth                              const ValueToValueMapTy &VMap, LoopInfo &LI,
1314693eedb1SChandler Carruth                              SmallVectorImpl<Loop *> &NonChildClonedLoops) {
1315693eedb1SChandler Carruth   Loop *ClonedL = nullptr;
1316693eedb1SChandler Carruth 
1317693eedb1SChandler Carruth   auto *OrigPH = OrigL.getLoopPreheader();
1318693eedb1SChandler Carruth   auto *OrigHeader = OrigL.getHeader();
1319693eedb1SChandler Carruth 
1320693eedb1SChandler Carruth   auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1321693eedb1SChandler Carruth   auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1322693eedb1SChandler Carruth 
1323693eedb1SChandler Carruth   // We need to know the loops of the cloned exit blocks to even compute the
1324693eedb1SChandler Carruth   // accurate parent loop. If we only clone exits to some parent of the
1325693eedb1SChandler Carruth   // original parent, we want to clone into that outer loop. We also keep track
1326693eedb1SChandler Carruth   // of the loops that our cloned exit blocks participate in.
1327693eedb1SChandler Carruth   Loop *ParentL = nullptr;
1328693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1329693eedb1SChandler Carruth   SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1330693eedb1SChandler Carruth   ClonedExitsInLoops.reserve(ExitBlocks.size());
1331693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks)
1332693eedb1SChandler Carruth     if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1333693eedb1SChandler Carruth       if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1334693eedb1SChandler Carruth         ExitLoopMap[ClonedExitBB] = ExitL;
1335693eedb1SChandler Carruth         ClonedExitsInLoops.push_back(ClonedExitBB);
1336693eedb1SChandler Carruth         if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1337693eedb1SChandler Carruth           ParentL = ExitL;
1338693eedb1SChandler Carruth       }
1339693eedb1SChandler Carruth   assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1340693eedb1SChandler Carruth           ParentL->contains(OrigL.getParentLoop())) &&
1341693eedb1SChandler Carruth          "The computed parent loop should always contain (or be) the parent of "
1342693eedb1SChandler Carruth          "the original loop.");
1343693eedb1SChandler Carruth 
1344693eedb1SChandler Carruth   // We build the set of blocks dominated by the cloned header from the set of
1345693eedb1SChandler Carruth   // cloned blocks out of the original loop. While not all of these will
1346693eedb1SChandler Carruth   // necessarily be in the cloned loop, it is enough to establish that they
1347693eedb1SChandler Carruth   // aren't in unreachable cycles, etc.
1348693eedb1SChandler Carruth   SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1349693eedb1SChandler Carruth   for (auto *BB : OrigL.blocks())
1350693eedb1SChandler Carruth     if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1351693eedb1SChandler Carruth       ClonedLoopBlocks.insert(ClonedBB);
1352693eedb1SChandler Carruth 
1353693eedb1SChandler Carruth   // Rebuild the set of blocks that will end up in the cloned loop. We may have
1354693eedb1SChandler Carruth   // skipped cloning some region of this loop which can in turn skip some of
1355693eedb1SChandler Carruth   // the backedges so we have to rebuild the blocks in the loop based on the
1356693eedb1SChandler Carruth   // backedges that remain after cloning.
1357693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1358693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1359693eedb1SChandler Carruth   for (auto *Pred : predecessors(ClonedHeader)) {
1360693eedb1SChandler Carruth     // The only possible non-loop header predecessor is the preheader because
1361693eedb1SChandler Carruth     // we know we cloned the loop in simplified form.
1362693eedb1SChandler Carruth     if (Pred == ClonedPH)
1363693eedb1SChandler Carruth       continue;
1364693eedb1SChandler Carruth 
1365693eedb1SChandler Carruth     // Because the loop was in simplified form, the only non-loop predecessor
1366693eedb1SChandler Carruth     // should be the preheader.
1367693eedb1SChandler Carruth     assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1368693eedb1SChandler Carruth                                            "header other than the preheader "
1369693eedb1SChandler Carruth                                            "that is not part of the loop!");
1370693eedb1SChandler Carruth 
1371693eedb1SChandler Carruth     // Insert this block into the loop set and on the first visit (and if it
1372693eedb1SChandler Carruth     // isn't the header we're currently walking) put it into the worklist to
1373693eedb1SChandler Carruth     // recurse through.
1374693eedb1SChandler Carruth     if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1375693eedb1SChandler Carruth       Worklist.push_back(Pred);
1376693eedb1SChandler Carruth   }
1377693eedb1SChandler Carruth 
1378693eedb1SChandler Carruth   // If we had any backedges then there *is* a cloned loop. Put the header into
1379693eedb1SChandler Carruth   // the loop set and then walk the worklist backwards to find all the blocks
1380693eedb1SChandler Carruth   // that remain within the loop after cloning.
1381693eedb1SChandler Carruth   if (!BlocksInClonedLoop.empty()) {
1382693eedb1SChandler Carruth     BlocksInClonedLoop.insert(ClonedHeader);
1383693eedb1SChandler Carruth 
1384693eedb1SChandler Carruth     while (!Worklist.empty()) {
1385693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1386693eedb1SChandler Carruth       assert(BlocksInClonedLoop.count(BB) &&
1387693eedb1SChandler Carruth              "Didn't put block into the loop set!");
1388693eedb1SChandler Carruth 
1389693eedb1SChandler Carruth       // Insert any predecessors that are in the possible set into the cloned
1390693eedb1SChandler Carruth       // set, and if the insert is successful, add them to the worklist. Note
1391693eedb1SChandler Carruth       // that we filter on the blocks that are definitely reachable via the
1392693eedb1SChandler Carruth       // backedge to the loop header so we may prune out dead code within the
1393693eedb1SChandler Carruth       // cloned loop.
1394693eedb1SChandler Carruth       for (auto *Pred : predecessors(BB))
1395693eedb1SChandler Carruth         if (ClonedLoopBlocks.count(Pred) &&
1396693eedb1SChandler Carruth             BlocksInClonedLoop.insert(Pred).second)
1397693eedb1SChandler Carruth           Worklist.push_back(Pred);
1398693eedb1SChandler Carruth     }
1399693eedb1SChandler Carruth 
1400693eedb1SChandler Carruth     ClonedL = LI.AllocateLoop();
1401693eedb1SChandler Carruth     if (ParentL) {
1402693eedb1SChandler Carruth       ParentL->addBasicBlockToLoop(ClonedPH, LI);
1403693eedb1SChandler Carruth       ParentL->addChildLoop(ClonedL);
1404693eedb1SChandler Carruth     } else {
1405693eedb1SChandler Carruth       LI.addTopLevelLoop(ClonedL);
1406693eedb1SChandler Carruth     }
14079281503eSChandler Carruth     NonChildClonedLoops.push_back(ClonedL);
1408693eedb1SChandler Carruth 
1409693eedb1SChandler Carruth     ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1410693eedb1SChandler Carruth     // We don't want to just add the cloned loop blocks based on how we
1411693eedb1SChandler Carruth     // discovered them. The original order of blocks was carefully built in
1412693eedb1SChandler Carruth     // a way that doesn't rely on predecessor ordering. Rather than re-invent
1413693eedb1SChandler Carruth     // that logic, we just re-walk the original blocks (and those of the child
1414693eedb1SChandler Carruth     // loops) and filter them as we add them into the cloned loop.
1415693eedb1SChandler Carruth     for (auto *BB : OrigL.blocks()) {
1416693eedb1SChandler Carruth       auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1417693eedb1SChandler Carruth       if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1418693eedb1SChandler Carruth         continue;
1419693eedb1SChandler Carruth 
1420693eedb1SChandler Carruth       // Directly add the blocks that are only in this loop.
1421693eedb1SChandler Carruth       if (LI.getLoopFor(BB) == &OrigL) {
1422693eedb1SChandler Carruth         ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1423693eedb1SChandler Carruth         continue;
1424693eedb1SChandler Carruth       }
1425693eedb1SChandler Carruth 
1426693eedb1SChandler Carruth       // We want to manually add it to this loop and parents.
1427693eedb1SChandler Carruth       // Registering it with LoopInfo will happen when we clone the top
1428693eedb1SChandler Carruth       // loop for this block.
1429693eedb1SChandler Carruth       for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1430693eedb1SChandler Carruth         PL->addBlockEntry(ClonedBB);
1431693eedb1SChandler Carruth     }
1432693eedb1SChandler Carruth 
1433693eedb1SChandler Carruth     // Now add each child loop whose header remains within the cloned loop. All
1434693eedb1SChandler Carruth     // of the blocks within the loop must satisfy the same constraints as the
1435693eedb1SChandler Carruth     // header so once we pass the header checks we can just clone the entire
1436693eedb1SChandler Carruth     // child loop nest.
1437693eedb1SChandler Carruth     for (Loop *ChildL : OrigL) {
1438693eedb1SChandler Carruth       auto *ClonedChildHeader =
1439693eedb1SChandler Carruth           cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1440693eedb1SChandler Carruth       if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1441693eedb1SChandler Carruth         continue;
1442693eedb1SChandler Carruth 
1443693eedb1SChandler Carruth #ifndef NDEBUG
1444693eedb1SChandler Carruth       // We should never have a cloned child loop header but fail to have
1445693eedb1SChandler Carruth       // all of the blocks for that child loop.
1446693eedb1SChandler Carruth       for (auto *ChildLoopBB : ChildL->blocks())
1447693eedb1SChandler Carruth         assert(BlocksInClonedLoop.count(
1448693eedb1SChandler Carruth                    cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1449693eedb1SChandler Carruth                "Child cloned loop has a header within the cloned outer "
1450693eedb1SChandler Carruth                "loop but not all of its blocks!");
1451693eedb1SChandler Carruth #endif
1452693eedb1SChandler Carruth 
1453693eedb1SChandler Carruth       cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1454693eedb1SChandler Carruth     }
1455693eedb1SChandler Carruth   }
1456693eedb1SChandler Carruth 
1457693eedb1SChandler Carruth   // Now that we've handled all the components of the original loop that were
1458693eedb1SChandler Carruth   // cloned into a new loop, we still need to handle anything from the original
1459693eedb1SChandler Carruth   // loop that wasn't in a cloned loop.
1460693eedb1SChandler Carruth 
1461693eedb1SChandler Carruth   // Figure out what blocks are left to place within any loop nest containing
1462693eedb1SChandler Carruth   // the unswitched loop. If we never formed a loop, the cloned PH is one of
1463693eedb1SChandler Carruth   // them.
1464693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1465693eedb1SChandler Carruth   if (BlocksInClonedLoop.empty())
1466693eedb1SChandler Carruth     UnloopedBlockSet.insert(ClonedPH);
1467693eedb1SChandler Carruth   for (auto *ClonedBB : ClonedLoopBlocks)
1468693eedb1SChandler Carruth     if (!BlocksInClonedLoop.count(ClonedBB))
1469693eedb1SChandler Carruth       UnloopedBlockSet.insert(ClonedBB);
1470693eedb1SChandler Carruth 
1471693eedb1SChandler Carruth   // Copy the cloned exits and sort them in ascending loop depth, we'll work
1472693eedb1SChandler Carruth   // backwards across these to process them inside out. The order shouldn't
1473693eedb1SChandler Carruth   // matter as we're just trying to build up the map from inside-out; we use
1474693eedb1SChandler Carruth   // the map in a more stably ordered way below.
1475693eedb1SChandler Carruth   auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
14760cac726aSFangrui Song   llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1477693eedb1SChandler Carruth     return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1478693eedb1SChandler Carruth            ExitLoopMap.lookup(RHS)->getLoopDepth();
1479693eedb1SChandler Carruth   });
1480693eedb1SChandler Carruth 
1481693eedb1SChandler Carruth   // Populate the existing ExitLoopMap with everything reachable from each
1482693eedb1SChandler Carruth   // exit, starting from the inner most exit.
1483693eedb1SChandler Carruth   while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1484693eedb1SChandler Carruth     assert(Worklist.empty() && "Didn't clear worklist!");
1485693eedb1SChandler Carruth 
1486693eedb1SChandler Carruth     BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1487693eedb1SChandler Carruth     Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1488693eedb1SChandler Carruth 
1489693eedb1SChandler Carruth     // Walk the CFG back until we hit the cloned PH adding everything reachable
1490693eedb1SChandler Carruth     // and in the unlooped set to this exit block's loop.
1491693eedb1SChandler Carruth     Worklist.push_back(ExitBB);
1492693eedb1SChandler Carruth     do {
1493693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1494693eedb1SChandler Carruth       // We can stop recursing at the cloned preheader (if we get there).
1495693eedb1SChandler Carruth       if (BB == ClonedPH)
1496693eedb1SChandler Carruth         continue;
1497693eedb1SChandler Carruth 
1498693eedb1SChandler Carruth       for (BasicBlock *PredBB : predecessors(BB)) {
1499693eedb1SChandler Carruth         // If this pred has already been moved to our set or is part of some
1500693eedb1SChandler Carruth         // (inner) loop, no update needed.
1501693eedb1SChandler Carruth         if (!UnloopedBlockSet.erase(PredBB)) {
1502693eedb1SChandler Carruth           assert(
1503693eedb1SChandler Carruth               (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1504693eedb1SChandler Carruth               "Predecessor not mapped to a loop!");
1505693eedb1SChandler Carruth           continue;
1506693eedb1SChandler Carruth         }
1507693eedb1SChandler Carruth 
1508693eedb1SChandler Carruth         // We just insert into the loop set here. We'll add these blocks to the
1509693eedb1SChandler Carruth         // exit loop after we build up the set in an order that doesn't rely on
1510693eedb1SChandler Carruth         // predecessor order (which in turn relies on use list order).
1511693eedb1SChandler Carruth         bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1512693eedb1SChandler Carruth         (void)Inserted;
1513693eedb1SChandler Carruth         assert(Inserted && "Should only visit an unlooped block once!");
1514693eedb1SChandler Carruth 
1515693eedb1SChandler Carruth         // And recurse through to its predecessors.
1516693eedb1SChandler Carruth         Worklist.push_back(PredBB);
1517693eedb1SChandler Carruth       }
1518693eedb1SChandler Carruth     } while (!Worklist.empty());
1519693eedb1SChandler Carruth   }
1520693eedb1SChandler Carruth 
1521693eedb1SChandler Carruth   // Now that the ExitLoopMap gives as  mapping for all the non-looping cloned
1522693eedb1SChandler Carruth   // blocks to their outer loops, walk the cloned blocks and the cloned exits
1523693eedb1SChandler Carruth   // in their original order adding them to the correct loop.
1524693eedb1SChandler Carruth 
1525693eedb1SChandler Carruth   // We need a stable insertion order. We use the order of the original loop
1526693eedb1SChandler Carruth   // order and map into the correct parent loop.
1527693eedb1SChandler Carruth   for (auto *BB : llvm::concat<BasicBlock *const>(
1528693eedb1SChandler Carruth            makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1529693eedb1SChandler Carruth     if (Loop *OuterL = ExitLoopMap.lookup(BB))
1530693eedb1SChandler Carruth       OuterL->addBasicBlockToLoop(BB, LI);
1531693eedb1SChandler Carruth 
1532693eedb1SChandler Carruth #ifndef NDEBUG
1533693eedb1SChandler Carruth   for (auto &BBAndL : ExitLoopMap) {
1534693eedb1SChandler Carruth     auto *BB = BBAndL.first;
1535693eedb1SChandler Carruth     auto *OuterL = BBAndL.second;
1536693eedb1SChandler Carruth     assert(LI.getLoopFor(BB) == OuterL &&
1537693eedb1SChandler Carruth            "Failed to put all blocks into outer loops!");
1538693eedb1SChandler Carruth   }
1539693eedb1SChandler Carruth #endif
1540693eedb1SChandler Carruth 
1541693eedb1SChandler Carruth   // Now that all the blocks are placed into the correct containing loop in the
1542693eedb1SChandler Carruth   // absence of child loops, find all the potentially cloned child loops and
1543693eedb1SChandler Carruth   // clone them into whatever outer loop we placed their header into.
1544693eedb1SChandler Carruth   for (Loop *ChildL : OrigL) {
1545693eedb1SChandler Carruth     auto *ClonedChildHeader =
1546693eedb1SChandler Carruth         cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1547693eedb1SChandler Carruth     if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1548693eedb1SChandler Carruth       continue;
1549693eedb1SChandler Carruth 
1550693eedb1SChandler Carruth #ifndef NDEBUG
1551693eedb1SChandler Carruth     for (auto *ChildLoopBB : ChildL->blocks())
1552693eedb1SChandler Carruth       assert(VMap.count(ChildLoopBB) &&
1553693eedb1SChandler Carruth              "Cloned a child loop header but not all of that loops blocks!");
1554693eedb1SChandler Carruth #endif
1555693eedb1SChandler Carruth 
1556693eedb1SChandler Carruth     NonChildClonedLoops.push_back(cloneLoopNest(
1557693eedb1SChandler Carruth         *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1558693eedb1SChandler Carruth   }
1559693eedb1SChandler Carruth }
1560693eedb1SChandler Carruth 
156169e68f84SChandler Carruth static void
15621652996fSChandler Carruth deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
15631652996fSChandler Carruth                        ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1564a2eebb82SAlina Sbirlea                        DominatorTree &DT, MemorySSAUpdater *MSSAU) {
15651652996fSChandler Carruth   // Find all the dead clones, and remove them from their successors.
15661652996fSChandler Carruth   SmallVector<BasicBlock *, 16> DeadBlocks;
15671652996fSChandler Carruth   for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
15681652996fSChandler Carruth     for (auto &VMap : VMaps)
15691652996fSChandler Carruth       if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
15701652996fSChandler Carruth         if (!DT.isReachableFromEntry(ClonedBB)) {
15711652996fSChandler Carruth           for (BasicBlock *SuccBB : successors(ClonedBB))
15721652996fSChandler Carruth             SuccBB->removePredecessor(ClonedBB);
15731652996fSChandler Carruth           DeadBlocks.push_back(ClonedBB);
15741652996fSChandler Carruth         }
15751652996fSChandler Carruth 
1576a2eebb82SAlina Sbirlea   // Remove all MemorySSA in the dead blocks
1577a2eebb82SAlina Sbirlea   if (MSSAU) {
1578db101864SAlina Sbirlea     SmallSetVector<BasicBlock *, 8> DeadBlockSet(DeadBlocks.begin(),
1579a2eebb82SAlina Sbirlea                                                  DeadBlocks.end());
1580a2eebb82SAlina Sbirlea     MSSAU->removeBlocks(DeadBlockSet);
1581a2eebb82SAlina Sbirlea   }
1582a2eebb82SAlina Sbirlea 
15831652996fSChandler Carruth   // Drop any remaining references to break cycles.
15841652996fSChandler Carruth   for (BasicBlock *BB : DeadBlocks)
15851652996fSChandler Carruth     BB->dropAllReferences();
15861652996fSChandler Carruth   // Erase them from the IR.
15871652996fSChandler Carruth   for (BasicBlock *BB : DeadBlocks)
15881652996fSChandler Carruth     BB->eraseFromParent();
15891652996fSChandler Carruth }
15901652996fSChandler Carruth 
15910f0344ddSBjorn Pettersson static void
15920f0344ddSBjorn Pettersson deleteDeadBlocksFromLoop(Loop &L,
1593693eedb1SChandler Carruth                          SmallVectorImpl<BasicBlock *> &ExitBlocks,
1594a2eebb82SAlina Sbirlea                          DominatorTree &DT, LoopInfo &LI,
15950f0344ddSBjorn Pettersson                          MemorySSAUpdater *MSSAU,
15960f0344ddSBjorn Pettersson                          function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
15978b6effd9SFedor Sergeev   // Find all the dead blocks tied to this loop, and remove them from their
15988b6effd9SFedor Sergeev   // successors.
1599db101864SAlina Sbirlea   SmallSetVector<BasicBlock *, 8> DeadBlockSet;
16007b49aa03SFedor Sergeev 
16018b6effd9SFedor Sergeev   // Start with loop/exit blocks and get a transitive closure of reachable dead
16028b6effd9SFedor Sergeev   // blocks.
16038b6effd9SFedor Sergeev   SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
16048b6effd9SFedor Sergeev                                                 ExitBlocks.end());
16058b6effd9SFedor Sergeev   DeathCandidates.append(L.blocks().begin(), L.blocks().end());
16068b6effd9SFedor Sergeev   while (!DeathCandidates.empty()) {
16078b6effd9SFedor Sergeev     auto *BB = DeathCandidates.pop_back_val();
16088b6effd9SFedor Sergeev     if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
16098b6effd9SFedor Sergeev       for (BasicBlock *SuccBB : successors(BB)) {
16101652996fSChandler Carruth         SuccBB->removePredecessor(BB);
16118b6effd9SFedor Sergeev         DeathCandidates.push_back(SuccBB);
16121652996fSChandler Carruth       }
16138b6effd9SFedor Sergeev       DeadBlockSet.insert(BB);
16148b6effd9SFedor Sergeev     }
16158b6effd9SFedor Sergeev   }
1616693eedb1SChandler Carruth 
1617a2eebb82SAlina Sbirlea   // Remove all MemorySSA in the dead blocks
1618a2eebb82SAlina Sbirlea   if (MSSAU)
1619a2eebb82SAlina Sbirlea     MSSAU->removeBlocks(DeadBlockSet);
1620a2eebb82SAlina Sbirlea 
1621693eedb1SChandler Carruth   // Filter out the dead blocks from the exit blocks list so that it can be
1622693eedb1SChandler Carruth   // used in the caller.
1623693eedb1SChandler Carruth   llvm::erase_if(ExitBlocks,
162469e68f84SChandler Carruth                  [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1625693eedb1SChandler Carruth 
1626693eedb1SChandler Carruth   // Walk from this loop up through its parents removing all of the dead blocks.
1627693eedb1SChandler Carruth   for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
16288b6effd9SFedor Sergeev     for (auto *BB : DeadBlockSet)
1629693eedb1SChandler Carruth       ParentL->getBlocksSet().erase(BB);
1630693eedb1SChandler Carruth     llvm::erase_if(ParentL->getBlocksVector(),
163169e68f84SChandler Carruth                    [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1632693eedb1SChandler Carruth   }
1633693eedb1SChandler Carruth 
1634693eedb1SChandler Carruth   // Now delete the dead child loops. This raw delete will clear them
1635693eedb1SChandler Carruth   // recursively.
1636693eedb1SChandler Carruth   llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
163769e68f84SChandler Carruth     if (!DeadBlockSet.count(ChildL->getHeader()))
1638693eedb1SChandler Carruth       return false;
1639693eedb1SChandler Carruth 
1640693eedb1SChandler Carruth     assert(llvm::all_of(ChildL->blocks(),
1641693eedb1SChandler Carruth                         [&](BasicBlock *ChildBB) {
164269e68f84SChandler Carruth                           return DeadBlockSet.count(ChildBB);
1643693eedb1SChandler Carruth                         }) &&
1644693eedb1SChandler Carruth            "If the child loop header is dead all blocks in the child loop must "
1645693eedb1SChandler Carruth            "be dead as well!");
16460f0344ddSBjorn Pettersson     DestroyLoopCB(*ChildL, ChildL->getName());
1647693eedb1SChandler Carruth     LI.destroy(ChildL);
1648693eedb1SChandler Carruth     return true;
1649693eedb1SChandler Carruth   });
1650693eedb1SChandler Carruth 
165169e68f84SChandler Carruth   // Remove the loop mappings for the dead blocks and drop all the references
165269e68f84SChandler Carruth   // from these blocks to others to handle cyclic references as we start
165369e68f84SChandler Carruth   // deleting the blocks themselves.
16548b6effd9SFedor Sergeev   for (auto *BB : DeadBlockSet) {
165569e68f84SChandler Carruth     // Check that the dominator tree has already been updated.
165669e68f84SChandler Carruth     assert(!DT.getNode(BB) && "Should already have cleared domtree!");
1657693eedb1SChandler Carruth     LI.changeLoopFor(BB, nullptr);
1658706b22e3SDaniil Suchkov     // Drop all uses of the instructions to make sure we won't have dangling
1659706b22e3SDaniil Suchkov     // uses in other blocks.
1660706b22e3SDaniil Suchkov     for (auto &I : *BB)
1661706b22e3SDaniil Suchkov       if (!I.use_empty())
1662706b22e3SDaniil Suchkov         I.replaceAllUsesWith(UndefValue::get(I.getType()));
1663693eedb1SChandler Carruth     BB->dropAllReferences();
1664693eedb1SChandler Carruth   }
166569e68f84SChandler Carruth 
166669e68f84SChandler Carruth   // Actually delete the blocks now that they've been fully unhooked from the
166769e68f84SChandler Carruth   // IR.
16687b49aa03SFedor Sergeev   for (auto *BB : DeadBlockSet)
166969e68f84SChandler Carruth     BB->eraseFromParent();
1670693eedb1SChandler Carruth }
1671693eedb1SChandler Carruth 
1672693eedb1SChandler Carruth /// Recompute the set of blocks in a loop after unswitching.
1673693eedb1SChandler Carruth ///
1674693eedb1SChandler Carruth /// This walks from the original headers predecessors to rebuild the loop. We
1675693eedb1SChandler Carruth /// take advantage of the fact that new blocks can't have been added, and so we
1676693eedb1SChandler Carruth /// filter by the original loop's blocks. This also handles potentially
1677693eedb1SChandler Carruth /// unreachable code that we don't want to explore but might be found examining
1678693eedb1SChandler Carruth /// the predecessors of the header.
1679693eedb1SChandler Carruth ///
1680693eedb1SChandler Carruth /// If the original loop is no longer a loop, this will return an empty set. If
1681693eedb1SChandler Carruth /// it remains a loop, all the blocks within it will be added to the set
1682693eedb1SChandler Carruth /// (including those blocks in inner loops).
1683693eedb1SChandler Carruth static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1684693eedb1SChandler Carruth                                                                  LoopInfo &LI) {
1685693eedb1SChandler Carruth   SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1686693eedb1SChandler Carruth 
1687693eedb1SChandler Carruth   auto *PH = L.getLoopPreheader();
1688693eedb1SChandler Carruth   auto *Header = L.getHeader();
1689693eedb1SChandler Carruth 
1690693eedb1SChandler Carruth   // A worklist to use while walking backwards from the header.
1691693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1692693eedb1SChandler Carruth 
1693693eedb1SChandler Carruth   // First walk the predecessors of the header to find the backedges. This will
1694693eedb1SChandler Carruth   // form the basis of our walk.
1695693eedb1SChandler Carruth   for (auto *Pred : predecessors(Header)) {
1696693eedb1SChandler Carruth     // Skip the preheader.
1697693eedb1SChandler Carruth     if (Pred == PH)
1698693eedb1SChandler Carruth       continue;
1699693eedb1SChandler Carruth 
1700693eedb1SChandler Carruth     // Because the loop was in simplified form, the only non-loop predecessor
1701693eedb1SChandler Carruth     // is the preheader.
1702693eedb1SChandler Carruth     assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1703693eedb1SChandler Carruth                                "than the preheader that is not part of the "
1704693eedb1SChandler Carruth                                "loop!");
1705693eedb1SChandler Carruth 
1706693eedb1SChandler Carruth     // Insert this block into the loop set and on the first visit and, if it
1707693eedb1SChandler Carruth     // isn't the header we're currently walking, put it into the worklist to
1708693eedb1SChandler Carruth     // recurse through.
1709693eedb1SChandler Carruth     if (LoopBlockSet.insert(Pred).second && Pred != Header)
1710693eedb1SChandler Carruth       Worklist.push_back(Pred);
1711693eedb1SChandler Carruth   }
1712693eedb1SChandler Carruth 
1713693eedb1SChandler Carruth   // If no backedges were found, we're done.
1714693eedb1SChandler Carruth   if (LoopBlockSet.empty())
1715693eedb1SChandler Carruth     return LoopBlockSet;
1716693eedb1SChandler Carruth 
1717693eedb1SChandler Carruth   // We found backedges, recurse through them to identify the loop blocks.
1718693eedb1SChandler Carruth   while (!Worklist.empty()) {
1719693eedb1SChandler Carruth     BasicBlock *BB = Worklist.pop_back_val();
1720693eedb1SChandler Carruth     assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1721693eedb1SChandler Carruth 
172243acdb35SChandler Carruth     // No need to walk past the header.
172343acdb35SChandler Carruth     if (BB == Header)
172443acdb35SChandler Carruth       continue;
172543acdb35SChandler Carruth 
1726693eedb1SChandler Carruth     // Because we know the inner loop structure remains valid we can use the
1727693eedb1SChandler Carruth     // loop structure to jump immediately across the entire nested loop.
1728693eedb1SChandler Carruth     // Further, because it is in loop simplified form, we can directly jump
1729693eedb1SChandler Carruth     // to its preheader afterward.
1730693eedb1SChandler Carruth     if (Loop *InnerL = LI.getLoopFor(BB))
1731693eedb1SChandler Carruth       if (InnerL != &L) {
1732693eedb1SChandler Carruth         assert(L.contains(InnerL) &&
1733693eedb1SChandler Carruth                "Should not reach a loop *outside* this loop!");
1734693eedb1SChandler Carruth         // The preheader is the only possible predecessor of the loop so
1735693eedb1SChandler Carruth         // insert it into the set and check whether it was already handled.
1736693eedb1SChandler Carruth         auto *InnerPH = InnerL->getLoopPreheader();
1737693eedb1SChandler Carruth         assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1738693eedb1SChandler Carruth                                       "but not contain the inner loop "
1739693eedb1SChandler Carruth                                       "preheader!");
1740693eedb1SChandler Carruth         if (!LoopBlockSet.insert(InnerPH).second)
1741693eedb1SChandler Carruth           // The only way to reach the preheader is through the loop body
1742693eedb1SChandler Carruth           // itself so if it has been visited the loop is already handled.
1743693eedb1SChandler Carruth           continue;
1744693eedb1SChandler Carruth 
1745693eedb1SChandler Carruth         // Insert all of the blocks (other than those already present) into
1746bf7190a1SChandler Carruth         // the loop set. We expect at least the block that led us to find the
1747bf7190a1SChandler Carruth         // inner loop to be in the block set, but we may also have other loop
1748bf7190a1SChandler Carruth         // blocks if they were already enqueued as predecessors of some other
1749bf7190a1SChandler Carruth         // outer loop block.
1750693eedb1SChandler Carruth         for (auto *InnerBB : InnerL->blocks()) {
1751693eedb1SChandler Carruth           if (InnerBB == BB) {
1752693eedb1SChandler Carruth             assert(LoopBlockSet.count(InnerBB) &&
1753693eedb1SChandler Carruth                    "Block should already be in the set!");
1754693eedb1SChandler Carruth             continue;
1755693eedb1SChandler Carruth           }
1756693eedb1SChandler Carruth 
1757bf7190a1SChandler Carruth           LoopBlockSet.insert(InnerBB);
1758693eedb1SChandler Carruth         }
1759693eedb1SChandler Carruth 
1760693eedb1SChandler Carruth         // Add the preheader to the worklist so we will continue past the
1761693eedb1SChandler Carruth         // loop body.
1762693eedb1SChandler Carruth         Worklist.push_back(InnerPH);
1763693eedb1SChandler Carruth         continue;
1764693eedb1SChandler Carruth       }
1765693eedb1SChandler Carruth 
1766693eedb1SChandler Carruth     // Insert any predecessors that were in the original loop into the new
1767693eedb1SChandler Carruth     // set, and if the insert is successful, add them to the worklist.
1768693eedb1SChandler Carruth     for (auto *Pred : predecessors(BB))
1769693eedb1SChandler Carruth       if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1770693eedb1SChandler Carruth         Worklist.push_back(Pred);
1771693eedb1SChandler Carruth   }
1772693eedb1SChandler Carruth 
177343acdb35SChandler Carruth   assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
177443acdb35SChandler Carruth 
1775693eedb1SChandler Carruth   // We've found all the blocks participating in the loop, return our completed
1776693eedb1SChandler Carruth   // set.
1777693eedb1SChandler Carruth   return LoopBlockSet;
1778693eedb1SChandler Carruth }
1779693eedb1SChandler Carruth 
1780693eedb1SChandler Carruth /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1781693eedb1SChandler Carruth ///
1782693eedb1SChandler Carruth /// The removal may have removed some child loops entirely but cannot have
1783693eedb1SChandler Carruth /// disturbed any remaining child loops. However, they may need to be hoisted
1784693eedb1SChandler Carruth /// to the parent loop (or to be top-level loops). The original loop may be
1785693eedb1SChandler Carruth /// completely removed.
1786693eedb1SChandler Carruth ///
1787693eedb1SChandler Carruth /// The sibling loops resulting from this update are returned. If the original
1788693eedb1SChandler Carruth /// loop remains a valid loop, it will be the first entry in this list with all
1789693eedb1SChandler Carruth /// of the newly sibling loops following it.
1790693eedb1SChandler Carruth ///
1791693eedb1SChandler Carruth /// Returns true if the loop remains a loop after unswitching, and false if it
1792693eedb1SChandler Carruth /// is no longer a loop after unswitching (and should not continue to be
1793693eedb1SChandler Carruth /// referenced).
1794693eedb1SChandler Carruth static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1795693eedb1SChandler Carruth                                      LoopInfo &LI,
1796693eedb1SChandler Carruth                                      SmallVectorImpl<Loop *> &HoistedLoops) {
1797693eedb1SChandler Carruth   auto *PH = L.getLoopPreheader();
1798693eedb1SChandler Carruth 
1799693eedb1SChandler Carruth   // Compute the actual parent loop from the exit blocks. Because we may have
1800693eedb1SChandler Carruth   // pruned some exits the loop may be different from the original parent.
1801693eedb1SChandler Carruth   Loop *ParentL = nullptr;
1802693eedb1SChandler Carruth   SmallVector<Loop *, 4> ExitLoops;
1803693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> ExitsInLoops;
1804693eedb1SChandler Carruth   ExitsInLoops.reserve(ExitBlocks.size());
1805693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks)
1806693eedb1SChandler Carruth     if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1807693eedb1SChandler Carruth       ExitLoops.push_back(ExitL);
1808693eedb1SChandler Carruth       ExitsInLoops.push_back(ExitBB);
1809693eedb1SChandler Carruth       if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1810693eedb1SChandler Carruth         ParentL = ExitL;
1811693eedb1SChandler Carruth     }
1812693eedb1SChandler Carruth 
1813693eedb1SChandler Carruth   // Recompute the blocks participating in this loop. This may be empty if it
1814693eedb1SChandler Carruth   // is no longer a loop.
1815693eedb1SChandler Carruth   auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1816693eedb1SChandler Carruth 
1817693eedb1SChandler Carruth   // If we still have a loop, we need to re-set the loop's parent as the exit
1818693eedb1SChandler Carruth   // block set changing may have moved it within the loop nest. Note that this
1819693eedb1SChandler Carruth   // can only happen when this loop has a parent as it can only hoist the loop
1820693eedb1SChandler Carruth   // *up* the nest.
1821693eedb1SChandler Carruth   if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1822693eedb1SChandler Carruth     // Remove this loop's (original) blocks from all of the intervening loops.
1823693eedb1SChandler Carruth     for (Loop *IL = L.getParentLoop(); IL != ParentL;
1824693eedb1SChandler Carruth          IL = IL->getParentLoop()) {
1825693eedb1SChandler Carruth       IL->getBlocksSet().erase(PH);
1826693eedb1SChandler Carruth       for (auto *BB : L.blocks())
1827693eedb1SChandler Carruth         IL->getBlocksSet().erase(BB);
1828693eedb1SChandler Carruth       llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1829693eedb1SChandler Carruth         return BB == PH || L.contains(BB);
1830693eedb1SChandler Carruth       });
1831693eedb1SChandler Carruth     }
1832693eedb1SChandler Carruth 
1833693eedb1SChandler Carruth     LI.changeLoopFor(PH, ParentL);
1834693eedb1SChandler Carruth     L.getParentLoop()->removeChildLoop(&L);
1835693eedb1SChandler Carruth     if (ParentL)
1836693eedb1SChandler Carruth       ParentL->addChildLoop(&L);
1837693eedb1SChandler Carruth     else
1838693eedb1SChandler Carruth       LI.addTopLevelLoop(&L);
1839693eedb1SChandler Carruth   }
1840693eedb1SChandler Carruth 
1841693eedb1SChandler Carruth   // Now we update all the blocks which are no longer within the loop.
1842693eedb1SChandler Carruth   auto &Blocks = L.getBlocksVector();
1843693eedb1SChandler Carruth   auto BlocksSplitI =
1844693eedb1SChandler Carruth       LoopBlockSet.empty()
1845693eedb1SChandler Carruth           ? Blocks.begin()
1846693eedb1SChandler Carruth           : std::stable_partition(
1847693eedb1SChandler Carruth                 Blocks.begin(), Blocks.end(),
1848693eedb1SChandler Carruth                 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1849693eedb1SChandler Carruth 
1850693eedb1SChandler Carruth   // Before we erase the list of unlooped blocks, build a set of them.
1851693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1852693eedb1SChandler Carruth   if (LoopBlockSet.empty())
1853693eedb1SChandler Carruth     UnloopedBlocks.insert(PH);
1854693eedb1SChandler Carruth 
1855693eedb1SChandler Carruth   // Now erase these blocks from the loop.
1856693eedb1SChandler Carruth   for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1857693eedb1SChandler Carruth     L.getBlocksSet().erase(BB);
1858693eedb1SChandler Carruth   Blocks.erase(BlocksSplitI, Blocks.end());
1859693eedb1SChandler Carruth 
1860693eedb1SChandler Carruth   // Sort the exits in ascending loop depth, we'll work backwards across these
1861693eedb1SChandler Carruth   // to process them inside out.
1862efd94c56SFangrui Song   llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1863693eedb1SChandler Carruth     return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1864693eedb1SChandler Carruth   });
1865693eedb1SChandler Carruth 
1866693eedb1SChandler Carruth   // We'll build up a set for each exit loop.
1867693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1868693eedb1SChandler Carruth   Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1869693eedb1SChandler Carruth 
1870693eedb1SChandler Carruth   auto RemoveUnloopedBlocksFromLoop =
1871693eedb1SChandler Carruth       [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1872693eedb1SChandler Carruth         for (auto *BB : UnloopedBlocks)
1873693eedb1SChandler Carruth           L.getBlocksSet().erase(BB);
1874693eedb1SChandler Carruth         llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1875693eedb1SChandler Carruth           return UnloopedBlocks.count(BB);
1876693eedb1SChandler Carruth         });
1877693eedb1SChandler Carruth       };
1878693eedb1SChandler Carruth 
1879693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1880693eedb1SChandler Carruth   while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1881693eedb1SChandler Carruth     assert(Worklist.empty() && "Didn't clear worklist!");
1882693eedb1SChandler Carruth     assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1883693eedb1SChandler Carruth 
1884693eedb1SChandler Carruth     // Grab the next exit block, in decreasing loop depth order.
1885693eedb1SChandler Carruth     BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1886693eedb1SChandler Carruth     Loop &ExitL = *LI.getLoopFor(ExitBB);
1887693eedb1SChandler Carruth     assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1888693eedb1SChandler Carruth 
1889693eedb1SChandler Carruth     // Erase all of the unlooped blocks from the loops between the previous
1890693eedb1SChandler Carruth     // exit loop and this exit loop. This works because the ExitInLoops list is
1891693eedb1SChandler Carruth     // sorted in increasing order of loop depth and thus we visit loops in
1892693eedb1SChandler Carruth     // decreasing order of loop depth.
1893693eedb1SChandler Carruth     for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1894693eedb1SChandler Carruth       RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1895693eedb1SChandler Carruth 
1896693eedb1SChandler Carruth     // Walk the CFG back until we hit the cloned PH adding everything reachable
1897693eedb1SChandler Carruth     // and in the unlooped set to this exit block's loop.
1898693eedb1SChandler Carruth     Worklist.push_back(ExitBB);
1899693eedb1SChandler Carruth     do {
1900693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1901693eedb1SChandler Carruth       // We can stop recursing at the cloned preheader (if we get there).
1902693eedb1SChandler Carruth       if (BB == PH)
1903693eedb1SChandler Carruth         continue;
1904693eedb1SChandler Carruth 
1905693eedb1SChandler Carruth       for (BasicBlock *PredBB : predecessors(BB)) {
1906693eedb1SChandler Carruth         // If this pred has already been moved to our set or is part of some
1907693eedb1SChandler Carruth         // (inner) loop, no update needed.
1908693eedb1SChandler Carruth         if (!UnloopedBlocks.erase(PredBB)) {
1909693eedb1SChandler Carruth           assert((NewExitLoopBlocks.count(PredBB) ||
1910693eedb1SChandler Carruth                   ExitL.contains(LI.getLoopFor(PredBB))) &&
1911693eedb1SChandler Carruth                  "Predecessor not in a nested loop (or already visited)!");
1912693eedb1SChandler Carruth           continue;
1913693eedb1SChandler Carruth         }
1914693eedb1SChandler Carruth 
1915693eedb1SChandler Carruth         // We just insert into the loop set here. We'll add these blocks to the
1916693eedb1SChandler Carruth         // exit loop after we build up the set in a deterministic order rather
1917693eedb1SChandler Carruth         // than the predecessor-influenced visit order.
1918693eedb1SChandler Carruth         bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1919693eedb1SChandler Carruth         (void)Inserted;
1920693eedb1SChandler Carruth         assert(Inserted && "Should only visit an unlooped block once!");
1921693eedb1SChandler Carruth 
1922693eedb1SChandler Carruth         // And recurse through to its predecessors.
1923693eedb1SChandler Carruth         Worklist.push_back(PredBB);
1924693eedb1SChandler Carruth       }
1925693eedb1SChandler Carruth     } while (!Worklist.empty());
1926693eedb1SChandler Carruth 
1927693eedb1SChandler Carruth     // If blocks in this exit loop were directly part of the original loop (as
1928693eedb1SChandler Carruth     // opposed to a child loop) update the map to point to this exit loop. This
1929693eedb1SChandler Carruth     // just updates a map and so the fact that the order is unstable is fine.
1930693eedb1SChandler Carruth     for (auto *BB : NewExitLoopBlocks)
1931693eedb1SChandler Carruth       if (Loop *BBL = LI.getLoopFor(BB))
1932693eedb1SChandler Carruth         if (BBL == &L || !L.contains(BBL))
1933693eedb1SChandler Carruth           LI.changeLoopFor(BB, &ExitL);
1934693eedb1SChandler Carruth 
1935693eedb1SChandler Carruth     // We will remove the remaining unlooped blocks from this loop in the next
1936693eedb1SChandler Carruth     // iteration or below.
1937693eedb1SChandler Carruth     NewExitLoopBlocks.clear();
1938693eedb1SChandler Carruth   }
1939693eedb1SChandler Carruth 
1940693eedb1SChandler Carruth   // Any remaining unlooped blocks are no longer part of any loop unless they
1941693eedb1SChandler Carruth   // are part of some child loop.
1942693eedb1SChandler Carruth   for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1943693eedb1SChandler Carruth     RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1944693eedb1SChandler Carruth   for (auto *BB : UnloopedBlocks)
1945693eedb1SChandler Carruth     if (Loop *BBL = LI.getLoopFor(BB))
1946693eedb1SChandler Carruth       if (BBL == &L || !L.contains(BBL))
1947693eedb1SChandler Carruth         LI.changeLoopFor(BB, nullptr);
1948693eedb1SChandler Carruth 
1949693eedb1SChandler Carruth   // Sink all the child loops whose headers are no longer in the loop set to
1950693eedb1SChandler Carruth   // the parent (or to be top level loops). We reach into the loop and directly
1951693eedb1SChandler Carruth   // update its subloop vector to make this batch update efficient.
1952693eedb1SChandler Carruth   auto &SubLoops = L.getSubLoopsVector();
1953693eedb1SChandler Carruth   auto SubLoopsSplitI =
1954693eedb1SChandler Carruth       LoopBlockSet.empty()
1955693eedb1SChandler Carruth           ? SubLoops.begin()
1956693eedb1SChandler Carruth           : std::stable_partition(
1957693eedb1SChandler Carruth                 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1958693eedb1SChandler Carruth                   return LoopBlockSet.count(SubL->getHeader());
1959693eedb1SChandler Carruth                 });
1960693eedb1SChandler Carruth   for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1961693eedb1SChandler Carruth     HoistedLoops.push_back(HoistedL);
1962693eedb1SChandler Carruth     HoistedL->setParentLoop(nullptr);
1963693eedb1SChandler Carruth 
1964693eedb1SChandler Carruth     // To compute the new parent of this hoisted loop we look at where we
1965693eedb1SChandler Carruth     // placed the preheader above. We can't lookup the header itself because we
1966693eedb1SChandler Carruth     // retained the mapping from the header to the hoisted loop. But the
1967693eedb1SChandler Carruth     // preheader and header should have the exact same new parent computed
1968693eedb1SChandler Carruth     // based on the set of exit blocks from the original loop as the preheader
1969693eedb1SChandler Carruth     // is a predecessor of the header and so reached in the reverse walk. And
1970693eedb1SChandler Carruth     // because the loops were all in simplified form the preheader of the
1971693eedb1SChandler Carruth     // hoisted loop can't be part of some *other* loop.
1972693eedb1SChandler Carruth     if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1973693eedb1SChandler Carruth       NewParentL->addChildLoop(HoistedL);
1974693eedb1SChandler Carruth     else
1975693eedb1SChandler Carruth       LI.addTopLevelLoop(HoistedL);
1976693eedb1SChandler Carruth   }
1977693eedb1SChandler Carruth   SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1978693eedb1SChandler Carruth 
1979693eedb1SChandler Carruth   // Actually delete the loop if nothing remained within it.
1980693eedb1SChandler Carruth   if (Blocks.empty()) {
1981693eedb1SChandler Carruth     assert(SubLoops.empty() &&
1982693eedb1SChandler Carruth            "Failed to remove all subloops from the original loop!");
1983693eedb1SChandler Carruth     if (Loop *ParentL = L.getParentLoop())
1984693eedb1SChandler Carruth       ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1985693eedb1SChandler Carruth     else
1986693eedb1SChandler Carruth       LI.removeLoop(llvm::find(LI, &L));
19870f0344ddSBjorn Pettersson     // markLoopAsDeleted for L should be triggered by the caller (it is typically
19880f0344ddSBjorn Pettersson     // done by using the UnswitchCB callback).
1989693eedb1SChandler Carruth     LI.destroy(&L);
1990693eedb1SChandler Carruth     return false;
1991693eedb1SChandler Carruth   }
1992693eedb1SChandler Carruth 
1993693eedb1SChandler Carruth   return true;
1994693eedb1SChandler Carruth }
1995693eedb1SChandler Carruth 
1996693eedb1SChandler Carruth /// Helper to visit a dominator subtree, invoking a callable on each node.
1997693eedb1SChandler Carruth ///
1998693eedb1SChandler Carruth /// Returning false at any point will stop walking past that node of the tree.
1999693eedb1SChandler Carruth template <typename CallableT>
2000693eedb1SChandler Carruth void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
2001693eedb1SChandler Carruth   SmallVector<DomTreeNode *, 4> DomWorklist;
2002693eedb1SChandler Carruth   DomWorklist.push_back(DT[BB]);
2003693eedb1SChandler Carruth #ifndef NDEBUG
2004693eedb1SChandler Carruth   SmallPtrSet<DomTreeNode *, 4> Visited;
2005693eedb1SChandler Carruth   Visited.insert(DT[BB]);
2006693eedb1SChandler Carruth #endif
2007693eedb1SChandler Carruth   do {
2008693eedb1SChandler Carruth     DomTreeNode *N = DomWorklist.pop_back_val();
2009693eedb1SChandler Carruth 
2010693eedb1SChandler Carruth     // Visit this node.
2011693eedb1SChandler Carruth     if (!Callable(N->getBlock()))
2012693eedb1SChandler Carruth       continue;
2013693eedb1SChandler Carruth 
2014693eedb1SChandler Carruth     // Accumulate the child nodes.
2015693eedb1SChandler Carruth     for (DomTreeNode *ChildN : *N) {
2016693eedb1SChandler Carruth       assert(Visited.insert(ChildN).second &&
2017693eedb1SChandler Carruth              "Cannot visit a node twice when walking a tree!");
2018693eedb1SChandler Carruth       DomWorklist.push_back(ChildN);
2019693eedb1SChandler Carruth     }
2020693eedb1SChandler Carruth   } while (!DomWorklist.empty());
2021693eedb1SChandler Carruth }
2022693eedb1SChandler Carruth 
2023bde31000SMax Kazantsev static void unswitchNontrivialInvariants(
202460b2e054SChandler Carruth     Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
2025f3a27511SJingu Kang     SmallVectorImpl<BasicBlock *> &ExitBlocks, IVConditionInfo &PartialIVInfo,
2026f3a27511SJingu Kang     DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
2027f3a27511SJingu Kang     function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
20280f0344ddSBjorn Pettersson     ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
20290f0344ddSBjorn Pettersson     function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
20301652996fSChandler Carruth   auto *ParentBB = TI.getParent();
20311652996fSChandler Carruth   BranchInst *BI = dyn_cast<BranchInst>(&TI);
20321652996fSChandler Carruth   SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
2033d1dab0c3SChandler Carruth 
20341652996fSChandler Carruth   // We can only unswitch switches, conditional branches with an invariant
2035f3a27511SJingu Kang   // condition, or combining invariant conditions with an instruction or
2036f3a27511SJingu Kang   // partially invariant instructions.
2037c598ef7fSSimon Pilgrim   assert((SI || (BI && BI->isConditional())) &&
20381652996fSChandler Carruth          "Can only unswitch switches and conditional branch!");
2039f3a27511SJingu Kang   bool PartiallyInvariant = !PartialIVInfo.InstToDuplicate.empty();
2040f3a27511SJingu Kang   bool FullUnswitch =
2041f3a27511SJingu Kang       SI || (BI->getCondition() == Invariants[0] && !PartiallyInvariant);
2042d1dab0c3SChandler Carruth   if (FullUnswitch)
2043d1dab0c3SChandler Carruth     assert(Invariants.size() == 1 &&
2044d1dab0c3SChandler Carruth            "Cannot have other invariants with full unswitching!");
2045d1dab0c3SChandler Carruth   else
20461652996fSChandler Carruth     assert(isa<Instruction>(BI->getCondition()) &&
2047d1dab0c3SChandler Carruth            "Partial unswitching requires an instruction as the condition!");
2048d1dab0c3SChandler Carruth 
2049a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
2050a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
2051a2eebb82SAlina Sbirlea 
2052d1dab0c3SChandler Carruth   // Constant and BBs tracking the cloned and continuing successor. When we are
2053d1dab0c3SChandler Carruth   // unswitching the entire condition, this can just be trivially chosen to
2054d1dab0c3SChandler Carruth   // unswitch towards `true`. However, when we are unswitching a set of
2055f3a27511SJingu Kang   // invariants combined with `and` or `or` or partially invariant instructions,
2056f3a27511SJingu Kang   // the combining operation determines the best direction to unswitch: we want
2057f3a27511SJingu Kang   // to unswitch the direction that will collapse the branch.
2058d1dab0c3SChandler Carruth   bool Direction = true;
2059d1dab0c3SChandler Carruth   int ClonedSucc = 0;
2060d1dab0c3SChandler Carruth   if (!FullUnswitch) {
2061431a40e1SJuneyoung Lee     Value *Cond = BI->getCondition();
20623e5ee194SFangrui Song     (void)Cond;
2063f3a27511SJingu Kang     assert(((match(Cond, m_LogicalAnd()) ^ match(Cond, m_LogicalOr())) ||
2064f3a27511SJingu Kang             PartiallyInvariant) &&
2065f3a27511SJingu Kang            "Only `or`, `and`, an `select`, partially invariant instructions "
2066f3a27511SJingu Kang            "can combine invariants being unswitched.");
2067431a40e1SJuneyoung Lee     if (!match(BI->getCondition(), m_LogicalOr())) {
2068f3a27511SJingu Kang       if (match(BI->getCondition(), m_LogicalAnd()) ||
2069f3a27511SJingu Kang           (PartiallyInvariant && !PartialIVInfo.KnownValue->isOneValue())) {
2070d1dab0c3SChandler Carruth         Direction = false;
2071d1dab0c3SChandler Carruth         ClonedSucc = 1;
2072d1dab0c3SChandler Carruth       }
2073d1dab0c3SChandler Carruth     }
2074f3a27511SJingu Kang   }
2075693eedb1SChandler Carruth 
20761652996fSChandler Carruth   BasicBlock *RetainedSuccBB =
20771652996fSChandler Carruth       BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
20781652996fSChandler Carruth   SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
20791652996fSChandler Carruth   if (BI)
20801652996fSChandler Carruth     UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
20811652996fSChandler Carruth   else
20821652996fSChandler Carruth     for (auto Case : SI->cases())
2083ed296543SChandler Carruth       if (Case.getCaseSuccessor() != RetainedSuccBB)
20841652996fSChandler Carruth         UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
20851652996fSChandler Carruth 
20861652996fSChandler Carruth   assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
20871652996fSChandler Carruth          "Should not unswitch the same successor we are retaining!");
2088693eedb1SChandler Carruth 
2089693eedb1SChandler Carruth   // The branch should be in this exact loop. Any inner loop's invariant branch
2090693eedb1SChandler Carruth   // should be handled by unswitching that inner loop. The caller of this
2091693eedb1SChandler Carruth   // routine should filter out any candidates that remain (but were skipped for
2092693eedb1SChandler Carruth   // whatever reason).
2093693eedb1SChandler Carruth   assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
2094693eedb1SChandler Carruth 
2095693eedb1SChandler Carruth   // Compute the parent loop now before we start hacking on things.
2096693eedb1SChandler Carruth   Loop *ParentL = L.getParentLoop();
2097a2eebb82SAlina Sbirlea   // Get blocks in RPO order for MSSA update, before changing the CFG.
2098a2eebb82SAlina Sbirlea   LoopBlocksRPO LBRPO(&L);
2099a2eebb82SAlina Sbirlea   if (MSSAU)
2100a2eebb82SAlina Sbirlea     LBRPO.perform(&LI);
2101693eedb1SChandler Carruth 
2102693eedb1SChandler Carruth   // Compute the outer-most loop containing one of our exit blocks. This is the
2103693eedb1SChandler Carruth   // furthest up our loopnest which can be mutated, which we will use below to
2104693eedb1SChandler Carruth   // update things.
2105693eedb1SChandler Carruth   Loop *OuterExitL = &L;
2106693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks) {
2107693eedb1SChandler Carruth     Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
2108693eedb1SChandler Carruth     if (!NewOuterExitL) {
2109693eedb1SChandler Carruth       // We exited the entire nest with this block, so we're done.
2110693eedb1SChandler Carruth       OuterExitL = nullptr;
2111693eedb1SChandler Carruth       break;
2112693eedb1SChandler Carruth     }
2113693eedb1SChandler Carruth     if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
2114693eedb1SChandler Carruth       OuterExitL = NewOuterExitL;
2115693eedb1SChandler Carruth   }
2116693eedb1SChandler Carruth 
21173897ded6SChandler Carruth   // At this point, we're definitely going to unswitch something so invalidate
21183897ded6SChandler Carruth   // any cached information in ScalarEvolution for the outer most loop
21193897ded6SChandler Carruth   // containing an exit block and all nested loops.
21203897ded6SChandler Carruth   if (SE) {
21213897ded6SChandler Carruth     if (OuterExitL)
21223897ded6SChandler Carruth       SE->forgetLoop(OuterExitL);
21233897ded6SChandler Carruth     else
21243897ded6SChandler Carruth       SE->forgetTopmostLoop(&L);
21253897ded6SChandler Carruth   }
21263897ded6SChandler Carruth 
21271652996fSChandler Carruth   // If the edge from this terminator to a successor dominates that successor,
21281652996fSChandler Carruth   // store a map from each block in its dominator subtree to it. This lets us
21291652996fSChandler Carruth   // tell when cloning for a particular successor if a block is dominated by
21301652996fSChandler Carruth   // some *other* successor with a single data structure. We use this to
21311652996fSChandler Carruth   // significantly reduce cloning.
21321652996fSChandler Carruth   SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
21331652996fSChandler Carruth   for (auto *SuccBB : llvm::concat<BasicBlock *const>(
21341652996fSChandler Carruth            makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
21351652996fSChandler Carruth     if (SuccBB->getUniquePredecessor() ||
21361652996fSChandler Carruth         llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
21371652996fSChandler Carruth           return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
21381652996fSChandler Carruth         }))
21391652996fSChandler Carruth       visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
21401652996fSChandler Carruth         DominatingSucc[BB] = SuccBB;
2141693eedb1SChandler Carruth         return true;
2142693eedb1SChandler Carruth       });
2143693eedb1SChandler Carruth 
2144693eedb1SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
2145693eedb1SChandler Carruth   // the conditional branch. We will change the preheader to have a conditional
2146693eedb1SChandler Carruth   // branch on LoopCond. The original preheader will become the split point
2147693eedb1SChandler Carruth   // between the unswitched versions, and we will have a new preheader for the
2148693eedb1SChandler Carruth   // original loop.
2149693eedb1SChandler Carruth   BasicBlock *SplitBB = L.getLoopPreheader();
2150a2eebb82SAlina Sbirlea   BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
2151693eedb1SChandler Carruth 
215269e68f84SChandler Carruth   // Keep track of the dominator tree updates needed.
215369e68f84SChandler Carruth   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
215469e68f84SChandler Carruth 
21551652996fSChandler Carruth   // Clone the loop for each unswitched successor.
21561652996fSChandler Carruth   SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
21571652996fSChandler Carruth   VMaps.reserve(UnswitchedSuccBBs.size());
21581652996fSChandler Carruth   SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
21591652996fSChandler Carruth   for (auto *SuccBB : UnswitchedSuccBBs) {
21601652996fSChandler Carruth     VMaps.emplace_back(new ValueToValueMapTy());
21611652996fSChandler Carruth     ClonedPHs[SuccBB] = buildClonedLoopBlocks(
21621652996fSChandler Carruth         L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2163a2eebb82SAlina Sbirlea         DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
21641652996fSChandler Carruth   }
2165693eedb1SChandler Carruth 
21668aaeee5fSMax Kazantsev   // Drop metadata if we may break its semantics by moving this instr into the
2167d889e17eSMax Kazantsev   // split block.
21688aaeee5fSMax Kazantsev   if (TI.getMetadata(LLVMContext::MD_make_implicit)) {
21697647c271SMax Kazantsev     if (DropNonTrivialImplicitNullChecks)
21707647c271SMax Kazantsev       // Do not spend time trying to understand if we can keep it, just drop it
21717647c271SMax Kazantsev       // to save compile time.
21727647c271SMax Kazantsev       TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
21737647c271SMax Kazantsev     else {
21747647c271SMax Kazantsev       // It is only legal to preserve make.implicit metadata if we are
21757647c271SMax Kazantsev       // guaranteed no reach implicit null check after following this branch.
21768aaeee5fSMax Kazantsev       ICFLoopSafetyInfo SafetyInfo;
21778aaeee5fSMax Kazantsev       SafetyInfo.computeLoopSafetyInfo(&L);
21788aaeee5fSMax Kazantsev       if (!SafetyInfo.isGuaranteedToExecute(TI, &DT, &L))
2179d889e17eSMax Kazantsev         TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
21808aaeee5fSMax Kazantsev     }
21817647c271SMax Kazantsev   }
2182d889e17eSMax Kazantsev 
2183d1dab0c3SChandler Carruth   // The stitching of the branched code back together depends on whether we're
2184d1dab0c3SChandler Carruth   // doing full unswitching or not with the exception that we always want to
2185d1dab0c3SChandler Carruth   // nuke the initial terminator placed in the split block.
2186d1dab0c3SChandler Carruth   SplitBB->getTerminator()->eraseFromParent();
2187d1dab0c3SChandler Carruth   if (FullUnswitch) {
2188a2eebb82SAlina Sbirlea     // Splice the terminator from the original loop and rewrite its
2189a2eebb82SAlina Sbirlea     // successors.
2190a2eebb82SAlina Sbirlea     SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2191a2eebb82SAlina Sbirlea 
2192a2eebb82SAlina Sbirlea     // Keep a clone of the terminator for MSSA updates.
2193a2eebb82SAlina Sbirlea     Instruction *NewTI = TI.clone();
2194a2eebb82SAlina Sbirlea     ParentBB->getInstList().push_back(NewTI);
2195a2eebb82SAlina Sbirlea 
2196a2eebb82SAlina Sbirlea     // First wire up the moved terminator to the preheaders.
2197a2eebb82SAlina Sbirlea     if (BI) {
2198a2eebb82SAlina Sbirlea       BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2199a2eebb82SAlina Sbirlea       BI->setSuccessor(ClonedSucc, ClonedPH);
2200a2eebb82SAlina Sbirlea       BI->setSuccessor(1 - ClonedSucc, LoopPH);
2201a2eebb82SAlina Sbirlea       DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2202a2eebb82SAlina Sbirlea     } else {
2203a2eebb82SAlina Sbirlea       assert(SI && "Must either be a branch or switch!");
2204a2eebb82SAlina Sbirlea 
2205a2eebb82SAlina Sbirlea       // Walk the cases and directly update their successors.
2206a2eebb82SAlina Sbirlea       assert(SI->getDefaultDest() == RetainedSuccBB &&
2207a2eebb82SAlina Sbirlea              "Not retaining default successor!");
2208a2eebb82SAlina Sbirlea       SI->setDefaultDest(LoopPH);
2209a2eebb82SAlina Sbirlea       for (auto &Case : SI->cases())
2210a2eebb82SAlina Sbirlea         if (Case.getCaseSuccessor() == RetainedSuccBB)
2211a2eebb82SAlina Sbirlea           Case.setSuccessor(LoopPH);
2212a2eebb82SAlina Sbirlea         else
2213a2eebb82SAlina Sbirlea           Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2214a2eebb82SAlina Sbirlea 
2215a2eebb82SAlina Sbirlea       // We need to use the set to populate domtree updates as even when there
2216a2eebb82SAlina Sbirlea       // are multiple cases pointing at the same successor we only want to
2217a2eebb82SAlina Sbirlea       // remove and insert one edge in the domtree.
2218a2eebb82SAlina Sbirlea       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2219a2eebb82SAlina Sbirlea         DTUpdates.push_back(
2220a2eebb82SAlina Sbirlea             {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2221a2eebb82SAlina Sbirlea     }
2222a2eebb82SAlina Sbirlea 
2223a2eebb82SAlina Sbirlea     if (MSSAU) {
2224a2eebb82SAlina Sbirlea       DT.applyUpdates(DTUpdates);
2225a2eebb82SAlina Sbirlea       DTUpdates.clear();
2226a2eebb82SAlina Sbirlea 
2227a2eebb82SAlina Sbirlea       // Remove all but one edge to the retained block and all unswitched
2228a2eebb82SAlina Sbirlea       // blocks. This is to avoid having duplicate entries in the cloned Phis,
2229a2eebb82SAlina Sbirlea       // when we know we only keep a single edge for each case.
2230a2eebb82SAlina Sbirlea       MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2231a2eebb82SAlina Sbirlea       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2232a2eebb82SAlina Sbirlea         MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2233a2eebb82SAlina Sbirlea 
2234a2eebb82SAlina Sbirlea       for (auto &VMap : VMaps)
2235a2eebb82SAlina Sbirlea         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2236a2eebb82SAlina Sbirlea                                    /*IgnoreIncomingWithNoClones=*/true);
2237a2eebb82SAlina Sbirlea       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2238a2eebb82SAlina Sbirlea 
2239a2eebb82SAlina Sbirlea       // Remove all edges to unswitched blocks.
2240a2eebb82SAlina Sbirlea       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2241a2eebb82SAlina Sbirlea         MSSAU->removeEdge(ParentBB, SuccBB);
2242a2eebb82SAlina Sbirlea     }
2243a2eebb82SAlina Sbirlea 
2244a2eebb82SAlina Sbirlea     // Now unhook the successor relationship as we'll be replacing
2245ed296543SChandler Carruth     // the terminator with a direct branch. This is much simpler for branches
2246ed296543SChandler Carruth     // than switches so we handle those first.
2247ed296543SChandler Carruth     if (BI) {
22481652996fSChandler Carruth       // Remove the parent as a predecessor of the unswitched successor.
2249ed296543SChandler Carruth       assert(UnswitchedSuccBBs.size() == 1 &&
2250ed296543SChandler Carruth              "Only one possible unswitched block for a branch!");
2251ed296543SChandler Carruth       BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2252ed296543SChandler Carruth       UnswitchedSuccBB->removePredecessor(ParentBB,
225320b91899SMax Kazantsev                                           /*KeepOneInputPHIs*/ true);
2254ed296543SChandler Carruth       DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2255ed296543SChandler Carruth     } else {
2256ed296543SChandler Carruth       // Note that we actually want to remove the parent block as a predecessor
2257ed296543SChandler Carruth       // of *every* case successor. The case successor is either unswitched,
2258ed296543SChandler Carruth       // completely eliminating an edge from the parent to that successor, or it
2259ed296543SChandler Carruth       // is a duplicate edge to the retained successor as the retained successor
2260ed296543SChandler Carruth       // is always the default successor and as we'll replace this with a direct
2261ed296543SChandler Carruth       // branch we no longer need the duplicate entries in the PHI nodes.
2262a2eebb82SAlina Sbirlea       SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2263a2eebb82SAlina Sbirlea       assert(NewSI->getDefaultDest() == RetainedSuccBB &&
2264ed296543SChandler Carruth              "Not retaining default successor!");
2265a2eebb82SAlina Sbirlea       for (auto &Case : NewSI->cases())
2266ed296543SChandler Carruth         Case.getCaseSuccessor()->removePredecessor(
2267ed296543SChandler Carruth             ParentBB,
226820b91899SMax Kazantsev             /*KeepOneInputPHIs*/ true);
2269ed296543SChandler Carruth 
2270ed296543SChandler Carruth       // We need to use the set to populate domtree updates as even when there
2271ed296543SChandler Carruth       // are multiple cases pointing at the same successor we only want to
2272ed296543SChandler Carruth       // remove and insert one edge in the domtree.
2273ed296543SChandler Carruth       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
22741652996fSChandler Carruth         DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
22751652996fSChandler Carruth     }
2276693eedb1SChandler Carruth 
2277a2eebb82SAlina Sbirlea     // After MSSAU update, remove the cloned terminator instruction NewTI.
2278a2eebb82SAlina Sbirlea     ParentBB->getTerminator()->eraseFromParent();
2279693eedb1SChandler Carruth 
2280693eedb1SChandler Carruth     // Create a new unconditional branch to the continuing block (as opposed to
2281693eedb1SChandler Carruth     // the one cloned).
22821652996fSChandler Carruth     BranchInst::Create(RetainedSuccBB, ParentBB);
2283d1dab0c3SChandler Carruth   } else {
22841652996fSChandler Carruth     assert(BI && "Only branches have partial unswitching.");
22851652996fSChandler Carruth     assert(UnswitchedSuccBBs.size() == 1 &&
22861652996fSChandler Carruth            "Only one possible unswitched block for a branch!");
22871652996fSChandler Carruth     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2288d1dab0c3SChandler Carruth     // When doing a partial unswitch, we have to do a bit more work to build up
2289d1dab0c3SChandler Carruth     // the branch in the split block.
2290f3a27511SJingu Kang     if (PartiallyInvariant)
2291f3a27511SJingu Kang       buildPartialInvariantUnswitchConditionalBranch(
2292f3a27511SJingu Kang           *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH, L, MSSAU);
2293f3a27511SJingu Kang     else
2294d1dab0c3SChandler Carruth       buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
22952b5a8976SJuneyoung Lee                                             *ClonedPH, *LoopPH);
229635c8af18SAlina Sbirlea     DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
229735c8af18SAlina Sbirlea 
2298b7a33530SAlina Sbirlea     if (MSSAU) {
229935c8af18SAlina Sbirlea       DT.applyUpdates(DTUpdates);
230035c8af18SAlina Sbirlea       DTUpdates.clear();
230135c8af18SAlina Sbirlea 
2302b7a33530SAlina Sbirlea       // Perform MSSA cloning updates.
2303b7a33530SAlina Sbirlea       for (auto &VMap : VMaps)
2304b7a33530SAlina Sbirlea         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2305b7a33530SAlina Sbirlea                                    /*IgnoreIncomingWithNoClones=*/true);
2306b7a33530SAlina Sbirlea       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2307b7a33530SAlina Sbirlea     }
23081652996fSChandler Carruth   }
23091652996fSChandler Carruth 
23101652996fSChandler Carruth   // Apply the updates accumulated above to get an up-to-date dominator tree.
231169e68f84SChandler Carruth   DT.applyUpdates(DTUpdates);
231269e68f84SChandler Carruth 
23131652996fSChandler Carruth   // Now that we have an accurate dominator tree, first delete the dead cloned
23141652996fSChandler Carruth   // blocks so that we can accurately build any cloned loops. It is important to
23151652996fSChandler Carruth   // not delete the blocks from the original loop yet because we still want to
23161652996fSChandler Carruth   // reference the original loop to understand the cloned loop's structure.
2317a2eebb82SAlina Sbirlea   deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
23181652996fSChandler Carruth 
231969e68f84SChandler Carruth   // Build the cloned loop structure itself. This may be substantially
232069e68f84SChandler Carruth   // different from the original structure due to the simplified CFG. This also
232169e68f84SChandler Carruth   // handles inserting all the cloned blocks into the correct loops.
232269e68f84SChandler Carruth   SmallVector<Loop *, 4> NonChildClonedLoops;
23231652996fSChandler Carruth   for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
23241652996fSChandler Carruth     buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
232569e68f84SChandler Carruth 
23261652996fSChandler Carruth   // Now that our cloned loops have been built, we can update the original loop.
23271652996fSChandler Carruth   // First we delete the dead blocks from it and then we rebuild the loop
23281652996fSChandler Carruth   // structure taking these deletions into account.
23290f0344ddSBjorn Pettersson   deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU, DestroyLoopCB);
2330a2eebb82SAlina Sbirlea 
2331a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
2332a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
2333a2eebb82SAlina Sbirlea 
2334693eedb1SChandler Carruth   SmallVector<Loop *, 4> HoistedLoops;
2335693eedb1SChandler Carruth   bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2336693eedb1SChandler Carruth 
2337a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
2338a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
2339a2eebb82SAlina Sbirlea 
234069e68f84SChandler Carruth   // This transformation has a high risk of corrupting the dominator tree, and
234169e68f84SChandler Carruth   // the below steps to rebuild loop structures will result in hard to debug
234269e68f84SChandler Carruth   // errors in that case so verify that the dominator tree is sane first.
234369e68f84SChandler Carruth   // FIXME: Remove this when the bugs stop showing up and rely on existing
234469e68f84SChandler Carruth   // verification steps.
234569e68f84SChandler Carruth   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2346693eedb1SChandler Carruth 
2347f3a27511SJingu Kang   if (BI && !PartiallyInvariant) {
23481652996fSChandler Carruth     // If we unswitched a branch which collapses the condition to a known
23491652996fSChandler Carruth     // constant we want to replace all the uses of the invariants within both
23501652996fSChandler Carruth     // the original and cloned blocks. We do this here so that we can use the
23511652996fSChandler Carruth     // now updated dominator tree to identify which side the users are on.
23521652996fSChandler Carruth     assert(UnswitchedSuccBBs.size() == 1 &&
23531652996fSChandler Carruth            "Only one possible unswitched block for a branch!");
23541652996fSChandler Carruth     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2355f9a02a70SFedor Sergeev 
2356f9a02a70SFedor Sergeev     // When considering multiple partially-unswitched invariants
2357f9a02a70SFedor Sergeev     // we cant just go replace them with constants in both branches.
2358f9a02a70SFedor Sergeev     //
2359f9a02a70SFedor Sergeev     // For 'AND' we infer that true branch ("continue") means true
2360f9a02a70SFedor Sergeev     // for each invariant operand.
2361f9a02a70SFedor Sergeev     // For 'OR' we can infer that false branch ("continue") means false
2362f9a02a70SFedor Sergeev     // for each invariant operand.
2363f9a02a70SFedor Sergeev     // So it happens that for multiple-partial case we dont replace
2364f9a02a70SFedor Sergeev     // in the unswitched branch.
2365f3a27511SJingu Kang     bool ReplaceUnswitched =
2366f3a27511SJingu Kang         FullUnswitch || (Invariants.size() == 1) || PartiallyInvariant;
2367f9a02a70SFedor Sergeev 
2368d1dab0c3SChandler Carruth     ConstantInt *UnswitchedReplacement =
23691652996fSChandler Carruth         Direction ? ConstantInt::getTrue(BI->getContext())
23701652996fSChandler Carruth                   : ConstantInt::getFalse(BI->getContext());
2371d1dab0c3SChandler Carruth     ConstantInt *ContinueReplacement =
23721652996fSChandler Carruth         Direction ? ConstantInt::getFalse(BI->getContext())
23731652996fSChandler Carruth                   : ConstantInt::getTrue(BI->getContext());
237445bd8d94SDaniil Suchkov     for (Value *Invariant : Invariants) {
237545bd8d94SDaniil Suchkov       assert(!isa<Constant>(Invariant) &&
237645bd8d94SDaniil Suchkov              "Should not be replacing constant values!");
23775fc9e309SKazu Hirata       // Use make_early_inc_range here as set invalidates the iterator.
23785fc9e309SKazu Hirata       for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
23795fc9e309SKazu Hirata         Instruction *UserI = dyn_cast<Instruction>(U.getUser());
2380d1dab0c3SChandler Carruth         if (!UserI)
2381d1dab0c3SChandler Carruth           continue;
2382d1dab0c3SChandler Carruth 
2383d1dab0c3SChandler Carruth         // Replace it with the 'continue' side if in the main loop body, and the
2384d1dab0c3SChandler Carruth         // unswitched if in the cloned blocks.
2385d1dab0c3SChandler Carruth         if (DT.dominates(LoopPH, UserI->getParent()))
23865fc9e309SKazu Hirata           U.set(ContinueReplacement);
2387f9a02a70SFedor Sergeev         else if (ReplaceUnswitched &&
2388f9a02a70SFedor Sergeev                  DT.dominates(ClonedPH, UserI->getParent()))
23895fc9e309SKazu Hirata           U.set(UnswitchedReplacement);
2390d1dab0c3SChandler Carruth       }
23911652996fSChandler Carruth     }
239245bd8d94SDaniil Suchkov   }
2393d1dab0c3SChandler Carruth 
2394693eedb1SChandler Carruth   // We can change which blocks are exit blocks of all the cloned sibling
2395693eedb1SChandler Carruth   // loops, the current loop, and any parent loops which shared exit blocks
2396693eedb1SChandler Carruth   // with the current loop. As a consequence, we need to re-form LCSSA for
2397693eedb1SChandler Carruth   // them. But we shouldn't need to re-form LCSSA for any child loops.
2398693eedb1SChandler Carruth   // FIXME: This could be made more efficient by tracking which exit blocks are
2399693eedb1SChandler Carruth   // new, and focusing on them, but that isn't likely to be necessary.
2400693eedb1SChandler Carruth   //
2401693eedb1SChandler Carruth   // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2402693eedb1SChandler Carruth   // loop nest and update every loop that could have had its exits changed. We
2403693eedb1SChandler Carruth   // also need to cover any intervening loops. We add all of these loops to
2404693eedb1SChandler Carruth   // a list and sort them by loop depth to achieve this without updating
2405693eedb1SChandler Carruth   // unnecessary loops.
24069281503eSChandler Carruth   auto UpdateLoop = [&](Loop &UpdateL) {
2407693eedb1SChandler Carruth #ifndef NDEBUG
240843acdb35SChandler Carruth     UpdateL.verifyLoop();
240943acdb35SChandler Carruth     for (Loop *ChildL : UpdateL) {
241043acdb35SChandler Carruth       ChildL->verifyLoop();
2411693eedb1SChandler Carruth       assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2412693eedb1SChandler Carruth              "Perturbed a child loop's LCSSA form!");
241343acdb35SChandler Carruth     }
2414693eedb1SChandler Carruth #endif
2415693eedb1SChandler Carruth     // First build LCSSA for this loop so that we can preserve it when
2416693eedb1SChandler Carruth     // forming dedicated exits. We don't want to perturb some other loop's
2417693eedb1SChandler Carruth     // LCSSA while doing that CFG edit.
2418c4d8c631SDaniil Suchkov     formLCSSA(UpdateL, DT, &LI, SE);
2419693eedb1SChandler Carruth 
2420693eedb1SChandler Carruth     // For loops reached by this loop's original exit blocks we may
2421693eedb1SChandler Carruth     // introduced new, non-dedicated exits. At least try to re-form dedicated
2422693eedb1SChandler Carruth     // exits for these loops. This may fail if they couldn't have dedicated
2423693eedb1SChandler Carruth     // exits to start with.
242497468e92SAlina Sbirlea     formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
24259281503eSChandler Carruth   };
24269281503eSChandler Carruth 
24279281503eSChandler Carruth   // For non-child cloned loops and hoisted loops, we just need to update LCSSA
24289281503eSChandler Carruth   // and we can do it in any order as they don't nest relative to each other.
24299281503eSChandler Carruth   //
24309281503eSChandler Carruth   // Also check if any of the loops we have updated have become top-level loops
24319281503eSChandler Carruth   // as that will necessitate widening the outer loop scope.
24329281503eSChandler Carruth   for (Loop *UpdatedL :
24339281503eSChandler Carruth        llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
24349281503eSChandler Carruth     UpdateLoop(*UpdatedL);
243589c1e35fSStefanos Baziotis     if (UpdatedL->isOutermost())
24369281503eSChandler Carruth       OuterExitL = nullptr;
2437693eedb1SChandler Carruth   }
24389281503eSChandler Carruth   if (IsStillLoop) {
24399281503eSChandler Carruth     UpdateLoop(L);
244089c1e35fSStefanos Baziotis     if (L.isOutermost())
24419281503eSChandler Carruth       OuterExitL = nullptr;
2442693eedb1SChandler Carruth   }
2443693eedb1SChandler Carruth 
24449281503eSChandler Carruth   // If the original loop had exit blocks, walk up through the outer most loop
24459281503eSChandler Carruth   // of those exit blocks to update LCSSA and form updated dedicated exits.
24469281503eSChandler Carruth   if (OuterExitL != &L)
24479281503eSChandler Carruth     for (Loop *OuterL = ParentL; OuterL != OuterExitL;
24489281503eSChandler Carruth          OuterL = OuterL->getParentLoop())
24499281503eSChandler Carruth       UpdateLoop(*OuterL);
24509281503eSChandler Carruth 
2451693eedb1SChandler Carruth #ifndef NDEBUG
2452693eedb1SChandler Carruth   // Verify the entire loop structure to catch any incorrect updates before we
2453693eedb1SChandler Carruth   // progress in the pass pipeline.
2454693eedb1SChandler Carruth   LI.verify(DT);
2455693eedb1SChandler Carruth #endif
2456693eedb1SChandler Carruth 
2457693eedb1SChandler Carruth   // Now that we've unswitched something, make callbacks to report the changes.
2458693eedb1SChandler Carruth   // For that we need to merge together the updated loops and the cloned loops
2459693eedb1SChandler Carruth   // and check whether the original loop survived.
2460693eedb1SChandler Carruth   SmallVector<Loop *, 4> SibLoops;
2461693eedb1SChandler Carruth   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2462693eedb1SChandler Carruth     if (UpdatedL->getParentLoop() == ParentL)
2463693eedb1SChandler Carruth       SibLoops.push_back(UpdatedL);
2464f3a27511SJingu Kang   UnswitchCB(IsStillLoop, PartiallyInvariant, SibLoops);
2465693eedb1SChandler Carruth 
2466a2eebb82SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
2467a2eebb82SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
2468a2eebb82SAlina Sbirlea 
2469b7dff9c9SZaara Syeda   if (BI)
2470693eedb1SChandler Carruth     ++NumBranches;
2471b7dff9c9SZaara Syeda   else
2472b7dff9c9SZaara Syeda     ++NumSwitches;
2473693eedb1SChandler Carruth }
2474693eedb1SChandler Carruth 
2475693eedb1SChandler Carruth /// Recursively compute the cost of a dominator subtree based on the per-block
2476693eedb1SChandler Carruth /// cost map provided.
2477693eedb1SChandler Carruth ///
2478693eedb1SChandler Carruth /// The recursive computation is memozied into the provided DT-indexed cost map
2479693eedb1SChandler Carruth /// to allow querying it for most nodes in the domtree without it becoming
2480693eedb1SChandler Carruth /// quadratic.
248100da3227SSander de Smalen static InstructionCost computeDomSubtreeCost(
248200da3227SSander de Smalen     DomTreeNode &N,
248300da3227SSander de Smalen     const SmallDenseMap<BasicBlock *, InstructionCost, 4> &BBCostMap,
248400da3227SSander de Smalen     SmallDenseMap<DomTreeNode *, InstructionCost, 4> &DTCostMap) {
2485693eedb1SChandler Carruth   // Don't accumulate cost (or recurse through) blocks not in our block cost
2486693eedb1SChandler Carruth   // map and thus not part of the duplication cost being considered.
2487693eedb1SChandler Carruth   auto BBCostIt = BBCostMap.find(N.getBlock());
2488693eedb1SChandler Carruth   if (BBCostIt == BBCostMap.end())
2489693eedb1SChandler Carruth     return 0;
2490693eedb1SChandler Carruth 
2491693eedb1SChandler Carruth   // Lookup this node to see if we already computed its cost.
2492693eedb1SChandler Carruth   auto DTCostIt = DTCostMap.find(&N);
2493693eedb1SChandler Carruth   if (DTCostIt != DTCostMap.end())
2494693eedb1SChandler Carruth     return DTCostIt->second;
2495693eedb1SChandler Carruth 
2496693eedb1SChandler Carruth   // If not, we have to compute it. We can't use insert above and update
2497693eedb1SChandler Carruth   // because computing the cost may insert more things into the map.
249800da3227SSander de Smalen   InstructionCost Cost = std::accumulate(
249900da3227SSander de Smalen       N.begin(), N.end(), BBCostIt->second,
250000da3227SSander de Smalen       [&](InstructionCost Sum, DomTreeNode *ChildN) -> InstructionCost {
2501693eedb1SChandler Carruth         return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2502693eedb1SChandler Carruth       });
2503693eedb1SChandler Carruth   bool Inserted = DTCostMap.insert({&N, Cost}).second;
2504693eedb1SChandler Carruth   (void)Inserted;
2505693eedb1SChandler Carruth   assert(Inserted && "Should not insert a node while visiting children!");
2506693eedb1SChandler Carruth   return Cost;
2507693eedb1SChandler Carruth }
2508693eedb1SChandler Carruth 
2509619a8346SMax Kazantsev /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2510619a8346SMax Kazantsev /// making the following replacement:
2511619a8346SMax Kazantsev ///
2512a132016dSSimon Pilgrim ///   --code before guard--
2513619a8346SMax Kazantsev ///   call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
2514a132016dSSimon Pilgrim ///   --code after guard--
2515619a8346SMax Kazantsev ///
2516619a8346SMax Kazantsev /// into
2517619a8346SMax Kazantsev ///
2518a132016dSSimon Pilgrim ///   --code before guard--
2519619a8346SMax Kazantsev ///   br i1 %cond, label %guarded, label %deopt
2520619a8346SMax Kazantsev ///
2521619a8346SMax Kazantsev /// guarded:
2522a132016dSSimon Pilgrim ///   --code after guard--
2523619a8346SMax Kazantsev ///
2524619a8346SMax Kazantsev /// deopt:
2525619a8346SMax Kazantsev ///   call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2526619a8346SMax Kazantsev ///   unreachable
2527619a8346SMax Kazantsev ///
2528619a8346SMax Kazantsev /// It also makes all relevant DT and LI updates, so that all structures are in
2529619a8346SMax Kazantsev /// valid state after this transform.
2530619a8346SMax Kazantsev static BranchInst *
2531619a8346SMax Kazantsev turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2532619a8346SMax Kazantsev                     SmallVectorImpl<BasicBlock *> &ExitBlocks,
2533a2eebb82SAlina Sbirlea                     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
2534619a8346SMax Kazantsev   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2535619a8346SMax Kazantsev   LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2536619a8346SMax Kazantsev   BasicBlock *CheckBB = GI->getParent();
2537619a8346SMax Kazantsev 
2538797935f4SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
2539a2eebb82SAlina Sbirlea      MSSAU->getMemorySSA()->verifyMemorySSA();
2540a2eebb82SAlina Sbirlea 
2541619a8346SMax Kazantsev   // Remove all CheckBB's successors from DomTree. A block can be seen among
2542619a8346SMax Kazantsev   // successors more than once, but for DomTree it should be added only once.
2543619a8346SMax Kazantsev   SmallPtrSet<BasicBlock *, 4> Successors;
2544619a8346SMax Kazantsev   for (auto *Succ : successors(CheckBB))
2545619a8346SMax Kazantsev     if (Successors.insert(Succ).second)
2546619a8346SMax Kazantsev       DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2547619a8346SMax Kazantsev 
2548619a8346SMax Kazantsev   Instruction *DeoptBlockTerm =
2549619a8346SMax Kazantsev       SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2550619a8346SMax Kazantsev   BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2551619a8346SMax Kazantsev   // SplitBlockAndInsertIfThen inserts control flow that branches to
2552619a8346SMax Kazantsev   // DeoptBlockTerm if the condition is true.  We want the opposite.
2553619a8346SMax Kazantsev   CheckBI->swapSuccessors();
2554619a8346SMax Kazantsev 
2555619a8346SMax Kazantsev   BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2556619a8346SMax Kazantsev   GuardedBlock->setName("guarded");
2557619a8346SMax Kazantsev   CheckBI->getSuccessor(1)->setName("deopt");
2558a2eebb82SAlina Sbirlea   BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
2559619a8346SMax Kazantsev 
2560619a8346SMax Kazantsev   // We now have a new exit block.
2561619a8346SMax Kazantsev   ExitBlocks.push_back(CheckBI->getSuccessor(1));
2562619a8346SMax Kazantsev 
2563a2eebb82SAlina Sbirlea   if (MSSAU)
2564a2eebb82SAlina Sbirlea     MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2565a2eebb82SAlina Sbirlea 
2566619a8346SMax Kazantsev   GI->moveBefore(DeoptBlockTerm);
2567619a8346SMax Kazantsev   GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2568619a8346SMax Kazantsev 
2569619a8346SMax Kazantsev   // Add new successors of CheckBB into DomTree.
2570619a8346SMax Kazantsev   for (auto *Succ : successors(CheckBB))
2571619a8346SMax Kazantsev     DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2572619a8346SMax Kazantsev 
2573619a8346SMax Kazantsev   // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2574619a8346SMax Kazantsev   // successors.
2575619a8346SMax Kazantsev   for (auto *Succ : Successors)
2576619a8346SMax Kazantsev     DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2577619a8346SMax Kazantsev 
2578619a8346SMax Kazantsev   // Make proper changes to DT.
2579619a8346SMax Kazantsev   DT.applyUpdates(DTUpdates);
2580619a8346SMax Kazantsev   // Inform LI of a new loop block.
2581619a8346SMax Kazantsev   L.addBasicBlockToLoop(GuardedBlock, LI);
2582619a8346SMax Kazantsev 
2583a2eebb82SAlina Sbirlea   if (MSSAU) {
2584a2eebb82SAlina Sbirlea     MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
25855c5cf899SAlina Sbirlea     MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::BeforeTerminator);
2586a2eebb82SAlina Sbirlea     if (VerifyMemorySSA)
2587a2eebb82SAlina Sbirlea       MSSAU->getMemorySSA()->verifyMemorySSA();
2588a2eebb82SAlina Sbirlea   }
2589a2eebb82SAlina Sbirlea 
2590619a8346SMax Kazantsev   ++NumGuards;
2591619a8346SMax Kazantsev   return CheckBI;
2592619a8346SMax Kazantsev }
2593619a8346SMax Kazantsev 
25942e3e224eSFedor Sergeev /// Cost multiplier is a way to limit potentially exponential behavior
25952e3e224eSFedor Sergeev /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
25962e3e224eSFedor Sergeev /// candidates available. Also accounting for the number of "sibling" loops with
25972e3e224eSFedor Sergeev /// the idea to account for previous unswitches that already happened on this
25982e3e224eSFedor Sergeev /// cluster of loops. There was an attempt to keep this formula simple,
25992e3e224eSFedor Sergeev /// just enough to limit the worst case behavior. Even if it is not that simple
26002e3e224eSFedor Sergeev /// now it is still not an attempt to provide a detailed heuristic size
26012e3e224eSFedor Sergeev /// prediction.
26022e3e224eSFedor Sergeev ///
26032e3e224eSFedor Sergeev /// TODO: Make a proper accounting of "explosion" effect for all kinds of
26042e3e224eSFedor Sergeev /// unswitch candidates, making adequate predictions instead of wild guesses.
26052e3e224eSFedor Sergeev /// That requires knowing not just the number of "remaining" candidates but
26062e3e224eSFedor Sergeev /// also costs of unswitching for each of these candidates.
26071c03cc5aSAlina Sbirlea static int CalculateUnswitchCostMultiplier(
26082e3e224eSFedor Sergeev     Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
26092e3e224eSFedor Sergeev     ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
26102e3e224eSFedor Sergeev         UnswitchCandidates) {
26112e3e224eSFedor Sergeev 
26122e3e224eSFedor Sergeev   // Guards and other exiting conditions do not contribute to exponential
26132e3e224eSFedor Sergeev   // explosion as soon as they dominate the latch (otherwise there might be
26142e3e224eSFedor Sergeev   // another path to the latch remaining that does not allow to eliminate the
26152e3e224eSFedor Sergeev   // loop copy on unswitch).
26162e3e224eSFedor Sergeev   BasicBlock *Latch = L.getLoopLatch();
26172e3e224eSFedor Sergeev   BasicBlock *CondBlock = TI.getParent();
26182e3e224eSFedor Sergeev   if (DT.dominates(CondBlock, Latch) &&
26192e3e224eSFedor Sergeev       (isGuard(&TI) ||
26202e3e224eSFedor Sergeev        llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
26212e3e224eSFedor Sergeev          return L.contains(SuccBB);
26222e3e224eSFedor Sergeev        }) <= 1)) {
26232e3e224eSFedor Sergeev     NumCostMultiplierSkipped++;
26242e3e224eSFedor Sergeev     return 1;
26252e3e224eSFedor Sergeev   }
26262e3e224eSFedor Sergeev 
26272e3e224eSFedor Sergeev   auto *ParentL = L.getParentLoop();
26282e3e224eSFedor Sergeev   int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
26292e3e224eSFedor Sergeev                                : std::distance(LI.begin(), LI.end()));
26302e3e224eSFedor Sergeev   // Count amount of clones that all the candidates might cause during
26312e3e224eSFedor Sergeev   // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
26322e3e224eSFedor Sergeev   int UnswitchedClones = 0;
26332e3e224eSFedor Sergeev   for (auto Candidate : UnswitchCandidates) {
26342e3e224eSFedor Sergeev     Instruction *CI = Candidate.first;
26352e3e224eSFedor Sergeev     BasicBlock *CondBlock = CI->getParent();
26362e3e224eSFedor Sergeev     bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
26372e3e224eSFedor Sergeev     if (isGuard(CI)) {
26382e3e224eSFedor Sergeev       if (!SkipExitingSuccessors)
26392e3e224eSFedor Sergeev         UnswitchedClones++;
26402e3e224eSFedor Sergeev       continue;
26412e3e224eSFedor Sergeev     }
26422e3e224eSFedor Sergeev     int NonExitingSuccessors = llvm::count_if(
26432e3e224eSFedor Sergeev         successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
26442e3e224eSFedor Sergeev           return !SkipExitingSuccessors || L.contains(SuccBB);
26452e3e224eSFedor Sergeev         });
26462e3e224eSFedor Sergeev     UnswitchedClones += Log2_32(NonExitingSuccessors);
26472e3e224eSFedor Sergeev   }
26482e3e224eSFedor Sergeev 
26492e3e224eSFedor Sergeev   // Ignore up to the "unscaled candidates" number of unswitch candidates
26502e3e224eSFedor Sergeev   // when calculating the power-of-two scaling of the cost. The main idea
26512e3e224eSFedor Sergeev   // with this control is to allow a small number of unswitches to happen
26522e3e224eSFedor Sergeev   // and rely more on siblings multiplier (see below) when the number
26532e3e224eSFedor Sergeev   // of candidates is small.
26542e3e224eSFedor Sergeev   unsigned ClonesPower =
26552e3e224eSFedor Sergeev       std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
26562e3e224eSFedor Sergeev 
26572e3e224eSFedor Sergeev   // Allowing top-level loops to spread a bit more than nested ones.
26582e3e224eSFedor Sergeev   int SiblingsMultiplier =
26592e3e224eSFedor Sergeev       std::max((ParentL ? SiblingsCount
26602e3e224eSFedor Sergeev                         : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
26612e3e224eSFedor Sergeev                1);
26622e3e224eSFedor Sergeev   // Compute the cost multiplier in a way that won't overflow by saturating
26632e3e224eSFedor Sergeev   // at an upper bound.
26642e3e224eSFedor Sergeev   int CostMultiplier;
26652e3e224eSFedor Sergeev   if (ClonesPower > Log2_32(UnswitchThreshold) ||
26662e3e224eSFedor Sergeev       SiblingsMultiplier > UnswitchThreshold)
26672e3e224eSFedor Sergeev     CostMultiplier = UnswitchThreshold;
26682e3e224eSFedor Sergeev   else
26692e3e224eSFedor Sergeev     CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
26702e3e224eSFedor Sergeev                               (int)UnswitchThreshold);
26712e3e224eSFedor Sergeev 
26722e3e224eSFedor Sergeev   LLVM_DEBUG(dbgs() << "  Computed multiplier  " << CostMultiplier
26732e3e224eSFedor Sergeev                     << " (siblings " << SiblingsMultiplier << " * clones "
26742e3e224eSFedor Sergeev                     << (1 << ClonesPower) << ")"
26752e3e224eSFedor Sergeev                     << " for unswitch candidate: " << TI << "\n");
26762e3e224eSFedor Sergeev   return CostMultiplier;
26772e3e224eSFedor Sergeev }
26782e3e224eSFedor Sergeev 
2679f3a27511SJingu Kang static bool unswitchBestCondition(
2680f3a27511SJingu Kang     Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
2681f3a27511SJingu Kang     AAResults &AA, TargetTransformInfo &TTI,
2682f3a27511SJingu Kang     function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
26830f0344ddSBjorn Pettersson     ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
26840f0344ddSBjorn Pettersson     function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
2685d1dab0c3SChandler Carruth   // Collect all invariant conditions within this loop (as opposed to an inner
2686d1dab0c3SChandler Carruth   // loop which would be handled when visiting that inner loop).
268760b2e054SChandler Carruth   SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
2688d1dab0c3SChandler Carruth       UnswitchCandidates;
2689619a8346SMax Kazantsev 
2690619a8346SMax Kazantsev   // Whether or not we should also collect guards in the loop.
2691619a8346SMax Kazantsev   bool CollectGuards = false;
2692619a8346SMax Kazantsev   if (UnswitchGuards) {
2693619a8346SMax Kazantsev     auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2694619a8346SMax Kazantsev         Intrinsic::getName(Intrinsic::experimental_guard));
2695619a8346SMax Kazantsev     if (GuardDecl && !GuardDecl->use_empty())
2696619a8346SMax Kazantsev       CollectGuards = true;
2697619a8346SMax Kazantsev   }
2698619a8346SMax Kazantsev 
2699f3a27511SJingu Kang   IVConditionInfo PartialIVInfo;
2700d1dab0c3SChandler Carruth   for (auto *BB : L.blocks()) {
2701d1dab0c3SChandler Carruth     if (LI.getLoopFor(BB) != &L)
2702d1dab0c3SChandler Carruth       continue;
27031353f9a4SChandler Carruth 
2704619a8346SMax Kazantsev     if (CollectGuards)
2705619a8346SMax Kazantsev       for (auto &I : *BB)
2706619a8346SMax Kazantsev         if (isGuard(&I)) {
2707619a8346SMax Kazantsev           auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2708619a8346SMax Kazantsev           // TODO: Support AND, OR conditions and partial unswitching.
2709619a8346SMax Kazantsev           if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2710619a8346SMax Kazantsev             UnswitchCandidates.push_back({&I, {Cond}});
2711619a8346SMax Kazantsev         }
2712619a8346SMax Kazantsev 
27131652996fSChandler Carruth     if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
27141652996fSChandler Carruth       // We can only consider fully loop-invariant switch conditions as we need
27151652996fSChandler Carruth       // to completely eliminate the switch after unswitching.
27161652996fSChandler Carruth       if (!isa<Constant>(SI->getCondition()) &&
2717d000f8b6SSerguei Katkov           L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor())
27181652996fSChandler Carruth         UnswitchCandidates.push_back({SI, {SI->getCondition()}});
27191652996fSChandler Carruth       continue;
27201652996fSChandler Carruth     }
27211652996fSChandler Carruth 
2722d1dab0c3SChandler Carruth     auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2723d1dab0c3SChandler Carruth     if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2724d1dab0c3SChandler Carruth         BI->getSuccessor(0) == BI->getSuccessor(1))
2725d1dab0c3SChandler Carruth       continue;
27261353f9a4SChandler Carruth 
27276b4b1dc6SJuneyoung Lee     // If BI's condition is 'select _, true, false', simplify it to confuse
27286b4b1dc6SJuneyoung Lee     // matchers
27296b4b1dc6SJuneyoung Lee     Value *Cond = BI->getCondition(), *CondNext;
27306b4b1dc6SJuneyoung Lee     while (match(Cond, m_Select(m_Value(CondNext), m_One(), m_Zero())))
27316b4b1dc6SJuneyoung Lee       Cond = CondNext;
27326b4b1dc6SJuneyoung Lee     BI->setCondition(Cond);
27336b4b1dc6SJuneyoung Lee 
273445bd8d94SDaniil Suchkov     if (isa<Constant>(Cond))
273545bd8d94SDaniil Suchkov       continue;
273645bd8d94SDaniil Suchkov 
2737d1dab0c3SChandler Carruth     if (L.isLoopInvariant(BI->getCondition())) {
2738d1dab0c3SChandler Carruth       UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2739d1dab0c3SChandler Carruth       continue;
274071fd2704SChandler Carruth     }
27411353f9a4SChandler Carruth 
2742d1dab0c3SChandler Carruth     Instruction &CondI = *cast<Instruction>(BI->getCondition());
2743f3a27511SJingu Kang     if (match(&CondI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()))) {
2744d1dab0c3SChandler Carruth       TinyPtrVector<Value *> Invariants =
2745d1dab0c3SChandler Carruth           collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2746d1dab0c3SChandler Carruth       if (Invariants.empty())
2747d1dab0c3SChandler Carruth         continue;
2748d1dab0c3SChandler Carruth 
2749d1dab0c3SChandler Carruth       UnswitchCandidates.push_back({BI, std::move(Invariants)});
2750f3a27511SJingu Kang       continue;
2751f3a27511SJingu Kang     }
2752f3a27511SJingu Kang   }
2753f3a27511SJingu Kang 
2754f3a27511SJingu Kang   Instruction *PartialIVCondBranch = nullptr;
2755f3a27511SJingu Kang   if (MSSAU && !findOptionMDForLoop(&L, "llvm.loop.unswitch.partial.disable") &&
2756f3a27511SJingu Kang       !any_of(UnswitchCandidates, [&L](auto &TerminatorAndInvariants) {
2757f3a27511SJingu Kang         return TerminatorAndInvariants.first == L.getHeader()->getTerminator();
2758f3a27511SJingu Kang       })) {
2759f3a27511SJingu Kang     MemorySSA *MSSA = MSSAU->getMemorySSA();
2760f3a27511SJingu Kang     if (auto Info = hasPartialIVCondition(L, MSSAThreshold, *MSSA, AA)) {
2761f3a27511SJingu Kang       LLVM_DEBUG(
2762f3a27511SJingu Kang           dbgs() << "simple-loop-unswitch: Found partially invariant condition "
2763f3a27511SJingu Kang                  << *Info->InstToDuplicate[0] << "\n");
2764f3a27511SJingu Kang       PartialIVInfo = *Info;
2765f3a27511SJingu Kang       PartialIVCondBranch = L.getHeader()->getTerminator();
2766f3a27511SJingu Kang       TinyPtrVector<Value *> ValsToDuplicate;
2767f3a27511SJingu Kang       for (auto *Inst : Info->InstToDuplicate)
2768f3a27511SJingu Kang         ValsToDuplicate.push_back(Inst);
2769f3a27511SJingu Kang       UnswitchCandidates.push_back(
2770f3a27511SJingu Kang           {L.getHeader()->getTerminator(), std::move(ValsToDuplicate)});
2771f3a27511SJingu Kang     }
2772d1dab0c3SChandler Carruth   }
2773693eedb1SChandler Carruth 
2774693eedb1SChandler Carruth   // If we didn't find any candidates, we're done.
2775693eedb1SChandler Carruth   if (UnswitchCandidates.empty())
277671fd2704SChandler Carruth     return false;
2777693eedb1SChandler Carruth 
277832e62f9cSChandler Carruth   // Check if there are irreducible CFG cycles in this loop. If so, we cannot
277932e62f9cSChandler Carruth   // easily unswitch non-trivial edges out of the loop. Doing so might turn the
278032e62f9cSChandler Carruth   // irreducible control flow into reducible control flow and introduce new
278132e62f9cSChandler Carruth   // loops "out of thin air". If we ever discover important use cases for doing
278232e62f9cSChandler Carruth   // this, we can add support to loop unswitch, but it is a lot of complexity
2783f209649dSHiroshi Inoue   // for what seems little or no real world benefit.
278432e62f9cSChandler Carruth   LoopBlocksRPO RPOT(&L);
278532e62f9cSChandler Carruth   RPOT.perform(&LI);
278632e62f9cSChandler Carruth   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
278771fd2704SChandler Carruth     return false;
278832e62f9cSChandler Carruth 
2789bde31000SMax Kazantsev   SmallVector<BasicBlock *, 4> ExitBlocks;
2790bde31000SMax Kazantsev   L.getUniqueExitBlocks(ExitBlocks);
2791bde31000SMax Kazantsev 
27925366de73SArthur Eubanks   // We cannot unswitch if exit blocks contain a cleanuppad/catchswitch
27935366de73SArthur Eubanks   // instruction as we don't know how to split those exit blocks.
2794bde31000SMax Kazantsev   // FIXME: We should teach SplitBlock to handle this and remove this
2795bde31000SMax Kazantsev   // restriction.
279670af2924SArthur Eubanks   for (auto *ExitBB : ExitBlocks) {
27975366de73SArthur Eubanks     auto *I = ExitBB->getFirstNonPHI();
27985366de73SArthur Eubanks     if (isa<CleanupPadInst>(I) || isa<CatchSwitchInst>(I)) {
27995366de73SArthur Eubanks       LLVM_DEBUG(dbgs() << "Cannot unswitch because of cleanuppad/catchswitch "
28005366de73SArthur Eubanks                            "in exit block\n");
2801bde31000SMax Kazantsev       return false;
2802bde31000SMax Kazantsev     }
280370af2924SArthur Eubanks   }
2804bde31000SMax Kazantsev 
2805d34e60caSNicola Zaghen   LLVM_DEBUG(
2806d34e60caSNicola Zaghen       dbgs() << "Considering " << UnswitchCandidates.size()
2807693eedb1SChandler Carruth              << " non-trivial loop invariant conditions for unswitching.\n");
2808693eedb1SChandler Carruth 
2809693eedb1SChandler Carruth   // Given that unswitching these terminators will require duplicating parts of
2810693eedb1SChandler Carruth   // the loop, so we need to be able to model that cost. Compute the ephemeral
2811693eedb1SChandler Carruth   // values and set up a data structure to hold per-BB costs. We cache each
2812693eedb1SChandler Carruth   // block's cost so that we don't recompute this when considering different
2813693eedb1SChandler Carruth   // subsets of the loop for duplication during unswitching.
2814693eedb1SChandler Carruth   SmallPtrSet<const Value *, 4> EphValues;
2815693eedb1SChandler Carruth   CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
281600da3227SSander de Smalen   SmallDenseMap<BasicBlock *, InstructionCost, 4> BBCostMap;
2817693eedb1SChandler Carruth 
2818693eedb1SChandler Carruth   // Compute the cost of each block, as well as the total loop cost. Also, bail
2819693eedb1SChandler Carruth   // out if we see instructions which are incompatible with loop unswitching
2820693eedb1SChandler Carruth   // (convergent, noduplicate, or cross-basic-block tokens).
2821693eedb1SChandler Carruth   // FIXME: We might be able to safely handle some of these in non-duplicated
2822693eedb1SChandler Carruth   // regions.
2823725400f9SSam Parker   TargetTransformInfo::TargetCostKind CostKind =
2824725400f9SSam Parker       L.getHeader()->getParent()->hasMinSize()
2825725400f9SSam Parker       ? TargetTransformInfo::TCK_CodeSize
2826725400f9SSam Parker       : TargetTransformInfo::TCK_SizeAndLatency;
282700da3227SSander de Smalen   InstructionCost LoopCost = 0;
2828693eedb1SChandler Carruth   for (auto *BB : L.blocks()) {
282900da3227SSander de Smalen     InstructionCost Cost = 0;
2830693eedb1SChandler Carruth     for (auto &I : *BB) {
2831693eedb1SChandler Carruth       if (EphValues.count(&I))
2832693eedb1SChandler Carruth         continue;
2833693eedb1SChandler Carruth 
2834693eedb1SChandler Carruth       if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
283571fd2704SChandler Carruth         return false;
2836592d8e7dSCraig Topper       if (auto *CB = dyn_cast<CallBase>(&I))
2837592d8e7dSCraig Topper         if (CB->isConvergent() || CB->cannotDuplicate())
283871fd2704SChandler Carruth           return false;
2839693eedb1SChandler Carruth 
2840725400f9SSam Parker       Cost += TTI.getUserCost(&I, CostKind);
2841693eedb1SChandler Carruth     }
2842693eedb1SChandler Carruth     assert(Cost >= 0 && "Must not have negative costs!");
2843693eedb1SChandler Carruth     LoopCost += Cost;
2844693eedb1SChandler Carruth     assert(LoopCost >= 0 && "Must not have negative loop costs!");
2845693eedb1SChandler Carruth     BBCostMap[BB] = Cost;
2846693eedb1SChandler Carruth   }
2847d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Total loop cost: " << LoopCost << "\n");
2848693eedb1SChandler Carruth 
2849693eedb1SChandler Carruth   // Now we find the best candidate by searching for the one with the following
2850693eedb1SChandler Carruth   // properties in order:
2851693eedb1SChandler Carruth   //
2852693eedb1SChandler Carruth   // 1) An unswitching cost below the threshold
2853693eedb1SChandler Carruth   // 2) The smallest number of duplicated unswitch candidates (to avoid
2854693eedb1SChandler Carruth   //    creating redundant subsequent unswitching)
2855693eedb1SChandler Carruth   // 3) The smallest cost after unswitching.
2856693eedb1SChandler Carruth   //
2857693eedb1SChandler Carruth   // We prioritize reducing fanout of unswitch candidates provided the cost
2858693eedb1SChandler Carruth   // remains below the threshold because this has a multiplicative effect.
2859693eedb1SChandler Carruth   //
2860693eedb1SChandler Carruth   // This requires memoizing each dominator subtree to avoid redundant work.
2861693eedb1SChandler Carruth   //
2862693eedb1SChandler Carruth   // FIXME: Need to actually do the number of candidates part above.
286300da3227SSander de Smalen   SmallDenseMap<DomTreeNode *, InstructionCost, 4> DTCostMap;
2864693eedb1SChandler Carruth   // Given a terminator which might be unswitched, computes the non-duplicated
2865693eedb1SChandler Carruth   // cost for that terminator.
286600da3227SSander de Smalen   auto ComputeUnswitchedCost = [&](Instruction &TI,
286700da3227SSander de Smalen                                    bool FullUnswitch) -> InstructionCost {
2868d1dab0c3SChandler Carruth     BasicBlock &BB = *TI.getParent();
2869693eedb1SChandler Carruth     SmallPtrSet<BasicBlock *, 4> Visited;
2870693eedb1SChandler Carruth 
287100da3227SSander de Smalen     InstructionCost Cost = 0;
2872693eedb1SChandler Carruth     for (BasicBlock *SuccBB : successors(&BB)) {
2873693eedb1SChandler Carruth       // Don't count successors more than once.
2874693eedb1SChandler Carruth       if (!Visited.insert(SuccBB).second)
2875693eedb1SChandler Carruth         continue;
2876693eedb1SChandler Carruth 
2877d1dab0c3SChandler Carruth       // If this is a partial unswitch candidate, then it must be a conditional
2878f3a27511SJingu Kang       // branch with a condition of either `or`, `and`, their corresponding
2879f3a27511SJingu Kang       // select forms or partially invariant instructions. In that case, one of
2880f3a27511SJingu Kang       // the successors is necessarily duplicated, so don't even try to remove
2881f3a27511SJingu Kang       // its cost.
2882d1dab0c3SChandler Carruth       if (!FullUnswitch) {
2883d1dab0c3SChandler Carruth         auto &BI = cast<BranchInst>(TI);
28845bb38e84SJuneyoung Lee         if (match(BI.getCondition(), m_LogicalAnd())) {
2885d1dab0c3SChandler Carruth           if (SuccBB == BI.getSuccessor(1))
2886d1dab0c3SChandler Carruth             continue;
2887f3a27511SJingu Kang         } else if (match(BI.getCondition(), m_LogicalOr())) {
2888d1dab0c3SChandler Carruth           if (SuccBB == BI.getSuccessor(0))
2889d1dab0c3SChandler Carruth             continue;
2890873ff5a7SJingu Kang         } else if ((PartialIVInfo.KnownValue->isOneValue() &&
2891873ff5a7SJingu Kang                     SuccBB == BI.getSuccessor(0)) ||
2892873ff5a7SJingu Kang                    (!PartialIVInfo.KnownValue->isOneValue() &&
2893873ff5a7SJingu Kang                     SuccBB == BI.getSuccessor(1)))
2894f3a27511SJingu Kang           continue;
2895d1dab0c3SChandler Carruth       }
2896d1dab0c3SChandler Carruth 
2897693eedb1SChandler Carruth       // This successor's domtree will not need to be duplicated after
2898693eedb1SChandler Carruth       // unswitching if the edge to the successor dominates it (and thus the
2899693eedb1SChandler Carruth       // entire tree). This essentially means there is no other path into this
2900693eedb1SChandler Carruth       // subtree and so it will end up live in only one clone of the loop.
2901693eedb1SChandler Carruth       if (SuccBB->getUniquePredecessor() ||
2902693eedb1SChandler Carruth           llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2903693eedb1SChandler Carruth             return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2904693eedb1SChandler Carruth           })) {
290500da3227SSander de Smalen         Cost += computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
290600da3227SSander de Smalen         assert(Cost <= LoopCost &&
2907693eedb1SChandler Carruth                "Non-duplicated cost should never exceed total loop cost!");
2908693eedb1SChandler Carruth       }
2909693eedb1SChandler Carruth     }
2910693eedb1SChandler Carruth 
2911693eedb1SChandler Carruth     // Now scale the cost by the number of unique successors minus one. We
2912693eedb1SChandler Carruth     // subtract one because there is already at least one copy of the entire
2913693eedb1SChandler Carruth     // loop. This is computing the new cost of unswitching a condition.
2914619a8346SMax Kazantsev     // Note that guards always have 2 unique successors that are implicit and
2915619a8346SMax Kazantsev     // will be materialized if we decide to unswitch it.
2916619a8346SMax Kazantsev     int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2917619a8346SMax Kazantsev     assert(SuccessorsCount > 1 &&
2918693eedb1SChandler Carruth            "Cannot unswitch a condition without multiple distinct successors!");
291900da3227SSander de Smalen     return (LoopCost - Cost) * (SuccessorsCount - 1);
2920693eedb1SChandler Carruth   };
292160b2e054SChandler Carruth   Instruction *BestUnswitchTI = nullptr;
292200da3227SSander de Smalen   InstructionCost BestUnswitchCost = 0;
2923d1dab0c3SChandler Carruth   ArrayRef<Value *> BestUnswitchInvariants;
2924d1dab0c3SChandler Carruth   for (auto &TerminatorAndInvariants : UnswitchCandidates) {
292560b2e054SChandler Carruth     Instruction &TI = *TerminatorAndInvariants.first;
2926d1dab0c3SChandler Carruth     ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2927d1dab0c3SChandler Carruth     BranchInst *BI = dyn_cast<BranchInst>(&TI);
292800da3227SSander de Smalen     InstructionCost CandidateCost = ComputeUnswitchedCost(
29291652996fSChandler Carruth         TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
29301652996fSChandler Carruth                                      Invariants[0] == BI->getCondition()));
29312e3e224eSFedor Sergeev     // Calculate cost multiplier which is a tool to limit potentially
29322e3e224eSFedor Sergeev     // exponential behavior of loop-unswitch.
29332e3e224eSFedor Sergeev     if (EnableUnswitchCostMultiplier) {
29342e3e224eSFedor Sergeev       int CostMultiplier =
29351c03cc5aSAlina Sbirlea           CalculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
29362e3e224eSFedor Sergeev       assert(
29372e3e224eSFedor Sergeev           (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
29382e3e224eSFedor Sergeev           "cost multiplier needs to be in the range of 1..UnswitchThreshold");
29392e3e224eSFedor Sergeev       CandidateCost *= CostMultiplier;
29402e3e224eSFedor Sergeev       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
29412e3e224eSFedor Sergeev                         << " (multiplier: " << CostMultiplier << ")"
29422e3e224eSFedor Sergeev                         << " for unswitch candidate: " << TI << "\n");
29432e3e224eSFedor Sergeev     } else {
2944d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
2945d1dab0c3SChandler Carruth                         << " for unswitch candidate: " << TI << "\n");
29462e3e224eSFedor Sergeev     }
29472e3e224eSFedor Sergeev 
2948693eedb1SChandler Carruth     if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2949d1dab0c3SChandler Carruth       BestUnswitchTI = &TI;
2950693eedb1SChandler Carruth       BestUnswitchCost = CandidateCost;
2951d1dab0c3SChandler Carruth       BestUnswitchInvariants = Invariants;
2952693eedb1SChandler Carruth     }
2953693eedb1SChandler Carruth   }
2954c598ef7fSSimon Pilgrim   assert(BestUnswitchTI && "Failed to find loop unswitch candidate");
2955693eedb1SChandler Carruth 
295671fd2704SChandler Carruth   if (BestUnswitchCost >= UnswitchThreshold) {
295771fd2704SChandler Carruth     LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
295871fd2704SChandler Carruth                       << BestUnswitchCost << "\n");
295971fd2704SChandler Carruth     return false;
296071fd2704SChandler Carruth   }
296171fd2704SChandler Carruth 
2962f3a27511SJingu Kang   if (BestUnswitchTI != PartialIVCondBranch)
2963f3a27511SJingu Kang     PartialIVInfo.InstToDuplicate.clear();
2964f3a27511SJingu Kang 
2965619a8346SMax Kazantsev   // If the best candidate is a guard, turn it into a branch.
2966619a8346SMax Kazantsev   if (isGuard(BestUnswitchTI))
2967619a8346SMax Kazantsev     BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
2968a2eebb82SAlina Sbirlea                                          ExitBlocks, DT, LI, MSSAU);
2969619a8346SMax Kazantsev 
2970bde31000SMax Kazantsev   LLVM_DEBUG(dbgs() << "  Unswitching non-trivial (cost = "
29711652996fSChandler Carruth                     << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
29721652996fSChandler Carruth                     << "\n");
2973bde31000SMax Kazantsev   unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
2974f3a27511SJingu Kang                                ExitBlocks, PartialIVInfo, DT, LI, AC,
29750f0344ddSBjorn Pettersson                                UnswitchCB, SE, MSSAU, DestroyLoopCB);
2976bde31000SMax Kazantsev   return true;
29771353f9a4SChandler Carruth }
29781353f9a4SChandler Carruth 
2979d1dab0c3SChandler Carruth /// Unswitch control flow predicated on loop invariant conditions.
2980d1dab0c3SChandler Carruth ///
2981d1dab0c3SChandler Carruth /// This first hoists all branches or switches which are trivial (IE, do not
2982d1dab0c3SChandler Carruth /// require duplicating any part of the loop) out of the loop body. It then
2983d1dab0c3SChandler Carruth /// looks at other loop invariant control flows and tries to unswitch those as
2984d1dab0c3SChandler Carruth /// well by cloning the loop if the result is small enough.
29853897ded6SChandler Carruth ///
2986f3a27511SJingu Kang /// The `DT`, `LI`, `AC`, `AA`, `TTI` parameters are required analyses that are
2987f3a27511SJingu Kang /// also updated based on the unswitch. The `MSSA` analysis is also updated if
2988f3a27511SJingu Kang /// valid (i.e. its use is enabled).
29893897ded6SChandler Carruth ///
29903897ded6SChandler Carruth /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
29913897ded6SChandler Carruth /// true, we will attempt to do non-trivial unswitching as well as trivial
29923897ded6SChandler Carruth /// unswitching.
29933897ded6SChandler Carruth ///
29943897ded6SChandler Carruth /// The `UnswitchCB` callback provided will be run after unswitching is
29953897ded6SChandler Carruth /// complete, with the first parameter set to `true` if the provided loop
29963897ded6SChandler Carruth /// remains a loop, and a list of new sibling loops created.
29973897ded6SChandler Carruth ///
29983897ded6SChandler Carruth /// If `SE` is non-null, we will update that analysis based on the unswitching
29993897ded6SChandler Carruth /// done.
3000f3a27511SJingu Kang static bool
3001f3a27511SJingu Kang unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
30020024ec59SArthur Eubanks              AAResults &AA, TargetTransformInfo &TTI, bool Trivial,
30030024ec59SArthur Eubanks              bool NonTrivial,
3004f3a27511SJingu Kang              function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
30050f0344ddSBjorn Pettersson              ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
30060f0344ddSBjorn Pettersson              function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
3007d1dab0c3SChandler Carruth   assert(L.isRecursivelyLCSSAForm(DT, LI) &&
3008d1dab0c3SChandler Carruth          "Loops must be in LCSSA form before unswitching.");
3009d1dab0c3SChandler Carruth 
3010d1dab0c3SChandler Carruth   // Must be in loop simplified form: we need a preheader and dedicated exits.
3011d1dab0c3SChandler Carruth   if (!L.isLoopSimplifyForm())
3012d1dab0c3SChandler Carruth     return false;
3013d1dab0c3SChandler Carruth 
3014d1dab0c3SChandler Carruth   // Try trivial unswitch first before loop over other basic blocks in the loop.
30150024ec59SArthur Eubanks   if (Trivial && unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
3016d1dab0c3SChandler Carruth     // If we unswitched successfully we will want to clean up the loop before
3017d1dab0c3SChandler Carruth     // processing it further so just mark it as unswitched and return.
3018f3a27511SJingu Kang     UnswitchCB(/*CurrentLoopValid*/ true, false, {});
3019d1dab0c3SChandler Carruth     return true;
3020d1dab0c3SChandler Carruth   }
3021d1dab0c3SChandler Carruth 
3022b92c8c22SSameer Sahasrabuddhe   // Check whether we should continue with non-trivial conditions.
3023b92c8c22SSameer Sahasrabuddhe   // EnableNonTrivialUnswitch: Global variable that forces non-trivial
3024b92c8c22SSameer Sahasrabuddhe   //                           unswitching for testing and debugging.
3025b92c8c22SSameer Sahasrabuddhe   // NonTrivial: Parameter that enables non-trivial unswitching for this
3026b92c8c22SSameer Sahasrabuddhe   //             invocation of the transform. But this should be allowed only
3027b92c8c22SSameer Sahasrabuddhe   //             for targets without branch divergence.
3028b92c8c22SSameer Sahasrabuddhe   //
3029b92c8c22SSameer Sahasrabuddhe   // FIXME: If divergence analysis becomes available to a loop
3030b92c8c22SSameer Sahasrabuddhe   // transform, we should allow unswitching for non-trivial uniform
3031b92c8c22SSameer Sahasrabuddhe   // branches even on targets that have divergence.
3032b92c8c22SSameer Sahasrabuddhe   // https://bugs.llvm.org/show_bug.cgi?id=48819
3033b92c8c22SSameer Sahasrabuddhe   bool ContinueWithNonTrivial =
3034b92c8c22SSameer Sahasrabuddhe       EnableNonTrivialUnswitch || (NonTrivial && !TTI.hasBranchDivergence());
3035b92c8c22SSameer Sahasrabuddhe   if (!ContinueWithNonTrivial)
3036d1dab0c3SChandler Carruth     return false;
3037d1dab0c3SChandler Carruth 
303839e6d242SArthur Eubanks   // Skip non-trivial unswitching for optsize functions.
303939e6d242SArthur Eubanks   if (L.getHeader()->getParent()->hasOptSize())
304039e6d242SArthur Eubanks     return false;
304139e6d242SArthur Eubanks 
30420eda4547SArthur Eubanks   // Skip non-trivial unswitching for loops that cannot be cloned.
30430eda4547SArthur Eubanks   if (!L.isSafeToClone())
30440eda4547SArthur Eubanks     return false;
30450eda4547SArthur Eubanks 
3046d1dab0c3SChandler Carruth   // For non-trivial unswitching, because it often creates new loops, we rely on
3047d1dab0c3SChandler Carruth   // the pass manager to iterate on the loops rather than trying to immediately
3048d1dab0c3SChandler Carruth   // reach a fixed point. There is no substantial advantage to iterating
3049d1dab0c3SChandler Carruth   // internally, and if any of the new loops are simplified enough to contain
3050d1dab0c3SChandler Carruth   // trivial unswitching we want to prefer those.
3051d1dab0c3SChandler Carruth 
3052d1dab0c3SChandler Carruth   // Try to unswitch the best invariant condition. We prefer this full unswitch to
3053d1dab0c3SChandler Carruth   // a partial unswitch when possible below the threshold.
30540f0344ddSBjorn Pettersson   if (unswitchBestCondition(L, DT, LI, AC, AA, TTI, UnswitchCB, SE, MSSAU,
30550f0344ddSBjorn Pettersson                             DestroyLoopCB))
3056d1dab0c3SChandler Carruth     return true;
3057d1dab0c3SChandler Carruth 
3058d1dab0c3SChandler Carruth   // No other opportunities to unswitch.
30593678ad88SMax Kazantsev   return false;
3060d1dab0c3SChandler Carruth }
3061d1dab0c3SChandler Carruth 
30621353f9a4SChandler Carruth PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
30631353f9a4SChandler Carruth                                               LoopStandardAnalysisResults &AR,
30641353f9a4SChandler Carruth                                               LPMUpdater &U) {
30651353f9a4SChandler Carruth   Function &F = *L.getHeader()->getParent();
30661353f9a4SChandler Carruth   (void)F;
30671353f9a4SChandler Carruth 
3068d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
3069d34e60caSNicola Zaghen                     << "\n");
30701353f9a4SChandler Carruth 
3071693eedb1SChandler Carruth   // Save the current loop name in a variable so that we can report it even
3072693eedb1SChandler Carruth   // after it has been deleted.
3073adcd0268SBenjamin Kramer   std::string LoopName = std::string(L.getName());
3074693eedb1SChandler Carruth 
307571fd2704SChandler Carruth   auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
3076f3a27511SJingu Kang                                         bool PartiallyInvariant,
3077693eedb1SChandler Carruth                                         ArrayRef<Loop *> NewLoops) {
3078693eedb1SChandler Carruth     // If we did a non-trivial unswitch, we have added new (cloned) loops.
307971fd2704SChandler Carruth     if (!NewLoops.empty())
3080693eedb1SChandler Carruth       U.addSiblingLoops(NewLoops);
3081693eedb1SChandler Carruth 
3082693eedb1SChandler Carruth     // If the current loop remains valid, we should revisit it to catch any
3083693eedb1SChandler Carruth     // other unswitch opportunities. Otherwise, we need to mark it as deleted.
3084f3a27511SJingu Kang     if (CurrentLoopValid) {
3085f3a27511SJingu Kang       if (PartiallyInvariant) {
3086f3a27511SJingu Kang         // Mark the new loop as partially unswitched, to avoid unswitching on
3087f3a27511SJingu Kang         // the same condition again.
3088f3a27511SJingu Kang         auto &Context = L.getHeader()->getContext();
3089f3a27511SJingu Kang         MDNode *DisableUnswitchMD = MDNode::get(
3090f3a27511SJingu Kang             Context,
3091f3a27511SJingu Kang             MDString::get(Context, "llvm.loop.unswitch.partial.disable"));
3092f3a27511SJingu Kang         MDNode *NewLoopID = makePostTransformationMetadata(
3093f3a27511SJingu Kang             Context, L.getLoopID(), {"llvm.loop.unswitch.partial"},
3094f3a27511SJingu Kang             {DisableUnswitchMD});
3095f3a27511SJingu Kang         L.setLoopID(NewLoopID);
3096f3a27511SJingu Kang       } else
3097693eedb1SChandler Carruth         U.revisitCurrentLoop();
3098f3a27511SJingu Kang     } else
3099693eedb1SChandler Carruth       U.markLoopAsDeleted(L, LoopName);
3100693eedb1SChandler Carruth   };
3101693eedb1SChandler Carruth 
31020f0344ddSBjorn Pettersson   auto DestroyLoopCB = [&U](Loop &L, StringRef Name) {
31030f0344ddSBjorn Pettersson     U.markLoopAsDeleted(L, Name);
31040f0344ddSBjorn Pettersson   };
31050f0344ddSBjorn Pettersson 
3106a2eebb82SAlina Sbirlea   Optional<MemorySSAUpdater> MSSAU;
3107a2eebb82SAlina Sbirlea   if (AR.MSSA) {
3108a2eebb82SAlina Sbirlea     MSSAU = MemorySSAUpdater(AR.MSSA);
3109a2eebb82SAlina Sbirlea     if (VerifyMemorySSA)
3110a2eebb82SAlina Sbirlea       AR.MSSA->verifyMemorySSA();
3111a2eebb82SAlina Sbirlea   }
31120024ec59SArthur Eubanks   if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.AA, AR.TTI, Trivial, NonTrivial,
3113f3a27511SJingu Kang                     UnswitchCB, &AR.SE,
31140f0344ddSBjorn Pettersson                     MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
31150f0344ddSBjorn Pettersson                     DestroyLoopCB))
31161353f9a4SChandler Carruth     return PreservedAnalyses::all();
31171353f9a4SChandler Carruth 
3118a2eebb82SAlina Sbirlea   if (AR.MSSA && VerifyMemorySSA)
3119a2eebb82SAlina Sbirlea     AR.MSSA->verifyMemorySSA();
3120a2eebb82SAlina Sbirlea 
31211353f9a4SChandler Carruth   // Historically this pass has had issues with the dominator tree so verify it
31221353f9a4SChandler Carruth   // in asserts builds.
31237c35de12SDavid Green   assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
31243cef1f7dSAlina Sbirlea 
31253cef1f7dSAlina Sbirlea   auto PA = getLoopPassPreservedAnalyses();
3126f92109dcSAlina Sbirlea   if (AR.MSSA)
31273cef1f7dSAlina Sbirlea     PA.preserve<MemorySSAAnalysis>();
31283cef1f7dSAlina Sbirlea   return PA;
31291353f9a4SChandler Carruth }
31301353f9a4SChandler Carruth 
31311ac209edSMarkus Lavin void SimpleLoopUnswitchPass::printPipeline(
31321ac209edSMarkus Lavin     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
31331ac209edSMarkus Lavin   static_cast<PassInfoMixin<SimpleLoopUnswitchPass> *>(this)->printPipeline(
31341ac209edSMarkus Lavin       OS, MapClassName2PassName);
31351ac209edSMarkus Lavin 
31361ac209edSMarkus Lavin   OS << "<";
31371ac209edSMarkus Lavin   OS << (NonTrivial ? "" : "no-") << "nontrivial;";
31381ac209edSMarkus Lavin   OS << (Trivial ? "" : "no-") << "trivial";
31391ac209edSMarkus Lavin   OS << ">";
31401ac209edSMarkus Lavin }
31411ac209edSMarkus Lavin 
31421353f9a4SChandler Carruth namespace {
3143a369a457SEugene Zelenko 
31441353f9a4SChandler Carruth class SimpleLoopUnswitchLegacyPass : public LoopPass {
3145693eedb1SChandler Carruth   bool NonTrivial;
3146693eedb1SChandler Carruth 
31471353f9a4SChandler Carruth public:
31481353f9a4SChandler Carruth   static char ID; // Pass ID, replacement for typeid
3149a369a457SEugene Zelenko 
3150693eedb1SChandler Carruth   explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
3151693eedb1SChandler Carruth       : LoopPass(ID), NonTrivial(NonTrivial) {
31521353f9a4SChandler Carruth     initializeSimpleLoopUnswitchLegacyPassPass(
31531353f9a4SChandler Carruth         *PassRegistry::getPassRegistry());
31541353f9a4SChandler Carruth   }
31551353f9a4SChandler Carruth 
31561353f9a4SChandler Carruth   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
31571353f9a4SChandler Carruth 
31581353f9a4SChandler Carruth   void getAnalysisUsage(AnalysisUsage &AU) const override {
31591353f9a4SChandler Carruth     AU.addRequired<AssumptionCacheTracker>();
3160693eedb1SChandler Carruth     AU.addRequired<TargetTransformInfoWrapperPass>();
3161a2eebb82SAlina Sbirlea     AU.addRequired<MemorySSAWrapperPass>();
3162a2eebb82SAlina Sbirlea     AU.addPreserved<MemorySSAWrapperPass>();
31631353f9a4SChandler Carruth     getLoopAnalysisUsage(AU);
31641353f9a4SChandler Carruth   }
31651353f9a4SChandler Carruth };
3166a369a457SEugene Zelenko 
3167a369a457SEugene Zelenko } // end anonymous namespace
31681353f9a4SChandler Carruth 
31691353f9a4SChandler Carruth bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
31701353f9a4SChandler Carruth   if (skipLoop(L))
31711353f9a4SChandler Carruth     return false;
31721353f9a4SChandler Carruth 
31731353f9a4SChandler Carruth   Function &F = *L->getHeader()->getParent();
31741353f9a4SChandler Carruth 
3175d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
3176d34e60caSNicola Zaghen                     << "\n");
31771353f9a4SChandler Carruth 
31781353f9a4SChandler Carruth   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
31791353f9a4SChandler Carruth   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
31801353f9a4SChandler Carruth   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3181f3a27511SJingu Kang   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
3182693eedb1SChandler Carruth   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3183735a5904SNikita Popov   MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
3184735a5904SNikita Popov   MemorySSAUpdater MSSAU(MSSA);
31851353f9a4SChandler Carruth 
31863897ded6SChandler Carruth   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
31873897ded6SChandler Carruth   auto *SE = SEWP ? &SEWP->getSE() : nullptr;
31883897ded6SChandler Carruth 
3189f3a27511SJingu Kang   auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid, bool PartiallyInvariant,
3190693eedb1SChandler Carruth                                ArrayRef<Loop *> NewLoops) {
3191693eedb1SChandler Carruth     // If we did a non-trivial unswitch, we have added new (cloned) loops.
3192693eedb1SChandler Carruth     for (auto *NewL : NewLoops)
3193693eedb1SChandler Carruth       LPM.addLoop(*NewL);
3194693eedb1SChandler Carruth 
3195693eedb1SChandler Carruth     // If the current loop remains valid, re-add it to the queue. This is
3196693eedb1SChandler Carruth     // a little wasteful as we'll finish processing the current loop as well,
3197693eedb1SChandler Carruth     // but it is the best we can do in the old PM.
3198f3a27511SJingu Kang     if (CurrentLoopValid) {
3199f3a27511SJingu Kang       // If the current loop has been unswitched using a partially invariant
3200f3a27511SJingu Kang       // condition, we should not re-add the current loop to avoid unswitching
3201f3a27511SJingu Kang       // on the same condition again.
3202f3a27511SJingu Kang       if (!PartiallyInvariant)
3203693eedb1SChandler Carruth         LPM.addLoop(*L);
3204f3a27511SJingu Kang     } else
3205693eedb1SChandler Carruth       LPM.markLoopAsDeleted(*L);
3206693eedb1SChandler Carruth   };
3207693eedb1SChandler Carruth 
32080f0344ddSBjorn Pettersson   auto DestroyLoopCB = [&LPM](Loop &L, StringRef /* Name */) {
32090f0344ddSBjorn Pettersson     LPM.markLoopAsDeleted(L);
32100f0344ddSBjorn Pettersson   };
32110f0344ddSBjorn Pettersson 
3212735a5904SNikita Popov   if (VerifyMemorySSA)
3213a2eebb82SAlina Sbirlea     MSSA->verifyMemorySSA();
3214a2eebb82SAlina Sbirlea 
3215735a5904SNikita Popov   bool Changed = unswitchLoop(*L, DT, LI, AC, AA, TTI, true, NonTrivial,
32160f0344ddSBjorn Pettersson                               UnswitchCB, SE, &MSSAU, DestroyLoopCB);
3217a2eebb82SAlina Sbirlea 
3218735a5904SNikita Popov   if (VerifyMemorySSA)
3219a2eebb82SAlina Sbirlea     MSSA->verifyMemorySSA();
3220693eedb1SChandler Carruth 
32211353f9a4SChandler Carruth   // Historically this pass has had issues with the dominator tree so verify it
32221353f9a4SChandler Carruth   // in asserts builds.
32237c35de12SDavid Green   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
32247c35de12SDavid Green 
32251353f9a4SChandler Carruth   return Changed;
32261353f9a4SChandler Carruth }
32271353f9a4SChandler Carruth 
32281353f9a4SChandler Carruth char SimpleLoopUnswitchLegacyPass::ID = 0;
32291353f9a4SChandler Carruth INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
32301353f9a4SChandler Carruth                       "Simple unswitch loops", false, false)
32311353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3232693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3233693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
32341353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopPass)
3235a2eebb82SAlina Sbirlea INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
32361353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
32371353f9a4SChandler Carruth INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
32381353f9a4SChandler Carruth                     "Simple unswitch loops", false, false)
32391353f9a4SChandler Carruth 
3240693eedb1SChandler Carruth Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
3241693eedb1SChandler Carruth   return new SimpleLoopUnswitchLegacyPass(NonTrivial);
32421353f9a4SChandler Carruth }
3243