10b57cec5SDimitry Andric ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
100b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
110b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
120b57cec5SDimitry Andric #include "llvm/ADT/Sequence.h"
130b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
140b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
150b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
160b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
170b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/CodeMetrics.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/GuardUtils.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/LoopAnalysisManager.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/LoopPass.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
280b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
29af732203SDimitry Andric #include "llvm/Analysis/MustExecute.h"
30af732203SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
310b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
320b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
330b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
340b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
350b57cec5SDimitry Andric #include "llvm/IR/Function.h"
36af732203SDimitry Andric #include "llvm/IR/IRBuilder.h"
370b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
380b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
390b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
400b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
415f7ddb14SDimitry Andric #include "llvm/IR/PatternMatch.h"
420b57cec5SDimitry Andric #include "llvm/IR/Use.h"
430b57cec5SDimitry Andric #include "llvm/IR/Value.h"
44480093f4SDimitry Andric #include "llvm/InitializePasses.h"
450b57cec5SDimitry Andric #include "llvm/Pass.h"
460b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
47480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
480b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
490b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
500b57cec5SDimitry Andric #include "llvm/Support/GenericDomTree.h"
510b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
520b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
530b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
540b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
55af732203SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
560b57cec5SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
570b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
580b57cec5SDimitry Andric #include <algorithm>
590b57cec5SDimitry Andric #include <cassert>
600b57cec5SDimitry Andric #include <iterator>
610b57cec5SDimitry Andric #include <numeric>
620b57cec5SDimitry Andric #include <utility>
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric #define DEBUG_TYPE "simple-loop-unswitch"
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric using namespace llvm;
675f7ddb14SDimitry Andric using namespace llvm::PatternMatch;
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric STATISTIC(NumBranches, "Number of branches unswitched");
700b57cec5SDimitry Andric STATISTIC(NumSwitches, "Number of switches unswitched");
710b57cec5SDimitry Andric STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
720b57cec5SDimitry Andric STATISTIC(NumTrivial, "Number of unswitches that are trivial");
730b57cec5SDimitry Andric STATISTIC(
740b57cec5SDimitry Andric     NumCostMultiplierSkipped,
750b57cec5SDimitry Andric     "Number of unswitch candidates that had their cost multiplier skipped");
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric static cl::opt<bool> EnableNonTrivialUnswitch(
780b57cec5SDimitry Andric     "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
790b57cec5SDimitry Andric     cl::desc("Forcibly enables non-trivial loop unswitching rather than "
800b57cec5SDimitry Andric              "following the configuration passed into the pass."));
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric static cl::opt<int>
830b57cec5SDimitry Andric     UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
840b57cec5SDimitry Andric                       cl::desc("The cost threshold for unswitching a loop."));
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric static cl::opt<bool> EnableUnswitchCostMultiplier(
870b57cec5SDimitry Andric     "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
880b57cec5SDimitry Andric     cl::desc("Enable unswitch cost multiplier that prohibits exponential "
890b57cec5SDimitry Andric              "explosion in nontrivial unswitch."));
900b57cec5SDimitry Andric static cl::opt<int> UnswitchSiblingsToplevelDiv(
910b57cec5SDimitry Andric     "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
920b57cec5SDimitry Andric     cl::desc("Toplevel siblings divisor for cost multiplier."));
930b57cec5SDimitry Andric static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
940b57cec5SDimitry Andric     "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
950b57cec5SDimitry Andric     cl::desc("Number of unswitch candidates that are ignored when calculating "
960b57cec5SDimitry Andric              "cost multiplier."));
970b57cec5SDimitry Andric static cl::opt<bool> UnswitchGuards(
980b57cec5SDimitry Andric     "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
990b57cec5SDimitry Andric     cl::desc("If enabled, simple loop unswitching will also consider "
1000b57cec5SDimitry Andric              "llvm.experimental.guard intrinsics as unswitch candidates."));
101af732203SDimitry Andric static cl::opt<bool> DropNonTrivialImplicitNullChecks(
102af732203SDimitry Andric     "simple-loop-unswitch-drop-non-trivial-implicit-null-checks",
103af732203SDimitry Andric     cl::init(false), cl::Hidden,
104af732203SDimitry Andric     cl::desc("If enabled, drop make.implicit metadata in unswitched implicit "
105af732203SDimitry Andric              "null checks to save time analyzing if we can keep it."));
1065f7ddb14SDimitry Andric static cl::opt<unsigned>
1075f7ddb14SDimitry Andric     MSSAThreshold("simple-loop-unswitch-memoryssa-threshold",
1085f7ddb14SDimitry Andric                   cl::desc("Max number of memory uses to explore during "
1095f7ddb14SDimitry Andric                            "partial unswitching analysis"),
1105f7ddb14SDimitry Andric                   cl::init(100), cl::Hidden);
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric /// Collect all of the loop invariant input values transitively used by the
1130b57cec5SDimitry Andric /// homogeneous instruction graph from a given root.
1140b57cec5SDimitry Andric ///
1150b57cec5SDimitry Andric /// This essentially walks from a root recursively through loop variant operands
1160b57cec5SDimitry Andric /// which have the exact same opcode and finds all inputs which are loop
1170b57cec5SDimitry Andric /// invariant. For some operations these can be re-associated and unswitched out
1180b57cec5SDimitry Andric /// of the loop entirely.
1190b57cec5SDimitry Andric static TinyPtrVector<Value *>
collectHomogenousInstGraphLoopInvariants(Loop & L,Instruction & Root,LoopInfo & LI)1200b57cec5SDimitry Andric collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
1210b57cec5SDimitry Andric                                          LoopInfo &LI) {
1220b57cec5SDimitry Andric   assert(!L.isLoopInvariant(&Root) &&
1230b57cec5SDimitry Andric          "Only need to walk the graph if root itself is not invariant.");
1240b57cec5SDimitry Andric   TinyPtrVector<Value *> Invariants;
1250b57cec5SDimitry Andric 
1265f7ddb14SDimitry Andric   bool IsRootAnd = match(&Root, m_LogicalAnd());
1275f7ddb14SDimitry Andric   bool IsRootOr  = match(&Root, m_LogicalOr());
1285f7ddb14SDimitry Andric 
1290b57cec5SDimitry Andric   // Build a worklist and recurse through operators collecting invariants.
1300b57cec5SDimitry Andric   SmallVector<Instruction *, 4> Worklist;
1310b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Visited;
1320b57cec5SDimitry Andric   Worklist.push_back(&Root);
1330b57cec5SDimitry Andric   Visited.insert(&Root);
1340b57cec5SDimitry Andric   do {
1350b57cec5SDimitry Andric     Instruction &I = *Worklist.pop_back_val();
1360b57cec5SDimitry Andric     for (Value *OpV : I.operand_values()) {
1370b57cec5SDimitry Andric       // Skip constants as unswitching isn't interesting for them.
1380b57cec5SDimitry Andric       if (isa<Constant>(OpV))
1390b57cec5SDimitry Andric         continue;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric       // Add it to our result if loop invariant.
1420b57cec5SDimitry Andric       if (L.isLoopInvariant(OpV)) {
1430b57cec5SDimitry Andric         Invariants.push_back(OpV);
1440b57cec5SDimitry Andric         continue;
1450b57cec5SDimitry Andric       }
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric       // If not an instruction with the same opcode, nothing we can do.
1480b57cec5SDimitry Andric       Instruction *OpI = dyn_cast<Instruction>(OpV);
1490b57cec5SDimitry Andric 
1505f7ddb14SDimitry Andric       if (OpI && ((IsRootAnd && match(OpI, m_LogicalAnd())) ||
1515f7ddb14SDimitry Andric                   (IsRootOr  && match(OpI, m_LogicalOr())))) {
1520b57cec5SDimitry Andric         // Visit this operand.
1530b57cec5SDimitry Andric         if (Visited.insert(OpI).second)
1540b57cec5SDimitry Andric           Worklist.push_back(OpI);
1550b57cec5SDimitry Andric       }
1565f7ddb14SDimitry Andric     }
1570b57cec5SDimitry Andric   } while (!Worklist.empty());
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   return Invariants;
1600b57cec5SDimitry Andric }
1610b57cec5SDimitry Andric 
replaceLoopInvariantUses(Loop & L,Value * Invariant,Constant & Replacement)1620b57cec5SDimitry Andric static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
1630b57cec5SDimitry Andric                                      Constant &Replacement) {
1640b57cec5SDimitry Andric   assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   // Replace uses of LIC in the loop with the given constant.
1675f7ddb14SDimitry Andric   // We use make_early_inc_range as set invalidates the iterator.
1685f7ddb14SDimitry Andric   for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
1695f7ddb14SDimitry Andric     Instruction *UserI = dyn_cast<Instruction>(U.getUser());
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric     // Replace this use within the loop body.
1720b57cec5SDimitry Andric     if (UserI && L.contains(UserI))
1735f7ddb14SDimitry Andric       U.set(&Replacement);
1740b57cec5SDimitry Andric   }
1750b57cec5SDimitry Andric }
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric /// Check that all the LCSSA PHI nodes in the loop exit block have trivial
1780b57cec5SDimitry Andric /// incoming values along this edge.
areLoopExitPHIsLoopInvariant(Loop & L,BasicBlock & ExitingBB,BasicBlock & ExitBB)1790b57cec5SDimitry Andric static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
1800b57cec5SDimitry Andric                                          BasicBlock &ExitBB) {
1810b57cec5SDimitry Andric   for (Instruction &I : ExitBB) {
1820b57cec5SDimitry Andric     auto *PN = dyn_cast<PHINode>(&I);
1830b57cec5SDimitry Andric     if (!PN)
1840b57cec5SDimitry Andric       // No more PHIs to check.
1850b57cec5SDimitry Andric       return true;
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric     // If the incoming value for this edge isn't loop invariant the unswitch
1880b57cec5SDimitry Andric     // won't be trivial.
1890b57cec5SDimitry Andric     if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
1900b57cec5SDimitry Andric       return false;
1910b57cec5SDimitry Andric   }
1920b57cec5SDimitry Andric   llvm_unreachable("Basic blocks should never be empty!");
1930b57cec5SDimitry Andric }
1940b57cec5SDimitry Andric 
1955f7ddb14SDimitry Andric /// Copy a set of loop invariant values \p ToDuplicate and insert them at the
1965f7ddb14SDimitry Andric /// end of \p BB and conditionally branch on the copied condition. We only
1975f7ddb14SDimitry Andric /// branch on a single value.
buildPartialUnswitchConditionalBranch(BasicBlock & BB,ArrayRef<Value * > Invariants,bool Direction,BasicBlock & UnswitchedSucc,BasicBlock & NormalSucc)1980b57cec5SDimitry Andric static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
1990b57cec5SDimitry Andric                                                   ArrayRef<Value *> Invariants,
2000b57cec5SDimitry Andric                                                   bool Direction,
2010b57cec5SDimitry Andric                                                   BasicBlock &UnswitchedSucc,
2020b57cec5SDimitry Andric                                                   BasicBlock &NormalSucc) {
2030b57cec5SDimitry Andric   IRBuilder<> IRB(&BB);
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   Value *Cond = Direction ? IRB.CreateOr(Invariants) :
2060b57cec5SDimitry Andric     IRB.CreateAnd(Invariants);
2070b57cec5SDimitry Andric   IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
2080b57cec5SDimitry Andric                    Direction ? &NormalSucc : &UnswitchedSucc);
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric 
2115f7ddb14SDimitry Andric /// Copy a set of loop invariant values, and conditionally branch on them.
buildPartialInvariantUnswitchConditionalBranch(BasicBlock & BB,ArrayRef<Value * > ToDuplicate,bool Direction,BasicBlock & UnswitchedSucc,BasicBlock & NormalSucc,Loop & L,MemorySSAUpdater * MSSAU)2125f7ddb14SDimitry Andric static void buildPartialInvariantUnswitchConditionalBranch(
2135f7ddb14SDimitry Andric     BasicBlock &BB, ArrayRef<Value *> ToDuplicate, bool Direction,
2145f7ddb14SDimitry Andric     BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, Loop &L,
2155f7ddb14SDimitry Andric     MemorySSAUpdater *MSSAU) {
2165f7ddb14SDimitry Andric   ValueToValueMapTy VMap;
2175f7ddb14SDimitry Andric   for (auto *Val : reverse(ToDuplicate)) {
2185f7ddb14SDimitry Andric     Instruction *Inst = cast<Instruction>(Val);
2195f7ddb14SDimitry Andric     Instruction *NewInst = Inst->clone();
2205f7ddb14SDimitry Andric     BB.getInstList().insert(BB.end(), NewInst);
2215f7ddb14SDimitry Andric     RemapInstruction(NewInst, VMap,
2225f7ddb14SDimitry Andric                      RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
2235f7ddb14SDimitry Andric     VMap[Val] = NewInst;
2245f7ddb14SDimitry Andric 
2255f7ddb14SDimitry Andric     if (!MSSAU)
2265f7ddb14SDimitry Andric       continue;
2275f7ddb14SDimitry Andric 
2285f7ddb14SDimitry Andric     MemorySSA *MSSA = MSSAU->getMemorySSA();
2295f7ddb14SDimitry Andric     if (auto *MemUse =
2305f7ddb14SDimitry Andric             dyn_cast_or_null<MemoryUse>(MSSA->getMemoryAccess(Inst))) {
2315f7ddb14SDimitry Andric       auto *DefiningAccess = MemUse->getDefiningAccess();
2325f7ddb14SDimitry Andric       // Get the first defining access before the loop.
2335f7ddb14SDimitry Andric       while (L.contains(DefiningAccess->getBlock())) {
2345f7ddb14SDimitry Andric         // If the defining access is a MemoryPhi, get the incoming
2355f7ddb14SDimitry Andric         // value for the pre-header as defining access.
2365f7ddb14SDimitry Andric         if (auto *MemPhi = dyn_cast<MemoryPhi>(DefiningAccess))
2375f7ddb14SDimitry Andric           DefiningAccess =
2385f7ddb14SDimitry Andric               MemPhi->getIncomingValueForBlock(L.getLoopPreheader());
2395f7ddb14SDimitry Andric         else
2405f7ddb14SDimitry Andric           DefiningAccess = cast<MemoryDef>(DefiningAccess)->getDefiningAccess();
2415f7ddb14SDimitry Andric       }
2425f7ddb14SDimitry Andric       MSSAU->createMemoryAccessInBB(NewInst, DefiningAccess,
2435f7ddb14SDimitry Andric                                     NewInst->getParent(),
2445f7ddb14SDimitry Andric                                     MemorySSA::BeforeTerminator);
2455f7ddb14SDimitry Andric     }
2465f7ddb14SDimitry Andric   }
2475f7ddb14SDimitry Andric 
2485f7ddb14SDimitry Andric   IRBuilder<> IRB(&BB);
2495f7ddb14SDimitry Andric   Value *Cond = VMap[ToDuplicate[0]];
2505f7ddb14SDimitry Andric   IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
2515f7ddb14SDimitry Andric                    Direction ? &NormalSucc : &UnswitchedSucc);
2525f7ddb14SDimitry Andric }
2535f7ddb14SDimitry Andric 
2540b57cec5SDimitry Andric /// Rewrite the PHI nodes in an unswitched loop exit basic block.
2550b57cec5SDimitry Andric ///
2560b57cec5SDimitry Andric /// Requires that the loop exit and unswitched basic block are the same, and
2570b57cec5SDimitry Andric /// that the exiting block was a unique predecessor of that block. Rewrites the
2580b57cec5SDimitry Andric /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
2590b57cec5SDimitry Andric /// PHI nodes from the old preheader that now contains the unswitched
2600b57cec5SDimitry Andric /// terminator.
rewritePHINodesForUnswitchedExitBlock(BasicBlock & UnswitchedBB,BasicBlock & OldExitingBB,BasicBlock & OldPH)2610b57cec5SDimitry Andric static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
2620b57cec5SDimitry Andric                                                   BasicBlock &OldExitingBB,
2630b57cec5SDimitry Andric                                                   BasicBlock &OldPH) {
2640b57cec5SDimitry Andric   for (PHINode &PN : UnswitchedBB.phis()) {
2650b57cec5SDimitry Andric     // When the loop exit is directly unswitched we just need to update the
2660b57cec5SDimitry Andric     // incoming basic block. We loop to handle weird cases with repeated
2670b57cec5SDimitry Andric     // incoming blocks, but expect to typically only have one operand here.
2680b57cec5SDimitry Andric     for (auto i : seq<int>(0, PN.getNumOperands())) {
2690b57cec5SDimitry Andric       assert(PN.getIncomingBlock(i) == &OldExitingBB &&
2700b57cec5SDimitry Andric              "Found incoming block different from unique predecessor!");
2710b57cec5SDimitry Andric       PN.setIncomingBlock(i, &OldPH);
2720b57cec5SDimitry Andric     }
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric }
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric /// Rewrite the PHI nodes in the loop exit basic block and the split off
2770b57cec5SDimitry Andric /// unswitched block.
2780b57cec5SDimitry Andric ///
2790b57cec5SDimitry Andric /// Because the exit block remains an exit from the loop, this rewrites the
2800b57cec5SDimitry Andric /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
2810b57cec5SDimitry Andric /// nodes into the unswitched basic block to select between the value in the
2820b57cec5SDimitry Andric /// old preheader and the loop exit.
rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock & ExitBB,BasicBlock & UnswitchedBB,BasicBlock & OldExitingBB,BasicBlock & OldPH,bool FullUnswitch)2830b57cec5SDimitry Andric static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
2840b57cec5SDimitry Andric                                                       BasicBlock &UnswitchedBB,
2850b57cec5SDimitry Andric                                                       BasicBlock &OldExitingBB,
2860b57cec5SDimitry Andric                                                       BasicBlock &OldPH,
2870b57cec5SDimitry Andric                                                       bool FullUnswitch) {
2880b57cec5SDimitry Andric   assert(&ExitBB != &UnswitchedBB &&
2890b57cec5SDimitry Andric          "Must have different loop exit and unswitched blocks!");
2900b57cec5SDimitry Andric   Instruction *InsertPt = &*UnswitchedBB.begin();
2910b57cec5SDimitry Andric   for (PHINode &PN : ExitBB.phis()) {
2920b57cec5SDimitry Andric     auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
2930b57cec5SDimitry Andric                                   PN.getName() + ".split", InsertPt);
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric     // Walk backwards over the old PHI node's inputs to minimize the cost of
2960b57cec5SDimitry Andric     // removing each one. We have to do this weird loop manually so that we
2970b57cec5SDimitry Andric     // create the same number of new incoming edges in the new PHI as we expect
2980b57cec5SDimitry Andric     // each case-based edge to be included in the unswitched switch in some
2990b57cec5SDimitry Andric     // cases.
3000b57cec5SDimitry Andric     // FIXME: This is really, really gross. It would be much cleaner if LLVM
3010b57cec5SDimitry Andric     // allowed us to create a single entry for a predecessor block without
3020b57cec5SDimitry Andric     // having separate entries for each "edge" even though these edges are
3030b57cec5SDimitry Andric     // required to produce identical results.
3040b57cec5SDimitry Andric     for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
3050b57cec5SDimitry Andric       if (PN.getIncomingBlock(i) != &OldExitingBB)
3060b57cec5SDimitry Andric         continue;
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric       Value *Incoming = PN.getIncomingValue(i);
3090b57cec5SDimitry Andric       if (FullUnswitch)
3100b57cec5SDimitry Andric         // No more edge from the old exiting block to the exit block.
3110b57cec5SDimitry Andric         PN.removeIncomingValue(i);
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric       NewPN->addIncoming(Incoming, &OldPH);
3140b57cec5SDimitry Andric     }
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric     // Now replace the old PHI with the new one and wire the old one in as an
3170b57cec5SDimitry Andric     // input to the new one.
3180b57cec5SDimitry Andric     PN.replaceAllUsesWith(NewPN);
3190b57cec5SDimitry Andric     NewPN->addIncoming(&PN, &ExitBB);
3200b57cec5SDimitry Andric   }
3210b57cec5SDimitry Andric }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric /// Hoist the current loop up to the innermost loop containing a remaining exit.
3240b57cec5SDimitry Andric ///
3250b57cec5SDimitry Andric /// Because we've removed an exit from the loop, we may have changed the set of
3260b57cec5SDimitry Andric /// loops reachable and need to move the current loop up the loop nest or even
3270b57cec5SDimitry Andric /// to an entirely separate nest.
hoistLoopToNewParent(Loop & L,BasicBlock & Preheader,DominatorTree & DT,LoopInfo & LI,MemorySSAUpdater * MSSAU,ScalarEvolution * SE)3280b57cec5SDimitry Andric static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
3290b57cec5SDimitry Andric                                  DominatorTree &DT, LoopInfo &LI,
330480093f4SDimitry Andric                                  MemorySSAUpdater *MSSAU, ScalarEvolution *SE) {
3310b57cec5SDimitry Andric   // If the loop is already at the top level, we can't hoist it anywhere.
3320b57cec5SDimitry Andric   Loop *OldParentL = L.getParentLoop();
3330b57cec5SDimitry Andric   if (!OldParentL)
3340b57cec5SDimitry Andric     return;
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> Exits;
3370b57cec5SDimitry Andric   L.getExitBlocks(Exits);
3380b57cec5SDimitry Andric   Loop *NewParentL = nullptr;
3390b57cec5SDimitry Andric   for (auto *ExitBB : Exits)
3400b57cec5SDimitry Andric     if (Loop *ExitL = LI.getLoopFor(ExitBB))
3410b57cec5SDimitry Andric       if (!NewParentL || NewParentL->contains(ExitL))
3420b57cec5SDimitry Andric         NewParentL = ExitL;
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   if (NewParentL == OldParentL)
3450b57cec5SDimitry Andric     return;
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   // The new parent loop (if different) should always contain the old one.
3480b57cec5SDimitry Andric   if (NewParentL)
3490b57cec5SDimitry Andric     assert(NewParentL->contains(OldParentL) &&
3500b57cec5SDimitry Andric            "Can only hoist this loop up the nest!");
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric   // The preheader will need to move with the body of this loop. However,
3530b57cec5SDimitry Andric   // because it isn't in this loop we also need to update the primary loop map.
3540b57cec5SDimitry Andric   assert(OldParentL == LI.getLoopFor(&Preheader) &&
3550b57cec5SDimitry Andric          "Parent loop of this loop should contain this loop's preheader!");
3560b57cec5SDimitry Andric   LI.changeLoopFor(&Preheader, NewParentL);
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric   // Remove this loop from its old parent.
3590b57cec5SDimitry Andric   OldParentL->removeChildLoop(&L);
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric   // Add the loop either to the new parent or as a top-level loop.
3620b57cec5SDimitry Andric   if (NewParentL)
3630b57cec5SDimitry Andric     NewParentL->addChildLoop(&L);
3640b57cec5SDimitry Andric   else
3650b57cec5SDimitry Andric     LI.addTopLevelLoop(&L);
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   // Remove this loops blocks from the old parent and every other loop up the
3680b57cec5SDimitry Andric   // nest until reaching the new parent. Also update all of these
3690b57cec5SDimitry Andric   // no-longer-containing loops to reflect the nesting change.
3700b57cec5SDimitry Andric   for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
3710b57cec5SDimitry Andric        OldContainingL = OldContainingL->getParentLoop()) {
3720b57cec5SDimitry Andric     llvm::erase_if(OldContainingL->getBlocksVector(),
3730b57cec5SDimitry Andric                    [&](const BasicBlock *BB) {
3740b57cec5SDimitry Andric                      return BB == &Preheader || L.contains(BB);
3750b57cec5SDimitry Andric                    });
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric     OldContainingL->getBlocksSet().erase(&Preheader);
3780b57cec5SDimitry Andric     for (BasicBlock *BB : L.blocks())
3790b57cec5SDimitry Andric       OldContainingL->getBlocksSet().erase(BB);
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric     // Because we just hoisted a loop out of this one, we have essentially
3820b57cec5SDimitry Andric     // created new exit paths from it. That means we need to form LCSSA PHI
3830b57cec5SDimitry Andric     // nodes for values used in the no-longer-nested loop.
384480093f4SDimitry Andric     formLCSSA(*OldContainingL, DT, &LI, SE);
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric     // We shouldn't need to form dedicated exits because the exit introduced
3870b57cec5SDimitry Andric     // here is the (just split by unswitching) preheader. However, after trivial
3880b57cec5SDimitry Andric     // unswitching it is possible to get new non-dedicated exits out of parent
3890b57cec5SDimitry Andric     // loop so let's conservatively form dedicated exit blocks and figure out
3900b57cec5SDimitry Andric     // if we can optimize later.
3910b57cec5SDimitry Andric     formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
3920b57cec5SDimitry Andric                             /*PreserveLCSSA*/ true);
3930b57cec5SDimitry Andric   }
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric 
396480093f4SDimitry Andric // Return the top-most loop containing ExitBB and having ExitBB as exiting block
397480093f4SDimitry Andric // or the loop containing ExitBB, if there is no parent loop containing ExitBB
398480093f4SDimitry Andric // as exiting block.
getTopMostExitingLoop(BasicBlock * ExitBB,LoopInfo & LI)399480093f4SDimitry Andric static Loop *getTopMostExitingLoop(BasicBlock *ExitBB, LoopInfo &LI) {
400480093f4SDimitry Andric   Loop *TopMost = LI.getLoopFor(ExitBB);
401480093f4SDimitry Andric   Loop *Current = TopMost;
402480093f4SDimitry Andric   while (Current) {
403480093f4SDimitry Andric     if (Current->isLoopExiting(ExitBB))
404480093f4SDimitry Andric       TopMost = Current;
405480093f4SDimitry Andric     Current = Current->getParentLoop();
406480093f4SDimitry Andric   }
407480093f4SDimitry Andric   return TopMost;
408480093f4SDimitry Andric }
409480093f4SDimitry Andric 
4100b57cec5SDimitry Andric /// Unswitch a trivial branch if the condition is loop invariant.
4110b57cec5SDimitry Andric ///
4120b57cec5SDimitry Andric /// This routine should only be called when loop code leading to the branch has
4130b57cec5SDimitry Andric /// been validated as trivial (no side effects). This routine checks if the
4140b57cec5SDimitry Andric /// condition is invariant and one of the successors is a loop exit. This
4150b57cec5SDimitry Andric /// allows us to unswitch without duplicating the loop, making it trivial.
4160b57cec5SDimitry Andric ///
4170b57cec5SDimitry Andric /// If this routine fails to unswitch the branch it returns false.
4180b57cec5SDimitry Andric ///
4190b57cec5SDimitry Andric /// If the branch can be unswitched, this routine splits the preheader and
4200b57cec5SDimitry Andric /// hoists the branch above that split. Preserves loop simplified form
4210b57cec5SDimitry Andric /// (splitting the exit block as necessary). It simplifies the branch within
4220b57cec5SDimitry Andric /// the loop to an unconditional branch but doesn't remove it entirely. Further
4235f7ddb14SDimitry Andric /// cleanup can be done with some simplifycfg like pass.
4240b57cec5SDimitry Andric ///
4250b57cec5SDimitry Andric /// If `SE` is not null, it will be updated based on the potential loop SCEVs
4260b57cec5SDimitry Andric /// invalidated by this.
unswitchTrivialBranch(Loop & L,BranchInst & BI,DominatorTree & DT,LoopInfo & LI,ScalarEvolution * SE,MemorySSAUpdater * MSSAU)4270b57cec5SDimitry Andric static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
4280b57cec5SDimitry Andric                                   LoopInfo &LI, ScalarEvolution *SE,
4290b57cec5SDimitry Andric                                   MemorySSAUpdater *MSSAU) {
4300b57cec5SDimitry Andric   assert(BI.isConditional() && "Can only unswitch a conditional branch!");
4310b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Trying to unswitch branch: " << BI << "\n");
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   // The loop invariant values that we want to unswitch.
4340b57cec5SDimitry Andric   TinyPtrVector<Value *> Invariants;
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric   // When true, we're fully unswitching the branch rather than just unswitching
4370b57cec5SDimitry Andric   // some input conditions to the branch.
4380b57cec5SDimitry Andric   bool FullUnswitch = false;
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   if (L.isLoopInvariant(BI.getCondition())) {
4410b57cec5SDimitry Andric     Invariants.push_back(BI.getCondition());
4420b57cec5SDimitry Andric     FullUnswitch = true;
4430b57cec5SDimitry Andric   } else {
4440b57cec5SDimitry Andric     if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
4450b57cec5SDimitry Andric       Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
4465f7ddb14SDimitry Andric     if (Invariants.empty()) {
4475f7ddb14SDimitry Andric       LLVM_DEBUG(dbgs() << "   Couldn't find invariant inputs!\n");
4480b57cec5SDimitry Andric       return false;
4490b57cec5SDimitry Andric     }
4505f7ddb14SDimitry Andric   }
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   // Check that one of the branch's successors exits, and which one.
4530b57cec5SDimitry Andric   bool ExitDirection = true;
4540b57cec5SDimitry Andric   int LoopExitSuccIdx = 0;
4550b57cec5SDimitry Andric   auto *LoopExitBB = BI.getSuccessor(0);
4560b57cec5SDimitry Andric   if (L.contains(LoopExitBB)) {
4570b57cec5SDimitry Andric     ExitDirection = false;
4580b57cec5SDimitry Andric     LoopExitSuccIdx = 1;
4590b57cec5SDimitry Andric     LoopExitBB = BI.getSuccessor(1);
4605f7ddb14SDimitry Andric     if (L.contains(LoopExitBB)) {
4615f7ddb14SDimitry Andric       LLVM_DEBUG(dbgs() << "   Branch doesn't exit the loop!\n");
4620b57cec5SDimitry Andric       return false;
4630b57cec5SDimitry Andric     }
4645f7ddb14SDimitry Andric   }
4650b57cec5SDimitry Andric   auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
4660b57cec5SDimitry Andric   auto *ParentBB = BI.getParent();
4675f7ddb14SDimitry Andric   if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) {
4685f7ddb14SDimitry Andric     LLVM_DEBUG(dbgs() << "   Loop exit PHI's aren't loop-invariant!\n");
4690b57cec5SDimitry Andric     return false;
4705f7ddb14SDimitry Andric   }
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   // When unswitching only part of the branch's condition, we need the exit
4730b57cec5SDimitry Andric   // block to be reached directly from the partially unswitched input. This can
4740b57cec5SDimitry Andric   // be done when the exit block is along the true edge and the branch condition
4750b57cec5SDimitry Andric   // is a graph of `or` operations, or the exit block is along the false edge
4760b57cec5SDimitry Andric   // and the condition is a graph of `and` operations.
4770b57cec5SDimitry Andric   if (!FullUnswitch) {
4785f7ddb14SDimitry Andric     if (ExitDirection ? !match(BI.getCondition(), m_LogicalOr())
4795f7ddb14SDimitry Andric                       : !match(BI.getCondition(), m_LogicalAnd())) {
4805f7ddb14SDimitry Andric       LLVM_DEBUG(dbgs() << "   Branch condition is in improper form for "
4815f7ddb14SDimitry Andric                            "non-full unswitch!\n");
4820b57cec5SDimitry Andric       return false;
4830b57cec5SDimitry Andric     }
4840b57cec5SDimitry Andric   }
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   LLVM_DEBUG({
4870b57cec5SDimitry Andric     dbgs() << "    unswitching trivial invariant conditions for: " << BI
4880b57cec5SDimitry Andric            << "\n";
4890b57cec5SDimitry Andric     for (Value *Invariant : Invariants) {
4900b57cec5SDimitry Andric       dbgs() << "      " << *Invariant << " == true";
4910b57cec5SDimitry Andric       if (Invariant != Invariants.back())
4920b57cec5SDimitry Andric         dbgs() << " ||";
4930b57cec5SDimitry Andric       dbgs() << "\n";
4940b57cec5SDimitry Andric     }
4950b57cec5SDimitry Andric   });
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric   // If we have scalar evolutions, we need to invalidate them including this
498480093f4SDimitry Andric   // loop, the loop containing the exit block and the topmost parent loop
499480093f4SDimitry Andric   // exiting via LoopExitBB.
5000b57cec5SDimitry Andric   if (SE) {
501480093f4SDimitry Andric     if (Loop *ExitL = getTopMostExitingLoop(LoopExitBB, LI))
5020b57cec5SDimitry Andric       SE->forgetLoop(ExitL);
5030b57cec5SDimitry Andric     else
5040b57cec5SDimitry Andric       // Forget the entire nest as this exits the entire nest.
5050b57cec5SDimitry Andric       SE->forgetTopmostLoop(&L);
5060b57cec5SDimitry Andric   }
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
5090b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric   // Split the preheader, so that we know that there is a safe place to insert
5120b57cec5SDimitry Andric   // the conditional branch. We will change the preheader to have a conditional
5130b57cec5SDimitry Andric   // branch on LoopCond.
5140b57cec5SDimitry Andric   BasicBlock *OldPH = L.getLoopPreheader();
5150b57cec5SDimitry Andric   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   // Now that we have a place to insert the conditional branch, create a place
5180b57cec5SDimitry Andric   // to branch to: this is the exit block out of the loop that we are
5190b57cec5SDimitry Andric   // unswitching. We need to split this if there are other loop predecessors.
5200b57cec5SDimitry Andric   // Because the loop is in simplified form, *any* other predecessor is enough.
5210b57cec5SDimitry Andric   BasicBlock *UnswitchedBB;
5220b57cec5SDimitry Andric   if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
5230b57cec5SDimitry Andric     assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
5240b57cec5SDimitry Andric            "A branch's parent isn't a predecessor!");
5250b57cec5SDimitry Andric     UnswitchedBB = LoopExitBB;
5260b57cec5SDimitry Andric   } else {
5270b57cec5SDimitry Andric     UnswitchedBB =
5280b57cec5SDimitry Andric         SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
5290b57cec5SDimitry Andric   }
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
5320b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   // Actually move the invariant uses into the unswitched position. If possible,
5350b57cec5SDimitry Andric   // we do this by moving the instructions, but when doing partial unswitching
5360b57cec5SDimitry Andric   // we do it by building a new merge of the values in the unswitched position.
5370b57cec5SDimitry Andric   OldPH->getTerminator()->eraseFromParent();
5380b57cec5SDimitry Andric   if (FullUnswitch) {
5390b57cec5SDimitry Andric     // If fully unswitching, we can use the existing branch instruction.
5400b57cec5SDimitry Andric     // Splice it into the old PH to gate reaching the new preheader and re-point
5410b57cec5SDimitry Andric     // its successors.
5420b57cec5SDimitry Andric     OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
5430b57cec5SDimitry Andric                                 BI);
5440b57cec5SDimitry Andric     if (MSSAU) {
5450b57cec5SDimitry Andric       // Temporarily clone the terminator, to make MSSA update cheaper by
5460b57cec5SDimitry Andric       // separating "insert edge" updates from "remove edge" ones.
5470b57cec5SDimitry Andric       ParentBB->getInstList().push_back(BI.clone());
5480b57cec5SDimitry Andric     } else {
5490b57cec5SDimitry Andric       // Create a new unconditional branch that will continue the loop as a new
5500b57cec5SDimitry Andric       // terminator.
5510b57cec5SDimitry Andric       BranchInst::Create(ContinueBB, ParentBB);
5520b57cec5SDimitry Andric     }
5530b57cec5SDimitry Andric     BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
5540b57cec5SDimitry Andric     BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
5550b57cec5SDimitry Andric   } else {
5560b57cec5SDimitry Andric     // Only unswitching a subset of inputs to the condition, so we will need to
5570b57cec5SDimitry Andric     // build a new branch that merges the invariant inputs.
5580b57cec5SDimitry Andric     if (ExitDirection)
5595f7ddb14SDimitry Andric       assert(match(BI.getCondition(), m_LogicalOr()) &&
5605f7ddb14SDimitry Andric              "Must have an `or` of `i1`s or `select i1 X, true, Y`s for the "
5615f7ddb14SDimitry Andric              "condition!");
5620b57cec5SDimitry Andric     else
5635f7ddb14SDimitry Andric       assert(match(BI.getCondition(), m_LogicalAnd()) &&
5645f7ddb14SDimitry Andric              "Must have an `and` of `i1`s or `select i1 X, Y, false`s for the"
5655f7ddb14SDimitry Andric              " condition!");
5660b57cec5SDimitry Andric     buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
5670b57cec5SDimitry Andric                                           *UnswitchedBB, *NewPH);
5680b57cec5SDimitry Andric   }
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric   // Update the dominator tree with the added edge.
5710b57cec5SDimitry Andric   DT.insertEdge(OldPH, UnswitchedBB);
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   // After the dominator tree was updated with the added edge, update MemorySSA
5740b57cec5SDimitry Andric   // if available.
5750b57cec5SDimitry Andric   if (MSSAU) {
5760b57cec5SDimitry Andric     SmallVector<CFGUpdate, 1> Updates;
5770b57cec5SDimitry Andric     Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
5780b57cec5SDimitry Andric     MSSAU->applyInsertUpdates(Updates, DT);
5790b57cec5SDimitry Andric   }
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric   // Finish updating dominator tree and memory ssa for full unswitch.
5820b57cec5SDimitry Andric   if (FullUnswitch) {
5830b57cec5SDimitry Andric     if (MSSAU) {
5840b57cec5SDimitry Andric       // Remove the cloned branch instruction.
5850b57cec5SDimitry Andric       ParentBB->getTerminator()->eraseFromParent();
5860b57cec5SDimitry Andric       // Create unconditional branch now.
5870b57cec5SDimitry Andric       BranchInst::Create(ContinueBB, ParentBB);
5880b57cec5SDimitry Andric       MSSAU->removeEdge(ParentBB, LoopExitBB);
5890b57cec5SDimitry Andric     }
5900b57cec5SDimitry Andric     DT.deleteEdge(ParentBB, LoopExitBB);
5910b57cec5SDimitry Andric   }
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
5940b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   // Rewrite the relevant PHI nodes.
5970b57cec5SDimitry Andric   if (UnswitchedBB == LoopExitBB)
5980b57cec5SDimitry Andric     rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
5990b57cec5SDimitry Andric   else
6000b57cec5SDimitry Andric     rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
6010b57cec5SDimitry Andric                                               *ParentBB, *OldPH, FullUnswitch);
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric   // The constant we can replace all of our invariants with inside the loop
6040b57cec5SDimitry Andric   // body. If any of the invariants have a value other than this the loop won't
6050b57cec5SDimitry Andric   // be entered.
6060b57cec5SDimitry Andric   ConstantInt *Replacement = ExitDirection
6070b57cec5SDimitry Andric                                  ? ConstantInt::getFalse(BI.getContext())
6080b57cec5SDimitry Andric                                  : ConstantInt::getTrue(BI.getContext());
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric   // Since this is an i1 condition we can also trivially replace uses of it
6110b57cec5SDimitry Andric   // within the loop with a constant.
6120b57cec5SDimitry Andric   for (Value *Invariant : Invariants)
6130b57cec5SDimitry Andric     replaceLoopInvariantUses(L, Invariant, *Replacement);
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric   // If this was full unswitching, we may have changed the nesting relationship
6160b57cec5SDimitry Andric   // for this loop so hoist it to its correct parent if needed.
6170b57cec5SDimitry Andric   if (FullUnswitch)
618480093f4SDimitry Andric     hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
6210b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "    done: unswitching trivial branch...\n");
6240b57cec5SDimitry Andric   ++NumTrivial;
6250b57cec5SDimitry Andric   ++NumBranches;
6260b57cec5SDimitry Andric   return true;
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric /// Unswitch a trivial switch if the condition is loop invariant.
6300b57cec5SDimitry Andric ///
6310b57cec5SDimitry Andric /// This routine should only be called when loop code leading to the switch has
6320b57cec5SDimitry Andric /// been validated as trivial (no side effects). This routine checks if the
6330b57cec5SDimitry Andric /// condition is invariant and that at least one of the successors is a loop
6340b57cec5SDimitry Andric /// exit. This allows us to unswitch without duplicating the loop, making it
6350b57cec5SDimitry Andric /// trivial.
6360b57cec5SDimitry Andric ///
6370b57cec5SDimitry Andric /// If this routine fails to unswitch the switch it returns false.
6380b57cec5SDimitry Andric ///
6390b57cec5SDimitry Andric /// If the switch can be unswitched, this routine splits the preheader and
6400b57cec5SDimitry Andric /// copies the switch above that split. If the default case is one of the
6410b57cec5SDimitry Andric /// exiting cases, it copies the non-exiting cases and points them at the new
6420b57cec5SDimitry Andric /// preheader. If the default case is not exiting, it copies the exiting cases
6430b57cec5SDimitry Andric /// and points the default at the preheader. It preserves loop simplified form
6440b57cec5SDimitry Andric /// (splitting the exit blocks as necessary). It simplifies the switch within
6450b57cec5SDimitry Andric /// the loop by removing now-dead cases. If the default case is one of those
6460b57cec5SDimitry Andric /// unswitched, it replaces its destination with a new basic block containing
6470b57cec5SDimitry Andric /// only unreachable. Such basic blocks, while technically loop exits, are not
6480b57cec5SDimitry Andric /// considered for unswitching so this is a stable transform and the same
6490b57cec5SDimitry Andric /// switch will not be revisited. If after unswitching there is only a single
6500b57cec5SDimitry Andric /// in-loop successor, the switch is further simplified to an unconditional
6515f7ddb14SDimitry Andric /// branch. Still more cleanup can be done with some simplifycfg like pass.
6520b57cec5SDimitry Andric ///
6530b57cec5SDimitry Andric /// If `SE` is not null, it will be updated based on the potential loop SCEVs
6540b57cec5SDimitry Andric /// invalidated by this.
unswitchTrivialSwitch(Loop & L,SwitchInst & SI,DominatorTree & DT,LoopInfo & LI,ScalarEvolution * SE,MemorySSAUpdater * MSSAU)6550b57cec5SDimitry Andric static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
6560b57cec5SDimitry Andric                                   LoopInfo &LI, ScalarEvolution *SE,
6570b57cec5SDimitry Andric                                   MemorySSAUpdater *MSSAU) {
6580b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Trying to unswitch switch: " << SI << "\n");
6590b57cec5SDimitry Andric   Value *LoopCond = SI.getCondition();
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   // If this isn't switching on an invariant condition, we can't unswitch it.
6620b57cec5SDimitry Andric   if (!L.isLoopInvariant(LoopCond))
6630b57cec5SDimitry Andric     return false;
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   auto *ParentBB = SI.getParent();
6660b57cec5SDimitry Andric 
6675ffd83dbSDimitry Andric   // The same check must be used both for the default and the exit cases. We
6685ffd83dbSDimitry Andric   // should never leave edges from the switch instruction to a basic block that
6695ffd83dbSDimitry Andric   // we are unswitching, hence the condition used to determine the default case
6705ffd83dbSDimitry Andric   // needs to also be used to populate ExitCaseIndices, which is then used to
6715ffd83dbSDimitry Andric   // remove cases from the switch.
6725ffd83dbSDimitry Andric   auto IsTriviallyUnswitchableExitBlock = [&](BasicBlock &BBToCheck) {
6735ffd83dbSDimitry Andric     // BBToCheck is not an exit block if it is inside loop L.
6745ffd83dbSDimitry Andric     if (L.contains(&BBToCheck))
6755ffd83dbSDimitry Andric       return false;
6765ffd83dbSDimitry Andric     // BBToCheck is not trivial to unswitch if its phis aren't loop invariant.
6775ffd83dbSDimitry Andric     if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, BBToCheck))
6785ffd83dbSDimitry Andric       return false;
6795ffd83dbSDimitry Andric     // We do not unswitch a block that only has an unreachable statement, as
6805ffd83dbSDimitry Andric     // it's possible this is a previously unswitched block. Only unswitch if
6815ffd83dbSDimitry Andric     // either the terminator is not unreachable, or, if it is, it's not the only
6825ffd83dbSDimitry Andric     // instruction in the block.
6835ffd83dbSDimitry Andric     auto *TI = BBToCheck.getTerminator();
6845ffd83dbSDimitry Andric     bool isUnreachable = isa<UnreachableInst>(TI);
6855ffd83dbSDimitry Andric     return !isUnreachable ||
6865ffd83dbSDimitry Andric            (isUnreachable && (BBToCheck.getFirstNonPHIOrDbg() != TI));
6875ffd83dbSDimitry Andric   };
6885ffd83dbSDimitry Andric 
6890b57cec5SDimitry Andric   SmallVector<int, 4> ExitCaseIndices;
6905ffd83dbSDimitry Andric   for (auto Case : SI.cases())
6915ffd83dbSDimitry Andric     if (IsTriviallyUnswitchableExitBlock(*Case.getCaseSuccessor()))
6920b57cec5SDimitry Andric       ExitCaseIndices.push_back(Case.getCaseIndex());
6930b57cec5SDimitry Andric   BasicBlock *DefaultExitBB = nullptr;
6940b57cec5SDimitry Andric   SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight =
6950b57cec5SDimitry Andric       SwitchInstProfUpdateWrapper::getSuccessorWeight(SI, 0);
6965ffd83dbSDimitry Andric   if (IsTriviallyUnswitchableExitBlock(*SI.getDefaultDest())) {
6970b57cec5SDimitry Andric     DefaultExitBB = SI.getDefaultDest();
6980b57cec5SDimitry Andric   } else if (ExitCaseIndices.empty())
6990b57cec5SDimitry Andric     return false;
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "    unswitching trivial switch...\n");
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
7040b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric   // We may need to invalidate SCEVs for the outermost loop reached by any of
7070b57cec5SDimitry Andric   // the exits.
7080b57cec5SDimitry Andric   Loop *OuterL = &L;
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric   if (DefaultExitBB) {
7110b57cec5SDimitry Andric     // Clear out the default destination temporarily to allow accurate
7120b57cec5SDimitry Andric     // predecessor lists to be examined below.
7130b57cec5SDimitry Andric     SI.setDefaultDest(nullptr);
7140b57cec5SDimitry Andric     // Check the loop containing this exit.
7150b57cec5SDimitry Andric     Loop *ExitL = LI.getLoopFor(DefaultExitBB);
7160b57cec5SDimitry Andric     if (!ExitL || ExitL->contains(OuterL))
7170b57cec5SDimitry Andric       OuterL = ExitL;
7180b57cec5SDimitry Andric   }
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric   // Store the exit cases into a separate data structure and remove them from
7210b57cec5SDimitry Andric   // the switch.
7220b57cec5SDimitry Andric   SmallVector<std::tuple<ConstantInt *, BasicBlock *,
7230b57cec5SDimitry Andric                          SwitchInstProfUpdateWrapper::CaseWeightOpt>,
7240b57cec5SDimitry Andric               4> ExitCases;
7250b57cec5SDimitry Andric   ExitCases.reserve(ExitCaseIndices.size());
7260b57cec5SDimitry Andric   SwitchInstProfUpdateWrapper SIW(SI);
7270b57cec5SDimitry Andric   // We walk the case indices backwards so that we remove the last case first
7280b57cec5SDimitry Andric   // and don't disrupt the earlier indices.
7290b57cec5SDimitry Andric   for (unsigned Index : reverse(ExitCaseIndices)) {
7300b57cec5SDimitry Andric     auto CaseI = SI.case_begin() + Index;
7310b57cec5SDimitry Andric     // Compute the outer loop from this exit.
7320b57cec5SDimitry Andric     Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
7330b57cec5SDimitry Andric     if (!ExitL || ExitL->contains(OuterL))
7340b57cec5SDimitry Andric       OuterL = ExitL;
7350b57cec5SDimitry Andric     // Save the value of this case.
7360b57cec5SDimitry Andric     auto W = SIW.getSuccessorWeight(CaseI->getSuccessorIndex());
7370b57cec5SDimitry Andric     ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W);
7380b57cec5SDimitry Andric     // Delete the unswitched cases.
7390b57cec5SDimitry Andric     SIW.removeCase(CaseI);
7400b57cec5SDimitry Andric   }
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric   if (SE) {
7430b57cec5SDimitry Andric     if (OuterL)
7440b57cec5SDimitry Andric       SE->forgetLoop(OuterL);
7450b57cec5SDimitry Andric     else
7460b57cec5SDimitry Andric       SE->forgetTopmostLoop(&L);
7470b57cec5SDimitry Andric   }
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric   // Check if after this all of the remaining cases point at the same
7500b57cec5SDimitry Andric   // successor.
7510b57cec5SDimitry Andric   BasicBlock *CommonSuccBB = nullptr;
7520b57cec5SDimitry Andric   if (SI.getNumCases() > 0 &&
753af732203SDimitry Andric       all_of(drop_begin(SI.cases()), [&SI](const SwitchInst::CaseHandle &Case) {
754af732203SDimitry Andric         return Case.getCaseSuccessor() == SI.case_begin()->getCaseSuccessor();
7550b57cec5SDimitry Andric       }))
7560b57cec5SDimitry Andric     CommonSuccBB = SI.case_begin()->getCaseSuccessor();
7570b57cec5SDimitry Andric   if (!DefaultExitBB) {
7580b57cec5SDimitry Andric     // If we're not unswitching the default, we need it to match any cases to
7590b57cec5SDimitry Andric     // have a common successor or if we have no cases it is the common
7600b57cec5SDimitry Andric     // successor.
7610b57cec5SDimitry Andric     if (SI.getNumCases() == 0)
7620b57cec5SDimitry Andric       CommonSuccBB = SI.getDefaultDest();
7630b57cec5SDimitry Andric     else if (SI.getDefaultDest() != CommonSuccBB)
7640b57cec5SDimitry Andric       CommonSuccBB = nullptr;
7650b57cec5SDimitry Andric   }
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric   // Split the preheader, so that we know that there is a safe place to insert
7680b57cec5SDimitry Andric   // the switch.
7690b57cec5SDimitry Andric   BasicBlock *OldPH = L.getLoopPreheader();
7700b57cec5SDimitry Andric   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
7710b57cec5SDimitry Andric   OldPH->getTerminator()->eraseFromParent();
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric   // Now add the unswitched switch.
7740b57cec5SDimitry Andric   auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
7750b57cec5SDimitry Andric   SwitchInstProfUpdateWrapper NewSIW(*NewSI);
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric   // Rewrite the IR for the unswitched basic blocks. This requires two steps.
7780b57cec5SDimitry Andric   // First, we split any exit blocks with remaining in-loop predecessors. Then
7790b57cec5SDimitry Andric   // we update the PHIs in one of two ways depending on if there was a split.
7800b57cec5SDimitry Andric   // We walk in reverse so that we split in the same order as the cases
7810b57cec5SDimitry Andric   // appeared. This is purely for convenience of reading the resulting IR, but
7820b57cec5SDimitry Andric   // it doesn't cost anything really.
7830b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
7840b57cec5SDimitry Andric   SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
7850b57cec5SDimitry Andric   // Handle the default exit if necessary.
7860b57cec5SDimitry Andric   // FIXME: It'd be great if we could merge this with the loop below but LLVM's
7870b57cec5SDimitry Andric   // ranges aren't quite powerful enough yet.
7880b57cec5SDimitry Andric   if (DefaultExitBB) {
7890b57cec5SDimitry Andric     if (pred_empty(DefaultExitBB)) {
7900b57cec5SDimitry Andric       UnswitchedExitBBs.insert(DefaultExitBB);
7910b57cec5SDimitry Andric       rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
7920b57cec5SDimitry Andric     } else {
7930b57cec5SDimitry Andric       auto *SplitBB =
7940b57cec5SDimitry Andric           SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
7950b57cec5SDimitry Andric       rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
7960b57cec5SDimitry Andric                                                 *ParentBB, *OldPH,
7970b57cec5SDimitry Andric                                                 /*FullUnswitch*/ true);
7980b57cec5SDimitry Andric       DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
7990b57cec5SDimitry Andric     }
8000b57cec5SDimitry Andric   }
8010b57cec5SDimitry Andric   // Note that we must use a reference in the for loop so that we update the
8020b57cec5SDimitry Andric   // container.
8030b57cec5SDimitry Andric   for (auto &ExitCase : reverse(ExitCases)) {
8040b57cec5SDimitry Andric     // Grab a reference to the exit block in the pair so that we can update it.
8050b57cec5SDimitry Andric     BasicBlock *ExitBB = std::get<1>(ExitCase);
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric     // If this case is the last edge into the exit block, we can simply reuse it
8080b57cec5SDimitry Andric     // as it will no longer be a loop exit. No mapping necessary.
8090b57cec5SDimitry Andric     if (pred_empty(ExitBB)) {
8100b57cec5SDimitry Andric       // Only rewrite once.
8110b57cec5SDimitry Andric       if (UnswitchedExitBBs.insert(ExitBB).second)
8120b57cec5SDimitry Andric         rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
8130b57cec5SDimitry Andric       continue;
8140b57cec5SDimitry Andric     }
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric     // Otherwise we need to split the exit block so that we retain an exit
8170b57cec5SDimitry Andric     // block from the loop and a target for the unswitched condition.
8180b57cec5SDimitry Andric     BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
8190b57cec5SDimitry Andric     if (!SplitExitBB) {
8200b57cec5SDimitry Andric       // If this is the first time we see this, do the split and remember it.
8210b57cec5SDimitry Andric       SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
8220b57cec5SDimitry Andric       rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
8230b57cec5SDimitry Andric                                                 *ParentBB, *OldPH,
8240b57cec5SDimitry Andric                                                 /*FullUnswitch*/ true);
8250b57cec5SDimitry Andric     }
8260b57cec5SDimitry Andric     // Update the case pair to point to the split block.
8270b57cec5SDimitry Andric     std::get<1>(ExitCase) = SplitExitBB;
8280b57cec5SDimitry Andric   }
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric   // Now add the unswitched cases. We do this in reverse order as we built them
8310b57cec5SDimitry Andric   // in reverse order.
8320b57cec5SDimitry Andric   for (auto &ExitCase : reverse(ExitCases)) {
8330b57cec5SDimitry Andric     ConstantInt *CaseVal = std::get<0>(ExitCase);
8340b57cec5SDimitry Andric     BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric     NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
8370b57cec5SDimitry Andric   }
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric   // If the default was unswitched, re-point it and add explicit cases for
8400b57cec5SDimitry Andric   // entering the loop.
8410b57cec5SDimitry Andric   if (DefaultExitBB) {
8420b57cec5SDimitry Andric     NewSIW->setDefaultDest(DefaultExitBB);
8430b57cec5SDimitry Andric     NewSIW.setSuccessorWeight(0, DefaultCaseWeight);
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric     // We removed all the exit cases, so we just copy the cases to the
8460b57cec5SDimitry Andric     // unswitched switch.
8470b57cec5SDimitry Andric     for (const auto &Case : SI.cases())
8480b57cec5SDimitry Andric       NewSIW.addCase(Case.getCaseValue(), NewPH,
8490b57cec5SDimitry Andric                      SIW.getSuccessorWeight(Case.getSuccessorIndex()));
8500b57cec5SDimitry Andric   } else if (DefaultCaseWeight) {
8510b57cec5SDimitry Andric     // We have to set branch weight of the default case.
8520b57cec5SDimitry Andric     uint64_t SW = *DefaultCaseWeight;
8530b57cec5SDimitry Andric     for (const auto &Case : SI.cases()) {
8540b57cec5SDimitry Andric       auto W = SIW.getSuccessorWeight(Case.getSuccessorIndex());
8550b57cec5SDimitry Andric       assert(W &&
8560b57cec5SDimitry Andric              "case weight must be defined as default case weight is defined");
8570b57cec5SDimitry Andric       SW += *W;
8580b57cec5SDimitry Andric     }
8590b57cec5SDimitry Andric     NewSIW.setSuccessorWeight(0, SW);
8600b57cec5SDimitry Andric   }
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   // If we ended up with a common successor for every path through the switch
8630b57cec5SDimitry Andric   // after unswitching, rewrite it to an unconditional branch to make it easy
8640b57cec5SDimitry Andric   // to recognize. Otherwise we potentially have to recognize the default case
8650b57cec5SDimitry Andric   // pointing at unreachable and other complexity.
8660b57cec5SDimitry Andric   if (CommonSuccBB) {
8670b57cec5SDimitry Andric     BasicBlock *BB = SI.getParent();
8680b57cec5SDimitry Andric     // We may have had multiple edges to this common successor block, so remove
8690b57cec5SDimitry Andric     // them as predecessors. We skip the first one, either the default or the
8700b57cec5SDimitry Andric     // actual first case.
8710b57cec5SDimitry Andric     bool SkippedFirst = DefaultExitBB == nullptr;
8720b57cec5SDimitry Andric     for (auto Case : SI.cases()) {
8730b57cec5SDimitry Andric       assert(Case.getCaseSuccessor() == CommonSuccBB &&
8740b57cec5SDimitry Andric              "Non-common successor!");
8750b57cec5SDimitry Andric       (void)Case;
8760b57cec5SDimitry Andric       if (!SkippedFirst) {
8770b57cec5SDimitry Andric         SkippedFirst = true;
8780b57cec5SDimitry Andric         continue;
8790b57cec5SDimitry Andric       }
8800b57cec5SDimitry Andric       CommonSuccBB->removePredecessor(BB,
8810b57cec5SDimitry Andric                                       /*KeepOneInputPHIs*/ true);
8820b57cec5SDimitry Andric     }
8830b57cec5SDimitry Andric     // Now nuke the switch and replace it with a direct branch.
8840b57cec5SDimitry Andric     SIW.eraseFromParent();
8850b57cec5SDimitry Andric     BranchInst::Create(CommonSuccBB, BB);
8860b57cec5SDimitry Andric   } else if (DefaultExitBB) {
8870b57cec5SDimitry Andric     assert(SI.getNumCases() > 0 &&
8880b57cec5SDimitry Andric            "If we had no cases we'd have a common successor!");
8890b57cec5SDimitry Andric     // Move the last case to the default successor. This is valid as if the
8900b57cec5SDimitry Andric     // default got unswitched it cannot be reached. This has the advantage of
8910b57cec5SDimitry Andric     // being simple and keeping the number of edges from this switch to
8920b57cec5SDimitry Andric     // successors the same, and avoiding any PHI update complexity.
8930b57cec5SDimitry Andric     auto LastCaseI = std::prev(SI.case_end());
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric     SI.setDefaultDest(LastCaseI->getCaseSuccessor());
8960b57cec5SDimitry Andric     SIW.setSuccessorWeight(
8970b57cec5SDimitry Andric         0, SIW.getSuccessorWeight(LastCaseI->getSuccessorIndex()));
8980b57cec5SDimitry Andric     SIW.removeCase(LastCaseI);
8990b57cec5SDimitry Andric   }
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric   // Walk the unswitched exit blocks and the unswitched split blocks and update
9020b57cec5SDimitry Andric   // the dominator tree based on the CFG edits. While we are walking unordered
9030b57cec5SDimitry Andric   // containers here, the API for applyUpdates takes an unordered list of
9040b57cec5SDimitry Andric   // updates and requires them to not contain duplicates.
9050b57cec5SDimitry Andric   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
9060b57cec5SDimitry Andric   for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
9070b57cec5SDimitry Andric     DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
9080b57cec5SDimitry Andric     DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
9090b57cec5SDimitry Andric   }
9100b57cec5SDimitry Andric   for (auto SplitUnswitchedPair : SplitExitBBMap) {
9110b57cec5SDimitry Andric     DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first});
9120b57cec5SDimitry Andric     DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second});
9130b57cec5SDimitry Andric   }
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric   if (MSSAU) {
916af732203SDimitry Andric     MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
9170b57cec5SDimitry Andric     if (VerifyMemorySSA)
9180b57cec5SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
919af732203SDimitry Andric   } else {
920af732203SDimitry Andric     DT.applyUpdates(DTUpdates);
9210b57cec5SDimitry Andric   }
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric   // We may have changed the nesting relationship for this loop so hoist it to
9260b57cec5SDimitry Andric   // its correct parent if needed.
927480093f4SDimitry Andric   hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
9300b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric   ++NumTrivial;
9330b57cec5SDimitry Andric   ++NumSwitches;
9340b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "    done: unswitching trivial switch...\n");
9350b57cec5SDimitry Andric   return true;
9360b57cec5SDimitry Andric }
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric /// This routine scans the loop to find a branch or switch which occurs before
9390b57cec5SDimitry Andric /// any side effects occur. These can potentially be unswitched without
9400b57cec5SDimitry Andric /// duplicating the loop. If a branch or switch is successfully unswitched the
9410b57cec5SDimitry Andric /// scanning continues to see if subsequent branches or switches have become
9420b57cec5SDimitry Andric /// trivial. Once all trivial candidates have been unswitched, this routine
9430b57cec5SDimitry Andric /// returns.
9440b57cec5SDimitry Andric ///
9450b57cec5SDimitry Andric /// The return value indicates whether anything was unswitched (and therefore
9460b57cec5SDimitry Andric /// changed).
9470b57cec5SDimitry Andric ///
9480b57cec5SDimitry Andric /// If `SE` is not null, it will be updated based on the potential loop SCEVs
9490b57cec5SDimitry Andric /// invalidated by this.
unswitchAllTrivialConditions(Loop & L,DominatorTree & DT,LoopInfo & LI,ScalarEvolution * SE,MemorySSAUpdater * MSSAU)9500b57cec5SDimitry Andric static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
9510b57cec5SDimitry Andric                                          LoopInfo &LI, ScalarEvolution *SE,
9520b57cec5SDimitry Andric                                          MemorySSAUpdater *MSSAU) {
9530b57cec5SDimitry Andric   bool Changed = false;
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric   // If loop header has only one reachable successor we should keep looking for
9560b57cec5SDimitry Andric   // trivial condition candidates in the successor as well. An alternative is
9570b57cec5SDimitry Andric   // to constant fold conditions and merge successors into loop header (then we
9580b57cec5SDimitry Andric   // only need to check header's terminator). The reason for not doing this in
9590b57cec5SDimitry Andric   // LoopUnswitch pass is that it could potentially break LoopPassManager's
9600b57cec5SDimitry Andric   // invariants. Folding dead branches could either eliminate the current loop
9610b57cec5SDimitry Andric   // or make other loops unreachable. LCSSA form might also not be preserved
9620b57cec5SDimitry Andric   // after deleting branches. The following code keeps traversing loop header's
9630b57cec5SDimitry Andric   // successors until it finds the trivial condition candidate (condition that
9640b57cec5SDimitry Andric   // is not a constant). Since unswitching generates branches with constant
9650b57cec5SDimitry Andric   // conditions, this scenario could be very common in practice.
9660b57cec5SDimitry Andric   BasicBlock *CurrentBB = L.getHeader();
9670b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 8> Visited;
9680b57cec5SDimitry Andric   Visited.insert(CurrentBB);
9690b57cec5SDimitry Andric   do {
9700b57cec5SDimitry Andric     // Check if there are any side-effecting instructions (e.g. stores, calls,
9710b57cec5SDimitry Andric     // volatile loads) in the part of the loop that the code *would* execute
9720b57cec5SDimitry Andric     // without unswitching.
9730b57cec5SDimitry Andric     if (MSSAU) // Possible early exit with MSSA
9740b57cec5SDimitry Andric       if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
9750b57cec5SDimitry Andric         if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
9760b57cec5SDimitry Andric           return Changed;
9770b57cec5SDimitry Andric     if (llvm::any_of(*CurrentBB,
9780b57cec5SDimitry Andric                      [](Instruction &I) { return I.mayHaveSideEffects(); }))
9790b57cec5SDimitry Andric       return Changed;
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric     Instruction *CurrentTerm = CurrentBB->getTerminator();
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric     if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
9840b57cec5SDimitry Andric       // Don't bother trying to unswitch past a switch with a constant
9850b57cec5SDimitry Andric       // condition. This should be removed prior to running this pass by
9865f7ddb14SDimitry Andric       // simplifycfg.
9870b57cec5SDimitry Andric       if (isa<Constant>(SI->getCondition()))
9880b57cec5SDimitry Andric         return Changed;
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric       if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
9910b57cec5SDimitry Andric         // Couldn't unswitch this one so we're done.
9920b57cec5SDimitry Andric         return Changed;
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric       // Mark that we managed to unswitch something.
9950b57cec5SDimitry Andric       Changed = true;
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric       // If unswitching turned the terminator into an unconditional branch then
9980b57cec5SDimitry Andric       // we can continue. The unswitching logic specifically works to fold any
9990b57cec5SDimitry Andric       // cases it can into an unconditional branch to make it easier to
10000b57cec5SDimitry Andric       // recognize here.
10010b57cec5SDimitry Andric       auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
10020b57cec5SDimitry Andric       if (!BI || BI->isConditional())
10030b57cec5SDimitry Andric         return Changed;
10040b57cec5SDimitry Andric 
10050b57cec5SDimitry Andric       CurrentBB = BI->getSuccessor(0);
10060b57cec5SDimitry Andric       continue;
10070b57cec5SDimitry Andric     }
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric     auto *BI = dyn_cast<BranchInst>(CurrentTerm);
10100b57cec5SDimitry Andric     if (!BI)
10110b57cec5SDimitry Andric       // We do not understand other terminator instructions.
10120b57cec5SDimitry Andric       return Changed;
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric     // Don't bother trying to unswitch past an unconditional branch or a branch
10155f7ddb14SDimitry Andric     // with a constant value. These should be removed by simplifycfg prior to
10160b57cec5SDimitry Andric     // running this pass.
10170b57cec5SDimitry Andric     if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
10180b57cec5SDimitry Andric       return Changed;
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric     // Found a trivial condition candidate: non-foldable conditional branch. If
10210b57cec5SDimitry Andric     // we fail to unswitch this, we can't do anything else that is trivial.
10220b57cec5SDimitry Andric     if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
10230b57cec5SDimitry Andric       return Changed;
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric     // Mark that we managed to unswitch something.
10260b57cec5SDimitry Andric     Changed = true;
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric     // If we only unswitched some of the conditions feeding the branch, we won't
10290b57cec5SDimitry Andric     // have collapsed it to a single successor.
10300b57cec5SDimitry Andric     BI = cast<BranchInst>(CurrentBB->getTerminator());
10310b57cec5SDimitry Andric     if (BI->isConditional())
10320b57cec5SDimitry Andric       return Changed;
10330b57cec5SDimitry Andric 
10340b57cec5SDimitry Andric     // Follow the newly unconditional branch into its successor.
10350b57cec5SDimitry Andric     CurrentBB = BI->getSuccessor(0);
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric     // When continuing, if we exit the loop or reach a previous visited block,
10380b57cec5SDimitry Andric     // then we can not reach any trivial condition candidates (unfoldable
10390b57cec5SDimitry Andric     // branch instructions or switch instructions) and no unswitch can happen.
10400b57cec5SDimitry Andric   } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric   return Changed;
10430b57cec5SDimitry Andric }
10440b57cec5SDimitry Andric 
10450b57cec5SDimitry Andric /// Build the cloned blocks for an unswitched copy of the given loop.
10460b57cec5SDimitry Andric ///
10470b57cec5SDimitry Andric /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
10480b57cec5SDimitry Andric /// after the split block (`SplitBB`) that will be used to select between the
10490b57cec5SDimitry Andric /// cloned and original loop.
10500b57cec5SDimitry Andric ///
10510b57cec5SDimitry Andric /// This routine handles cloning all of the necessary loop blocks and exit
10520b57cec5SDimitry Andric /// blocks including rewriting their instructions and the relevant PHI nodes.
10530b57cec5SDimitry Andric /// Any loop blocks or exit blocks which are dominated by a different successor
10540b57cec5SDimitry Andric /// than the one for this clone of the loop blocks can be trivially skipped. We
10550b57cec5SDimitry Andric /// use the `DominatingSucc` map to determine whether a block satisfies that
10560b57cec5SDimitry Andric /// property with a simple map lookup.
10570b57cec5SDimitry Andric ///
10580b57cec5SDimitry Andric /// It also correctly creates the unconditional branch in the cloned
10590b57cec5SDimitry Andric /// unswitched parent block to only point at the unswitched successor.
10600b57cec5SDimitry Andric ///
10610b57cec5SDimitry Andric /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
10620b57cec5SDimitry Andric /// block splitting is correctly reflected in `LoopInfo`, essentially all of
10630b57cec5SDimitry Andric /// the cloned blocks (and their loops) are left without full `LoopInfo`
10640b57cec5SDimitry Andric /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
10650b57cec5SDimitry Andric /// blocks to them but doesn't create the cloned `DominatorTree` structure and
10660b57cec5SDimitry Andric /// instead the caller must recompute an accurate DT. It *does* correctly
10670b57cec5SDimitry Andric /// update the `AssumptionCache` provided in `AC`.
buildClonedLoopBlocks(Loop & L,BasicBlock * LoopPH,BasicBlock * SplitBB,ArrayRef<BasicBlock * > ExitBlocks,BasicBlock * ParentBB,BasicBlock * UnswitchedSuccBB,BasicBlock * ContinueSuccBB,const SmallDenseMap<BasicBlock *,BasicBlock *,16> & DominatingSucc,ValueToValueMapTy & VMap,SmallVectorImpl<DominatorTree::UpdateType> & DTUpdates,AssumptionCache & AC,DominatorTree & DT,LoopInfo & LI,MemorySSAUpdater * MSSAU)10680b57cec5SDimitry Andric static BasicBlock *buildClonedLoopBlocks(
10690b57cec5SDimitry Andric     Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
10700b57cec5SDimitry Andric     ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
10710b57cec5SDimitry Andric     BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
10720b57cec5SDimitry Andric     const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
10730b57cec5SDimitry Andric     ValueToValueMapTy &VMap,
10740b57cec5SDimitry Andric     SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
10750b57cec5SDimitry Andric     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
10760b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> NewBlocks;
10770b57cec5SDimitry Andric   NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
10780b57cec5SDimitry Andric 
10790b57cec5SDimitry Andric   // We will need to clone a bunch of blocks, wrap up the clone operation in
10800b57cec5SDimitry Andric   // a helper.
10810b57cec5SDimitry Andric   auto CloneBlock = [&](BasicBlock *OldBB) {
10820b57cec5SDimitry Andric     // Clone the basic block and insert it before the new preheader.
10830b57cec5SDimitry Andric     BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
10840b57cec5SDimitry Andric     NewBB->moveBefore(LoopPH);
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric     // Record this block and the mapping.
10870b57cec5SDimitry Andric     NewBlocks.push_back(NewBB);
10880b57cec5SDimitry Andric     VMap[OldBB] = NewBB;
10890b57cec5SDimitry Andric 
10900b57cec5SDimitry Andric     return NewBB;
10910b57cec5SDimitry Andric   };
10920b57cec5SDimitry Andric 
10930b57cec5SDimitry Andric   // We skip cloning blocks when they have a dominating succ that is not the
10940b57cec5SDimitry Andric   // succ we are cloning for.
10950b57cec5SDimitry Andric   auto SkipBlock = [&](BasicBlock *BB) {
10960b57cec5SDimitry Andric     auto It = DominatingSucc.find(BB);
10970b57cec5SDimitry Andric     return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
10980b57cec5SDimitry Andric   };
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric   // First, clone the preheader.
11010b57cec5SDimitry Andric   auto *ClonedPH = CloneBlock(LoopPH);
11020b57cec5SDimitry Andric 
11030b57cec5SDimitry Andric   // Then clone all the loop blocks, skipping the ones that aren't necessary.
11040b57cec5SDimitry Andric   for (auto *LoopBB : L.blocks())
11050b57cec5SDimitry Andric     if (!SkipBlock(LoopBB))
11060b57cec5SDimitry Andric       CloneBlock(LoopBB);
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric   // Split all the loop exit edges so that when we clone the exit blocks, if
11090b57cec5SDimitry Andric   // any of the exit blocks are *also* a preheader for some other loop, we
11100b57cec5SDimitry Andric   // don't create multiple predecessors entering the loop header.
11110b57cec5SDimitry Andric   for (auto *ExitBB : ExitBlocks) {
11120b57cec5SDimitry Andric     if (SkipBlock(ExitBB))
11130b57cec5SDimitry Andric       continue;
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric     // When we are going to clone an exit, we don't need to clone all the
11160b57cec5SDimitry Andric     // instructions in the exit block and we want to ensure we have an easy
11170b57cec5SDimitry Andric     // place to merge the CFG, so split the exit first. This is always safe to
11180b57cec5SDimitry Andric     // do because there cannot be any non-loop predecessors of a loop exit in
11190b57cec5SDimitry Andric     // loop simplified form.
11200b57cec5SDimitry Andric     auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric     // Rearrange the names to make it easier to write test cases by having the
11230b57cec5SDimitry Andric     // exit block carry the suffix rather than the merge block carrying the
11240b57cec5SDimitry Andric     // suffix.
11250b57cec5SDimitry Andric     MergeBB->takeName(ExitBB);
11260b57cec5SDimitry Andric     ExitBB->setName(Twine(MergeBB->getName()) + ".split");
11270b57cec5SDimitry Andric 
11280b57cec5SDimitry Andric     // Now clone the original exit block.
11290b57cec5SDimitry Andric     auto *ClonedExitBB = CloneBlock(ExitBB);
11300b57cec5SDimitry Andric     assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
11310b57cec5SDimitry Andric            "Exit block should have been split to have one successor!");
11320b57cec5SDimitry Andric     assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
11330b57cec5SDimitry Andric            "Cloned exit block has the wrong successor!");
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric     // Remap any cloned instructions and create a merge phi node for them.
11360b57cec5SDimitry Andric     for (auto ZippedInsts : llvm::zip_first(
11370b57cec5SDimitry Andric              llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
11380b57cec5SDimitry Andric              llvm::make_range(ClonedExitBB->begin(),
11390b57cec5SDimitry Andric                               std::prev(ClonedExitBB->end())))) {
11400b57cec5SDimitry Andric       Instruction &I = std::get<0>(ZippedInsts);
11410b57cec5SDimitry Andric       Instruction &ClonedI = std::get<1>(ZippedInsts);
11420b57cec5SDimitry Andric 
11430b57cec5SDimitry Andric       // The only instructions in the exit block should be PHI nodes and
11440b57cec5SDimitry Andric       // potentially a landing pad.
11450b57cec5SDimitry Andric       assert(
11460b57cec5SDimitry Andric           (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
11470b57cec5SDimitry Andric           "Bad instruction in exit block!");
11480b57cec5SDimitry Andric       // We should have a value map between the instruction and its clone.
11490b57cec5SDimitry Andric       assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric       auto *MergePN =
11520b57cec5SDimitry Andric           PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
11530b57cec5SDimitry Andric                           &*MergeBB->getFirstInsertionPt());
11540b57cec5SDimitry Andric       I.replaceAllUsesWith(MergePN);
11550b57cec5SDimitry Andric       MergePN->addIncoming(&I, ExitBB);
11560b57cec5SDimitry Andric       MergePN->addIncoming(&ClonedI, ClonedExitBB);
11570b57cec5SDimitry Andric     }
11580b57cec5SDimitry Andric   }
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric   // Rewrite the instructions in the cloned blocks to refer to the instructions
11610b57cec5SDimitry Andric   // in the cloned blocks. We have to do this as a second pass so that we have
11620b57cec5SDimitry Andric   // everything available. Also, we have inserted new instructions which may
11630b57cec5SDimitry Andric   // include assume intrinsics, so we update the assumption cache while
11640b57cec5SDimitry Andric   // processing this.
11650b57cec5SDimitry Andric   for (auto *ClonedBB : NewBlocks)
11660b57cec5SDimitry Andric     for (Instruction &I : *ClonedBB) {
11670b57cec5SDimitry Andric       RemapInstruction(&I, VMap,
11680b57cec5SDimitry Andric                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
11695f7ddb14SDimitry Andric       if (auto *II = dyn_cast<AssumeInst>(&I))
11700b57cec5SDimitry Andric         AC.registerAssumption(II);
11710b57cec5SDimitry Andric     }
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric   // Update any PHI nodes in the cloned successors of the skipped blocks to not
11740b57cec5SDimitry Andric   // have spurious incoming values.
11750b57cec5SDimitry Andric   for (auto *LoopBB : L.blocks())
11760b57cec5SDimitry Andric     if (SkipBlock(LoopBB))
11770b57cec5SDimitry Andric       for (auto *SuccBB : successors(LoopBB))
11780b57cec5SDimitry Andric         if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
11790b57cec5SDimitry Andric           for (PHINode &PN : ClonedSuccBB->phis())
11800b57cec5SDimitry Andric             PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
11810b57cec5SDimitry Andric 
11820b57cec5SDimitry Andric   // Remove the cloned parent as a predecessor of any successor we ended up
11830b57cec5SDimitry Andric   // cloning other than the unswitched one.
11840b57cec5SDimitry Andric   auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
11850b57cec5SDimitry Andric   for (auto *SuccBB : successors(ParentBB)) {
11860b57cec5SDimitry Andric     if (SuccBB == UnswitchedSuccBB)
11870b57cec5SDimitry Andric       continue;
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric     auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
11900b57cec5SDimitry Andric     if (!ClonedSuccBB)
11910b57cec5SDimitry Andric       continue;
11920b57cec5SDimitry Andric 
11930b57cec5SDimitry Andric     ClonedSuccBB->removePredecessor(ClonedParentBB,
11940b57cec5SDimitry Andric                                     /*KeepOneInputPHIs*/ true);
11950b57cec5SDimitry Andric   }
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric   // Replace the cloned branch with an unconditional branch to the cloned
11980b57cec5SDimitry Andric   // unswitched successor.
11990b57cec5SDimitry Andric   auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1200af732203SDimitry Andric   Instruction *ClonedTerminator = ClonedParentBB->getTerminator();
1201af732203SDimitry Andric   // Trivial Simplification. If Terminator is a conditional branch and
1202af732203SDimitry Andric   // condition becomes dead - erase it.
1203af732203SDimitry Andric   Value *ClonedConditionToErase = nullptr;
1204af732203SDimitry Andric   if (auto *BI = dyn_cast<BranchInst>(ClonedTerminator))
1205af732203SDimitry Andric     ClonedConditionToErase = BI->getCondition();
1206af732203SDimitry Andric   else if (auto *SI = dyn_cast<SwitchInst>(ClonedTerminator))
1207af732203SDimitry Andric     ClonedConditionToErase = SI->getCondition();
1208af732203SDimitry Andric 
1209af732203SDimitry Andric   ClonedTerminator->eraseFromParent();
12100b57cec5SDimitry Andric   BranchInst::Create(ClonedSuccBB, ClonedParentBB);
12110b57cec5SDimitry Andric 
1212af732203SDimitry Andric   if (ClonedConditionToErase)
1213af732203SDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(ClonedConditionToErase, nullptr,
1214af732203SDimitry Andric                                                MSSAU);
1215af732203SDimitry Andric 
12160b57cec5SDimitry Andric   // If there are duplicate entries in the PHI nodes because of multiple edges
12170b57cec5SDimitry Andric   // to the unswitched successor, we need to nuke all but one as we replaced it
12180b57cec5SDimitry Andric   // with a direct branch.
12190b57cec5SDimitry Andric   for (PHINode &PN : ClonedSuccBB->phis()) {
12200b57cec5SDimitry Andric     bool Found = false;
12210b57cec5SDimitry Andric     // Loop over the incoming operands backwards so we can easily delete as we
12220b57cec5SDimitry Andric     // go without invalidating the index.
12230b57cec5SDimitry Andric     for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
12240b57cec5SDimitry Andric       if (PN.getIncomingBlock(i) != ClonedParentBB)
12250b57cec5SDimitry Andric         continue;
12260b57cec5SDimitry Andric       if (!Found) {
12270b57cec5SDimitry Andric         Found = true;
12280b57cec5SDimitry Andric         continue;
12290b57cec5SDimitry Andric       }
12300b57cec5SDimitry Andric       PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
12310b57cec5SDimitry Andric     }
12320b57cec5SDimitry Andric   }
12330b57cec5SDimitry Andric 
12340b57cec5SDimitry Andric   // Record the domtree updates for the new blocks.
12350b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 4> SuccSet;
12360b57cec5SDimitry Andric   for (auto *ClonedBB : NewBlocks) {
12370b57cec5SDimitry Andric     for (auto *SuccBB : successors(ClonedBB))
12380b57cec5SDimitry Andric       if (SuccSet.insert(SuccBB).second)
12390b57cec5SDimitry Andric         DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
12400b57cec5SDimitry Andric     SuccSet.clear();
12410b57cec5SDimitry Andric   }
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric   return ClonedPH;
12440b57cec5SDimitry Andric }
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric /// Recursively clone the specified loop and all of its children.
12470b57cec5SDimitry Andric ///
12480b57cec5SDimitry Andric /// The target parent loop for the clone should be provided, or can be null if
12490b57cec5SDimitry Andric /// the clone is a top-level loop. While cloning, all the blocks are mapped
12500b57cec5SDimitry Andric /// with the provided value map. The entire original loop must be present in
12510b57cec5SDimitry Andric /// the value map. The cloned loop is returned.
cloneLoopNest(Loop & OrigRootL,Loop * RootParentL,const ValueToValueMapTy & VMap,LoopInfo & LI)12520b57cec5SDimitry Andric static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
12530b57cec5SDimitry Andric                            const ValueToValueMapTy &VMap, LoopInfo &LI) {
12540b57cec5SDimitry Andric   auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
12550b57cec5SDimitry Andric     assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
12560b57cec5SDimitry Andric     ClonedL.reserveBlocks(OrigL.getNumBlocks());
12570b57cec5SDimitry Andric     for (auto *BB : OrigL.blocks()) {
12580b57cec5SDimitry Andric       auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
12590b57cec5SDimitry Andric       ClonedL.addBlockEntry(ClonedBB);
12600b57cec5SDimitry Andric       if (LI.getLoopFor(BB) == &OrigL)
12610b57cec5SDimitry Andric         LI.changeLoopFor(ClonedBB, &ClonedL);
12620b57cec5SDimitry Andric     }
12630b57cec5SDimitry Andric   };
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric   // We specially handle the first loop because it may get cloned into
12660b57cec5SDimitry Andric   // a different parent and because we most commonly are cloning leaf loops.
12670b57cec5SDimitry Andric   Loop *ClonedRootL = LI.AllocateLoop();
12680b57cec5SDimitry Andric   if (RootParentL)
12690b57cec5SDimitry Andric     RootParentL->addChildLoop(ClonedRootL);
12700b57cec5SDimitry Andric   else
12710b57cec5SDimitry Andric     LI.addTopLevelLoop(ClonedRootL);
12720b57cec5SDimitry Andric   AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
12730b57cec5SDimitry Andric 
1274af732203SDimitry Andric   if (OrigRootL.isInnermost())
12750b57cec5SDimitry Andric     return ClonedRootL;
12760b57cec5SDimitry Andric 
12770b57cec5SDimitry Andric   // If we have a nest, we can quickly clone the entire loop nest using an
12780b57cec5SDimitry Andric   // iterative approach because it is a tree. We keep the cloned parent in the
12790b57cec5SDimitry Andric   // data structure to avoid repeatedly querying through a map to find it.
12800b57cec5SDimitry Andric   SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
12810b57cec5SDimitry Andric   // Build up the loops to clone in reverse order as we'll clone them from the
12820b57cec5SDimitry Andric   // back.
12830b57cec5SDimitry Andric   for (Loop *ChildL : llvm::reverse(OrigRootL))
12840b57cec5SDimitry Andric     LoopsToClone.push_back({ClonedRootL, ChildL});
12850b57cec5SDimitry Andric   do {
12860b57cec5SDimitry Andric     Loop *ClonedParentL, *L;
12870b57cec5SDimitry Andric     std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
12880b57cec5SDimitry Andric     Loop *ClonedL = LI.AllocateLoop();
12890b57cec5SDimitry Andric     ClonedParentL->addChildLoop(ClonedL);
12900b57cec5SDimitry Andric     AddClonedBlocksToLoop(*L, *ClonedL);
12910b57cec5SDimitry Andric     for (Loop *ChildL : llvm::reverse(*L))
12920b57cec5SDimitry Andric       LoopsToClone.push_back({ClonedL, ChildL});
12930b57cec5SDimitry Andric   } while (!LoopsToClone.empty());
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric   return ClonedRootL;
12960b57cec5SDimitry Andric }
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric /// Build the cloned loops of an original loop from unswitching.
12990b57cec5SDimitry Andric ///
13000b57cec5SDimitry Andric /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
13010b57cec5SDimitry Andric /// operation. We need to re-verify that there even is a loop (as the backedge
13020b57cec5SDimitry Andric /// may not have been cloned), and even if there are remaining backedges the
13030b57cec5SDimitry Andric /// backedge set may be different. However, we know that each child loop is
13040b57cec5SDimitry Andric /// undisturbed, we only need to find where to place each child loop within
13050b57cec5SDimitry Andric /// either any parent loop or within a cloned version of the original loop.
13060b57cec5SDimitry Andric ///
13070b57cec5SDimitry Andric /// Because child loops may end up cloned outside of any cloned version of the
13080b57cec5SDimitry Andric /// original loop, multiple cloned sibling loops may be created. All of them
13090b57cec5SDimitry Andric /// are returned so that the newly introduced loop nest roots can be
13100b57cec5SDimitry Andric /// identified.
buildClonedLoops(Loop & OrigL,ArrayRef<BasicBlock * > ExitBlocks,const ValueToValueMapTy & VMap,LoopInfo & LI,SmallVectorImpl<Loop * > & NonChildClonedLoops)13110b57cec5SDimitry Andric static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
13120b57cec5SDimitry Andric                              const ValueToValueMapTy &VMap, LoopInfo &LI,
13130b57cec5SDimitry Andric                              SmallVectorImpl<Loop *> &NonChildClonedLoops) {
13140b57cec5SDimitry Andric   Loop *ClonedL = nullptr;
13150b57cec5SDimitry Andric 
13160b57cec5SDimitry Andric   auto *OrigPH = OrigL.getLoopPreheader();
13170b57cec5SDimitry Andric   auto *OrigHeader = OrigL.getHeader();
13180b57cec5SDimitry Andric 
13190b57cec5SDimitry Andric   auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
13200b57cec5SDimitry Andric   auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric   // We need to know the loops of the cloned exit blocks to even compute the
13230b57cec5SDimitry Andric   // accurate parent loop. If we only clone exits to some parent of the
13240b57cec5SDimitry Andric   // original parent, we want to clone into that outer loop. We also keep track
13250b57cec5SDimitry Andric   // of the loops that our cloned exit blocks participate in.
13260b57cec5SDimitry Andric   Loop *ParentL = nullptr;
13270b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
13280b57cec5SDimitry Andric   SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
13290b57cec5SDimitry Andric   ClonedExitsInLoops.reserve(ExitBlocks.size());
13300b57cec5SDimitry Andric   for (auto *ExitBB : ExitBlocks)
13310b57cec5SDimitry Andric     if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
13320b57cec5SDimitry Andric       if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
13330b57cec5SDimitry Andric         ExitLoopMap[ClonedExitBB] = ExitL;
13340b57cec5SDimitry Andric         ClonedExitsInLoops.push_back(ClonedExitBB);
13350b57cec5SDimitry Andric         if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
13360b57cec5SDimitry Andric           ParentL = ExitL;
13370b57cec5SDimitry Andric       }
13380b57cec5SDimitry Andric   assert((!ParentL || ParentL == OrigL.getParentLoop() ||
13390b57cec5SDimitry Andric           ParentL->contains(OrigL.getParentLoop())) &&
13400b57cec5SDimitry Andric          "The computed parent loop should always contain (or be) the parent of "
13410b57cec5SDimitry Andric          "the original loop.");
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric   // We build the set of blocks dominated by the cloned header from the set of
13440b57cec5SDimitry Andric   // cloned blocks out of the original loop. While not all of these will
13450b57cec5SDimitry Andric   // necessarily be in the cloned loop, it is enough to establish that they
13460b57cec5SDimitry Andric   // aren't in unreachable cycles, etc.
13470b57cec5SDimitry Andric   SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
13480b57cec5SDimitry Andric   for (auto *BB : OrigL.blocks())
13490b57cec5SDimitry Andric     if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
13500b57cec5SDimitry Andric       ClonedLoopBlocks.insert(ClonedBB);
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric   // Rebuild the set of blocks that will end up in the cloned loop. We may have
13530b57cec5SDimitry Andric   // skipped cloning some region of this loop which can in turn skip some of
13540b57cec5SDimitry Andric   // the backedges so we have to rebuild the blocks in the loop based on the
13550b57cec5SDimitry Andric   // backedges that remain after cloning.
13560b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> Worklist;
13570b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
13580b57cec5SDimitry Andric   for (auto *Pred : predecessors(ClonedHeader)) {
13590b57cec5SDimitry Andric     // The only possible non-loop header predecessor is the preheader because
13600b57cec5SDimitry Andric     // we know we cloned the loop in simplified form.
13610b57cec5SDimitry Andric     if (Pred == ClonedPH)
13620b57cec5SDimitry Andric       continue;
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric     // Because the loop was in simplified form, the only non-loop predecessor
13650b57cec5SDimitry Andric     // should be the preheader.
13660b57cec5SDimitry Andric     assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
13670b57cec5SDimitry Andric                                            "header other than the preheader "
13680b57cec5SDimitry Andric                                            "that is not part of the loop!");
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric     // Insert this block into the loop set and on the first visit (and if it
13710b57cec5SDimitry Andric     // isn't the header we're currently walking) put it into the worklist to
13720b57cec5SDimitry Andric     // recurse through.
13730b57cec5SDimitry Andric     if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
13740b57cec5SDimitry Andric       Worklist.push_back(Pred);
13750b57cec5SDimitry Andric   }
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric   // If we had any backedges then there *is* a cloned loop. Put the header into
13780b57cec5SDimitry Andric   // the loop set and then walk the worklist backwards to find all the blocks
13790b57cec5SDimitry Andric   // that remain within the loop after cloning.
13800b57cec5SDimitry Andric   if (!BlocksInClonedLoop.empty()) {
13810b57cec5SDimitry Andric     BlocksInClonedLoop.insert(ClonedHeader);
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric     while (!Worklist.empty()) {
13840b57cec5SDimitry Andric       BasicBlock *BB = Worklist.pop_back_val();
13850b57cec5SDimitry Andric       assert(BlocksInClonedLoop.count(BB) &&
13860b57cec5SDimitry Andric              "Didn't put block into the loop set!");
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric       // Insert any predecessors that are in the possible set into the cloned
13890b57cec5SDimitry Andric       // set, and if the insert is successful, add them to the worklist. Note
13900b57cec5SDimitry Andric       // that we filter on the blocks that are definitely reachable via the
13910b57cec5SDimitry Andric       // backedge to the loop header so we may prune out dead code within the
13920b57cec5SDimitry Andric       // cloned loop.
13930b57cec5SDimitry Andric       for (auto *Pred : predecessors(BB))
13940b57cec5SDimitry Andric         if (ClonedLoopBlocks.count(Pred) &&
13950b57cec5SDimitry Andric             BlocksInClonedLoop.insert(Pred).second)
13960b57cec5SDimitry Andric           Worklist.push_back(Pred);
13970b57cec5SDimitry Andric     }
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric     ClonedL = LI.AllocateLoop();
14000b57cec5SDimitry Andric     if (ParentL) {
14010b57cec5SDimitry Andric       ParentL->addBasicBlockToLoop(ClonedPH, LI);
14020b57cec5SDimitry Andric       ParentL->addChildLoop(ClonedL);
14030b57cec5SDimitry Andric     } else {
14040b57cec5SDimitry Andric       LI.addTopLevelLoop(ClonedL);
14050b57cec5SDimitry Andric     }
14060b57cec5SDimitry Andric     NonChildClonedLoops.push_back(ClonedL);
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric     ClonedL->reserveBlocks(BlocksInClonedLoop.size());
14090b57cec5SDimitry Andric     // We don't want to just add the cloned loop blocks based on how we
14100b57cec5SDimitry Andric     // discovered them. The original order of blocks was carefully built in
14110b57cec5SDimitry Andric     // a way that doesn't rely on predecessor ordering. Rather than re-invent
14120b57cec5SDimitry Andric     // that logic, we just re-walk the original blocks (and those of the child
14130b57cec5SDimitry Andric     // loops) and filter them as we add them into the cloned loop.
14140b57cec5SDimitry Andric     for (auto *BB : OrigL.blocks()) {
14150b57cec5SDimitry Andric       auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
14160b57cec5SDimitry Andric       if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
14170b57cec5SDimitry Andric         continue;
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric       // Directly add the blocks that are only in this loop.
14200b57cec5SDimitry Andric       if (LI.getLoopFor(BB) == &OrigL) {
14210b57cec5SDimitry Andric         ClonedL->addBasicBlockToLoop(ClonedBB, LI);
14220b57cec5SDimitry Andric         continue;
14230b57cec5SDimitry Andric       }
14240b57cec5SDimitry Andric 
14250b57cec5SDimitry Andric       // We want to manually add it to this loop and parents.
14260b57cec5SDimitry Andric       // Registering it with LoopInfo will happen when we clone the top
14270b57cec5SDimitry Andric       // loop for this block.
14280b57cec5SDimitry Andric       for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
14290b57cec5SDimitry Andric         PL->addBlockEntry(ClonedBB);
14300b57cec5SDimitry Andric     }
14310b57cec5SDimitry Andric 
14320b57cec5SDimitry Andric     // Now add each child loop whose header remains within the cloned loop. All
14330b57cec5SDimitry Andric     // of the blocks within the loop must satisfy the same constraints as the
14340b57cec5SDimitry Andric     // header so once we pass the header checks we can just clone the entire
14350b57cec5SDimitry Andric     // child loop nest.
14360b57cec5SDimitry Andric     for (Loop *ChildL : OrigL) {
14370b57cec5SDimitry Andric       auto *ClonedChildHeader =
14380b57cec5SDimitry Andric           cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
14390b57cec5SDimitry Andric       if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
14400b57cec5SDimitry Andric         continue;
14410b57cec5SDimitry Andric 
14420b57cec5SDimitry Andric #ifndef NDEBUG
14430b57cec5SDimitry Andric       // We should never have a cloned child loop header but fail to have
14440b57cec5SDimitry Andric       // all of the blocks for that child loop.
14450b57cec5SDimitry Andric       for (auto *ChildLoopBB : ChildL->blocks())
14460b57cec5SDimitry Andric         assert(BlocksInClonedLoop.count(
14470b57cec5SDimitry Andric                    cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
14480b57cec5SDimitry Andric                "Child cloned loop has a header within the cloned outer "
14490b57cec5SDimitry Andric                "loop but not all of its blocks!");
14500b57cec5SDimitry Andric #endif
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric       cloneLoopNest(*ChildL, ClonedL, VMap, LI);
14530b57cec5SDimitry Andric     }
14540b57cec5SDimitry Andric   }
14550b57cec5SDimitry Andric 
14560b57cec5SDimitry Andric   // Now that we've handled all the components of the original loop that were
14570b57cec5SDimitry Andric   // cloned into a new loop, we still need to handle anything from the original
14580b57cec5SDimitry Andric   // loop that wasn't in a cloned loop.
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   // Figure out what blocks are left to place within any loop nest containing
14610b57cec5SDimitry Andric   // the unswitched loop. If we never formed a loop, the cloned PH is one of
14620b57cec5SDimitry Andric   // them.
14630b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
14640b57cec5SDimitry Andric   if (BlocksInClonedLoop.empty())
14650b57cec5SDimitry Andric     UnloopedBlockSet.insert(ClonedPH);
14660b57cec5SDimitry Andric   for (auto *ClonedBB : ClonedLoopBlocks)
14670b57cec5SDimitry Andric     if (!BlocksInClonedLoop.count(ClonedBB))
14680b57cec5SDimitry Andric       UnloopedBlockSet.insert(ClonedBB);
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric   // Copy the cloned exits and sort them in ascending loop depth, we'll work
14710b57cec5SDimitry Andric   // backwards across these to process them inside out. The order shouldn't
14720b57cec5SDimitry Andric   // matter as we're just trying to build up the map from inside-out; we use
14730b57cec5SDimitry Andric   // the map in a more stably ordered way below.
14740b57cec5SDimitry Andric   auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
14750b57cec5SDimitry Andric   llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
14760b57cec5SDimitry Andric     return ExitLoopMap.lookup(LHS)->getLoopDepth() <
14770b57cec5SDimitry Andric            ExitLoopMap.lookup(RHS)->getLoopDepth();
14780b57cec5SDimitry Andric   });
14790b57cec5SDimitry Andric 
14800b57cec5SDimitry Andric   // Populate the existing ExitLoopMap with everything reachable from each
14810b57cec5SDimitry Andric   // exit, starting from the inner most exit.
14820b57cec5SDimitry Andric   while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
14830b57cec5SDimitry Andric     assert(Worklist.empty() && "Didn't clear worklist!");
14840b57cec5SDimitry Andric 
14850b57cec5SDimitry Andric     BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
14860b57cec5SDimitry Andric     Loop *ExitL = ExitLoopMap.lookup(ExitBB);
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric     // Walk the CFG back until we hit the cloned PH adding everything reachable
14890b57cec5SDimitry Andric     // and in the unlooped set to this exit block's loop.
14900b57cec5SDimitry Andric     Worklist.push_back(ExitBB);
14910b57cec5SDimitry Andric     do {
14920b57cec5SDimitry Andric       BasicBlock *BB = Worklist.pop_back_val();
14930b57cec5SDimitry Andric       // We can stop recursing at the cloned preheader (if we get there).
14940b57cec5SDimitry Andric       if (BB == ClonedPH)
14950b57cec5SDimitry Andric         continue;
14960b57cec5SDimitry Andric 
14970b57cec5SDimitry Andric       for (BasicBlock *PredBB : predecessors(BB)) {
14980b57cec5SDimitry Andric         // If this pred has already been moved to our set or is part of some
14990b57cec5SDimitry Andric         // (inner) loop, no update needed.
15000b57cec5SDimitry Andric         if (!UnloopedBlockSet.erase(PredBB)) {
15010b57cec5SDimitry Andric           assert(
15020b57cec5SDimitry Andric               (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
15030b57cec5SDimitry Andric               "Predecessor not mapped to a loop!");
15040b57cec5SDimitry Andric           continue;
15050b57cec5SDimitry Andric         }
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric         // We just insert into the loop set here. We'll add these blocks to the
15080b57cec5SDimitry Andric         // exit loop after we build up the set in an order that doesn't rely on
15090b57cec5SDimitry Andric         // predecessor order (which in turn relies on use list order).
15100b57cec5SDimitry Andric         bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
15110b57cec5SDimitry Andric         (void)Inserted;
15120b57cec5SDimitry Andric         assert(Inserted && "Should only visit an unlooped block once!");
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric         // And recurse through to its predecessors.
15150b57cec5SDimitry Andric         Worklist.push_back(PredBB);
15160b57cec5SDimitry Andric       }
15170b57cec5SDimitry Andric     } while (!Worklist.empty());
15180b57cec5SDimitry Andric   }
15190b57cec5SDimitry Andric 
15200b57cec5SDimitry Andric   // Now that the ExitLoopMap gives as  mapping for all the non-looping cloned
15210b57cec5SDimitry Andric   // blocks to their outer loops, walk the cloned blocks and the cloned exits
15220b57cec5SDimitry Andric   // in their original order adding them to the correct loop.
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric   // We need a stable insertion order. We use the order of the original loop
15250b57cec5SDimitry Andric   // order and map into the correct parent loop.
15260b57cec5SDimitry Andric   for (auto *BB : llvm::concat<BasicBlock *const>(
15270b57cec5SDimitry Andric            makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
15280b57cec5SDimitry Andric     if (Loop *OuterL = ExitLoopMap.lookup(BB))
15290b57cec5SDimitry Andric       OuterL->addBasicBlockToLoop(BB, LI);
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric #ifndef NDEBUG
15320b57cec5SDimitry Andric   for (auto &BBAndL : ExitLoopMap) {
15330b57cec5SDimitry Andric     auto *BB = BBAndL.first;
15340b57cec5SDimitry Andric     auto *OuterL = BBAndL.second;
15350b57cec5SDimitry Andric     assert(LI.getLoopFor(BB) == OuterL &&
15360b57cec5SDimitry Andric            "Failed to put all blocks into outer loops!");
15370b57cec5SDimitry Andric   }
15380b57cec5SDimitry Andric #endif
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric   // Now that all the blocks are placed into the correct containing loop in the
15410b57cec5SDimitry Andric   // absence of child loops, find all the potentially cloned child loops and
15420b57cec5SDimitry Andric   // clone them into whatever outer loop we placed their header into.
15430b57cec5SDimitry Andric   for (Loop *ChildL : OrigL) {
15440b57cec5SDimitry Andric     auto *ClonedChildHeader =
15450b57cec5SDimitry Andric         cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
15460b57cec5SDimitry Andric     if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
15470b57cec5SDimitry Andric       continue;
15480b57cec5SDimitry Andric 
15490b57cec5SDimitry Andric #ifndef NDEBUG
15500b57cec5SDimitry Andric     for (auto *ChildLoopBB : ChildL->blocks())
15510b57cec5SDimitry Andric       assert(VMap.count(ChildLoopBB) &&
15520b57cec5SDimitry Andric              "Cloned a child loop header but not all of that loops blocks!");
15530b57cec5SDimitry Andric #endif
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric     NonChildClonedLoops.push_back(cloneLoopNest(
15560b57cec5SDimitry Andric         *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
15570b57cec5SDimitry Andric   }
15580b57cec5SDimitry Andric }
15590b57cec5SDimitry Andric 
15600b57cec5SDimitry Andric static void
deleteDeadClonedBlocks(Loop & L,ArrayRef<BasicBlock * > ExitBlocks,ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,DominatorTree & DT,MemorySSAUpdater * MSSAU)15610b57cec5SDimitry Andric deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
15620b57cec5SDimitry Andric                        ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
15630b57cec5SDimitry Andric                        DominatorTree &DT, MemorySSAUpdater *MSSAU) {
15640b57cec5SDimitry Andric   // Find all the dead clones, and remove them from their successors.
15650b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> DeadBlocks;
15660b57cec5SDimitry Andric   for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
15670b57cec5SDimitry Andric     for (auto &VMap : VMaps)
15680b57cec5SDimitry Andric       if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
15690b57cec5SDimitry Andric         if (!DT.isReachableFromEntry(ClonedBB)) {
15700b57cec5SDimitry Andric           for (BasicBlock *SuccBB : successors(ClonedBB))
15710b57cec5SDimitry Andric             SuccBB->removePredecessor(ClonedBB);
15720b57cec5SDimitry Andric           DeadBlocks.push_back(ClonedBB);
15730b57cec5SDimitry Andric         }
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric   // Remove all MemorySSA in the dead blocks
15760b57cec5SDimitry Andric   if (MSSAU) {
15770b57cec5SDimitry Andric     SmallSetVector<BasicBlock *, 8> DeadBlockSet(DeadBlocks.begin(),
15780b57cec5SDimitry Andric                                                  DeadBlocks.end());
15790b57cec5SDimitry Andric     MSSAU->removeBlocks(DeadBlockSet);
15800b57cec5SDimitry Andric   }
15810b57cec5SDimitry Andric 
15820b57cec5SDimitry Andric   // Drop any remaining references to break cycles.
15830b57cec5SDimitry Andric   for (BasicBlock *BB : DeadBlocks)
15840b57cec5SDimitry Andric     BB->dropAllReferences();
15850b57cec5SDimitry Andric   // Erase them from the IR.
15860b57cec5SDimitry Andric   for (BasicBlock *BB : DeadBlocks)
15870b57cec5SDimitry Andric     BB->eraseFromParent();
15880b57cec5SDimitry Andric }
15890b57cec5SDimitry Andric 
1590*18baa991SDimitry Andric static void
deleteDeadBlocksFromLoop(Loop & L,SmallVectorImpl<BasicBlock * > & ExitBlocks,DominatorTree & DT,LoopInfo & LI,MemorySSAUpdater * MSSAU,function_ref<void (Loop &,StringRef)> DestroyLoopCB)1591*18baa991SDimitry Andric deleteDeadBlocksFromLoop(Loop &L,
15920b57cec5SDimitry Andric                          SmallVectorImpl<BasicBlock *> &ExitBlocks,
15930b57cec5SDimitry Andric                          DominatorTree &DT, LoopInfo &LI,
1594*18baa991SDimitry Andric                          MemorySSAUpdater *MSSAU,
1595*18baa991SDimitry Andric                          function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
15960b57cec5SDimitry Andric   // Find all the dead blocks tied to this loop, and remove them from their
15970b57cec5SDimitry Andric   // successors.
15980b57cec5SDimitry Andric   SmallSetVector<BasicBlock *, 8> DeadBlockSet;
15990b57cec5SDimitry Andric 
16000b57cec5SDimitry Andric   // Start with loop/exit blocks and get a transitive closure of reachable dead
16010b57cec5SDimitry Andric   // blocks.
16020b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
16030b57cec5SDimitry Andric                                                 ExitBlocks.end());
16040b57cec5SDimitry Andric   DeathCandidates.append(L.blocks().begin(), L.blocks().end());
16050b57cec5SDimitry Andric   while (!DeathCandidates.empty()) {
16060b57cec5SDimitry Andric     auto *BB = DeathCandidates.pop_back_val();
16070b57cec5SDimitry Andric     if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
16080b57cec5SDimitry Andric       for (BasicBlock *SuccBB : successors(BB)) {
16090b57cec5SDimitry Andric         SuccBB->removePredecessor(BB);
16100b57cec5SDimitry Andric         DeathCandidates.push_back(SuccBB);
16110b57cec5SDimitry Andric       }
16120b57cec5SDimitry Andric       DeadBlockSet.insert(BB);
16130b57cec5SDimitry Andric     }
16140b57cec5SDimitry Andric   }
16150b57cec5SDimitry Andric 
16160b57cec5SDimitry Andric   // Remove all MemorySSA in the dead blocks
16170b57cec5SDimitry Andric   if (MSSAU)
16180b57cec5SDimitry Andric     MSSAU->removeBlocks(DeadBlockSet);
16190b57cec5SDimitry Andric 
16200b57cec5SDimitry Andric   // Filter out the dead blocks from the exit blocks list so that it can be
16210b57cec5SDimitry Andric   // used in the caller.
16220b57cec5SDimitry Andric   llvm::erase_if(ExitBlocks,
16230b57cec5SDimitry Andric                  [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
16240b57cec5SDimitry Andric 
16250b57cec5SDimitry Andric   // Walk from this loop up through its parents removing all of the dead blocks.
16260b57cec5SDimitry Andric   for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
16270b57cec5SDimitry Andric     for (auto *BB : DeadBlockSet)
16280b57cec5SDimitry Andric       ParentL->getBlocksSet().erase(BB);
16290b57cec5SDimitry Andric     llvm::erase_if(ParentL->getBlocksVector(),
16300b57cec5SDimitry Andric                    [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
16310b57cec5SDimitry Andric   }
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric   // Now delete the dead child loops. This raw delete will clear them
16340b57cec5SDimitry Andric   // recursively.
16350b57cec5SDimitry Andric   llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
16360b57cec5SDimitry Andric     if (!DeadBlockSet.count(ChildL->getHeader()))
16370b57cec5SDimitry Andric       return false;
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric     assert(llvm::all_of(ChildL->blocks(),
16400b57cec5SDimitry Andric                         [&](BasicBlock *ChildBB) {
16410b57cec5SDimitry Andric                           return DeadBlockSet.count(ChildBB);
16420b57cec5SDimitry Andric                         }) &&
16430b57cec5SDimitry Andric            "If the child loop header is dead all blocks in the child loop must "
16440b57cec5SDimitry Andric            "be dead as well!");
1645*18baa991SDimitry Andric     DestroyLoopCB(*ChildL, ChildL->getName());
16460b57cec5SDimitry Andric     LI.destroy(ChildL);
16470b57cec5SDimitry Andric     return true;
16480b57cec5SDimitry Andric   });
16490b57cec5SDimitry Andric 
16500b57cec5SDimitry Andric   // Remove the loop mappings for the dead blocks and drop all the references
16510b57cec5SDimitry Andric   // from these blocks to others to handle cyclic references as we start
16520b57cec5SDimitry Andric   // deleting the blocks themselves.
16530b57cec5SDimitry Andric   for (auto *BB : DeadBlockSet) {
16540b57cec5SDimitry Andric     // Check that the dominator tree has already been updated.
16550b57cec5SDimitry Andric     assert(!DT.getNode(BB) && "Should already have cleared domtree!");
16560b57cec5SDimitry Andric     LI.changeLoopFor(BB, nullptr);
16575ffd83dbSDimitry Andric     // Drop all uses of the instructions to make sure we won't have dangling
16585ffd83dbSDimitry Andric     // uses in other blocks.
16595ffd83dbSDimitry Andric     for (auto &I : *BB)
16605ffd83dbSDimitry Andric       if (!I.use_empty())
16615ffd83dbSDimitry Andric         I.replaceAllUsesWith(UndefValue::get(I.getType()));
16620b57cec5SDimitry Andric     BB->dropAllReferences();
16630b57cec5SDimitry Andric   }
16640b57cec5SDimitry Andric 
16650b57cec5SDimitry Andric   // Actually delete the blocks now that they've been fully unhooked from the
16660b57cec5SDimitry Andric   // IR.
16670b57cec5SDimitry Andric   for (auto *BB : DeadBlockSet)
16680b57cec5SDimitry Andric     BB->eraseFromParent();
16690b57cec5SDimitry Andric }
16700b57cec5SDimitry Andric 
16710b57cec5SDimitry Andric /// Recompute the set of blocks in a loop after unswitching.
16720b57cec5SDimitry Andric ///
16730b57cec5SDimitry Andric /// This walks from the original headers predecessors to rebuild the loop. We
16740b57cec5SDimitry Andric /// take advantage of the fact that new blocks can't have been added, and so we
16750b57cec5SDimitry Andric /// filter by the original loop's blocks. This also handles potentially
16760b57cec5SDimitry Andric /// unreachable code that we don't want to explore but might be found examining
16770b57cec5SDimitry Andric /// the predecessors of the header.
16780b57cec5SDimitry Andric ///
16790b57cec5SDimitry Andric /// If the original loop is no longer a loop, this will return an empty set. If
16800b57cec5SDimitry Andric /// it remains a loop, all the blocks within it will be added to the set
16810b57cec5SDimitry Andric /// (including those blocks in inner loops).
recomputeLoopBlockSet(Loop & L,LoopInfo & LI)16820b57cec5SDimitry Andric static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
16830b57cec5SDimitry Andric                                                                  LoopInfo &LI) {
16840b57cec5SDimitry Andric   SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric   auto *PH = L.getLoopPreheader();
16870b57cec5SDimitry Andric   auto *Header = L.getHeader();
16880b57cec5SDimitry Andric 
16890b57cec5SDimitry Andric   // A worklist to use while walking backwards from the header.
16900b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> Worklist;
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric   // First walk the predecessors of the header to find the backedges. This will
16930b57cec5SDimitry Andric   // form the basis of our walk.
16940b57cec5SDimitry Andric   for (auto *Pred : predecessors(Header)) {
16950b57cec5SDimitry Andric     // Skip the preheader.
16960b57cec5SDimitry Andric     if (Pred == PH)
16970b57cec5SDimitry Andric       continue;
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric     // Because the loop was in simplified form, the only non-loop predecessor
17000b57cec5SDimitry Andric     // is the preheader.
17010b57cec5SDimitry Andric     assert(L.contains(Pred) && "Found a predecessor of the loop header other "
17020b57cec5SDimitry Andric                                "than the preheader that is not part of the "
17030b57cec5SDimitry Andric                                "loop!");
17040b57cec5SDimitry Andric 
17050b57cec5SDimitry Andric     // Insert this block into the loop set and on the first visit and, if it
17060b57cec5SDimitry Andric     // isn't the header we're currently walking, put it into the worklist to
17070b57cec5SDimitry Andric     // recurse through.
17080b57cec5SDimitry Andric     if (LoopBlockSet.insert(Pred).second && Pred != Header)
17090b57cec5SDimitry Andric       Worklist.push_back(Pred);
17100b57cec5SDimitry Andric   }
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric   // If no backedges were found, we're done.
17130b57cec5SDimitry Andric   if (LoopBlockSet.empty())
17140b57cec5SDimitry Andric     return LoopBlockSet;
17150b57cec5SDimitry Andric 
17160b57cec5SDimitry Andric   // We found backedges, recurse through them to identify the loop blocks.
17170b57cec5SDimitry Andric   while (!Worklist.empty()) {
17180b57cec5SDimitry Andric     BasicBlock *BB = Worklist.pop_back_val();
17190b57cec5SDimitry Andric     assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric     // No need to walk past the header.
17220b57cec5SDimitry Andric     if (BB == Header)
17230b57cec5SDimitry Andric       continue;
17240b57cec5SDimitry Andric 
17250b57cec5SDimitry Andric     // Because we know the inner loop structure remains valid we can use the
17260b57cec5SDimitry Andric     // loop structure to jump immediately across the entire nested loop.
17270b57cec5SDimitry Andric     // Further, because it is in loop simplified form, we can directly jump
17280b57cec5SDimitry Andric     // to its preheader afterward.
17290b57cec5SDimitry Andric     if (Loop *InnerL = LI.getLoopFor(BB))
17300b57cec5SDimitry Andric       if (InnerL != &L) {
17310b57cec5SDimitry Andric         assert(L.contains(InnerL) &&
17320b57cec5SDimitry Andric                "Should not reach a loop *outside* this loop!");
17330b57cec5SDimitry Andric         // The preheader is the only possible predecessor of the loop so
17340b57cec5SDimitry Andric         // insert it into the set and check whether it was already handled.
17350b57cec5SDimitry Andric         auto *InnerPH = InnerL->getLoopPreheader();
17360b57cec5SDimitry Andric         assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
17370b57cec5SDimitry Andric                                       "but not contain the inner loop "
17380b57cec5SDimitry Andric                                       "preheader!");
17390b57cec5SDimitry Andric         if (!LoopBlockSet.insert(InnerPH).second)
17400b57cec5SDimitry Andric           // The only way to reach the preheader is through the loop body
17410b57cec5SDimitry Andric           // itself so if it has been visited the loop is already handled.
17420b57cec5SDimitry Andric           continue;
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric         // Insert all of the blocks (other than those already present) into
17450b57cec5SDimitry Andric         // the loop set. We expect at least the block that led us to find the
17460b57cec5SDimitry Andric         // inner loop to be in the block set, but we may also have other loop
17470b57cec5SDimitry Andric         // blocks if they were already enqueued as predecessors of some other
17480b57cec5SDimitry Andric         // outer loop block.
17490b57cec5SDimitry Andric         for (auto *InnerBB : InnerL->blocks()) {
17500b57cec5SDimitry Andric           if (InnerBB == BB) {
17510b57cec5SDimitry Andric             assert(LoopBlockSet.count(InnerBB) &&
17520b57cec5SDimitry Andric                    "Block should already be in the set!");
17530b57cec5SDimitry Andric             continue;
17540b57cec5SDimitry Andric           }
17550b57cec5SDimitry Andric 
17560b57cec5SDimitry Andric           LoopBlockSet.insert(InnerBB);
17570b57cec5SDimitry Andric         }
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric         // Add the preheader to the worklist so we will continue past the
17600b57cec5SDimitry Andric         // loop body.
17610b57cec5SDimitry Andric         Worklist.push_back(InnerPH);
17620b57cec5SDimitry Andric         continue;
17630b57cec5SDimitry Andric       }
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric     // Insert any predecessors that were in the original loop into the new
17660b57cec5SDimitry Andric     // set, and if the insert is successful, add them to the worklist.
17670b57cec5SDimitry Andric     for (auto *Pred : predecessors(BB))
17680b57cec5SDimitry Andric       if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
17690b57cec5SDimitry Andric         Worklist.push_back(Pred);
17700b57cec5SDimitry Andric   }
17710b57cec5SDimitry Andric 
17720b57cec5SDimitry Andric   assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric   // We've found all the blocks participating in the loop, return our completed
17750b57cec5SDimitry Andric   // set.
17760b57cec5SDimitry Andric   return LoopBlockSet;
17770b57cec5SDimitry Andric }
17780b57cec5SDimitry Andric 
17790b57cec5SDimitry Andric /// Rebuild a loop after unswitching removes some subset of blocks and edges.
17800b57cec5SDimitry Andric ///
17810b57cec5SDimitry Andric /// The removal may have removed some child loops entirely but cannot have
17820b57cec5SDimitry Andric /// disturbed any remaining child loops. However, they may need to be hoisted
17830b57cec5SDimitry Andric /// to the parent loop (or to be top-level loops). The original loop may be
17840b57cec5SDimitry Andric /// completely removed.
17850b57cec5SDimitry Andric ///
17860b57cec5SDimitry Andric /// The sibling loops resulting from this update are returned. If the original
17870b57cec5SDimitry Andric /// loop remains a valid loop, it will be the first entry in this list with all
17880b57cec5SDimitry Andric /// of the newly sibling loops following it.
17890b57cec5SDimitry Andric ///
17900b57cec5SDimitry Andric /// Returns true if the loop remains a loop after unswitching, and false if it
17910b57cec5SDimitry Andric /// is no longer a loop after unswitching (and should not continue to be
17920b57cec5SDimitry Andric /// referenced).
rebuildLoopAfterUnswitch(Loop & L,ArrayRef<BasicBlock * > ExitBlocks,LoopInfo & LI,SmallVectorImpl<Loop * > & HoistedLoops)17930b57cec5SDimitry Andric static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
17940b57cec5SDimitry Andric                                      LoopInfo &LI,
17950b57cec5SDimitry Andric                                      SmallVectorImpl<Loop *> &HoistedLoops) {
17960b57cec5SDimitry Andric   auto *PH = L.getLoopPreheader();
17970b57cec5SDimitry Andric 
17980b57cec5SDimitry Andric   // Compute the actual parent loop from the exit blocks. Because we may have
17990b57cec5SDimitry Andric   // pruned some exits the loop may be different from the original parent.
18000b57cec5SDimitry Andric   Loop *ParentL = nullptr;
18010b57cec5SDimitry Andric   SmallVector<Loop *, 4> ExitLoops;
18020b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> ExitsInLoops;
18030b57cec5SDimitry Andric   ExitsInLoops.reserve(ExitBlocks.size());
18040b57cec5SDimitry Andric   for (auto *ExitBB : ExitBlocks)
18050b57cec5SDimitry Andric     if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
18060b57cec5SDimitry Andric       ExitLoops.push_back(ExitL);
18070b57cec5SDimitry Andric       ExitsInLoops.push_back(ExitBB);
18080b57cec5SDimitry Andric       if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
18090b57cec5SDimitry Andric         ParentL = ExitL;
18100b57cec5SDimitry Andric     }
18110b57cec5SDimitry Andric 
18120b57cec5SDimitry Andric   // Recompute the blocks participating in this loop. This may be empty if it
18130b57cec5SDimitry Andric   // is no longer a loop.
18140b57cec5SDimitry Andric   auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
18150b57cec5SDimitry Andric 
18160b57cec5SDimitry Andric   // If we still have a loop, we need to re-set the loop's parent as the exit
18170b57cec5SDimitry Andric   // block set changing may have moved it within the loop nest. Note that this
18180b57cec5SDimitry Andric   // can only happen when this loop has a parent as it can only hoist the loop
18190b57cec5SDimitry Andric   // *up* the nest.
18200b57cec5SDimitry Andric   if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
18210b57cec5SDimitry Andric     // Remove this loop's (original) blocks from all of the intervening loops.
18220b57cec5SDimitry Andric     for (Loop *IL = L.getParentLoop(); IL != ParentL;
18230b57cec5SDimitry Andric          IL = IL->getParentLoop()) {
18240b57cec5SDimitry Andric       IL->getBlocksSet().erase(PH);
18250b57cec5SDimitry Andric       for (auto *BB : L.blocks())
18260b57cec5SDimitry Andric         IL->getBlocksSet().erase(BB);
18270b57cec5SDimitry Andric       llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
18280b57cec5SDimitry Andric         return BB == PH || L.contains(BB);
18290b57cec5SDimitry Andric       });
18300b57cec5SDimitry Andric     }
18310b57cec5SDimitry Andric 
18320b57cec5SDimitry Andric     LI.changeLoopFor(PH, ParentL);
18330b57cec5SDimitry Andric     L.getParentLoop()->removeChildLoop(&L);
18340b57cec5SDimitry Andric     if (ParentL)
18350b57cec5SDimitry Andric       ParentL->addChildLoop(&L);
18360b57cec5SDimitry Andric     else
18370b57cec5SDimitry Andric       LI.addTopLevelLoop(&L);
18380b57cec5SDimitry Andric   }
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric   // Now we update all the blocks which are no longer within the loop.
18410b57cec5SDimitry Andric   auto &Blocks = L.getBlocksVector();
18420b57cec5SDimitry Andric   auto BlocksSplitI =
18430b57cec5SDimitry Andric       LoopBlockSet.empty()
18440b57cec5SDimitry Andric           ? Blocks.begin()
18450b57cec5SDimitry Andric           : std::stable_partition(
18460b57cec5SDimitry Andric                 Blocks.begin(), Blocks.end(),
18470b57cec5SDimitry Andric                 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric   // Before we erase the list of unlooped blocks, build a set of them.
18500b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
18510b57cec5SDimitry Andric   if (LoopBlockSet.empty())
18520b57cec5SDimitry Andric     UnloopedBlocks.insert(PH);
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric   // Now erase these blocks from the loop.
18550b57cec5SDimitry Andric   for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
18560b57cec5SDimitry Andric     L.getBlocksSet().erase(BB);
18570b57cec5SDimitry Andric   Blocks.erase(BlocksSplitI, Blocks.end());
18580b57cec5SDimitry Andric 
18590b57cec5SDimitry Andric   // Sort the exits in ascending loop depth, we'll work backwards across these
18600b57cec5SDimitry Andric   // to process them inside out.
18610b57cec5SDimitry Andric   llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
18620b57cec5SDimitry Andric     return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
18630b57cec5SDimitry Andric   });
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric   // We'll build up a set for each exit loop.
18660b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
18670b57cec5SDimitry Andric   Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric   auto RemoveUnloopedBlocksFromLoop =
18700b57cec5SDimitry Andric       [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
18710b57cec5SDimitry Andric         for (auto *BB : UnloopedBlocks)
18720b57cec5SDimitry Andric           L.getBlocksSet().erase(BB);
18730b57cec5SDimitry Andric         llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
18740b57cec5SDimitry Andric           return UnloopedBlocks.count(BB);
18750b57cec5SDimitry Andric         });
18760b57cec5SDimitry Andric       };
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> Worklist;
18790b57cec5SDimitry Andric   while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
18800b57cec5SDimitry Andric     assert(Worklist.empty() && "Didn't clear worklist!");
18810b57cec5SDimitry Andric     assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
18820b57cec5SDimitry Andric 
18830b57cec5SDimitry Andric     // Grab the next exit block, in decreasing loop depth order.
18840b57cec5SDimitry Andric     BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
18850b57cec5SDimitry Andric     Loop &ExitL = *LI.getLoopFor(ExitBB);
18860b57cec5SDimitry Andric     assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
18870b57cec5SDimitry Andric 
18880b57cec5SDimitry Andric     // Erase all of the unlooped blocks from the loops between the previous
18890b57cec5SDimitry Andric     // exit loop and this exit loop. This works because the ExitInLoops list is
18900b57cec5SDimitry Andric     // sorted in increasing order of loop depth and thus we visit loops in
18910b57cec5SDimitry Andric     // decreasing order of loop depth.
18920b57cec5SDimitry Andric     for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
18930b57cec5SDimitry Andric       RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
18940b57cec5SDimitry Andric 
18950b57cec5SDimitry Andric     // Walk the CFG back until we hit the cloned PH adding everything reachable
18960b57cec5SDimitry Andric     // and in the unlooped set to this exit block's loop.
18970b57cec5SDimitry Andric     Worklist.push_back(ExitBB);
18980b57cec5SDimitry Andric     do {
18990b57cec5SDimitry Andric       BasicBlock *BB = Worklist.pop_back_val();
19000b57cec5SDimitry Andric       // We can stop recursing at the cloned preheader (if we get there).
19010b57cec5SDimitry Andric       if (BB == PH)
19020b57cec5SDimitry Andric         continue;
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric       for (BasicBlock *PredBB : predecessors(BB)) {
19050b57cec5SDimitry Andric         // If this pred has already been moved to our set or is part of some
19060b57cec5SDimitry Andric         // (inner) loop, no update needed.
19070b57cec5SDimitry Andric         if (!UnloopedBlocks.erase(PredBB)) {
19080b57cec5SDimitry Andric           assert((NewExitLoopBlocks.count(PredBB) ||
19090b57cec5SDimitry Andric                   ExitL.contains(LI.getLoopFor(PredBB))) &&
19100b57cec5SDimitry Andric                  "Predecessor not in a nested loop (or already visited)!");
19110b57cec5SDimitry Andric           continue;
19120b57cec5SDimitry Andric         }
19130b57cec5SDimitry Andric 
19140b57cec5SDimitry Andric         // We just insert into the loop set here. We'll add these blocks to the
19150b57cec5SDimitry Andric         // exit loop after we build up the set in a deterministic order rather
19160b57cec5SDimitry Andric         // than the predecessor-influenced visit order.
19170b57cec5SDimitry Andric         bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
19180b57cec5SDimitry Andric         (void)Inserted;
19190b57cec5SDimitry Andric         assert(Inserted && "Should only visit an unlooped block once!");
19200b57cec5SDimitry Andric 
19210b57cec5SDimitry Andric         // And recurse through to its predecessors.
19220b57cec5SDimitry Andric         Worklist.push_back(PredBB);
19230b57cec5SDimitry Andric       }
19240b57cec5SDimitry Andric     } while (!Worklist.empty());
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric     // If blocks in this exit loop were directly part of the original loop (as
19270b57cec5SDimitry Andric     // opposed to a child loop) update the map to point to this exit loop. This
19280b57cec5SDimitry Andric     // just updates a map and so the fact that the order is unstable is fine.
19290b57cec5SDimitry Andric     for (auto *BB : NewExitLoopBlocks)
19300b57cec5SDimitry Andric       if (Loop *BBL = LI.getLoopFor(BB))
19310b57cec5SDimitry Andric         if (BBL == &L || !L.contains(BBL))
19320b57cec5SDimitry Andric           LI.changeLoopFor(BB, &ExitL);
19330b57cec5SDimitry Andric 
19340b57cec5SDimitry Andric     // We will remove the remaining unlooped blocks from this loop in the next
19350b57cec5SDimitry Andric     // iteration or below.
19360b57cec5SDimitry Andric     NewExitLoopBlocks.clear();
19370b57cec5SDimitry Andric   }
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric   // Any remaining unlooped blocks are no longer part of any loop unless they
19400b57cec5SDimitry Andric   // are part of some child loop.
19410b57cec5SDimitry Andric   for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
19420b57cec5SDimitry Andric     RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
19430b57cec5SDimitry Andric   for (auto *BB : UnloopedBlocks)
19440b57cec5SDimitry Andric     if (Loop *BBL = LI.getLoopFor(BB))
19450b57cec5SDimitry Andric       if (BBL == &L || !L.contains(BBL))
19460b57cec5SDimitry Andric         LI.changeLoopFor(BB, nullptr);
19470b57cec5SDimitry Andric 
19480b57cec5SDimitry Andric   // Sink all the child loops whose headers are no longer in the loop set to
19490b57cec5SDimitry Andric   // the parent (or to be top level loops). We reach into the loop and directly
19500b57cec5SDimitry Andric   // update its subloop vector to make this batch update efficient.
19510b57cec5SDimitry Andric   auto &SubLoops = L.getSubLoopsVector();
19520b57cec5SDimitry Andric   auto SubLoopsSplitI =
19530b57cec5SDimitry Andric       LoopBlockSet.empty()
19540b57cec5SDimitry Andric           ? SubLoops.begin()
19550b57cec5SDimitry Andric           : std::stable_partition(
19560b57cec5SDimitry Andric                 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
19570b57cec5SDimitry Andric                   return LoopBlockSet.count(SubL->getHeader());
19580b57cec5SDimitry Andric                 });
19590b57cec5SDimitry Andric   for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
19600b57cec5SDimitry Andric     HoistedLoops.push_back(HoistedL);
19610b57cec5SDimitry Andric     HoistedL->setParentLoop(nullptr);
19620b57cec5SDimitry Andric 
19630b57cec5SDimitry Andric     // To compute the new parent of this hoisted loop we look at where we
19640b57cec5SDimitry Andric     // placed the preheader above. We can't lookup the header itself because we
19650b57cec5SDimitry Andric     // retained the mapping from the header to the hoisted loop. But the
19660b57cec5SDimitry Andric     // preheader and header should have the exact same new parent computed
19670b57cec5SDimitry Andric     // based on the set of exit blocks from the original loop as the preheader
19680b57cec5SDimitry Andric     // is a predecessor of the header and so reached in the reverse walk. And
19690b57cec5SDimitry Andric     // because the loops were all in simplified form the preheader of the
19700b57cec5SDimitry Andric     // hoisted loop can't be part of some *other* loop.
19710b57cec5SDimitry Andric     if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
19720b57cec5SDimitry Andric       NewParentL->addChildLoop(HoistedL);
19730b57cec5SDimitry Andric     else
19740b57cec5SDimitry Andric       LI.addTopLevelLoop(HoistedL);
19750b57cec5SDimitry Andric   }
19760b57cec5SDimitry Andric   SubLoops.erase(SubLoopsSplitI, SubLoops.end());
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric   // Actually delete the loop if nothing remained within it.
19790b57cec5SDimitry Andric   if (Blocks.empty()) {
19800b57cec5SDimitry Andric     assert(SubLoops.empty() &&
19810b57cec5SDimitry Andric            "Failed to remove all subloops from the original loop!");
19820b57cec5SDimitry Andric     if (Loop *ParentL = L.getParentLoop())
19830b57cec5SDimitry Andric       ParentL->removeChildLoop(llvm::find(*ParentL, &L));
19840b57cec5SDimitry Andric     else
19850b57cec5SDimitry Andric       LI.removeLoop(llvm::find(LI, &L));
1986*18baa991SDimitry Andric     // markLoopAsDeleted for L should be triggered by the caller (it is typically
1987*18baa991SDimitry Andric     // done by using the UnswitchCB callback).
19880b57cec5SDimitry Andric     LI.destroy(&L);
19890b57cec5SDimitry Andric     return false;
19900b57cec5SDimitry Andric   }
19910b57cec5SDimitry Andric 
19920b57cec5SDimitry Andric   return true;
19930b57cec5SDimitry Andric }
19940b57cec5SDimitry Andric 
19950b57cec5SDimitry Andric /// Helper to visit a dominator subtree, invoking a callable on each node.
19960b57cec5SDimitry Andric ///
19970b57cec5SDimitry Andric /// Returning false at any point will stop walking past that node of the tree.
19980b57cec5SDimitry Andric template <typename CallableT>
visitDomSubTree(DominatorTree & DT,BasicBlock * BB,CallableT Callable)19990b57cec5SDimitry Andric void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
20000b57cec5SDimitry Andric   SmallVector<DomTreeNode *, 4> DomWorklist;
20010b57cec5SDimitry Andric   DomWorklist.push_back(DT[BB]);
20020b57cec5SDimitry Andric #ifndef NDEBUG
20030b57cec5SDimitry Andric   SmallPtrSet<DomTreeNode *, 4> Visited;
20040b57cec5SDimitry Andric   Visited.insert(DT[BB]);
20050b57cec5SDimitry Andric #endif
20060b57cec5SDimitry Andric   do {
20070b57cec5SDimitry Andric     DomTreeNode *N = DomWorklist.pop_back_val();
20080b57cec5SDimitry Andric 
20090b57cec5SDimitry Andric     // Visit this node.
20100b57cec5SDimitry Andric     if (!Callable(N->getBlock()))
20110b57cec5SDimitry Andric       continue;
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric     // Accumulate the child nodes.
20140b57cec5SDimitry Andric     for (DomTreeNode *ChildN : *N) {
20150b57cec5SDimitry Andric       assert(Visited.insert(ChildN).second &&
20160b57cec5SDimitry Andric              "Cannot visit a node twice when walking a tree!");
20170b57cec5SDimitry Andric       DomWorklist.push_back(ChildN);
20180b57cec5SDimitry Andric     }
20190b57cec5SDimitry Andric   } while (!DomWorklist.empty());
20200b57cec5SDimitry Andric }
20210b57cec5SDimitry Andric 
unswitchNontrivialInvariants(Loop & L,Instruction & TI,ArrayRef<Value * > Invariants,SmallVectorImpl<BasicBlock * > & ExitBlocks,IVConditionInfo & PartialIVInfo,DominatorTree & DT,LoopInfo & LI,AssumptionCache & AC,function_ref<void (bool,bool,ArrayRef<Loop * >)> UnswitchCB,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,function_ref<void (Loop &,StringRef)> DestroyLoopCB)20220b57cec5SDimitry Andric static void unswitchNontrivialInvariants(
20230b57cec5SDimitry Andric     Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
20245f7ddb14SDimitry Andric     SmallVectorImpl<BasicBlock *> &ExitBlocks, IVConditionInfo &PartialIVInfo,
20255f7ddb14SDimitry Andric     DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
20265f7ddb14SDimitry Andric     function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
2027*18baa991SDimitry Andric     ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
2028*18baa991SDimitry Andric     function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
20290b57cec5SDimitry Andric   auto *ParentBB = TI.getParent();
20300b57cec5SDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(&TI);
20310b57cec5SDimitry Andric   SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
20320b57cec5SDimitry Andric 
20330b57cec5SDimitry Andric   // We can only unswitch switches, conditional branches with an invariant
20345f7ddb14SDimitry Andric   // condition, or combining invariant conditions with an instruction or
20355f7ddb14SDimitry Andric   // partially invariant instructions.
20368bcb0991SDimitry Andric   assert((SI || (BI && BI->isConditional())) &&
20370b57cec5SDimitry Andric          "Can only unswitch switches and conditional branch!");
20385f7ddb14SDimitry Andric   bool PartiallyInvariant = !PartialIVInfo.InstToDuplicate.empty();
20395f7ddb14SDimitry Andric   bool FullUnswitch =
20405f7ddb14SDimitry Andric       SI || (BI->getCondition() == Invariants[0] && !PartiallyInvariant);
20410b57cec5SDimitry Andric   if (FullUnswitch)
20420b57cec5SDimitry Andric     assert(Invariants.size() == 1 &&
20430b57cec5SDimitry Andric            "Cannot have other invariants with full unswitching!");
20440b57cec5SDimitry Andric   else
20450b57cec5SDimitry Andric     assert(isa<Instruction>(BI->getCondition()) &&
20460b57cec5SDimitry Andric            "Partial unswitching requires an instruction as the condition!");
20470b57cec5SDimitry Andric 
20480b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
20490b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
20500b57cec5SDimitry Andric 
20510b57cec5SDimitry Andric   // Constant and BBs tracking the cloned and continuing successor. When we are
20520b57cec5SDimitry Andric   // unswitching the entire condition, this can just be trivially chosen to
20530b57cec5SDimitry Andric   // unswitch towards `true`. However, when we are unswitching a set of
20545f7ddb14SDimitry Andric   // invariants combined with `and` or `or` or partially invariant instructions,
20555f7ddb14SDimitry Andric   // the combining operation determines the best direction to unswitch: we want
20565f7ddb14SDimitry Andric   // to unswitch the direction that will collapse the branch.
20570b57cec5SDimitry Andric   bool Direction = true;
20580b57cec5SDimitry Andric   int ClonedSucc = 0;
20590b57cec5SDimitry Andric   if (!FullUnswitch) {
20605f7ddb14SDimitry Andric     Value *Cond = BI->getCondition();
20615f7ddb14SDimitry Andric     (void)Cond;
20625f7ddb14SDimitry Andric     assert(((match(Cond, m_LogicalAnd()) ^ match(Cond, m_LogicalOr())) ||
20635f7ddb14SDimitry Andric             PartiallyInvariant) &&
20645f7ddb14SDimitry Andric            "Only `or`, `and`, an `select`, partially invariant instructions "
20655f7ddb14SDimitry Andric            "can combine invariants being unswitched.");
20665f7ddb14SDimitry Andric     if (!match(BI->getCondition(), m_LogicalOr())) {
20675f7ddb14SDimitry Andric       if (match(BI->getCondition(), m_LogicalAnd()) ||
20685f7ddb14SDimitry Andric           (PartiallyInvariant && !PartialIVInfo.KnownValue->isOneValue())) {
20690b57cec5SDimitry Andric         Direction = false;
20700b57cec5SDimitry Andric         ClonedSucc = 1;
20710b57cec5SDimitry Andric       }
20720b57cec5SDimitry Andric     }
20735f7ddb14SDimitry Andric   }
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric   BasicBlock *RetainedSuccBB =
20760b57cec5SDimitry Andric       BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
20770b57cec5SDimitry Andric   SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
20780b57cec5SDimitry Andric   if (BI)
20790b57cec5SDimitry Andric     UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
20800b57cec5SDimitry Andric   else
20810b57cec5SDimitry Andric     for (auto Case : SI->cases())
20820b57cec5SDimitry Andric       if (Case.getCaseSuccessor() != RetainedSuccBB)
20830b57cec5SDimitry Andric         UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric   assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
20860b57cec5SDimitry Andric          "Should not unswitch the same successor we are retaining!");
20870b57cec5SDimitry Andric 
20880b57cec5SDimitry Andric   // The branch should be in this exact loop. Any inner loop's invariant branch
20890b57cec5SDimitry Andric   // should be handled by unswitching that inner loop. The caller of this
20900b57cec5SDimitry Andric   // routine should filter out any candidates that remain (but were skipped for
20910b57cec5SDimitry Andric   // whatever reason).
20920b57cec5SDimitry Andric   assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
20930b57cec5SDimitry Andric 
20940b57cec5SDimitry Andric   // Compute the parent loop now before we start hacking on things.
20950b57cec5SDimitry Andric   Loop *ParentL = L.getParentLoop();
20960b57cec5SDimitry Andric   // Get blocks in RPO order for MSSA update, before changing the CFG.
20970b57cec5SDimitry Andric   LoopBlocksRPO LBRPO(&L);
20980b57cec5SDimitry Andric   if (MSSAU)
20990b57cec5SDimitry Andric     LBRPO.perform(&LI);
21000b57cec5SDimitry Andric 
21010b57cec5SDimitry Andric   // Compute the outer-most loop containing one of our exit blocks. This is the
21020b57cec5SDimitry Andric   // furthest up our loopnest which can be mutated, which we will use below to
21030b57cec5SDimitry Andric   // update things.
21040b57cec5SDimitry Andric   Loop *OuterExitL = &L;
21050b57cec5SDimitry Andric   for (auto *ExitBB : ExitBlocks) {
21060b57cec5SDimitry Andric     Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
21070b57cec5SDimitry Andric     if (!NewOuterExitL) {
21080b57cec5SDimitry Andric       // We exited the entire nest with this block, so we're done.
21090b57cec5SDimitry Andric       OuterExitL = nullptr;
21100b57cec5SDimitry Andric       break;
21110b57cec5SDimitry Andric     }
21120b57cec5SDimitry Andric     if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
21130b57cec5SDimitry Andric       OuterExitL = NewOuterExitL;
21140b57cec5SDimitry Andric   }
21150b57cec5SDimitry Andric 
21160b57cec5SDimitry Andric   // At this point, we're definitely going to unswitch something so invalidate
21170b57cec5SDimitry Andric   // any cached information in ScalarEvolution for the outer most loop
21180b57cec5SDimitry Andric   // containing an exit block and all nested loops.
21190b57cec5SDimitry Andric   if (SE) {
21200b57cec5SDimitry Andric     if (OuterExitL)
21210b57cec5SDimitry Andric       SE->forgetLoop(OuterExitL);
21220b57cec5SDimitry Andric     else
21230b57cec5SDimitry Andric       SE->forgetTopmostLoop(&L);
21240b57cec5SDimitry Andric   }
21250b57cec5SDimitry Andric 
21260b57cec5SDimitry Andric   // If the edge from this terminator to a successor dominates that successor,
21270b57cec5SDimitry Andric   // store a map from each block in its dominator subtree to it. This lets us
21280b57cec5SDimitry Andric   // tell when cloning for a particular successor if a block is dominated by
21290b57cec5SDimitry Andric   // some *other* successor with a single data structure. We use this to
21300b57cec5SDimitry Andric   // significantly reduce cloning.
21310b57cec5SDimitry Andric   SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
21320b57cec5SDimitry Andric   for (auto *SuccBB : llvm::concat<BasicBlock *const>(
21330b57cec5SDimitry Andric            makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
21340b57cec5SDimitry Andric     if (SuccBB->getUniquePredecessor() ||
21350b57cec5SDimitry Andric         llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
21360b57cec5SDimitry Andric           return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
21370b57cec5SDimitry Andric         }))
21380b57cec5SDimitry Andric       visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
21390b57cec5SDimitry Andric         DominatingSucc[BB] = SuccBB;
21400b57cec5SDimitry Andric         return true;
21410b57cec5SDimitry Andric       });
21420b57cec5SDimitry Andric 
21430b57cec5SDimitry Andric   // Split the preheader, so that we know that there is a safe place to insert
21440b57cec5SDimitry Andric   // the conditional branch. We will change the preheader to have a conditional
21450b57cec5SDimitry Andric   // branch on LoopCond. The original preheader will become the split point
21460b57cec5SDimitry Andric   // between the unswitched versions, and we will have a new preheader for the
21470b57cec5SDimitry Andric   // original loop.
21480b57cec5SDimitry Andric   BasicBlock *SplitBB = L.getLoopPreheader();
21490b57cec5SDimitry Andric   BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
21500b57cec5SDimitry Andric 
21510b57cec5SDimitry Andric   // Keep track of the dominator tree updates needed.
21520b57cec5SDimitry Andric   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
21530b57cec5SDimitry Andric 
21540b57cec5SDimitry Andric   // Clone the loop for each unswitched successor.
21550b57cec5SDimitry Andric   SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
21560b57cec5SDimitry Andric   VMaps.reserve(UnswitchedSuccBBs.size());
21570b57cec5SDimitry Andric   SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
21580b57cec5SDimitry Andric   for (auto *SuccBB : UnswitchedSuccBBs) {
21590b57cec5SDimitry Andric     VMaps.emplace_back(new ValueToValueMapTy());
21600b57cec5SDimitry Andric     ClonedPHs[SuccBB] = buildClonedLoopBlocks(
21610b57cec5SDimitry Andric         L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
21620b57cec5SDimitry Andric         DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
21630b57cec5SDimitry Andric   }
21640b57cec5SDimitry Andric 
2165af732203SDimitry Andric   // Drop metadata if we may break its semantics by moving this instr into the
2166af732203SDimitry Andric   // split block.
2167af732203SDimitry Andric   if (TI.getMetadata(LLVMContext::MD_make_implicit)) {
2168af732203SDimitry Andric     if (DropNonTrivialImplicitNullChecks)
2169af732203SDimitry Andric       // Do not spend time trying to understand if we can keep it, just drop it
2170af732203SDimitry Andric       // to save compile time.
2171af732203SDimitry Andric       TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
2172af732203SDimitry Andric     else {
2173af732203SDimitry Andric       // It is only legal to preserve make.implicit metadata if we are
2174af732203SDimitry Andric       // guaranteed no reach implicit null check after following this branch.
2175af732203SDimitry Andric       ICFLoopSafetyInfo SafetyInfo;
2176af732203SDimitry Andric       SafetyInfo.computeLoopSafetyInfo(&L);
2177af732203SDimitry Andric       if (!SafetyInfo.isGuaranteedToExecute(TI, &DT, &L))
2178af732203SDimitry Andric         TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
2179af732203SDimitry Andric     }
2180af732203SDimitry Andric   }
2181af732203SDimitry Andric 
21820b57cec5SDimitry Andric   // The stitching of the branched code back together depends on whether we're
21830b57cec5SDimitry Andric   // doing full unswitching or not with the exception that we always want to
21840b57cec5SDimitry Andric   // nuke the initial terminator placed in the split block.
21850b57cec5SDimitry Andric   SplitBB->getTerminator()->eraseFromParent();
21860b57cec5SDimitry Andric   if (FullUnswitch) {
21870b57cec5SDimitry Andric     // Splice the terminator from the original loop and rewrite its
21880b57cec5SDimitry Andric     // successors.
21890b57cec5SDimitry Andric     SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric     // Keep a clone of the terminator for MSSA updates.
21920b57cec5SDimitry Andric     Instruction *NewTI = TI.clone();
21930b57cec5SDimitry Andric     ParentBB->getInstList().push_back(NewTI);
21940b57cec5SDimitry Andric 
21950b57cec5SDimitry Andric     // First wire up the moved terminator to the preheaders.
21960b57cec5SDimitry Andric     if (BI) {
21970b57cec5SDimitry Andric       BasicBlock *ClonedPH = ClonedPHs.begin()->second;
21980b57cec5SDimitry Andric       BI->setSuccessor(ClonedSucc, ClonedPH);
21990b57cec5SDimitry Andric       BI->setSuccessor(1 - ClonedSucc, LoopPH);
22000b57cec5SDimitry Andric       DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
22010b57cec5SDimitry Andric     } else {
22020b57cec5SDimitry Andric       assert(SI && "Must either be a branch or switch!");
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric       // Walk the cases and directly update their successors.
22050b57cec5SDimitry Andric       assert(SI->getDefaultDest() == RetainedSuccBB &&
22060b57cec5SDimitry Andric              "Not retaining default successor!");
22070b57cec5SDimitry Andric       SI->setDefaultDest(LoopPH);
22080b57cec5SDimitry Andric       for (auto &Case : SI->cases())
22090b57cec5SDimitry Andric         if (Case.getCaseSuccessor() == RetainedSuccBB)
22100b57cec5SDimitry Andric           Case.setSuccessor(LoopPH);
22110b57cec5SDimitry Andric         else
22120b57cec5SDimitry Andric           Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
22130b57cec5SDimitry Andric 
22140b57cec5SDimitry Andric       // We need to use the set to populate domtree updates as even when there
22150b57cec5SDimitry Andric       // are multiple cases pointing at the same successor we only want to
22160b57cec5SDimitry Andric       // remove and insert one edge in the domtree.
22170b57cec5SDimitry Andric       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
22180b57cec5SDimitry Andric         DTUpdates.push_back(
22190b57cec5SDimitry Andric             {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
22200b57cec5SDimitry Andric     }
22210b57cec5SDimitry Andric 
22220b57cec5SDimitry Andric     if (MSSAU) {
22230b57cec5SDimitry Andric       DT.applyUpdates(DTUpdates);
22240b57cec5SDimitry Andric       DTUpdates.clear();
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric       // Remove all but one edge to the retained block and all unswitched
22270b57cec5SDimitry Andric       // blocks. This is to avoid having duplicate entries in the cloned Phis,
22280b57cec5SDimitry Andric       // when we know we only keep a single edge for each case.
22290b57cec5SDimitry Andric       MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
22300b57cec5SDimitry Andric       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
22310b57cec5SDimitry Andric         MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric       for (auto &VMap : VMaps)
22340b57cec5SDimitry Andric         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
22350b57cec5SDimitry Andric                                    /*IgnoreIncomingWithNoClones=*/true);
22360b57cec5SDimitry Andric       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
22370b57cec5SDimitry Andric 
22380b57cec5SDimitry Andric       // Remove all edges to unswitched blocks.
22390b57cec5SDimitry Andric       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
22400b57cec5SDimitry Andric         MSSAU->removeEdge(ParentBB, SuccBB);
22410b57cec5SDimitry Andric     }
22420b57cec5SDimitry Andric 
22430b57cec5SDimitry Andric     // Now unhook the successor relationship as we'll be replacing
22440b57cec5SDimitry Andric     // the terminator with a direct branch. This is much simpler for branches
22450b57cec5SDimitry Andric     // than switches so we handle those first.
22460b57cec5SDimitry Andric     if (BI) {
22470b57cec5SDimitry Andric       // Remove the parent as a predecessor of the unswitched successor.
22480b57cec5SDimitry Andric       assert(UnswitchedSuccBBs.size() == 1 &&
22490b57cec5SDimitry Andric              "Only one possible unswitched block for a branch!");
22500b57cec5SDimitry Andric       BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
22510b57cec5SDimitry Andric       UnswitchedSuccBB->removePredecessor(ParentBB,
22520b57cec5SDimitry Andric                                           /*KeepOneInputPHIs*/ true);
22530b57cec5SDimitry Andric       DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
22540b57cec5SDimitry Andric     } else {
22550b57cec5SDimitry Andric       // Note that we actually want to remove the parent block as a predecessor
22560b57cec5SDimitry Andric       // of *every* case successor. The case successor is either unswitched,
22570b57cec5SDimitry Andric       // completely eliminating an edge from the parent to that successor, or it
22580b57cec5SDimitry Andric       // is a duplicate edge to the retained successor as the retained successor
22590b57cec5SDimitry Andric       // is always the default successor and as we'll replace this with a direct
22600b57cec5SDimitry Andric       // branch we no longer need the duplicate entries in the PHI nodes.
22610b57cec5SDimitry Andric       SwitchInst *NewSI = cast<SwitchInst>(NewTI);
22620b57cec5SDimitry Andric       assert(NewSI->getDefaultDest() == RetainedSuccBB &&
22630b57cec5SDimitry Andric              "Not retaining default successor!");
22640b57cec5SDimitry Andric       for (auto &Case : NewSI->cases())
22650b57cec5SDimitry Andric         Case.getCaseSuccessor()->removePredecessor(
22660b57cec5SDimitry Andric             ParentBB,
22670b57cec5SDimitry Andric             /*KeepOneInputPHIs*/ true);
22680b57cec5SDimitry Andric 
22690b57cec5SDimitry Andric       // We need to use the set to populate domtree updates as even when there
22700b57cec5SDimitry Andric       // are multiple cases pointing at the same successor we only want to
22710b57cec5SDimitry Andric       // remove and insert one edge in the domtree.
22720b57cec5SDimitry Andric       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
22730b57cec5SDimitry Andric         DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
22740b57cec5SDimitry Andric     }
22750b57cec5SDimitry Andric 
22760b57cec5SDimitry Andric     // After MSSAU update, remove the cloned terminator instruction NewTI.
22770b57cec5SDimitry Andric     ParentBB->getTerminator()->eraseFromParent();
22780b57cec5SDimitry Andric 
22790b57cec5SDimitry Andric     // Create a new unconditional branch to the continuing block (as opposed to
22800b57cec5SDimitry Andric     // the one cloned).
22810b57cec5SDimitry Andric     BranchInst::Create(RetainedSuccBB, ParentBB);
22820b57cec5SDimitry Andric   } else {
22830b57cec5SDimitry Andric     assert(BI && "Only branches have partial unswitching.");
22840b57cec5SDimitry Andric     assert(UnswitchedSuccBBs.size() == 1 &&
22850b57cec5SDimitry Andric            "Only one possible unswitched block for a branch!");
22860b57cec5SDimitry Andric     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
22870b57cec5SDimitry Andric     // When doing a partial unswitch, we have to do a bit more work to build up
22880b57cec5SDimitry Andric     // the branch in the split block.
22895f7ddb14SDimitry Andric     if (PartiallyInvariant)
22905f7ddb14SDimitry Andric       buildPartialInvariantUnswitchConditionalBranch(
22915f7ddb14SDimitry Andric           *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH, L, MSSAU);
22925f7ddb14SDimitry Andric     else
22930b57cec5SDimitry Andric       buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
22940b57cec5SDimitry Andric                                             *ClonedPH, *LoopPH);
22950b57cec5SDimitry Andric     DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
22968bcb0991SDimitry Andric 
22978bcb0991SDimitry Andric     if (MSSAU) {
22988bcb0991SDimitry Andric       DT.applyUpdates(DTUpdates);
22998bcb0991SDimitry Andric       DTUpdates.clear();
23008bcb0991SDimitry Andric 
23018bcb0991SDimitry Andric       // Perform MSSA cloning updates.
23028bcb0991SDimitry Andric       for (auto &VMap : VMaps)
23038bcb0991SDimitry Andric         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
23048bcb0991SDimitry Andric                                    /*IgnoreIncomingWithNoClones=*/true);
23058bcb0991SDimitry Andric       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
23068bcb0991SDimitry Andric     }
23070b57cec5SDimitry Andric   }
23080b57cec5SDimitry Andric 
23090b57cec5SDimitry Andric   // Apply the updates accumulated above to get an up-to-date dominator tree.
23100b57cec5SDimitry Andric   DT.applyUpdates(DTUpdates);
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric   // Now that we have an accurate dominator tree, first delete the dead cloned
23130b57cec5SDimitry Andric   // blocks so that we can accurately build any cloned loops. It is important to
23140b57cec5SDimitry Andric   // not delete the blocks from the original loop yet because we still want to
23150b57cec5SDimitry Andric   // reference the original loop to understand the cloned loop's structure.
23160b57cec5SDimitry Andric   deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
23170b57cec5SDimitry Andric 
23180b57cec5SDimitry Andric   // Build the cloned loop structure itself. This may be substantially
23190b57cec5SDimitry Andric   // different from the original structure due to the simplified CFG. This also
23200b57cec5SDimitry Andric   // handles inserting all the cloned blocks into the correct loops.
23210b57cec5SDimitry Andric   SmallVector<Loop *, 4> NonChildClonedLoops;
23220b57cec5SDimitry Andric   for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
23230b57cec5SDimitry Andric     buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric   // Now that our cloned loops have been built, we can update the original loop.
23260b57cec5SDimitry Andric   // First we delete the dead blocks from it and then we rebuild the loop
23270b57cec5SDimitry Andric   // structure taking these deletions into account.
2328*18baa991SDimitry Andric   deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU, DestroyLoopCB);
23290b57cec5SDimitry Andric 
23300b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
23310b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
23320b57cec5SDimitry Andric 
23330b57cec5SDimitry Andric   SmallVector<Loop *, 4> HoistedLoops;
23340b57cec5SDimitry Andric   bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
23350b57cec5SDimitry Andric 
23360b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
23370b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric   // This transformation has a high risk of corrupting the dominator tree, and
23400b57cec5SDimitry Andric   // the below steps to rebuild loop structures will result in hard to debug
23410b57cec5SDimitry Andric   // errors in that case so verify that the dominator tree is sane first.
23420b57cec5SDimitry Andric   // FIXME: Remove this when the bugs stop showing up and rely on existing
23430b57cec5SDimitry Andric   // verification steps.
23440b57cec5SDimitry Andric   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
23450b57cec5SDimitry Andric 
23465f7ddb14SDimitry Andric   if (BI && !PartiallyInvariant) {
23470b57cec5SDimitry Andric     // If we unswitched a branch which collapses the condition to a known
23480b57cec5SDimitry Andric     // constant we want to replace all the uses of the invariants within both
23490b57cec5SDimitry Andric     // the original and cloned blocks. We do this here so that we can use the
23500b57cec5SDimitry Andric     // now updated dominator tree to identify which side the users are on.
23510b57cec5SDimitry Andric     assert(UnswitchedSuccBBs.size() == 1 &&
23520b57cec5SDimitry Andric            "Only one possible unswitched block for a branch!");
23530b57cec5SDimitry Andric     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
23540b57cec5SDimitry Andric 
23550b57cec5SDimitry Andric     // When considering multiple partially-unswitched invariants
23560b57cec5SDimitry Andric     // we cant just go replace them with constants in both branches.
23570b57cec5SDimitry Andric     //
23580b57cec5SDimitry Andric     // For 'AND' we infer that true branch ("continue") means true
23590b57cec5SDimitry Andric     // for each invariant operand.
23600b57cec5SDimitry Andric     // For 'OR' we can infer that false branch ("continue") means false
23610b57cec5SDimitry Andric     // for each invariant operand.
23620b57cec5SDimitry Andric     // So it happens that for multiple-partial case we dont replace
23630b57cec5SDimitry Andric     // in the unswitched branch.
23645f7ddb14SDimitry Andric     bool ReplaceUnswitched =
23655f7ddb14SDimitry Andric         FullUnswitch || (Invariants.size() == 1) || PartiallyInvariant;
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric     ConstantInt *UnswitchedReplacement =
23680b57cec5SDimitry Andric         Direction ? ConstantInt::getTrue(BI->getContext())
23690b57cec5SDimitry Andric                   : ConstantInt::getFalse(BI->getContext());
23700b57cec5SDimitry Andric     ConstantInt *ContinueReplacement =
23710b57cec5SDimitry Andric         Direction ? ConstantInt::getFalse(BI->getContext())
23720b57cec5SDimitry Andric                   : ConstantInt::getTrue(BI->getContext());
23730b57cec5SDimitry Andric     for (Value *Invariant : Invariants)
23745f7ddb14SDimitry Andric       // Use make_early_inc_range here as set invalidates the iterator.
23755f7ddb14SDimitry Andric       for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
23765f7ddb14SDimitry Andric         Instruction *UserI = dyn_cast<Instruction>(U.getUser());
23770b57cec5SDimitry Andric         if (!UserI)
23780b57cec5SDimitry Andric           continue;
23790b57cec5SDimitry Andric 
23800b57cec5SDimitry Andric         // Replace it with the 'continue' side if in the main loop body, and the
23810b57cec5SDimitry Andric         // unswitched if in the cloned blocks.
23820b57cec5SDimitry Andric         if (DT.dominates(LoopPH, UserI->getParent()))
23835f7ddb14SDimitry Andric           U.set(ContinueReplacement);
23840b57cec5SDimitry Andric         else if (ReplaceUnswitched &&
23850b57cec5SDimitry Andric                  DT.dominates(ClonedPH, UserI->getParent()))
23865f7ddb14SDimitry Andric           U.set(UnswitchedReplacement);
23870b57cec5SDimitry Andric       }
23880b57cec5SDimitry Andric   }
23890b57cec5SDimitry Andric 
23900b57cec5SDimitry Andric   // We can change which blocks are exit blocks of all the cloned sibling
23910b57cec5SDimitry Andric   // loops, the current loop, and any parent loops which shared exit blocks
23920b57cec5SDimitry Andric   // with the current loop. As a consequence, we need to re-form LCSSA for
23930b57cec5SDimitry Andric   // them. But we shouldn't need to re-form LCSSA for any child loops.
23940b57cec5SDimitry Andric   // FIXME: This could be made more efficient by tracking which exit blocks are
23950b57cec5SDimitry Andric   // new, and focusing on them, but that isn't likely to be necessary.
23960b57cec5SDimitry Andric   //
23970b57cec5SDimitry Andric   // In order to reasonably rebuild LCSSA we need to walk inside-out across the
23980b57cec5SDimitry Andric   // loop nest and update every loop that could have had its exits changed. We
23990b57cec5SDimitry Andric   // also need to cover any intervening loops. We add all of these loops to
24000b57cec5SDimitry Andric   // a list and sort them by loop depth to achieve this without updating
24010b57cec5SDimitry Andric   // unnecessary loops.
24020b57cec5SDimitry Andric   auto UpdateLoop = [&](Loop &UpdateL) {
24030b57cec5SDimitry Andric #ifndef NDEBUG
24040b57cec5SDimitry Andric     UpdateL.verifyLoop();
24050b57cec5SDimitry Andric     for (Loop *ChildL : UpdateL) {
24060b57cec5SDimitry Andric       ChildL->verifyLoop();
24070b57cec5SDimitry Andric       assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
24080b57cec5SDimitry Andric              "Perturbed a child loop's LCSSA form!");
24090b57cec5SDimitry Andric     }
24100b57cec5SDimitry Andric #endif
24110b57cec5SDimitry Andric     // First build LCSSA for this loop so that we can preserve it when
24120b57cec5SDimitry Andric     // forming dedicated exits. We don't want to perturb some other loop's
24130b57cec5SDimitry Andric     // LCSSA while doing that CFG edit.
2414480093f4SDimitry Andric     formLCSSA(UpdateL, DT, &LI, SE);
24150b57cec5SDimitry Andric 
24160b57cec5SDimitry Andric     // For loops reached by this loop's original exit blocks we may
24170b57cec5SDimitry Andric     // introduced new, non-dedicated exits. At least try to re-form dedicated
24180b57cec5SDimitry Andric     // exits for these loops. This may fail if they couldn't have dedicated
24190b57cec5SDimitry Andric     // exits to start with.
24200b57cec5SDimitry Andric     formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
24210b57cec5SDimitry Andric   };
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric   // For non-child cloned loops and hoisted loops, we just need to update LCSSA
24240b57cec5SDimitry Andric   // and we can do it in any order as they don't nest relative to each other.
24250b57cec5SDimitry Andric   //
24260b57cec5SDimitry Andric   // Also check if any of the loops we have updated have become top-level loops
24270b57cec5SDimitry Andric   // as that will necessitate widening the outer loop scope.
24280b57cec5SDimitry Andric   for (Loop *UpdatedL :
24290b57cec5SDimitry Andric        llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
24300b57cec5SDimitry Andric     UpdateLoop(*UpdatedL);
2431af732203SDimitry Andric     if (UpdatedL->isOutermost())
24320b57cec5SDimitry Andric       OuterExitL = nullptr;
24330b57cec5SDimitry Andric   }
24340b57cec5SDimitry Andric   if (IsStillLoop) {
24350b57cec5SDimitry Andric     UpdateLoop(L);
2436af732203SDimitry Andric     if (L.isOutermost())
24370b57cec5SDimitry Andric       OuterExitL = nullptr;
24380b57cec5SDimitry Andric   }
24390b57cec5SDimitry Andric 
24400b57cec5SDimitry Andric   // If the original loop had exit blocks, walk up through the outer most loop
24410b57cec5SDimitry Andric   // of those exit blocks to update LCSSA and form updated dedicated exits.
24420b57cec5SDimitry Andric   if (OuterExitL != &L)
24430b57cec5SDimitry Andric     for (Loop *OuterL = ParentL; OuterL != OuterExitL;
24440b57cec5SDimitry Andric          OuterL = OuterL->getParentLoop())
24450b57cec5SDimitry Andric       UpdateLoop(*OuterL);
24460b57cec5SDimitry Andric 
24470b57cec5SDimitry Andric #ifndef NDEBUG
24480b57cec5SDimitry Andric   // Verify the entire loop structure to catch any incorrect updates before we
24490b57cec5SDimitry Andric   // progress in the pass pipeline.
24500b57cec5SDimitry Andric   LI.verify(DT);
24510b57cec5SDimitry Andric #endif
24520b57cec5SDimitry Andric 
24530b57cec5SDimitry Andric   // Now that we've unswitched something, make callbacks to report the changes.
24540b57cec5SDimitry Andric   // For that we need to merge together the updated loops and the cloned loops
24550b57cec5SDimitry Andric   // and check whether the original loop survived.
24560b57cec5SDimitry Andric   SmallVector<Loop *, 4> SibLoops;
24570b57cec5SDimitry Andric   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
24580b57cec5SDimitry Andric     if (UpdatedL->getParentLoop() == ParentL)
24590b57cec5SDimitry Andric       SibLoops.push_back(UpdatedL);
24605f7ddb14SDimitry Andric   UnswitchCB(IsStillLoop, PartiallyInvariant, SibLoops);
24610b57cec5SDimitry Andric 
24620b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
24630b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
24640b57cec5SDimitry Andric 
24650b57cec5SDimitry Andric   if (BI)
24660b57cec5SDimitry Andric     ++NumBranches;
24670b57cec5SDimitry Andric   else
24680b57cec5SDimitry Andric     ++NumSwitches;
24690b57cec5SDimitry Andric }
24700b57cec5SDimitry Andric 
24710b57cec5SDimitry Andric /// Recursively compute the cost of a dominator subtree based on the per-block
24720b57cec5SDimitry Andric /// cost map provided.
24730b57cec5SDimitry Andric ///
24740b57cec5SDimitry Andric /// The recursive computation is memozied into the provided DT-indexed cost map
24750b57cec5SDimitry Andric /// to allow querying it for most nodes in the domtree without it becoming
24760b57cec5SDimitry Andric /// quadratic.
computeDomSubtreeCost(DomTreeNode & N,const SmallDenseMap<BasicBlock *,InstructionCost,4> & BBCostMap,SmallDenseMap<DomTreeNode *,InstructionCost,4> & DTCostMap)24775f7ddb14SDimitry Andric static InstructionCost computeDomSubtreeCost(
24785f7ddb14SDimitry Andric     DomTreeNode &N,
24795f7ddb14SDimitry Andric     const SmallDenseMap<BasicBlock *, InstructionCost, 4> &BBCostMap,
24805f7ddb14SDimitry Andric     SmallDenseMap<DomTreeNode *, InstructionCost, 4> &DTCostMap) {
24810b57cec5SDimitry Andric   // Don't accumulate cost (or recurse through) blocks not in our block cost
24820b57cec5SDimitry Andric   // map and thus not part of the duplication cost being considered.
24830b57cec5SDimitry Andric   auto BBCostIt = BBCostMap.find(N.getBlock());
24840b57cec5SDimitry Andric   if (BBCostIt == BBCostMap.end())
24850b57cec5SDimitry Andric     return 0;
24860b57cec5SDimitry Andric 
24870b57cec5SDimitry Andric   // Lookup this node to see if we already computed its cost.
24880b57cec5SDimitry Andric   auto DTCostIt = DTCostMap.find(&N);
24890b57cec5SDimitry Andric   if (DTCostIt != DTCostMap.end())
24900b57cec5SDimitry Andric     return DTCostIt->second;
24910b57cec5SDimitry Andric 
24920b57cec5SDimitry Andric   // If not, we have to compute it. We can't use insert above and update
24930b57cec5SDimitry Andric   // because computing the cost may insert more things into the map.
24945f7ddb14SDimitry Andric   InstructionCost Cost = std::accumulate(
24955f7ddb14SDimitry Andric       N.begin(), N.end(), BBCostIt->second,
24965f7ddb14SDimitry Andric       [&](InstructionCost Sum, DomTreeNode *ChildN) -> InstructionCost {
24970b57cec5SDimitry Andric         return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
24980b57cec5SDimitry Andric       });
24990b57cec5SDimitry Andric   bool Inserted = DTCostMap.insert({&N, Cost}).second;
25000b57cec5SDimitry Andric   (void)Inserted;
25010b57cec5SDimitry Andric   assert(Inserted && "Should not insert a node while visiting children!");
25020b57cec5SDimitry Andric   return Cost;
25030b57cec5SDimitry Andric }
25040b57cec5SDimitry Andric 
25050b57cec5SDimitry Andric /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
25060b57cec5SDimitry Andric /// making the following replacement:
25070b57cec5SDimitry Andric ///
25080b57cec5SDimitry Andric ///   --code before guard--
25090b57cec5SDimitry Andric ///   call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
25100b57cec5SDimitry Andric ///   --code after guard--
25110b57cec5SDimitry Andric ///
25120b57cec5SDimitry Andric /// into
25130b57cec5SDimitry Andric ///
25140b57cec5SDimitry Andric ///   --code before guard--
25150b57cec5SDimitry Andric ///   br i1 %cond, label %guarded, label %deopt
25160b57cec5SDimitry Andric ///
25170b57cec5SDimitry Andric /// guarded:
25180b57cec5SDimitry Andric ///   --code after guard--
25190b57cec5SDimitry Andric ///
25200b57cec5SDimitry Andric /// deopt:
25210b57cec5SDimitry Andric ///   call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
25220b57cec5SDimitry Andric ///   unreachable
25230b57cec5SDimitry Andric ///
25240b57cec5SDimitry Andric /// It also makes all relevant DT and LI updates, so that all structures are in
25250b57cec5SDimitry Andric /// valid state after this transform.
25260b57cec5SDimitry Andric static BranchInst *
turnGuardIntoBranch(IntrinsicInst * GI,Loop & L,SmallVectorImpl<BasicBlock * > & ExitBlocks,DominatorTree & DT,LoopInfo & LI,MemorySSAUpdater * MSSAU)25270b57cec5SDimitry Andric turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
25280b57cec5SDimitry Andric                     SmallVectorImpl<BasicBlock *> &ExitBlocks,
25290b57cec5SDimitry Andric                     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
25300b57cec5SDimitry Andric   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
25310b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
25320b57cec5SDimitry Andric   BasicBlock *CheckBB = GI->getParent();
25330b57cec5SDimitry Andric 
25340b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
25350b57cec5SDimitry Andric      MSSAU->getMemorySSA()->verifyMemorySSA();
25360b57cec5SDimitry Andric 
25370b57cec5SDimitry Andric   // Remove all CheckBB's successors from DomTree. A block can be seen among
25380b57cec5SDimitry Andric   // successors more than once, but for DomTree it should be added only once.
25390b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 4> Successors;
25400b57cec5SDimitry Andric   for (auto *Succ : successors(CheckBB))
25410b57cec5SDimitry Andric     if (Successors.insert(Succ).second)
25420b57cec5SDimitry Andric       DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
25430b57cec5SDimitry Andric 
25440b57cec5SDimitry Andric   Instruction *DeoptBlockTerm =
25450b57cec5SDimitry Andric       SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
25460b57cec5SDimitry Andric   BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
25470b57cec5SDimitry Andric   // SplitBlockAndInsertIfThen inserts control flow that branches to
25480b57cec5SDimitry Andric   // DeoptBlockTerm if the condition is true.  We want the opposite.
25490b57cec5SDimitry Andric   CheckBI->swapSuccessors();
25500b57cec5SDimitry Andric 
25510b57cec5SDimitry Andric   BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
25520b57cec5SDimitry Andric   GuardedBlock->setName("guarded");
25530b57cec5SDimitry Andric   CheckBI->getSuccessor(1)->setName("deopt");
25540b57cec5SDimitry Andric   BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
25550b57cec5SDimitry Andric 
25560b57cec5SDimitry Andric   // We now have a new exit block.
25570b57cec5SDimitry Andric   ExitBlocks.push_back(CheckBI->getSuccessor(1));
25580b57cec5SDimitry Andric 
25590b57cec5SDimitry Andric   if (MSSAU)
25600b57cec5SDimitry Andric     MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
25610b57cec5SDimitry Andric 
25620b57cec5SDimitry Andric   GI->moveBefore(DeoptBlockTerm);
25630b57cec5SDimitry Andric   GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
25640b57cec5SDimitry Andric 
25650b57cec5SDimitry Andric   // Add new successors of CheckBB into DomTree.
25660b57cec5SDimitry Andric   for (auto *Succ : successors(CheckBB))
25670b57cec5SDimitry Andric     DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
25680b57cec5SDimitry Andric 
25690b57cec5SDimitry Andric   // Now the blocks that used to be CheckBB's successors are GuardedBlock's
25700b57cec5SDimitry Andric   // successors.
25710b57cec5SDimitry Andric   for (auto *Succ : Successors)
25720b57cec5SDimitry Andric     DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
25730b57cec5SDimitry Andric 
25740b57cec5SDimitry Andric   // Make proper changes to DT.
25750b57cec5SDimitry Andric   DT.applyUpdates(DTUpdates);
25760b57cec5SDimitry Andric   // Inform LI of a new loop block.
25770b57cec5SDimitry Andric   L.addBasicBlockToLoop(GuardedBlock, LI);
25780b57cec5SDimitry Andric 
25790b57cec5SDimitry Andric   if (MSSAU) {
25800b57cec5SDimitry Andric     MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2581480093f4SDimitry Andric     MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::BeforeTerminator);
25820b57cec5SDimitry Andric     if (VerifyMemorySSA)
25830b57cec5SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
25840b57cec5SDimitry Andric   }
25850b57cec5SDimitry Andric 
25860b57cec5SDimitry Andric   ++NumGuards;
25870b57cec5SDimitry Andric   return CheckBI;
25880b57cec5SDimitry Andric }
25890b57cec5SDimitry Andric 
25900b57cec5SDimitry Andric /// Cost multiplier is a way to limit potentially exponential behavior
25910b57cec5SDimitry Andric /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
25920b57cec5SDimitry Andric /// candidates available. Also accounting for the number of "sibling" loops with
25930b57cec5SDimitry Andric /// the idea to account for previous unswitches that already happened on this
25940b57cec5SDimitry Andric /// cluster of loops. There was an attempt to keep this formula simple,
25950b57cec5SDimitry Andric /// just enough to limit the worst case behavior. Even if it is not that simple
25960b57cec5SDimitry Andric /// now it is still not an attempt to provide a detailed heuristic size
25970b57cec5SDimitry Andric /// prediction.
25980b57cec5SDimitry Andric ///
25990b57cec5SDimitry Andric /// TODO: Make a proper accounting of "explosion" effect for all kinds of
26000b57cec5SDimitry Andric /// unswitch candidates, making adequate predictions instead of wild guesses.
26010b57cec5SDimitry Andric /// That requires knowing not just the number of "remaining" candidates but
26020b57cec5SDimitry Andric /// also costs of unswitching for each of these candidates.
CalculateUnswitchCostMultiplier(Instruction & TI,Loop & L,LoopInfo & LI,DominatorTree & DT,ArrayRef<std::pair<Instruction *,TinyPtrVector<Value * >>> UnswitchCandidates)26035ffd83dbSDimitry Andric static int CalculateUnswitchCostMultiplier(
26040b57cec5SDimitry Andric     Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
26050b57cec5SDimitry Andric     ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
26060b57cec5SDimitry Andric         UnswitchCandidates) {
26070b57cec5SDimitry Andric 
26080b57cec5SDimitry Andric   // Guards and other exiting conditions do not contribute to exponential
26090b57cec5SDimitry Andric   // explosion as soon as they dominate the latch (otherwise there might be
26100b57cec5SDimitry Andric   // another path to the latch remaining that does not allow to eliminate the
26110b57cec5SDimitry Andric   // loop copy on unswitch).
26120b57cec5SDimitry Andric   BasicBlock *Latch = L.getLoopLatch();
26130b57cec5SDimitry Andric   BasicBlock *CondBlock = TI.getParent();
26140b57cec5SDimitry Andric   if (DT.dominates(CondBlock, Latch) &&
26150b57cec5SDimitry Andric       (isGuard(&TI) ||
26160b57cec5SDimitry Andric        llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
26170b57cec5SDimitry Andric          return L.contains(SuccBB);
26180b57cec5SDimitry Andric        }) <= 1)) {
26190b57cec5SDimitry Andric     NumCostMultiplierSkipped++;
26200b57cec5SDimitry Andric     return 1;
26210b57cec5SDimitry Andric   }
26220b57cec5SDimitry Andric 
26230b57cec5SDimitry Andric   auto *ParentL = L.getParentLoop();
26240b57cec5SDimitry Andric   int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
26250b57cec5SDimitry Andric                                : std::distance(LI.begin(), LI.end()));
26260b57cec5SDimitry Andric   // Count amount of clones that all the candidates might cause during
26270b57cec5SDimitry Andric   // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
26280b57cec5SDimitry Andric   int UnswitchedClones = 0;
26290b57cec5SDimitry Andric   for (auto Candidate : UnswitchCandidates) {
26300b57cec5SDimitry Andric     Instruction *CI = Candidate.first;
26310b57cec5SDimitry Andric     BasicBlock *CondBlock = CI->getParent();
26320b57cec5SDimitry Andric     bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
26330b57cec5SDimitry Andric     if (isGuard(CI)) {
26340b57cec5SDimitry Andric       if (!SkipExitingSuccessors)
26350b57cec5SDimitry Andric         UnswitchedClones++;
26360b57cec5SDimitry Andric       continue;
26370b57cec5SDimitry Andric     }
26380b57cec5SDimitry Andric     int NonExitingSuccessors = llvm::count_if(
26390b57cec5SDimitry Andric         successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
26400b57cec5SDimitry Andric           return !SkipExitingSuccessors || L.contains(SuccBB);
26410b57cec5SDimitry Andric         });
26420b57cec5SDimitry Andric     UnswitchedClones += Log2_32(NonExitingSuccessors);
26430b57cec5SDimitry Andric   }
26440b57cec5SDimitry Andric 
26450b57cec5SDimitry Andric   // Ignore up to the "unscaled candidates" number of unswitch candidates
26460b57cec5SDimitry Andric   // when calculating the power-of-two scaling of the cost. The main idea
26470b57cec5SDimitry Andric   // with this control is to allow a small number of unswitches to happen
26480b57cec5SDimitry Andric   // and rely more on siblings multiplier (see below) when the number
26490b57cec5SDimitry Andric   // of candidates is small.
26500b57cec5SDimitry Andric   unsigned ClonesPower =
26510b57cec5SDimitry Andric       std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
26520b57cec5SDimitry Andric 
26530b57cec5SDimitry Andric   // Allowing top-level loops to spread a bit more than nested ones.
26540b57cec5SDimitry Andric   int SiblingsMultiplier =
26550b57cec5SDimitry Andric       std::max((ParentL ? SiblingsCount
26560b57cec5SDimitry Andric                         : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
26570b57cec5SDimitry Andric                1);
26580b57cec5SDimitry Andric   // Compute the cost multiplier in a way that won't overflow by saturating
26590b57cec5SDimitry Andric   // at an upper bound.
26600b57cec5SDimitry Andric   int CostMultiplier;
26610b57cec5SDimitry Andric   if (ClonesPower > Log2_32(UnswitchThreshold) ||
26620b57cec5SDimitry Andric       SiblingsMultiplier > UnswitchThreshold)
26630b57cec5SDimitry Andric     CostMultiplier = UnswitchThreshold;
26640b57cec5SDimitry Andric   else
26650b57cec5SDimitry Andric     CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
26660b57cec5SDimitry Andric                               (int)UnswitchThreshold);
26670b57cec5SDimitry Andric 
26680b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Computed multiplier  " << CostMultiplier
26690b57cec5SDimitry Andric                     << " (siblings " << SiblingsMultiplier << " * clones "
26700b57cec5SDimitry Andric                     << (1 << ClonesPower) << ")"
26710b57cec5SDimitry Andric                     << " for unswitch candidate: " << TI << "\n");
26720b57cec5SDimitry Andric   return CostMultiplier;
26730b57cec5SDimitry Andric }
26740b57cec5SDimitry Andric 
unswitchBestCondition(Loop & L,DominatorTree & DT,LoopInfo & LI,AssumptionCache & AC,AAResults & AA,TargetTransformInfo & TTI,function_ref<void (bool,bool,ArrayRef<Loop * >)> UnswitchCB,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,function_ref<void (Loop &,StringRef)> DestroyLoopCB)26755f7ddb14SDimitry Andric static bool unswitchBestCondition(
26765f7ddb14SDimitry Andric     Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
26775f7ddb14SDimitry Andric     AAResults &AA, TargetTransformInfo &TTI,
26785f7ddb14SDimitry Andric     function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
2679*18baa991SDimitry Andric     ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
2680*18baa991SDimitry Andric     function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
26810b57cec5SDimitry Andric   // Collect all invariant conditions within this loop (as opposed to an inner
26820b57cec5SDimitry Andric   // loop which would be handled when visiting that inner loop).
26830b57cec5SDimitry Andric   SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
26840b57cec5SDimitry Andric       UnswitchCandidates;
26850b57cec5SDimitry Andric 
26860b57cec5SDimitry Andric   // Whether or not we should also collect guards in the loop.
26870b57cec5SDimitry Andric   bool CollectGuards = false;
26880b57cec5SDimitry Andric   if (UnswitchGuards) {
26890b57cec5SDimitry Andric     auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
26900b57cec5SDimitry Andric         Intrinsic::getName(Intrinsic::experimental_guard));
26910b57cec5SDimitry Andric     if (GuardDecl && !GuardDecl->use_empty())
26920b57cec5SDimitry Andric       CollectGuards = true;
26930b57cec5SDimitry Andric   }
26940b57cec5SDimitry Andric 
26955f7ddb14SDimitry Andric   IVConditionInfo PartialIVInfo;
26960b57cec5SDimitry Andric   for (auto *BB : L.blocks()) {
26970b57cec5SDimitry Andric     if (LI.getLoopFor(BB) != &L)
26980b57cec5SDimitry Andric       continue;
26990b57cec5SDimitry Andric 
27000b57cec5SDimitry Andric     if (CollectGuards)
27010b57cec5SDimitry Andric       for (auto &I : *BB)
27020b57cec5SDimitry Andric         if (isGuard(&I)) {
27030b57cec5SDimitry Andric           auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
27040b57cec5SDimitry Andric           // TODO: Support AND, OR conditions and partial unswitching.
27050b57cec5SDimitry Andric           if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
27060b57cec5SDimitry Andric             UnswitchCandidates.push_back({&I, {Cond}});
27070b57cec5SDimitry Andric         }
27080b57cec5SDimitry Andric 
27090b57cec5SDimitry Andric     if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
27100b57cec5SDimitry Andric       // We can only consider fully loop-invariant switch conditions as we need
27110b57cec5SDimitry Andric       // to completely eliminate the switch after unswitching.
27120b57cec5SDimitry Andric       if (!isa<Constant>(SI->getCondition()) &&
27130b57cec5SDimitry Andric           L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor())
27140b57cec5SDimitry Andric         UnswitchCandidates.push_back({SI, {SI->getCondition()}});
27150b57cec5SDimitry Andric       continue;
27160b57cec5SDimitry Andric     }
27170b57cec5SDimitry Andric 
27180b57cec5SDimitry Andric     auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
27190b57cec5SDimitry Andric     if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
27200b57cec5SDimitry Andric         BI->getSuccessor(0) == BI->getSuccessor(1))
27210b57cec5SDimitry Andric       continue;
27220b57cec5SDimitry Andric 
27235f7ddb14SDimitry Andric     // If BI's condition is 'select _, true, false', simplify it to confuse
27245f7ddb14SDimitry Andric     // matchers
27255f7ddb14SDimitry Andric     Value *Cond = BI->getCondition(), *CondNext;
27265f7ddb14SDimitry Andric     while (match(Cond, m_Select(m_Value(CondNext), m_One(), m_Zero())))
27275f7ddb14SDimitry Andric       Cond = CondNext;
27285f7ddb14SDimitry Andric     BI->setCondition(Cond);
27295f7ddb14SDimitry Andric 
27300b57cec5SDimitry Andric     if (L.isLoopInvariant(BI->getCondition())) {
27310b57cec5SDimitry Andric       UnswitchCandidates.push_back({BI, {BI->getCondition()}});
27320b57cec5SDimitry Andric       continue;
27330b57cec5SDimitry Andric     }
27340b57cec5SDimitry Andric 
27350b57cec5SDimitry Andric     Instruction &CondI = *cast<Instruction>(BI->getCondition());
27365f7ddb14SDimitry Andric     if (match(&CondI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()))) {
27370b57cec5SDimitry Andric       TinyPtrVector<Value *> Invariants =
27380b57cec5SDimitry Andric           collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
27390b57cec5SDimitry Andric       if (Invariants.empty())
27400b57cec5SDimitry Andric         continue;
27410b57cec5SDimitry Andric 
27420b57cec5SDimitry Andric       UnswitchCandidates.push_back({BI, std::move(Invariants)});
27435f7ddb14SDimitry Andric       continue;
27445f7ddb14SDimitry Andric     }
27455f7ddb14SDimitry Andric   }
27465f7ddb14SDimitry Andric 
27475f7ddb14SDimitry Andric   Instruction *PartialIVCondBranch = nullptr;
27485f7ddb14SDimitry Andric   if (MSSAU && !findOptionMDForLoop(&L, "llvm.loop.unswitch.partial.disable") &&
27495f7ddb14SDimitry Andric       !any_of(UnswitchCandidates, [&L](auto &TerminatorAndInvariants) {
27505f7ddb14SDimitry Andric         return TerminatorAndInvariants.first == L.getHeader()->getTerminator();
27515f7ddb14SDimitry Andric       })) {
27525f7ddb14SDimitry Andric     MemorySSA *MSSA = MSSAU->getMemorySSA();
27535f7ddb14SDimitry Andric     if (auto Info = hasPartialIVCondition(L, MSSAThreshold, *MSSA, AA)) {
27545f7ddb14SDimitry Andric       LLVM_DEBUG(
27555f7ddb14SDimitry Andric           dbgs() << "simple-loop-unswitch: Found partially invariant condition "
27565f7ddb14SDimitry Andric                  << *Info->InstToDuplicate[0] << "\n");
27575f7ddb14SDimitry Andric       PartialIVInfo = *Info;
27585f7ddb14SDimitry Andric       PartialIVCondBranch = L.getHeader()->getTerminator();
27595f7ddb14SDimitry Andric       TinyPtrVector<Value *> ValsToDuplicate;
27605f7ddb14SDimitry Andric       for (auto *Inst : Info->InstToDuplicate)
27615f7ddb14SDimitry Andric         ValsToDuplicate.push_back(Inst);
27625f7ddb14SDimitry Andric       UnswitchCandidates.push_back(
27635f7ddb14SDimitry Andric           {L.getHeader()->getTerminator(), std::move(ValsToDuplicate)});
27645f7ddb14SDimitry Andric     }
27650b57cec5SDimitry Andric   }
27660b57cec5SDimitry Andric 
27670b57cec5SDimitry Andric   // If we didn't find any candidates, we're done.
27680b57cec5SDimitry Andric   if (UnswitchCandidates.empty())
27690b57cec5SDimitry Andric     return false;
27700b57cec5SDimitry Andric 
27710b57cec5SDimitry Andric   // Check if there are irreducible CFG cycles in this loop. If so, we cannot
27720b57cec5SDimitry Andric   // easily unswitch non-trivial edges out of the loop. Doing so might turn the
27730b57cec5SDimitry Andric   // irreducible control flow into reducible control flow and introduce new
27740b57cec5SDimitry Andric   // loops "out of thin air". If we ever discover important use cases for doing
27750b57cec5SDimitry Andric   // this, we can add support to loop unswitch, but it is a lot of complexity
27760b57cec5SDimitry Andric   // for what seems little or no real world benefit.
27770b57cec5SDimitry Andric   LoopBlocksRPO RPOT(&L);
27780b57cec5SDimitry Andric   RPOT.perform(&LI);
27790b57cec5SDimitry Andric   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
27800b57cec5SDimitry Andric     return false;
27810b57cec5SDimitry Andric 
27820b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> ExitBlocks;
27830b57cec5SDimitry Andric   L.getUniqueExitBlocks(ExitBlocks);
27840b57cec5SDimitry Andric 
27855f7ddb14SDimitry Andric   // We cannot unswitch if exit blocks contain a cleanuppad/catchswitch
27865f7ddb14SDimitry Andric   // instruction as we don't know how to split those exit blocks.
27870b57cec5SDimitry Andric   // FIXME: We should teach SplitBlock to handle this and remove this
27880b57cec5SDimitry Andric   // restriction.
27895f7ddb14SDimitry Andric   for (auto *ExitBB : ExitBlocks) {
27905f7ddb14SDimitry Andric     auto *I = ExitBB->getFirstNonPHI();
27915f7ddb14SDimitry Andric     if (isa<CleanupPadInst>(I) || isa<CatchSwitchInst>(I)) {
27925f7ddb14SDimitry Andric       LLVM_DEBUG(dbgs() << "Cannot unswitch because of cleanuppad/catchswitch "
27935f7ddb14SDimitry Andric                            "in exit block\n");
27940b57cec5SDimitry Andric       return false;
27950b57cec5SDimitry Andric     }
27965f7ddb14SDimitry Andric   }
27970b57cec5SDimitry Andric 
27980b57cec5SDimitry Andric   LLVM_DEBUG(
27990b57cec5SDimitry Andric       dbgs() << "Considering " << UnswitchCandidates.size()
28000b57cec5SDimitry Andric              << " non-trivial loop invariant conditions for unswitching.\n");
28010b57cec5SDimitry Andric 
28020b57cec5SDimitry Andric   // Given that unswitching these terminators will require duplicating parts of
28030b57cec5SDimitry Andric   // the loop, so we need to be able to model that cost. Compute the ephemeral
28040b57cec5SDimitry Andric   // values and set up a data structure to hold per-BB costs. We cache each
28050b57cec5SDimitry Andric   // block's cost so that we don't recompute this when considering different
28060b57cec5SDimitry Andric   // subsets of the loop for duplication during unswitching.
28070b57cec5SDimitry Andric   SmallPtrSet<const Value *, 4> EphValues;
28080b57cec5SDimitry Andric   CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
28095f7ddb14SDimitry Andric   SmallDenseMap<BasicBlock *, InstructionCost, 4> BBCostMap;
28100b57cec5SDimitry Andric 
28110b57cec5SDimitry Andric   // Compute the cost of each block, as well as the total loop cost. Also, bail
28120b57cec5SDimitry Andric   // out if we see instructions which are incompatible with loop unswitching
28130b57cec5SDimitry Andric   // (convergent, noduplicate, or cross-basic-block tokens).
28140b57cec5SDimitry Andric   // FIXME: We might be able to safely handle some of these in non-duplicated
28150b57cec5SDimitry Andric   // regions.
2816af732203SDimitry Andric   TargetTransformInfo::TargetCostKind CostKind =
2817af732203SDimitry Andric       L.getHeader()->getParent()->hasMinSize()
2818af732203SDimitry Andric       ? TargetTransformInfo::TCK_CodeSize
2819af732203SDimitry Andric       : TargetTransformInfo::TCK_SizeAndLatency;
28205f7ddb14SDimitry Andric   InstructionCost LoopCost = 0;
28210b57cec5SDimitry Andric   for (auto *BB : L.blocks()) {
28225f7ddb14SDimitry Andric     InstructionCost Cost = 0;
28230b57cec5SDimitry Andric     for (auto &I : *BB) {
28240b57cec5SDimitry Andric       if (EphValues.count(&I))
28250b57cec5SDimitry Andric         continue;
28260b57cec5SDimitry Andric 
28270b57cec5SDimitry Andric       if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
28280b57cec5SDimitry Andric         return false;
28295ffd83dbSDimitry Andric       if (auto *CB = dyn_cast<CallBase>(&I))
28305ffd83dbSDimitry Andric         if (CB->isConvergent() || CB->cannotDuplicate())
28310b57cec5SDimitry Andric           return false;
28320b57cec5SDimitry Andric 
2833af732203SDimitry Andric       Cost += TTI.getUserCost(&I, CostKind);
28340b57cec5SDimitry Andric     }
28350b57cec5SDimitry Andric     assert(Cost >= 0 && "Must not have negative costs!");
28360b57cec5SDimitry Andric     LoopCost += Cost;
28370b57cec5SDimitry Andric     assert(LoopCost >= 0 && "Must not have negative loop costs!");
28380b57cec5SDimitry Andric     BBCostMap[BB] = Cost;
28390b57cec5SDimitry Andric   }
28400b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Total loop cost: " << LoopCost << "\n");
28410b57cec5SDimitry Andric 
28420b57cec5SDimitry Andric   // Now we find the best candidate by searching for the one with the following
28430b57cec5SDimitry Andric   // properties in order:
28440b57cec5SDimitry Andric   //
28450b57cec5SDimitry Andric   // 1) An unswitching cost below the threshold
28460b57cec5SDimitry Andric   // 2) The smallest number of duplicated unswitch candidates (to avoid
28470b57cec5SDimitry Andric   //    creating redundant subsequent unswitching)
28480b57cec5SDimitry Andric   // 3) The smallest cost after unswitching.
28490b57cec5SDimitry Andric   //
28500b57cec5SDimitry Andric   // We prioritize reducing fanout of unswitch candidates provided the cost
28510b57cec5SDimitry Andric   // remains below the threshold because this has a multiplicative effect.
28520b57cec5SDimitry Andric   //
28530b57cec5SDimitry Andric   // This requires memoizing each dominator subtree to avoid redundant work.
28540b57cec5SDimitry Andric   //
28550b57cec5SDimitry Andric   // FIXME: Need to actually do the number of candidates part above.
28565f7ddb14SDimitry Andric   SmallDenseMap<DomTreeNode *, InstructionCost, 4> DTCostMap;
28570b57cec5SDimitry Andric   // Given a terminator which might be unswitched, computes the non-duplicated
28580b57cec5SDimitry Andric   // cost for that terminator.
28595f7ddb14SDimitry Andric   auto ComputeUnswitchedCost = [&](Instruction &TI,
28605f7ddb14SDimitry Andric                                    bool FullUnswitch) -> InstructionCost {
28610b57cec5SDimitry Andric     BasicBlock &BB = *TI.getParent();
28620b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 4> Visited;
28630b57cec5SDimitry Andric 
28645f7ddb14SDimitry Andric     InstructionCost Cost = 0;
28650b57cec5SDimitry Andric     for (BasicBlock *SuccBB : successors(&BB)) {
28660b57cec5SDimitry Andric       // Don't count successors more than once.
28670b57cec5SDimitry Andric       if (!Visited.insert(SuccBB).second)
28680b57cec5SDimitry Andric         continue;
28690b57cec5SDimitry Andric 
28700b57cec5SDimitry Andric       // If this is a partial unswitch candidate, then it must be a conditional
28715f7ddb14SDimitry Andric       // branch with a condition of either `or`, `and`, their corresponding
28725f7ddb14SDimitry Andric       // select forms or partially invariant instructions. In that case, one of
28730b57cec5SDimitry Andric       // the successors is necessarily duplicated, so don't even try to remove
28740b57cec5SDimitry Andric       // its cost.
28750b57cec5SDimitry Andric       if (!FullUnswitch) {
28760b57cec5SDimitry Andric         auto &BI = cast<BranchInst>(TI);
28775f7ddb14SDimitry Andric         if (match(BI.getCondition(), m_LogicalAnd())) {
28780b57cec5SDimitry Andric           if (SuccBB == BI.getSuccessor(1))
28790b57cec5SDimitry Andric             continue;
28805f7ddb14SDimitry Andric         } else if (match(BI.getCondition(), m_LogicalOr())) {
28810b57cec5SDimitry Andric           if (SuccBB == BI.getSuccessor(0))
28820b57cec5SDimitry Andric             continue;
28835f7ddb14SDimitry Andric         } else if ((PartialIVInfo.KnownValue->isOneValue() &&
28845f7ddb14SDimitry Andric                     SuccBB == BI.getSuccessor(0)) ||
28855f7ddb14SDimitry Andric                    (!PartialIVInfo.KnownValue->isOneValue() &&
28865f7ddb14SDimitry Andric                     SuccBB == BI.getSuccessor(1)))
28875f7ddb14SDimitry Andric           continue;
28880b57cec5SDimitry Andric       }
28890b57cec5SDimitry Andric 
28900b57cec5SDimitry Andric       // This successor's domtree will not need to be duplicated after
28910b57cec5SDimitry Andric       // unswitching if the edge to the successor dominates it (and thus the
28920b57cec5SDimitry Andric       // entire tree). This essentially means there is no other path into this
28930b57cec5SDimitry Andric       // subtree and so it will end up live in only one clone of the loop.
28940b57cec5SDimitry Andric       if (SuccBB->getUniquePredecessor() ||
28950b57cec5SDimitry Andric           llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
28960b57cec5SDimitry Andric             return PredBB == &BB || DT.dominates(SuccBB, PredBB);
28970b57cec5SDimitry Andric           })) {
28985f7ddb14SDimitry Andric         Cost += computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
28995f7ddb14SDimitry Andric         assert(Cost <= LoopCost &&
29000b57cec5SDimitry Andric                "Non-duplicated cost should never exceed total loop cost!");
29010b57cec5SDimitry Andric       }
29020b57cec5SDimitry Andric     }
29030b57cec5SDimitry Andric 
29040b57cec5SDimitry Andric     // Now scale the cost by the number of unique successors minus one. We
29050b57cec5SDimitry Andric     // subtract one because there is already at least one copy of the entire
29060b57cec5SDimitry Andric     // loop. This is computing the new cost of unswitching a condition.
29070b57cec5SDimitry Andric     // Note that guards always have 2 unique successors that are implicit and
29080b57cec5SDimitry Andric     // will be materialized if we decide to unswitch it.
29090b57cec5SDimitry Andric     int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
29100b57cec5SDimitry Andric     assert(SuccessorsCount > 1 &&
29110b57cec5SDimitry Andric            "Cannot unswitch a condition without multiple distinct successors!");
29125f7ddb14SDimitry Andric     return (LoopCost - Cost) * (SuccessorsCount - 1);
29130b57cec5SDimitry Andric   };
29140b57cec5SDimitry Andric   Instruction *BestUnswitchTI = nullptr;
29155f7ddb14SDimitry Andric   InstructionCost BestUnswitchCost = 0;
29160b57cec5SDimitry Andric   ArrayRef<Value *> BestUnswitchInvariants;
29170b57cec5SDimitry Andric   for (auto &TerminatorAndInvariants : UnswitchCandidates) {
29180b57cec5SDimitry Andric     Instruction &TI = *TerminatorAndInvariants.first;
29190b57cec5SDimitry Andric     ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
29200b57cec5SDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(&TI);
29215f7ddb14SDimitry Andric     InstructionCost CandidateCost = ComputeUnswitchedCost(
29220b57cec5SDimitry Andric         TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
29230b57cec5SDimitry Andric                                      Invariants[0] == BI->getCondition()));
29240b57cec5SDimitry Andric     // Calculate cost multiplier which is a tool to limit potentially
29250b57cec5SDimitry Andric     // exponential behavior of loop-unswitch.
29260b57cec5SDimitry Andric     if (EnableUnswitchCostMultiplier) {
29270b57cec5SDimitry Andric       int CostMultiplier =
29285ffd83dbSDimitry Andric           CalculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
29290b57cec5SDimitry Andric       assert(
29300b57cec5SDimitry Andric           (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
29310b57cec5SDimitry Andric           "cost multiplier needs to be in the range of 1..UnswitchThreshold");
29320b57cec5SDimitry Andric       CandidateCost *= CostMultiplier;
29330b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
29340b57cec5SDimitry Andric                         << " (multiplier: " << CostMultiplier << ")"
29350b57cec5SDimitry Andric                         << " for unswitch candidate: " << TI << "\n");
29360b57cec5SDimitry Andric     } else {
29370b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
29380b57cec5SDimitry Andric                         << " for unswitch candidate: " << TI << "\n");
29390b57cec5SDimitry Andric     }
29400b57cec5SDimitry Andric 
29410b57cec5SDimitry Andric     if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
29420b57cec5SDimitry Andric       BestUnswitchTI = &TI;
29430b57cec5SDimitry Andric       BestUnswitchCost = CandidateCost;
29440b57cec5SDimitry Andric       BestUnswitchInvariants = Invariants;
29450b57cec5SDimitry Andric     }
29460b57cec5SDimitry Andric   }
29478bcb0991SDimitry Andric   assert(BestUnswitchTI && "Failed to find loop unswitch candidate");
29480b57cec5SDimitry Andric 
29490b57cec5SDimitry Andric   if (BestUnswitchCost >= UnswitchThreshold) {
29500b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
29510b57cec5SDimitry Andric                       << BestUnswitchCost << "\n");
29520b57cec5SDimitry Andric     return false;
29530b57cec5SDimitry Andric   }
29540b57cec5SDimitry Andric 
29555f7ddb14SDimitry Andric   if (BestUnswitchTI != PartialIVCondBranch)
29565f7ddb14SDimitry Andric     PartialIVInfo.InstToDuplicate.clear();
29575f7ddb14SDimitry Andric 
29580b57cec5SDimitry Andric   // If the best candidate is a guard, turn it into a branch.
29590b57cec5SDimitry Andric   if (isGuard(BestUnswitchTI))
29600b57cec5SDimitry Andric     BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
29610b57cec5SDimitry Andric                                          ExitBlocks, DT, LI, MSSAU);
29620b57cec5SDimitry Andric 
29630b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Unswitching non-trivial (cost = "
29640b57cec5SDimitry Andric                     << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
29650b57cec5SDimitry Andric                     << "\n");
29660b57cec5SDimitry Andric   unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
29675f7ddb14SDimitry Andric                                ExitBlocks, PartialIVInfo, DT, LI, AC,
2968*18baa991SDimitry Andric                                UnswitchCB, SE, MSSAU, DestroyLoopCB);
29690b57cec5SDimitry Andric   return true;
29700b57cec5SDimitry Andric }
29710b57cec5SDimitry Andric 
29720b57cec5SDimitry Andric /// Unswitch control flow predicated on loop invariant conditions.
29730b57cec5SDimitry Andric ///
29740b57cec5SDimitry Andric /// This first hoists all branches or switches which are trivial (IE, do not
29750b57cec5SDimitry Andric /// require duplicating any part of the loop) out of the loop body. It then
29760b57cec5SDimitry Andric /// looks at other loop invariant control flows and tries to unswitch those as
29770b57cec5SDimitry Andric /// well by cloning the loop if the result is small enough.
29780b57cec5SDimitry Andric ///
29795f7ddb14SDimitry Andric /// The `DT`, `LI`, `AC`, `AA`, `TTI` parameters are required analyses that are
29805f7ddb14SDimitry Andric /// also updated based on the unswitch. The `MSSA` analysis is also updated if
29815f7ddb14SDimitry Andric /// valid (i.e. its use is enabled).
29820b57cec5SDimitry Andric ///
29830b57cec5SDimitry Andric /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
29840b57cec5SDimitry Andric /// true, we will attempt to do non-trivial unswitching as well as trivial
29850b57cec5SDimitry Andric /// unswitching.
29860b57cec5SDimitry Andric ///
29870b57cec5SDimitry Andric /// The `UnswitchCB` callback provided will be run after unswitching is
29880b57cec5SDimitry Andric /// complete, with the first parameter set to `true` if the provided loop
29890b57cec5SDimitry Andric /// remains a loop, and a list of new sibling loops created.
29900b57cec5SDimitry Andric ///
29910b57cec5SDimitry Andric /// If `SE` is non-null, we will update that analysis based on the unswitching
29920b57cec5SDimitry Andric /// done.
29935f7ddb14SDimitry Andric static bool
unswitchLoop(Loop & L,DominatorTree & DT,LoopInfo & LI,AssumptionCache & AC,AAResults & AA,TargetTransformInfo & TTI,bool Trivial,bool NonTrivial,function_ref<void (bool,bool,ArrayRef<Loop * >)> UnswitchCB,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,function_ref<void (Loop &,StringRef)> DestroyLoopCB)29945f7ddb14SDimitry Andric unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
29955f7ddb14SDimitry Andric              AAResults &AA, TargetTransformInfo &TTI, bool Trivial,
29960b57cec5SDimitry Andric              bool NonTrivial,
29975f7ddb14SDimitry Andric              function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
2998*18baa991SDimitry Andric              ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
2999*18baa991SDimitry Andric              function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
30000b57cec5SDimitry Andric   assert(L.isRecursivelyLCSSAForm(DT, LI) &&
30010b57cec5SDimitry Andric          "Loops must be in LCSSA form before unswitching.");
30020b57cec5SDimitry Andric 
30030b57cec5SDimitry Andric   // Must be in loop simplified form: we need a preheader and dedicated exits.
30040b57cec5SDimitry Andric   if (!L.isLoopSimplifyForm())
30050b57cec5SDimitry Andric     return false;
30060b57cec5SDimitry Andric 
30070b57cec5SDimitry Andric   // Try trivial unswitch first before loop over other basic blocks in the loop.
30085f7ddb14SDimitry Andric   if (Trivial && unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
30090b57cec5SDimitry Andric     // If we unswitched successfully we will want to clean up the loop before
30100b57cec5SDimitry Andric     // processing it further so just mark it as unswitched and return.
30115f7ddb14SDimitry Andric     UnswitchCB(/*CurrentLoopValid*/ true, false, {});
30120b57cec5SDimitry Andric     return true;
30130b57cec5SDimitry Andric   }
30140b57cec5SDimitry Andric 
30155f7ddb14SDimitry Andric   // Check whether we should continue with non-trivial conditions.
30165f7ddb14SDimitry Andric   // EnableNonTrivialUnswitch: Global variable that forces non-trivial
30175f7ddb14SDimitry Andric   //                           unswitching for testing and debugging.
30185f7ddb14SDimitry Andric   // NonTrivial: Parameter that enables non-trivial unswitching for this
30195f7ddb14SDimitry Andric   //             invocation of the transform. But this should be allowed only
30205f7ddb14SDimitry Andric   //             for targets without branch divergence.
30215f7ddb14SDimitry Andric   //
30225f7ddb14SDimitry Andric   // FIXME: If divergence analysis becomes available to a loop
30235f7ddb14SDimitry Andric   // transform, we should allow unswitching for non-trivial uniform
30245f7ddb14SDimitry Andric   // branches even on targets that have divergence.
30255f7ddb14SDimitry Andric   // https://bugs.llvm.org/show_bug.cgi?id=48819
30265f7ddb14SDimitry Andric   bool ContinueWithNonTrivial =
30275f7ddb14SDimitry Andric       EnableNonTrivialUnswitch || (NonTrivial && !TTI.hasBranchDivergence());
30285f7ddb14SDimitry Andric   if (!ContinueWithNonTrivial)
30290b57cec5SDimitry Andric     return false;
30300b57cec5SDimitry Andric 
3031af732203SDimitry Andric   // Skip non-trivial unswitching for optsize functions.
3032af732203SDimitry Andric   if (L.getHeader()->getParent()->hasOptSize())
3033af732203SDimitry Andric     return false;
3034af732203SDimitry Andric 
30355f7ddb14SDimitry Andric   // Skip non-trivial unswitching for loops that cannot be cloned.
30365f7ddb14SDimitry Andric   if (!L.isSafeToClone())
30375f7ddb14SDimitry Andric     return false;
30385f7ddb14SDimitry Andric 
30390b57cec5SDimitry Andric   // For non-trivial unswitching, because it often creates new loops, we rely on
30400b57cec5SDimitry Andric   // the pass manager to iterate on the loops rather than trying to immediately
30410b57cec5SDimitry Andric   // reach a fixed point. There is no substantial advantage to iterating
30420b57cec5SDimitry Andric   // internally, and if any of the new loops are simplified enough to contain
30430b57cec5SDimitry Andric   // trivial unswitching we want to prefer those.
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric   // Try to unswitch the best invariant condition. We prefer this full unswitch to
30460b57cec5SDimitry Andric   // a partial unswitch when possible below the threshold.
3047*18baa991SDimitry Andric   if (unswitchBestCondition(L, DT, LI, AC, AA, TTI, UnswitchCB, SE, MSSAU,
3048*18baa991SDimitry Andric                             DestroyLoopCB))
30490b57cec5SDimitry Andric     return true;
30500b57cec5SDimitry Andric 
30510b57cec5SDimitry Andric   // No other opportunities to unswitch.
3052af732203SDimitry Andric   return false;
30530b57cec5SDimitry Andric }
30540b57cec5SDimitry Andric 
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater & U)30550b57cec5SDimitry Andric PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
30560b57cec5SDimitry Andric                                               LoopStandardAnalysisResults &AR,
30570b57cec5SDimitry Andric                                               LPMUpdater &U) {
30580b57cec5SDimitry Andric   Function &F = *L.getHeader()->getParent();
30590b57cec5SDimitry Andric   (void)F;
30600b57cec5SDimitry Andric 
30610b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
30620b57cec5SDimitry Andric                     << "\n");
30630b57cec5SDimitry Andric 
30640b57cec5SDimitry Andric   // Save the current loop name in a variable so that we can report it even
30650b57cec5SDimitry Andric   // after it has been deleted.
30665ffd83dbSDimitry Andric   std::string LoopName = std::string(L.getName());
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric   auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
30695f7ddb14SDimitry Andric                                         bool PartiallyInvariant,
30700b57cec5SDimitry Andric                                         ArrayRef<Loop *> NewLoops) {
30710b57cec5SDimitry Andric     // If we did a non-trivial unswitch, we have added new (cloned) loops.
30720b57cec5SDimitry Andric     if (!NewLoops.empty())
30730b57cec5SDimitry Andric       U.addSiblingLoops(NewLoops);
30740b57cec5SDimitry Andric 
30750b57cec5SDimitry Andric     // If the current loop remains valid, we should revisit it to catch any
30760b57cec5SDimitry Andric     // other unswitch opportunities. Otherwise, we need to mark it as deleted.
30775f7ddb14SDimitry Andric     if (CurrentLoopValid) {
30785f7ddb14SDimitry Andric       if (PartiallyInvariant) {
30795f7ddb14SDimitry Andric         // Mark the new loop as partially unswitched, to avoid unswitching on
30805f7ddb14SDimitry Andric         // the same condition again.
30815f7ddb14SDimitry Andric         auto &Context = L.getHeader()->getContext();
30825f7ddb14SDimitry Andric         MDNode *DisableUnswitchMD = MDNode::get(
30835f7ddb14SDimitry Andric             Context,
30845f7ddb14SDimitry Andric             MDString::get(Context, "llvm.loop.unswitch.partial.disable"));
30855f7ddb14SDimitry Andric         MDNode *NewLoopID = makePostTransformationMetadata(
30865f7ddb14SDimitry Andric             Context, L.getLoopID(), {"llvm.loop.unswitch.partial"},
30875f7ddb14SDimitry Andric             {DisableUnswitchMD});
30885f7ddb14SDimitry Andric         L.setLoopID(NewLoopID);
30895f7ddb14SDimitry Andric       } else
30900b57cec5SDimitry Andric         U.revisitCurrentLoop();
30915f7ddb14SDimitry Andric     } else
30920b57cec5SDimitry Andric       U.markLoopAsDeleted(L, LoopName);
30930b57cec5SDimitry Andric   };
30940b57cec5SDimitry Andric 
3095*18baa991SDimitry Andric   auto DestroyLoopCB = [&U](Loop &L, StringRef Name) {
3096*18baa991SDimitry Andric     U.markLoopAsDeleted(L, Name);
3097*18baa991SDimitry Andric   };
3098*18baa991SDimitry Andric 
30990b57cec5SDimitry Andric   Optional<MemorySSAUpdater> MSSAU;
31000b57cec5SDimitry Andric   if (AR.MSSA) {
31010b57cec5SDimitry Andric     MSSAU = MemorySSAUpdater(AR.MSSA);
31020b57cec5SDimitry Andric     if (VerifyMemorySSA)
31030b57cec5SDimitry Andric       AR.MSSA->verifyMemorySSA();
31040b57cec5SDimitry Andric   }
31055f7ddb14SDimitry Andric   if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.AA, AR.TTI, Trivial, NonTrivial,
31065f7ddb14SDimitry Andric                     UnswitchCB, &AR.SE,
3107*18baa991SDimitry Andric                     MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
3108*18baa991SDimitry Andric                     DestroyLoopCB))
31090b57cec5SDimitry Andric     return PreservedAnalyses::all();
31100b57cec5SDimitry Andric 
31110b57cec5SDimitry Andric   if (AR.MSSA && VerifyMemorySSA)
31120b57cec5SDimitry Andric     AR.MSSA->verifyMemorySSA();
31130b57cec5SDimitry Andric 
31140b57cec5SDimitry Andric   // Historically this pass has had issues with the dominator tree so verify it
31150b57cec5SDimitry Andric   // in asserts builds.
31160b57cec5SDimitry Andric   assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
31170b57cec5SDimitry Andric 
31180b57cec5SDimitry Andric   auto PA = getLoopPassPreservedAnalyses();
31198bcb0991SDimitry Andric   if (AR.MSSA)
31200b57cec5SDimitry Andric     PA.preserve<MemorySSAAnalysis>();
31210b57cec5SDimitry Andric   return PA;
31220b57cec5SDimitry Andric }
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric namespace {
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric class SimpleLoopUnswitchLegacyPass : public LoopPass {
31270b57cec5SDimitry Andric   bool NonTrivial;
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric public:
31300b57cec5SDimitry Andric   static char ID; // Pass ID, replacement for typeid
31310b57cec5SDimitry Andric 
SimpleLoopUnswitchLegacyPass(bool NonTrivial=false)31320b57cec5SDimitry Andric   explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
31330b57cec5SDimitry Andric       : LoopPass(ID), NonTrivial(NonTrivial) {
31340b57cec5SDimitry Andric     initializeSimpleLoopUnswitchLegacyPassPass(
31350b57cec5SDimitry Andric         *PassRegistry::getPassRegistry());
31360b57cec5SDimitry Andric   }
31370b57cec5SDimitry Andric 
31380b57cec5SDimitry Andric   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
31390b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const31400b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
31410b57cec5SDimitry Andric     AU.addRequired<AssumptionCacheTracker>();
31420b57cec5SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
31430b57cec5SDimitry Andric     if (EnableMSSALoopDependency) {
31440b57cec5SDimitry Andric       AU.addRequired<MemorySSAWrapperPass>();
31450b57cec5SDimitry Andric       AU.addPreserved<MemorySSAWrapperPass>();
31460b57cec5SDimitry Andric     }
31470b57cec5SDimitry Andric     getLoopAnalysisUsage(AU);
31480b57cec5SDimitry Andric   }
31490b57cec5SDimitry Andric };
31500b57cec5SDimitry Andric 
31510b57cec5SDimitry Andric } // end anonymous namespace
31520b57cec5SDimitry Andric 
runOnLoop(Loop * L,LPPassManager & LPM)31530b57cec5SDimitry Andric bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
31540b57cec5SDimitry Andric   if (skipLoop(L))
31550b57cec5SDimitry Andric     return false;
31560b57cec5SDimitry Andric 
31570b57cec5SDimitry Andric   Function &F = *L->getHeader()->getParent();
31580b57cec5SDimitry Andric 
31590b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
31600b57cec5SDimitry Andric                     << "\n");
31610b57cec5SDimitry Andric 
31620b57cec5SDimitry Andric   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
31630b57cec5SDimitry Andric   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
31640b57cec5SDimitry Andric   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
31655f7ddb14SDimitry Andric   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
31660b57cec5SDimitry Andric   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
31670b57cec5SDimitry Andric   MemorySSA *MSSA = nullptr;
31680b57cec5SDimitry Andric   Optional<MemorySSAUpdater> MSSAU;
31690b57cec5SDimitry Andric   if (EnableMSSALoopDependency) {
31700b57cec5SDimitry Andric     MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
31710b57cec5SDimitry Andric     MSSAU = MemorySSAUpdater(MSSA);
31720b57cec5SDimitry Andric   }
31730b57cec5SDimitry Andric 
31740b57cec5SDimitry Andric   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
31750b57cec5SDimitry Andric   auto *SE = SEWP ? &SEWP->getSE() : nullptr;
31760b57cec5SDimitry Andric 
31775f7ddb14SDimitry Andric   auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid, bool PartiallyInvariant,
31780b57cec5SDimitry Andric                                ArrayRef<Loop *> NewLoops) {
31790b57cec5SDimitry Andric     // If we did a non-trivial unswitch, we have added new (cloned) loops.
31800b57cec5SDimitry Andric     for (auto *NewL : NewLoops)
31810b57cec5SDimitry Andric       LPM.addLoop(*NewL);
31820b57cec5SDimitry Andric 
31830b57cec5SDimitry Andric     // If the current loop remains valid, re-add it to the queue. This is
31840b57cec5SDimitry Andric     // a little wasteful as we'll finish processing the current loop as well,
31850b57cec5SDimitry Andric     // but it is the best we can do in the old PM.
31865f7ddb14SDimitry Andric     if (CurrentLoopValid) {
31875f7ddb14SDimitry Andric       // If the current loop has been unswitched using a partially invariant
31885f7ddb14SDimitry Andric       // condition, we should not re-add the current loop to avoid unswitching
31895f7ddb14SDimitry Andric       // on the same condition again.
31905f7ddb14SDimitry Andric       if (!PartiallyInvariant)
31910b57cec5SDimitry Andric         LPM.addLoop(*L);
31925f7ddb14SDimitry Andric     } else
31930b57cec5SDimitry Andric       LPM.markLoopAsDeleted(*L);
31940b57cec5SDimitry Andric   };
31950b57cec5SDimitry Andric 
3196*18baa991SDimitry Andric   auto DestroyLoopCB = [&LPM](Loop &L, StringRef /* Name */) {
3197*18baa991SDimitry Andric     LPM.markLoopAsDeleted(L);
3198*18baa991SDimitry Andric   };
3199*18baa991SDimitry Andric 
32000b57cec5SDimitry Andric   if (MSSA && VerifyMemorySSA)
32010b57cec5SDimitry Andric     MSSA->verifyMemorySSA();
32020b57cec5SDimitry Andric 
32035f7ddb14SDimitry Andric   bool Changed =
32045f7ddb14SDimitry Andric       unswitchLoop(*L, DT, LI, AC, AA, TTI, true, NonTrivial, UnswitchCB, SE,
3205*18baa991SDimitry Andric                    MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
3206*18baa991SDimitry Andric                    DestroyLoopCB);
32070b57cec5SDimitry Andric 
32080b57cec5SDimitry Andric   if (MSSA && VerifyMemorySSA)
32090b57cec5SDimitry Andric     MSSA->verifyMemorySSA();
32100b57cec5SDimitry Andric 
32110b57cec5SDimitry Andric   // Historically this pass has had issues with the dominator tree so verify it
32120b57cec5SDimitry Andric   // in asserts builds.
32130b57cec5SDimitry Andric   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
32140b57cec5SDimitry Andric 
32150b57cec5SDimitry Andric   return Changed;
32160b57cec5SDimitry Andric }
32170b57cec5SDimitry Andric 
32180b57cec5SDimitry Andric char SimpleLoopUnswitchLegacyPass::ID = 0;
32190b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
32200b57cec5SDimitry Andric                       "Simple unswitch loops", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)32210b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
32220b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
32230b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
32240b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopPass)
32250b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
32260b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
32270b57cec5SDimitry Andric INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
32280b57cec5SDimitry Andric                     "Simple unswitch loops", false, false)
32290b57cec5SDimitry Andric 
32300b57cec5SDimitry Andric Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
32310b57cec5SDimitry Andric   return new SimpleLoopUnswitchLegacyPass(NonTrivial);
32320b57cec5SDimitry Andric }
3233