1*0b57cec5SDimitry Andric ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric 
9*0b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
10*0b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
11*0b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
12*0b57cec5SDimitry Andric #include "llvm/ADT/Sequence.h"
13*0b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
14*0b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
15*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
16*0b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
18*0b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
19*0b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
20*0b57cec5SDimitry Andric #include "llvm/Analysis/CodeMetrics.h"
21*0b57cec5SDimitry Andric #include "llvm/Analysis/GuardUtils.h"
22*0b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
23*0b57cec5SDimitry Andric #include "llvm/Analysis/LoopAnalysisManager.h"
24*0b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
25*0b57cec5SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
26*0b57cec5SDimitry Andric #include "llvm/Analysis/LoopPass.h"
27*0b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
28*0b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
29*0b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
30*0b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
31*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
32*0b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
33*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
34*0b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
35*0b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
36*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
37*0b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
385ffd83dbSDimitry Andric #include "llvm/IR/IRBuilder.h"
39*0b57cec5SDimitry Andric #include "llvm/IR/Use.h"
40*0b57cec5SDimitry Andric #include "llvm/IR/Value.h"
41480093f4SDimitry Andric #include "llvm/InitializePasses.h"
42*0b57cec5SDimitry Andric #include "llvm/Pass.h"
43*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
44480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
45*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
46*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
47*0b57cec5SDimitry Andric #include "llvm/Support/GenericDomTree.h"
48*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
49*0b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
50*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
51*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
52*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
53*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
54*0b57cec5SDimitry Andric #include <algorithm>
55*0b57cec5SDimitry Andric #include <cassert>
56*0b57cec5SDimitry Andric #include <iterator>
57*0b57cec5SDimitry Andric #include <numeric>
58*0b57cec5SDimitry Andric #include <utility>
59*0b57cec5SDimitry Andric 
60*0b57cec5SDimitry Andric #define DEBUG_TYPE "simple-loop-unswitch"
61*0b57cec5SDimitry Andric 
62*0b57cec5SDimitry Andric using namespace llvm;
63*0b57cec5SDimitry Andric 
64*0b57cec5SDimitry Andric STATISTIC(NumBranches, "Number of branches unswitched");
65*0b57cec5SDimitry Andric STATISTIC(NumSwitches, "Number of switches unswitched");
66*0b57cec5SDimitry Andric STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
67*0b57cec5SDimitry Andric STATISTIC(NumTrivial, "Number of unswitches that are trivial");
68*0b57cec5SDimitry Andric STATISTIC(
69*0b57cec5SDimitry Andric     NumCostMultiplierSkipped,
70*0b57cec5SDimitry Andric     "Number of unswitch candidates that had their cost multiplier skipped");
71*0b57cec5SDimitry Andric 
72*0b57cec5SDimitry Andric static cl::opt<bool> EnableNonTrivialUnswitch(
73*0b57cec5SDimitry Andric     "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
74*0b57cec5SDimitry Andric     cl::desc("Forcibly enables non-trivial loop unswitching rather than "
75*0b57cec5SDimitry Andric              "following the configuration passed into the pass."));
76*0b57cec5SDimitry Andric 
77*0b57cec5SDimitry Andric static cl::opt<int>
78*0b57cec5SDimitry Andric     UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
79*0b57cec5SDimitry Andric                       cl::desc("The cost threshold for unswitching a loop."));
80*0b57cec5SDimitry Andric 
81*0b57cec5SDimitry Andric static cl::opt<bool> EnableUnswitchCostMultiplier(
82*0b57cec5SDimitry Andric     "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
83*0b57cec5SDimitry Andric     cl::desc("Enable unswitch cost multiplier that prohibits exponential "
84*0b57cec5SDimitry Andric              "explosion in nontrivial unswitch."));
85*0b57cec5SDimitry Andric static cl::opt<int> UnswitchSiblingsToplevelDiv(
86*0b57cec5SDimitry Andric     "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
87*0b57cec5SDimitry Andric     cl::desc("Toplevel siblings divisor for cost multiplier."));
88*0b57cec5SDimitry Andric static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
89*0b57cec5SDimitry Andric     "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
90*0b57cec5SDimitry Andric     cl::desc("Number of unswitch candidates that are ignored when calculating "
91*0b57cec5SDimitry Andric              "cost multiplier."));
92*0b57cec5SDimitry Andric static cl::opt<bool> UnswitchGuards(
93*0b57cec5SDimitry Andric     "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
94*0b57cec5SDimitry Andric     cl::desc("If enabled, simple loop unswitching will also consider "
95*0b57cec5SDimitry Andric              "llvm.experimental.guard intrinsics as unswitch candidates."));
96*0b57cec5SDimitry Andric 
97*0b57cec5SDimitry Andric /// Collect all of the loop invariant input values transitively used by the
98*0b57cec5SDimitry Andric /// homogeneous instruction graph from a given root.
99*0b57cec5SDimitry Andric ///
100*0b57cec5SDimitry Andric /// This essentially walks from a root recursively through loop variant operands
101*0b57cec5SDimitry Andric /// which have the exact same opcode and finds all inputs which are loop
102*0b57cec5SDimitry Andric /// invariant. For some operations these can be re-associated and unswitched out
103*0b57cec5SDimitry Andric /// of the loop entirely.
104*0b57cec5SDimitry Andric static TinyPtrVector<Value *>
105*0b57cec5SDimitry Andric collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
106*0b57cec5SDimitry Andric                                          LoopInfo &LI) {
107*0b57cec5SDimitry Andric   assert(!L.isLoopInvariant(&Root) &&
108*0b57cec5SDimitry Andric          "Only need to walk the graph if root itself is not invariant.");
109*0b57cec5SDimitry Andric   TinyPtrVector<Value *> Invariants;
110*0b57cec5SDimitry Andric 
111*0b57cec5SDimitry Andric   // Build a worklist and recurse through operators collecting invariants.
112*0b57cec5SDimitry Andric   SmallVector<Instruction *, 4> Worklist;
113*0b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Visited;
114*0b57cec5SDimitry Andric   Worklist.push_back(&Root);
115*0b57cec5SDimitry Andric   Visited.insert(&Root);
116*0b57cec5SDimitry Andric   do {
117*0b57cec5SDimitry Andric     Instruction &I = *Worklist.pop_back_val();
118*0b57cec5SDimitry Andric     for (Value *OpV : I.operand_values()) {
119*0b57cec5SDimitry Andric       // Skip constants as unswitching isn't interesting for them.
120*0b57cec5SDimitry Andric       if (isa<Constant>(OpV))
121*0b57cec5SDimitry Andric         continue;
122*0b57cec5SDimitry Andric 
123*0b57cec5SDimitry Andric       // Add it to our result if loop invariant.
124*0b57cec5SDimitry Andric       if (L.isLoopInvariant(OpV)) {
125*0b57cec5SDimitry Andric         Invariants.push_back(OpV);
126*0b57cec5SDimitry Andric         continue;
127*0b57cec5SDimitry Andric       }
128*0b57cec5SDimitry Andric 
129*0b57cec5SDimitry Andric       // If not an instruction with the same opcode, nothing we can do.
130*0b57cec5SDimitry Andric       Instruction *OpI = dyn_cast<Instruction>(OpV);
131*0b57cec5SDimitry Andric       if (!OpI || OpI->getOpcode() != Root.getOpcode())
132*0b57cec5SDimitry Andric         continue;
133*0b57cec5SDimitry Andric 
134*0b57cec5SDimitry Andric       // Visit this operand.
135*0b57cec5SDimitry Andric       if (Visited.insert(OpI).second)
136*0b57cec5SDimitry Andric         Worklist.push_back(OpI);
137*0b57cec5SDimitry Andric     }
138*0b57cec5SDimitry Andric   } while (!Worklist.empty());
139*0b57cec5SDimitry Andric 
140*0b57cec5SDimitry Andric   return Invariants;
141*0b57cec5SDimitry Andric }
142*0b57cec5SDimitry Andric 
143*0b57cec5SDimitry Andric static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
144*0b57cec5SDimitry Andric                                      Constant &Replacement) {
145*0b57cec5SDimitry Andric   assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
146*0b57cec5SDimitry Andric 
147*0b57cec5SDimitry Andric   // Replace uses of LIC in the loop with the given constant.
148*0b57cec5SDimitry Andric   for (auto UI = Invariant->use_begin(), UE = Invariant->use_end(); UI != UE;) {
149*0b57cec5SDimitry Andric     // Grab the use and walk past it so we can clobber it in the use list.
150*0b57cec5SDimitry Andric     Use *U = &*UI++;
151*0b57cec5SDimitry Andric     Instruction *UserI = dyn_cast<Instruction>(U->getUser());
152*0b57cec5SDimitry Andric 
153*0b57cec5SDimitry Andric     // Replace this use within the loop body.
154*0b57cec5SDimitry Andric     if (UserI && L.contains(UserI))
155*0b57cec5SDimitry Andric       U->set(&Replacement);
156*0b57cec5SDimitry Andric   }
157*0b57cec5SDimitry Andric }
158*0b57cec5SDimitry Andric 
159*0b57cec5SDimitry Andric /// Check that all the LCSSA PHI nodes in the loop exit block have trivial
160*0b57cec5SDimitry Andric /// incoming values along this edge.
161*0b57cec5SDimitry Andric static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
162*0b57cec5SDimitry Andric                                          BasicBlock &ExitBB) {
163*0b57cec5SDimitry Andric   for (Instruction &I : ExitBB) {
164*0b57cec5SDimitry Andric     auto *PN = dyn_cast<PHINode>(&I);
165*0b57cec5SDimitry Andric     if (!PN)
166*0b57cec5SDimitry Andric       // No more PHIs to check.
167*0b57cec5SDimitry Andric       return true;
168*0b57cec5SDimitry Andric 
169*0b57cec5SDimitry Andric     // If the incoming value for this edge isn't loop invariant the unswitch
170*0b57cec5SDimitry Andric     // won't be trivial.
171*0b57cec5SDimitry Andric     if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
172*0b57cec5SDimitry Andric       return false;
173*0b57cec5SDimitry Andric   }
174*0b57cec5SDimitry Andric   llvm_unreachable("Basic blocks should never be empty!");
175*0b57cec5SDimitry Andric }
176*0b57cec5SDimitry Andric 
177*0b57cec5SDimitry Andric /// Insert code to test a set of loop invariant values, and conditionally branch
178*0b57cec5SDimitry Andric /// on them.
179*0b57cec5SDimitry Andric static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
180*0b57cec5SDimitry Andric                                                   ArrayRef<Value *> Invariants,
181*0b57cec5SDimitry Andric                                                   bool Direction,
182*0b57cec5SDimitry Andric                                                   BasicBlock &UnswitchedSucc,
183*0b57cec5SDimitry Andric                                                   BasicBlock &NormalSucc) {
184*0b57cec5SDimitry Andric   IRBuilder<> IRB(&BB);
185*0b57cec5SDimitry Andric 
186*0b57cec5SDimitry Andric   Value *Cond = Direction ? IRB.CreateOr(Invariants) :
187*0b57cec5SDimitry Andric     IRB.CreateAnd(Invariants);
188*0b57cec5SDimitry Andric   IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
189*0b57cec5SDimitry Andric                    Direction ? &NormalSucc : &UnswitchedSucc);
190*0b57cec5SDimitry Andric }
191*0b57cec5SDimitry Andric 
192*0b57cec5SDimitry Andric /// Rewrite the PHI nodes in an unswitched loop exit basic block.
193*0b57cec5SDimitry Andric ///
194*0b57cec5SDimitry Andric /// Requires that the loop exit and unswitched basic block are the same, and
195*0b57cec5SDimitry Andric /// that the exiting block was a unique predecessor of that block. Rewrites the
196*0b57cec5SDimitry Andric /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
197*0b57cec5SDimitry Andric /// PHI nodes from the old preheader that now contains the unswitched
198*0b57cec5SDimitry Andric /// terminator.
199*0b57cec5SDimitry Andric static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
200*0b57cec5SDimitry Andric                                                   BasicBlock &OldExitingBB,
201*0b57cec5SDimitry Andric                                                   BasicBlock &OldPH) {
202*0b57cec5SDimitry Andric   for (PHINode &PN : UnswitchedBB.phis()) {
203*0b57cec5SDimitry Andric     // When the loop exit is directly unswitched we just need to update the
204*0b57cec5SDimitry Andric     // incoming basic block. We loop to handle weird cases with repeated
205*0b57cec5SDimitry Andric     // incoming blocks, but expect to typically only have one operand here.
206*0b57cec5SDimitry Andric     for (auto i : seq<int>(0, PN.getNumOperands())) {
207*0b57cec5SDimitry Andric       assert(PN.getIncomingBlock(i) == &OldExitingBB &&
208*0b57cec5SDimitry Andric              "Found incoming block different from unique predecessor!");
209*0b57cec5SDimitry Andric       PN.setIncomingBlock(i, &OldPH);
210*0b57cec5SDimitry Andric     }
211*0b57cec5SDimitry Andric   }
212*0b57cec5SDimitry Andric }
213*0b57cec5SDimitry Andric 
214*0b57cec5SDimitry Andric /// Rewrite the PHI nodes in the loop exit basic block and the split off
215*0b57cec5SDimitry Andric /// unswitched block.
216*0b57cec5SDimitry Andric ///
217*0b57cec5SDimitry Andric /// Because the exit block remains an exit from the loop, this rewrites the
218*0b57cec5SDimitry Andric /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
219*0b57cec5SDimitry Andric /// nodes into the unswitched basic block to select between the value in the
220*0b57cec5SDimitry Andric /// old preheader and the loop exit.
221*0b57cec5SDimitry Andric static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
222*0b57cec5SDimitry Andric                                                       BasicBlock &UnswitchedBB,
223*0b57cec5SDimitry Andric                                                       BasicBlock &OldExitingBB,
224*0b57cec5SDimitry Andric                                                       BasicBlock &OldPH,
225*0b57cec5SDimitry Andric                                                       bool FullUnswitch) {
226*0b57cec5SDimitry Andric   assert(&ExitBB != &UnswitchedBB &&
227*0b57cec5SDimitry Andric          "Must have different loop exit and unswitched blocks!");
228*0b57cec5SDimitry Andric   Instruction *InsertPt = &*UnswitchedBB.begin();
229*0b57cec5SDimitry Andric   for (PHINode &PN : ExitBB.phis()) {
230*0b57cec5SDimitry Andric     auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
231*0b57cec5SDimitry Andric                                   PN.getName() + ".split", InsertPt);
232*0b57cec5SDimitry Andric 
233*0b57cec5SDimitry Andric     // Walk backwards over the old PHI node's inputs to minimize the cost of
234*0b57cec5SDimitry Andric     // removing each one. We have to do this weird loop manually so that we
235*0b57cec5SDimitry Andric     // create the same number of new incoming edges in the new PHI as we expect
236*0b57cec5SDimitry Andric     // each case-based edge to be included in the unswitched switch in some
237*0b57cec5SDimitry Andric     // cases.
238*0b57cec5SDimitry Andric     // FIXME: This is really, really gross. It would be much cleaner if LLVM
239*0b57cec5SDimitry Andric     // allowed us to create a single entry for a predecessor block without
240*0b57cec5SDimitry Andric     // having separate entries for each "edge" even though these edges are
241*0b57cec5SDimitry Andric     // required to produce identical results.
242*0b57cec5SDimitry Andric     for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
243*0b57cec5SDimitry Andric       if (PN.getIncomingBlock(i) != &OldExitingBB)
244*0b57cec5SDimitry Andric         continue;
245*0b57cec5SDimitry Andric 
246*0b57cec5SDimitry Andric       Value *Incoming = PN.getIncomingValue(i);
247*0b57cec5SDimitry Andric       if (FullUnswitch)
248*0b57cec5SDimitry Andric         // No more edge from the old exiting block to the exit block.
249*0b57cec5SDimitry Andric         PN.removeIncomingValue(i);
250*0b57cec5SDimitry Andric 
251*0b57cec5SDimitry Andric       NewPN->addIncoming(Incoming, &OldPH);
252*0b57cec5SDimitry Andric     }
253*0b57cec5SDimitry Andric 
254*0b57cec5SDimitry Andric     // Now replace the old PHI with the new one and wire the old one in as an
255*0b57cec5SDimitry Andric     // input to the new one.
256*0b57cec5SDimitry Andric     PN.replaceAllUsesWith(NewPN);
257*0b57cec5SDimitry Andric     NewPN->addIncoming(&PN, &ExitBB);
258*0b57cec5SDimitry Andric   }
259*0b57cec5SDimitry Andric }
260*0b57cec5SDimitry Andric 
261*0b57cec5SDimitry Andric /// Hoist the current loop up to the innermost loop containing a remaining exit.
262*0b57cec5SDimitry Andric ///
263*0b57cec5SDimitry Andric /// Because we've removed an exit from the loop, we may have changed the set of
264*0b57cec5SDimitry Andric /// loops reachable and need to move the current loop up the loop nest or even
265*0b57cec5SDimitry Andric /// to an entirely separate nest.
266*0b57cec5SDimitry Andric static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
267*0b57cec5SDimitry Andric                                  DominatorTree &DT, LoopInfo &LI,
268480093f4SDimitry Andric                                  MemorySSAUpdater *MSSAU, ScalarEvolution *SE) {
269*0b57cec5SDimitry Andric   // If the loop is already at the top level, we can't hoist it anywhere.
270*0b57cec5SDimitry Andric   Loop *OldParentL = L.getParentLoop();
271*0b57cec5SDimitry Andric   if (!OldParentL)
272*0b57cec5SDimitry Andric     return;
273*0b57cec5SDimitry Andric 
274*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> Exits;
275*0b57cec5SDimitry Andric   L.getExitBlocks(Exits);
276*0b57cec5SDimitry Andric   Loop *NewParentL = nullptr;
277*0b57cec5SDimitry Andric   for (auto *ExitBB : Exits)
278*0b57cec5SDimitry Andric     if (Loop *ExitL = LI.getLoopFor(ExitBB))
279*0b57cec5SDimitry Andric       if (!NewParentL || NewParentL->contains(ExitL))
280*0b57cec5SDimitry Andric         NewParentL = ExitL;
281*0b57cec5SDimitry Andric 
282*0b57cec5SDimitry Andric   if (NewParentL == OldParentL)
283*0b57cec5SDimitry Andric     return;
284*0b57cec5SDimitry Andric 
285*0b57cec5SDimitry Andric   // The new parent loop (if different) should always contain the old one.
286*0b57cec5SDimitry Andric   if (NewParentL)
287*0b57cec5SDimitry Andric     assert(NewParentL->contains(OldParentL) &&
288*0b57cec5SDimitry Andric            "Can only hoist this loop up the nest!");
289*0b57cec5SDimitry Andric 
290*0b57cec5SDimitry Andric   // The preheader will need to move with the body of this loop. However,
291*0b57cec5SDimitry Andric   // because it isn't in this loop we also need to update the primary loop map.
292*0b57cec5SDimitry Andric   assert(OldParentL == LI.getLoopFor(&Preheader) &&
293*0b57cec5SDimitry Andric          "Parent loop of this loop should contain this loop's preheader!");
294*0b57cec5SDimitry Andric   LI.changeLoopFor(&Preheader, NewParentL);
295*0b57cec5SDimitry Andric 
296*0b57cec5SDimitry Andric   // Remove this loop from its old parent.
297*0b57cec5SDimitry Andric   OldParentL->removeChildLoop(&L);
298*0b57cec5SDimitry Andric 
299*0b57cec5SDimitry Andric   // Add the loop either to the new parent or as a top-level loop.
300*0b57cec5SDimitry Andric   if (NewParentL)
301*0b57cec5SDimitry Andric     NewParentL->addChildLoop(&L);
302*0b57cec5SDimitry Andric   else
303*0b57cec5SDimitry Andric     LI.addTopLevelLoop(&L);
304*0b57cec5SDimitry Andric 
305*0b57cec5SDimitry Andric   // Remove this loops blocks from the old parent and every other loop up the
306*0b57cec5SDimitry Andric   // nest until reaching the new parent. Also update all of these
307*0b57cec5SDimitry Andric   // no-longer-containing loops to reflect the nesting change.
308*0b57cec5SDimitry Andric   for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
309*0b57cec5SDimitry Andric        OldContainingL = OldContainingL->getParentLoop()) {
310*0b57cec5SDimitry Andric     llvm::erase_if(OldContainingL->getBlocksVector(),
311*0b57cec5SDimitry Andric                    [&](const BasicBlock *BB) {
312*0b57cec5SDimitry Andric                      return BB == &Preheader || L.contains(BB);
313*0b57cec5SDimitry Andric                    });
314*0b57cec5SDimitry Andric 
315*0b57cec5SDimitry Andric     OldContainingL->getBlocksSet().erase(&Preheader);
316*0b57cec5SDimitry Andric     for (BasicBlock *BB : L.blocks())
317*0b57cec5SDimitry Andric       OldContainingL->getBlocksSet().erase(BB);
318*0b57cec5SDimitry Andric 
319*0b57cec5SDimitry Andric     // Because we just hoisted a loop out of this one, we have essentially
320*0b57cec5SDimitry Andric     // created new exit paths from it. That means we need to form LCSSA PHI
321*0b57cec5SDimitry Andric     // nodes for values used in the no-longer-nested loop.
322480093f4SDimitry Andric     formLCSSA(*OldContainingL, DT, &LI, SE);
323*0b57cec5SDimitry Andric 
324*0b57cec5SDimitry Andric     // We shouldn't need to form dedicated exits because the exit introduced
325*0b57cec5SDimitry Andric     // here is the (just split by unswitching) preheader. However, after trivial
326*0b57cec5SDimitry Andric     // unswitching it is possible to get new non-dedicated exits out of parent
327*0b57cec5SDimitry Andric     // loop so let's conservatively form dedicated exit blocks and figure out
328*0b57cec5SDimitry Andric     // if we can optimize later.
329*0b57cec5SDimitry Andric     formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
330*0b57cec5SDimitry Andric                             /*PreserveLCSSA*/ true);
331*0b57cec5SDimitry Andric   }
332*0b57cec5SDimitry Andric }
333*0b57cec5SDimitry Andric 
334480093f4SDimitry Andric // Return the top-most loop containing ExitBB and having ExitBB as exiting block
335480093f4SDimitry Andric // or the loop containing ExitBB, if there is no parent loop containing ExitBB
336480093f4SDimitry Andric // as exiting block.
337480093f4SDimitry Andric static Loop *getTopMostExitingLoop(BasicBlock *ExitBB, LoopInfo &LI) {
338480093f4SDimitry Andric   Loop *TopMost = LI.getLoopFor(ExitBB);
339480093f4SDimitry Andric   Loop *Current = TopMost;
340480093f4SDimitry Andric   while (Current) {
341480093f4SDimitry Andric     if (Current->isLoopExiting(ExitBB))
342480093f4SDimitry Andric       TopMost = Current;
343480093f4SDimitry Andric     Current = Current->getParentLoop();
344480093f4SDimitry Andric   }
345480093f4SDimitry Andric   return TopMost;
346480093f4SDimitry Andric }
347480093f4SDimitry Andric 
348*0b57cec5SDimitry Andric /// Unswitch a trivial branch if the condition is loop invariant.
349*0b57cec5SDimitry Andric ///
350*0b57cec5SDimitry Andric /// This routine should only be called when loop code leading to the branch has
351*0b57cec5SDimitry Andric /// been validated as trivial (no side effects). This routine checks if the
352*0b57cec5SDimitry Andric /// condition is invariant and one of the successors is a loop exit. This
353*0b57cec5SDimitry Andric /// allows us to unswitch without duplicating the loop, making it trivial.
354*0b57cec5SDimitry Andric ///
355*0b57cec5SDimitry Andric /// If this routine fails to unswitch the branch it returns false.
356*0b57cec5SDimitry Andric ///
357*0b57cec5SDimitry Andric /// If the branch can be unswitched, this routine splits the preheader and
358*0b57cec5SDimitry Andric /// hoists the branch above that split. Preserves loop simplified form
359*0b57cec5SDimitry Andric /// (splitting the exit block as necessary). It simplifies the branch within
360*0b57cec5SDimitry Andric /// the loop to an unconditional branch but doesn't remove it entirely. Further
361*0b57cec5SDimitry Andric /// cleanup can be done with some simplify-cfg like pass.
362*0b57cec5SDimitry Andric ///
363*0b57cec5SDimitry Andric /// If `SE` is not null, it will be updated based on the potential loop SCEVs
364*0b57cec5SDimitry Andric /// invalidated by this.
365*0b57cec5SDimitry Andric static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
366*0b57cec5SDimitry Andric                                   LoopInfo &LI, ScalarEvolution *SE,
367*0b57cec5SDimitry Andric                                   MemorySSAUpdater *MSSAU) {
368*0b57cec5SDimitry Andric   assert(BI.isConditional() && "Can only unswitch a conditional branch!");
369*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Trying to unswitch branch: " << BI << "\n");
370*0b57cec5SDimitry Andric 
371*0b57cec5SDimitry Andric   // The loop invariant values that we want to unswitch.
372*0b57cec5SDimitry Andric   TinyPtrVector<Value *> Invariants;
373*0b57cec5SDimitry Andric 
374*0b57cec5SDimitry Andric   // When true, we're fully unswitching the branch rather than just unswitching
375*0b57cec5SDimitry Andric   // some input conditions to the branch.
376*0b57cec5SDimitry Andric   bool FullUnswitch = false;
377*0b57cec5SDimitry Andric 
378*0b57cec5SDimitry Andric   if (L.isLoopInvariant(BI.getCondition())) {
379*0b57cec5SDimitry Andric     Invariants.push_back(BI.getCondition());
380*0b57cec5SDimitry Andric     FullUnswitch = true;
381*0b57cec5SDimitry Andric   } else {
382*0b57cec5SDimitry Andric     if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
383*0b57cec5SDimitry Andric       Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
384*0b57cec5SDimitry Andric     if (Invariants.empty())
385*0b57cec5SDimitry Andric       // Couldn't find invariant inputs!
386*0b57cec5SDimitry Andric       return false;
387*0b57cec5SDimitry Andric   }
388*0b57cec5SDimitry Andric 
389*0b57cec5SDimitry Andric   // Check that one of the branch's successors exits, and which one.
390*0b57cec5SDimitry Andric   bool ExitDirection = true;
391*0b57cec5SDimitry Andric   int LoopExitSuccIdx = 0;
392*0b57cec5SDimitry Andric   auto *LoopExitBB = BI.getSuccessor(0);
393*0b57cec5SDimitry Andric   if (L.contains(LoopExitBB)) {
394*0b57cec5SDimitry Andric     ExitDirection = false;
395*0b57cec5SDimitry Andric     LoopExitSuccIdx = 1;
396*0b57cec5SDimitry Andric     LoopExitBB = BI.getSuccessor(1);
397*0b57cec5SDimitry Andric     if (L.contains(LoopExitBB))
398*0b57cec5SDimitry Andric       return false;
399*0b57cec5SDimitry Andric   }
400*0b57cec5SDimitry Andric   auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
401*0b57cec5SDimitry Andric   auto *ParentBB = BI.getParent();
402*0b57cec5SDimitry Andric   if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
403*0b57cec5SDimitry Andric     return false;
404*0b57cec5SDimitry Andric 
405*0b57cec5SDimitry Andric   // When unswitching only part of the branch's condition, we need the exit
406*0b57cec5SDimitry Andric   // block to be reached directly from the partially unswitched input. This can
407*0b57cec5SDimitry Andric   // be done when the exit block is along the true edge and the branch condition
408*0b57cec5SDimitry Andric   // is a graph of `or` operations, or the exit block is along the false edge
409*0b57cec5SDimitry Andric   // and the condition is a graph of `and` operations.
410*0b57cec5SDimitry Andric   if (!FullUnswitch) {
411*0b57cec5SDimitry Andric     if (ExitDirection) {
412*0b57cec5SDimitry Andric       if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or)
413*0b57cec5SDimitry Andric         return false;
414*0b57cec5SDimitry Andric     } else {
415*0b57cec5SDimitry Andric       if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And)
416*0b57cec5SDimitry Andric         return false;
417*0b57cec5SDimitry Andric     }
418*0b57cec5SDimitry Andric   }
419*0b57cec5SDimitry Andric 
420*0b57cec5SDimitry Andric   LLVM_DEBUG({
421*0b57cec5SDimitry Andric     dbgs() << "    unswitching trivial invariant conditions for: " << BI
422*0b57cec5SDimitry Andric            << "\n";
423*0b57cec5SDimitry Andric     for (Value *Invariant : Invariants) {
424*0b57cec5SDimitry Andric       dbgs() << "      " << *Invariant << " == true";
425*0b57cec5SDimitry Andric       if (Invariant != Invariants.back())
426*0b57cec5SDimitry Andric         dbgs() << " ||";
427*0b57cec5SDimitry Andric       dbgs() << "\n";
428*0b57cec5SDimitry Andric     }
429*0b57cec5SDimitry Andric   });
430*0b57cec5SDimitry Andric 
431*0b57cec5SDimitry Andric   // If we have scalar evolutions, we need to invalidate them including this
432480093f4SDimitry Andric   // loop, the loop containing the exit block and the topmost parent loop
433480093f4SDimitry Andric   // exiting via LoopExitBB.
434*0b57cec5SDimitry Andric   if (SE) {
435480093f4SDimitry Andric     if (Loop *ExitL = getTopMostExitingLoop(LoopExitBB, LI))
436*0b57cec5SDimitry Andric       SE->forgetLoop(ExitL);
437*0b57cec5SDimitry Andric     else
438*0b57cec5SDimitry Andric       // Forget the entire nest as this exits the entire nest.
439*0b57cec5SDimitry Andric       SE->forgetTopmostLoop(&L);
440*0b57cec5SDimitry Andric   }
441*0b57cec5SDimitry Andric 
442*0b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
443*0b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
444*0b57cec5SDimitry Andric 
445*0b57cec5SDimitry Andric   // Split the preheader, so that we know that there is a safe place to insert
446*0b57cec5SDimitry Andric   // the conditional branch. We will change the preheader to have a conditional
447*0b57cec5SDimitry Andric   // branch on LoopCond.
448*0b57cec5SDimitry Andric   BasicBlock *OldPH = L.getLoopPreheader();
449*0b57cec5SDimitry Andric   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
450*0b57cec5SDimitry Andric 
451*0b57cec5SDimitry Andric   // Now that we have a place to insert the conditional branch, create a place
452*0b57cec5SDimitry Andric   // to branch to: this is the exit block out of the loop that we are
453*0b57cec5SDimitry Andric   // unswitching. We need to split this if there are other loop predecessors.
454*0b57cec5SDimitry Andric   // Because the loop is in simplified form, *any* other predecessor is enough.
455*0b57cec5SDimitry Andric   BasicBlock *UnswitchedBB;
456*0b57cec5SDimitry Andric   if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
457*0b57cec5SDimitry Andric     assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
458*0b57cec5SDimitry Andric            "A branch's parent isn't a predecessor!");
459*0b57cec5SDimitry Andric     UnswitchedBB = LoopExitBB;
460*0b57cec5SDimitry Andric   } else {
461*0b57cec5SDimitry Andric     UnswitchedBB =
462*0b57cec5SDimitry Andric         SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
463*0b57cec5SDimitry Andric   }
464*0b57cec5SDimitry Andric 
465*0b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
466*0b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
467*0b57cec5SDimitry Andric 
468*0b57cec5SDimitry Andric   // Actually move the invariant uses into the unswitched position. If possible,
469*0b57cec5SDimitry Andric   // we do this by moving the instructions, but when doing partial unswitching
470*0b57cec5SDimitry Andric   // we do it by building a new merge of the values in the unswitched position.
471*0b57cec5SDimitry Andric   OldPH->getTerminator()->eraseFromParent();
472*0b57cec5SDimitry Andric   if (FullUnswitch) {
473*0b57cec5SDimitry Andric     // If fully unswitching, we can use the existing branch instruction.
474*0b57cec5SDimitry Andric     // Splice it into the old PH to gate reaching the new preheader and re-point
475*0b57cec5SDimitry Andric     // its successors.
476*0b57cec5SDimitry Andric     OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
477*0b57cec5SDimitry Andric                                 BI);
478*0b57cec5SDimitry Andric     if (MSSAU) {
479*0b57cec5SDimitry Andric       // Temporarily clone the terminator, to make MSSA update cheaper by
480*0b57cec5SDimitry Andric       // separating "insert edge" updates from "remove edge" ones.
481*0b57cec5SDimitry Andric       ParentBB->getInstList().push_back(BI.clone());
482*0b57cec5SDimitry Andric     } else {
483*0b57cec5SDimitry Andric       // Create a new unconditional branch that will continue the loop as a new
484*0b57cec5SDimitry Andric       // terminator.
485*0b57cec5SDimitry Andric       BranchInst::Create(ContinueBB, ParentBB);
486*0b57cec5SDimitry Andric     }
487*0b57cec5SDimitry Andric     BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
488*0b57cec5SDimitry Andric     BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
489*0b57cec5SDimitry Andric   } else {
490*0b57cec5SDimitry Andric     // Only unswitching a subset of inputs to the condition, so we will need to
491*0b57cec5SDimitry Andric     // build a new branch that merges the invariant inputs.
492*0b57cec5SDimitry Andric     if (ExitDirection)
493*0b57cec5SDimitry Andric       assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
494*0b57cec5SDimitry Andric                  Instruction::Or &&
495*0b57cec5SDimitry Andric              "Must have an `or` of `i1`s for the condition!");
496*0b57cec5SDimitry Andric     else
497*0b57cec5SDimitry Andric       assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
498*0b57cec5SDimitry Andric                  Instruction::And &&
499*0b57cec5SDimitry Andric              "Must have an `and` of `i1`s for the condition!");
500*0b57cec5SDimitry Andric     buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
501*0b57cec5SDimitry Andric                                           *UnswitchedBB, *NewPH);
502*0b57cec5SDimitry Andric   }
503*0b57cec5SDimitry Andric 
504*0b57cec5SDimitry Andric   // Update the dominator tree with the added edge.
505*0b57cec5SDimitry Andric   DT.insertEdge(OldPH, UnswitchedBB);
506*0b57cec5SDimitry Andric 
507*0b57cec5SDimitry Andric   // After the dominator tree was updated with the added edge, update MemorySSA
508*0b57cec5SDimitry Andric   // if available.
509*0b57cec5SDimitry Andric   if (MSSAU) {
510*0b57cec5SDimitry Andric     SmallVector<CFGUpdate, 1> Updates;
511*0b57cec5SDimitry Andric     Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
512*0b57cec5SDimitry Andric     MSSAU->applyInsertUpdates(Updates, DT);
513*0b57cec5SDimitry Andric   }
514*0b57cec5SDimitry Andric 
515*0b57cec5SDimitry Andric   // Finish updating dominator tree and memory ssa for full unswitch.
516*0b57cec5SDimitry Andric   if (FullUnswitch) {
517*0b57cec5SDimitry Andric     if (MSSAU) {
518*0b57cec5SDimitry Andric       // Remove the cloned branch instruction.
519*0b57cec5SDimitry Andric       ParentBB->getTerminator()->eraseFromParent();
520*0b57cec5SDimitry Andric       // Create unconditional branch now.
521*0b57cec5SDimitry Andric       BranchInst::Create(ContinueBB, ParentBB);
522*0b57cec5SDimitry Andric       MSSAU->removeEdge(ParentBB, LoopExitBB);
523*0b57cec5SDimitry Andric     }
524*0b57cec5SDimitry Andric     DT.deleteEdge(ParentBB, LoopExitBB);
525*0b57cec5SDimitry Andric   }
526*0b57cec5SDimitry Andric 
527*0b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
528*0b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
529*0b57cec5SDimitry Andric 
530*0b57cec5SDimitry Andric   // Rewrite the relevant PHI nodes.
531*0b57cec5SDimitry Andric   if (UnswitchedBB == LoopExitBB)
532*0b57cec5SDimitry Andric     rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
533*0b57cec5SDimitry Andric   else
534*0b57cec5SDimitry Andric     rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
535*0b57cec5SDimitry Andric                                               *ParentBB, *OldPH, FullUnswitch);
536*0b57cec5SDimitry Andric 
537*0b57cec5SDimitry Andric   // The constant we can replace all of our invariants with inside the loop
538*0b57cec5SDimitry Andric   // body. If any of the invariants have a value other than this the loop won't
539*0b57cec5SDimitry Andric   // be entered.
540*0b57cec5SDimitry Andric   ConstantInt *Replacement = ExitDirection
541*0b57cec5SDimitry Andric                                  ? ConstantInt::getFalse(BI.getContext())
542*0b57cec5SDimitry Andric                                  : ConstantInt::getTrue(BI.getContext());
543*0b57cec5SDimitry Andric 
544*0b57cec5SDimitry Andric   // Since this is an i1 condition we can also trivially replace uses of it
545*0b57cec5SDimitry Andric   // within the loop with a constant.
546*0b57cec5SDimitry Andric   for (Value *Invariant : Invariants)
547*0b57cec5SDimitry Andric     replaceLoopInvariantUses(L, Invariant, *Replacement);
548*0b57cec5SDimitry Andric 
549*0b57cec5SDimitry Andric   // If this was full unswitching, we may have changed the nesting relationship
550*0b57cec5SDimitry Andric   // for this loop so hoist it to its correct parent if needed.
551*0b57cec5SDimitry Andric   if (FullUnswitch)
552480093f4SDimitry Andric     hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
553*0b57cec5SDimitry Andric 
554*0b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
555*0b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
556*0b57cec5SDimitry Andric 
557*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "    done: unswitching trivial branch...\n");
558*0b57cec5SDimitry Andric   ++NumTrivial;
559*0b57cec5SDimitry Andric   ++NumBranches;
560*0b57cec5SDimitry Andric   return true;
561*0b57cec5SDimitry Andric }
562*0b57cec5SDimitry Andric 
563*0b57cec5SDimitry Andric /// Unswitch a trivial switch if the condition is loop invariant.
564*0b57cec5SDimitry Andric ///
565*0b57cec5SDimitry Andric /// This routine should only be called when loop code leading to the switch has
566*0b57cec5SDimitry Andric /// been validated as trivial (no side effects). This routine checks if the
567*0b57cec5SDimitry Andric /// condition is invariant and that at least one of the successors is a loop
568*0b57cec5SDimitry Andric /// exit. This allows us to unswitch without duplicating the loop, making it
569*0b57cec5SDimitry Andric /// trivial.
570*0b57cec5SDimitry Andric ///
571*0b57cec5SDimitry Andric /// If this routine fails to unswitch the switch it returns false.
572*0b57cec5SDimitry Andric ///
573*0b57cec5SDimitry Andric /// If the switch can be unswitched, this routine splits the preheader and
574*0b57cec5SDimitry Andric /// copies the switch above that split. If the default case is one of the
575*0b57cec5SDimitry Andric /// exiting cases, it copies the non-exiting cases and points them at the new
576*0b57cec5SDimitry Andric /// preheader. If the default case is not exiting, it copies the exiting cases
577*0b57cec5SDimitry Andric /// and points the default at the preheader. It preserves loop simplified form
578*0b57cec5SDimitry Andric /// (splitting the exit blocks as necessary). It simplifies the switch within
579*0b57cec5SDimitry Andric /// the loop by removing now-dead cases. If the default case is one of those
580*0b57cec5SDimitry Andric /// unswitched, it replaces its destination with a new basic block containing
581*0b57cec5SDimitry Andric /// only unreachable. Such basic blocks, while technically loop exits, are not
582*0b57cec5SDimitry Andric /// considered for unswitching so this is a stable transform and the same
583*0b57cec5SDimitry Andric /// switch will not be revisited. If after unswitching there is only a single
584*0b57cec5SDimitry Andric /// in-loop successor, the switch is further simplified to an unconditional
585*0b57cec5SDimitry Andric /// branch. Still more cleanup can be done with some simplify-cfg like pass.
586*0b57cec5SDimitry Andric ///
587*0b57cec5SDimitry Andric /// If `SE` is not null, it will be updated based on the potential loop SCEVs
588*0b57cec5SDimitry Andric /// invalidated by this.
589*0b57cec5SDimitry Andric static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
590*0b57cec5SDimitry Andric                                   LoopInfo &LI, ScalarEvolution *SE,
591*0b57cec5SDimitry Andric                                   MemorySSAUpdater *MSSAU) {
592*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Trying to unswitch switch: " << SI << "\n");
593*0b57cec5SDimitry Andric   Value *LoopCond = SI.getCondition();
594*0b57cec5SDimitry Andric 
595*0b57cec5SDimitry Andric   // If this isn't switching on an invariant condition, we can't unswitch it.
596*0b57cec5SDimitry Andric   if (!L.isLoopInvariant(LoopCond))
597*0b57cec5SDimitry Andric     return false;
598*0b57cec5SDimitry Andric 
599*0b57cec5SDimitry Andric   auto *ParentBB = SI.getParent();
600*0b57cec5SDimitry Andric 
6015ffd83dbSDimitry Andric   // The same check must be used both for the default and the exit cases. We
6025ffd83dbSDimitry Andric   // should never leave edges from the switch instruction to a basic block that
6035ffd83dbSDimitry Andric   // we are unswitching, hence the condition used to determine the default case
6045ffd83dbSDimitry Andric   // needs to also be used to populate ExitCaseIndices, which is then used to
6055ffd83dbSDimitry Andric   // remove cases from the switch.
6065ffd83dbSDimitry Andric   auto IsTriviallyUnswitchableExitBlock = [&](BasicBlock &BBToCheck) {
6075ffd83dbSDimitry Andric     // BBToCheck is not an exit block if it is inside loop L.
6085ffd83dbSDimitry Andric     if (L.contains(&BBToCheck))
6095ffd83dbSDimitry Andric       return false;
6105ffd83dbSDimitry Andric     // BBToCheck is not trivial to unswitch if its phis aren't loop invariant.
6115ffd83dbSDimitry Andric     if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, BBToCheck))
6125ffd83dbSDimitry Andric       return false;
6135ffd83dbSDimitry Andric     // We do not unswitch a block that only has an unreachable statement, as
6145ffd83dbSDimitry Andric     // it's possible this is a previously unswitched block. Only unswitch if
6155ffd83dbSDimitry Andric     // either the terminator is not unreachable, or, if it is, it's not the only
6165ffd83dbSDimitry Andric     // instruction in the block.
6175ffd83dbSDimitry Andric     auto *TI = BBToCheck.getTerminator();
6185ffd83dbSDimitry Andric     bool isUnreachable = isa<UnreachableInst>(TI);
6195ffd83dbSDimitry Andric     return !isUnreachable ||
6205ffd83dbSDimitry Andric            (isUnreachable && (BBToCheck.getFirstNonPHIOrDbg() != TI));
6215ffd83dbSDimitry Andric   };
6225ffd83dbSDimitry Andric 
623*0b57cec5SDimitry Andric   SmallVector<int, 4> ExitCaseIndices;
6245ffd83dbSDimitry Andric   for (auto Case : SI.cases())
6255ffd83dbSDimitry Andric     if (IsTriviallyUnswitchableExitBlock(*Case.getCaseSuccessor()))
626*0b57cec5SDimitry Andric       ExitCaseIndices.push_back(Case.getCaseIndex());
627*0b57cec5SDimitry Andric   BasicBlock *DefaultExitBB = nullptr;
628*0b57cec5SDimitry Andric   SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight =
629*0b57cec5SDimitry Andric       SwitchInstProfUpdateWrapper::getSuccessorWeight(SI, 0);
6305ffd83dbSDimitry Andric   if (IsTriviallyUnswitchableExitBlock(*SI.getDefaultDest())) {
631*0b57cec5SDimitry Andric     DefaultExitBB = SI.getDefaultDest();
632*0b57cec5SDimitry Andric   } else if (ExitCaseIndices.empty())
633*0b57cec5SDimitry Andric     return false;
634*0b57cec5SDimitry Andric 
635*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "    unswitching trivial switch...\n");
636*0b57cec5SDimitry Andric 
637*0b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
638*0b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
639*0b57cec5SDimitry Andric 
640*0b57cec5SDimitry Andric   // We may need to invalidate SCEVs for the outermost loop reached by any of
641*0b57cec5SDimitry Andric   // the exits.
642*0b57cec5SDimitry Andric   Loop *OuterL = &L;
643*0b57cec5SDimitry Andric 
644*0b57cec5SDimitry Andric   if (DefaultExitBB) {
645*0b57cec5SDimitry Andric     // Clear out the default destination temporarily to allow accurate
646*0b57cec5SDimitry Andric     // predecessor lists to be examined below.
647*0b57cec5SDimitry Andric     SI.setDefaultDest(nullptr);
648*0b57cec5SDimitry Andric     // Check the loop containing this exit.
649*0b57cec5SDimitry Andric     Loop *ExitL = LI.getLoopFor(DefaultExitBB);
650*0b57cec5SDimitry Andric     if (!ExitL || ExitL->contains(OuterL))
651*0b57cec5SDimitry Andric       OuterL = ExitL;
652*0b57cec5SDimitry Andric   }
653*0b57cec5SDimitry Andric 
654*0b57cec5SDimitry Andric   // Store the exit cases into a separate data structure and remove them from
655*0b57cec5SDimitry Andric   // the switch.
656*0b57cec5SDimitry Andric   SmallVector<std::tuple<ConstantInt *, BasicBlock *,
657*0b57cec5SDimitry Andric                          SwitchInstProfUpdateWrapper::CaseWeightOpt>,
658*0b57cec5SDimitry Andric               4> ExitCases;
659*0b57cec5SDimitry Andric   ExitCases.reserve(ExitCaseIndices.size());
660*0b57cec5SDimitry Andric   SwitchInstProfUpdateWrapper SIW(SI);
661*0b57cec5SDimitry Andric   // We walk the case indices backwards so that we remove the last case first
662*0b57cec5SDimitry Andric   // and don't disrupt the earlier indices.
663*0b57cec5SDimitry Andric   for (unsigned Index : reverse(ExitCaseIndices)) {
664*0b57cec5SDimitry Andric     auto CaseI = SI.case_begin() + Index;
665*0b57cec5SDimitry Andric     // Compute the outer loop from this exit.
666*0b57cec5SDimitry Andric     Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
667*0b57cec5SDimitry Andric     if (!ExitL || ExitL->contains(OuterL))
668*0b57cec5SDimitry Andric       OuterL = ExitL;
669*0b57cec5SDimitry Andric     // Save the value of this case.
670*0b57cec5SDimitry Andric     auto W = SIW.getSuccessorWeight(CaseI->getSuccessorIndex());
671*0b57cec5SDimitry Andric     ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W);
672*0b57cec5SDimitry Andric     // Delete the unswitched cases.
673*0b57cec5SDimitry Andric     SIW.removeCase(CaseI);
674*0b57cec5SDimitry Andric   }
675*0b57cec5SDimitry Andric 
676*0b57cec5SDimitry Andric   if (SE) {
677*0b57cec5SDimitry Andric     if (OuterL)
678*0b57cec5SDimitry Andric       SE->forgetLoop(OuterL);
679*0b57cec5SDimitry Andric     else
680*0b57cec5SDimitry Andric       SE->forgetTopmostLoop(&L);
681*0b57cec5SDimitry Andric   }
682*0b57cec5SDimitry Andric 
683*0b57cec5SDimitry Andric   // Check if after this all of the remaining cases point at the same
684*0b57cec5SDimitry Andric   // successor.
685*0b57cec5SDimitry Andric   BasicBlock *CommonSuccBB = nullptr;
686*0b57cec5SDimitry Andric   if (SI.getNumCases() > 0 &&
687*0b57cec5SDimitry Andric       std::all_of(std::next(SI.case_begin()), SI.case_end(),
688*0b57cec5SDimitry Andric                   [&SI](const SwitchInst::CaseHandle &Case) {
689*0b57cec5SDimitry Andric                     return Case.getCaseSuccessor() ==
690*0b57cec5SDimitry Andric                            SI.case_begin()->getCaseSuccessor();
691*0b57cec5SDimitry Andric                   }))
692*0b57cec5SDimitry Andric     CommonSuccBB = SI.case_begin()->getCaseSuccessor();
693*0b57cec5SDimitry Andric   if (!DefaultExitBB) {
694*0b57cec5SDimitry Andric     // If we're not unswitching the default, we need it to match any cases to
695*0b57cec5SDimitry Andric     // have a common successor or if we have no cases it is the common
696*0b57cec5SDimitry Andric     // successor.
697*0b57cec5SDimitry Andric     if (SI.getNumCases() == 0)
698*0b57cec5SDimitry Andric       CommonSuccBB = SI.getDefaultDest();
699*0b57cec5SDimitry Andric     else if (SI.getDefaultDest() != CommonSuccBB)
700*0b57cec5SDimitry Andric       CommonSuccBB = nullptr;
701*0b57cec5SDimitry Andric   }
702*0b57cec5SDimitry Andric 
703*0b57cec5SDimitry Andric   // Split the preheader, so that we know that there is a safe place to insert
704*0b57cec5SDimitry Andric   // the switch.
705*0b57cec5SDimitry Andric   BasicBlock *OldPH = L.getLoopPreheader();
706*0b57cec5SDimitry Andric   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
707*0b57cec5SDimitry Andric   OldPH->getTerminator()->eraseFromParent();
708*0b57cec5SDimitry Andric 
709*0b57cec5SDimitry Andric   // Now add the unswitched switch.
710*0b57cec5SDimitry Andric   auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
711*0b57cec5SDimitry Andric   SwitchInstProfUpdateWrapper NewSIW(*NewSI);
712*0b57cec5SDimitry Andric 
713*0b57cec5SDimitry Andric   // Rewrite the IR for the unswitched basic blocks. This requires two steps.
714*0b57cec5SDimitry Andric   // First, we split any exit blocks with remaining in-loop predecessors. Then
715*0b57cec5SDimitry Andric   // we update the PHIs in one of two ways depending on if there was a split.
716*0b57cec5SDimitry Andric   // We walk in reverse so that we split in the same order as the cases
717*0b57cec5SDimitry Andric   // appeared. This is purely for convenience of reading the resulting IR, but
718*0b57cec5SDimitry Andric   // it doesn't cost anything really.
719*0b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
720*0b57cec5SDimitry Andric   SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
721*0b57cec5SDimitry Andric   // Handle the default exit if necessary.
722*0b57cec5SDimitry Andric   // FIXME: It'd be great if we could merge this with the loop below but LLVM's
723*0b57cec5SDimitry Andric   // ranges aren't quite powerful enough yet.
724*0b57cec5SDimitry Andric   if (DefaultExitBB) {
725*0b57cec5SDimitry Andric     if (pred_empty(DefaultExitBB)) {
726*0b57cec5SDimitry Andric       UnswitchedExitBBs.insert(DefaultExitBB);
727*0b57cec5SDimitry Andric       rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
728*0b57cec5SDimitry Andric     } else {
729*0b57cec5SDimitry Andric       auto *SplitBB =
730*0b57cec5SDimitry Andric           SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
731*0b57cec5SDimitry Andric       rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
732*0b57cec5SDimitry Andric                                                 *ParentBB, *OldPH,
733*0b57cec5SDimitry Andric                                                 /*FullUnswitch*/ true);
734*0b57cec5SDimitry Andric       DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
735*0b57cec5SDimitry Andric     }
736*0b57cec5SDimitry Andric   }
737*0b57cec5SDimitry Andric   // Note that we must use a reference in the for loop so that we update the
738*0b57cec5SDimitry Andric   // container.
739*0b57cec5SDimitry Andric   for (auto &ExitCase : reverse(ExitCases)) {
740*0b57cec5SDimitry Andric     // Grab a reference to the exit block in the pair so that we can update it.
741*0b57cec5SDimitry Andric     BasicBlock *ExitBB = std::get<1>(ExitCase);
742*0b57cec5SDimitry Andric 
743*0b57cec5SDimitry Andric     // If this case is the last edge into the exit block, we can simply reuse it
744*0b57cec5SDimitry Andric     // as it will no longer be a loop exit. No mapping necessary.
745*0b57cec5SDimitry Andric     if (pred_empty(ExitBB)) {
746*0b57cec5SDimitry Andric       // Only rewrite once.
747*0b57cec5SDimitry Andric       if (UnswitchedExitBBs.insert(ExitBB).second)
748*0b57cec5SDimitry Andric         rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
749*0b57cec5SDimitry Andric       continue;
750*0b57cec5SDimitry Andric     }
751*0b57cec5SDimitry Andric 
752*0b57cec5SDimitry Andric     // Otherwise we need to split the exit block so that we retain an exit
753*0b57cec5SDimitry Andric     // block from the loop and a target for the unswitched condition.
754*0b57cec5SDimitry Andric     BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
755*0b57cec5SDimitry Andric     if (!SplitExitBB) {
756*0b57cec5SDimitry Andric       // If this is the first time we see this, do the split and remember it.
757*0b57cec5SDimitry Andric       SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
758*0b57cec5SDimitry Andric       rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
759*0b57cec5SDimitry Andric                                                 *ParentBB, *OldPH,
760*0b57cec5SDimitry Andric                                                 /*FullUnswitch*/ true);
761*0b57cec5SDimitry Andric     }
762*0b57cec5SDimitry Andric     // Update the case pair to point to the split block.
763*0b57cec5SDimitry Andric     std::get<1>(ExitCase) = SplitExitBB;
764*0b57cec5SDimitry Andric   }
765*0b57cec5SDimitry Andric 
766*0b57cec5SDimitry Andric   // Now add the unswitched cases. We do this in reverse order as we built them
767*0b57cec5SDimitry Andric   // in reverse order.
768*0b57cec5SDimitry Andric   for (auto &ExitCase : reverse(ExitCases)) {
769*0b57cec5SDimitry Andric     ConstantInt *CaseVal = std::get<0>(ExitCase);
770*0b57cec5SDimitry Andric     BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
771*0b57cec5SDimitry Andric 
772*0b57cec5SDimitry Andric     NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
773*0b57cec5SDimitry Andric   }
774*0b57cec5SDimitry Andric 
775*0b57cec5SDimitry Andric   // If the default was unswitched, re-point it and add explicit cases for
776*0b57cec5SDimitry Andric   // entering the loop.
777*0b57cec5SDimitry Andric   if (DefaultExitBB) {
778*0b57cec5SDimitry Andric     NewSIW->setDefaultDest(DefaultExitBB);
779*0b57cec5SDimitry Andric     NewSIW.setSuccessorWeight(0, DefaultCaseWeight);
780*0b57cec5SDimitry Andric 
781*0b57cec5SDimitry Andric     // We removed all the exit cases, so we just copy the cases to the
782*0b57cec5SDimitry Andric     // unswitched switch.
783*0b57cec5SDimitry Andric     for (const auto &Case : SI.cases())
784*0b57cec5SDimitry Andric       NewSIW.addCase(Case.getCaseValue(), NewPH,
785*0b57cec5SDimitry Andric                      SIW.getSuccessorWeight(Case.getSuccessorIndex()));
786*0b57cec5SDimitry Andric   } else if (DefaultCaseWeight) {
787*0b57cec5SDimitry Andric     // We have to set branch weight of the default case.
788*0b57cec5SDimitry Andric     uint64_t SW = *DefaultCaseWeight;
789*0b57cec5SDimitry Andric     for (const auto &Case : SI.cases()) {
790*0b57cec5SDimitry Andric       auto W = SIW.getSuccessorWeight(Case.getSuccessorIndex());
791*0b57cec5SDimitry Andric       assert(W &&
792*0b57cec5SDimitry Andric              "case weight must be defined as default case weight is defined");
793*0b57cec5SDimitry Andric       SW += *W;
794*0b57cec5SDimitry Andric     }
795*0b57cec5SDimitry Andric     NewSIW.setSuccessorWeight(0, SW);
796*0b57cec5SDimitry Andric   }
797*0b57cec5SDimitry Andric 
798*0b57cec5SDimitry Andric   // If we ended up with a common successor for every path through the switch
799*0b57cec5SDimitry Andric   // after unswitching, rewrite it to an unconditional branch to make it easy
800*0b57cec5SDimitry Andric   // to recognize. Otherwise we potentially have to recognize the default case
801*0b57cec5SDimitry Andric   // pointing at unreachable and other complexity.
802*0b57cec5SDimitry Andric   if (CommonSuccBB) {
803*0b57cec5SDimitry Andric     BasicBlock *BB = SI.getParent();
804*0b57cec5SDimitry Andric     // We may have had multiple edges to this common successor block, so remove
805*0b57cec5SDimitry Andric     // them as predecessors. We skip the first one, either the default or the
806*0b57cec5SDimitry Andric     // actual first case.
807*0b57cec5SDimitry Andric     bool SkippedFirst = DefaultExitBB == nullptr;
808*0b57cec5SDimitry Andric     for (auto Case : SI.cases()) {
809*0b57cec5SDimitry Andric       assert(Case.getCaseSuccessor() == CommonSuccBB &&
810*0b57cec5SDimitry Andric              "Non-common successor!");
811*0b57cec5SDimitry Andric       (void)Case;
812*0b57cec5SDimitry Andric       if (!SkippedFirst) {
813*0b57cec5SDimitry Andric         SkippedFirst = true;
814*0b57cec5SDimitry Andric         continue;
815*0b57cec5SDimitry Andric       }
816*0b57cec5SDimitry Andric       CommonSuccBB->removePredecessor(BB,
817*0b57cec5SDimitry Andric                                       /*KeepOneInputPHIs*/ true);
818*0b57cec5SDimitry Andric     }
819*0b57cec5SDimitry Andric     // Now nuke the switch and replace it with a direct branch.
820*0b57cec5SDimitry Andric     SIW.eraseFromParent();
821*0b57cec5SDimitry Andric     BranchInst::Create(CommonSuccBB, BB);
822*0b57cec5SDimitry Andric   } else if (DefaultExitBB) {
823*0b57cec5SDimitry Andric     assert(SI.getNumCases() > 0 &&
824*0b57cec5SDimitry Andric            "If we had no cases we'd have a common successor!");
825*0b57cec5SDimitry Andric     // Move the last case to the default successor. This is valid as if the
826*0b57cec5SDimitry Andric     // default got unswitched it cannot be reached. This has the advantage of
827*0b57cec5SDimitry Andric     // being simple and keeping the number of edges from this switch to
828*0b57cec5SDimitry Andric     // successors the same, and avoiding any PHI update complexity.
829*0b57cec5SDimitry Andric     auto LastCaseI = std::prev(SI.case_end());
830*0b57cec5SDimitry Andric 
831*0b57cec5SDimitry Andric     SI.setDefaultDest(LastCaseI->getCaseSuccessor());
832*0b57cec5SDimitry Andric     SIW.setSuccessorWeight(
833*0b57cec5SDimitry Andric         0, SIW.getSuccessorWeight(LastCaseI->getSuccessorIndex()));
834*0b57cec5SDimitry Andric     SIW.removeCase(LastCaseI);
835*0b57cec5SDimitry Andric   }
836*0b57cec5SDimitry Andric 
837*0b57cec5SDimitry Andric   // Walk the unswitched exit blocks and the unswitched split blocks and update
838*0b57cec5SDimitry Andric   // the dominator tree based on the CFG edits. While we are walking unordered
839*0b57cec5SDimitry Andric   // containers here, the API for applyUpdates takes an unordered list of
840*0b57cec5SDimitry Andric   // updates and requires them to not contain duplicates.
841*0b57cec5SDimitry Andric   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
842*0b57cec5SDimitry Andric   for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
843*0b57cec5SDimitry Andric     DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
844*0b57cec5SDimitry Andric     DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
845*0b57cec5SDimitry Andric   }
846*0b57cec5SDimitry Andric   for (auto SplitUnswitchedPair : SplitExitBBMap) {
847*0b57cec5SDimitry Andric     DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first});
848*0b57cec5SDimitry Andric     DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second});
849*0b57cec5SDimitry Andric   }
850*0b57cec5SDimitry Andric   DT.applyUpdates(DTUpdates);
851*0b57cec5SDimitry Andric 
852*0b57cec5SDimitry Andric   if (MSSAU) {
853*0b57cec5SDimitry Andric     MSSAU->applyUpdates(DTUpdates, DT);
854*0b57cec5SDimitry Andric     if (VerifyMemorySSA)
855*0b57cec5SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
856*0b57cec5SDimitry Andric   }
857*0b57cec5SDimitry Andric 
858*0b57cec5SDimitry Andric   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
859*0b57cec5SDimitry Andric 
860*0b57cec5SDimitry Andric   // We may have changed the nesting relationship for this loop so hoist it to
861*0b57cec5SDimitry Andric   // its correct parent if needed.
862480093f4SDimitry Andric   hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
863*0b57cec5SDimitry Andric 
864*0b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
865*0b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
866*0b57cec5SDimitry Andric 
867*0b57cec5SDimitry Andric   ++NumTrivial;
868*0b57cec5SDimitry Andric   ++NumSwitches;
869*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "    done: unswitching trivial switch...\n");
870*0b57cec5SDimitry Andric   return true;
871*0b57cec5SDimitry Andric }
872*0b57cec5SDimitry Andric 
873*0b57cec5SDimitry Andric /// This routine scans the loop to find a branch or switch which occurs before
874*0b57cec5SDimitry Andric /// any side effects occur. These can potentially be unswitched without
875*0b57cec5SDimitry Andric /// duplicating the loop. If a branch or switch is successfully unswitched the
876*0b57cec5SDimitry Andric /// scanning continues to see if subsequent branches or switches have become
877*0b57cec5SDimitry Andric /// trivial. Once all trivial candidates have been unswitched, this routine
878*0b57cec5SDimitry Andric /// returns.
879*0b57cec5SDimitry Andric ///
880*0b57cec5SDimitry Andric /// The return value indicates whether anything was unswitched (and therefore
881*0b57cec5SDimitry Andric /// changed).
882*0b57cec5SDimitry Andric ///
883*0b57cec5SDimitry Andric /// If `SE` is not null, it will be updated based on the potential loop SCEVs
884*0b57cec5SDimitry Andric /// invalidated by this.
885*0b57cec5SDimitry Andric static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
886*0b57cec5SDimitry Andric                                          LoopInfo &LI, ScalarEvolution *SE,
887*0b57cec5SDimitry Andric                                          MemorySSAUpdater *MSSAU) {
888*0b57cec5SDimitry Andric   bool Changed = false;
889*0b57cec5SDimitry Andric 
890*0b57cec5SDimitry Andric   // If loop header has only one reachable successor we should keep looking for
891*0b57cec5SDimitry Andric   // trivial condition candidates in the successor as well. An alternative is
892*0b57cec5SDimitry Andric   // to constant fold conditions and merge successors into loop header (then we
893*0b57cec5SDimitry Andric   // only need to check header's terminator). The reason for not doing this in
894*0b57cec5SDimitry Andric   // LoopUnswitch pass is that it could potentially break LoopPassManager's
895*0b57cec5SDimitry Andric   // invariants. Folding dead branches could either eliminate the current loop
896*0b57cec5SDimitry Andric   // or make other loops unreachable. LCSSA form might also not be preserved
897*0b57cec5SDimitry Andric   // after deleting branches. The following code keeps traversing loop header's
898*0b57cec5SDimitry Andric   // successors until it finds the trivial condition candidate (condition that
899*0b57cec5SDimitry Andric   // is not a constant). Since unswitching generates branches with constant
900*0b57cec5SDimitry Andric   // conditions, this scenario could be very common in practice.
901*0b57cec5SDimitry Andric   BasicBlock *CurrentBB = L.getHeader();
902*0b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 8> Visited;
903*0b57cec5SDimitry Andric   Visited.insert(CurrentBB);
904*0b57cec5SDimitry Andric   do {
905*0b57cec5SDimitry Andric     // Check if there are any side-effecting instructions (e.g. stores, calls,
906*0b57cec5SDimitry Andric     // volatile loads) in the part of the loop that the code *would* execute
907*0b57cec5SDimitry Andric     // without unswitching.
908*0b57cec5SDimitry Andric     if (MSSAU) // Possible early exit with MSSA
909*0b57cec5SDimitry Andric       if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
910*0b57cec5SDimitry Andric         if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
911*0b57cec5SDimitry Andric           return Changed;
912*0b57cec5SDimitry Andric     if (llvm::any_of(*CurrentBB,
913*0b57cec5SDimitry Andric                      [](Instruction &I) { return I.mayHaveSideEffects(); }))
914*0b57cec5SDimitry Andric       return Changed;
915*0b57cec5SDimitry Andric 
916*0b57cec5SDimitry Andric     Instruction *CurrentTerm = CurrentBB->getTerminator();
917*0b57cec5SDimitry Andric 
918*0b57cec5SDimitry Andric     if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
919*0b57cec5SDimitry Andric       // Don't bother trying to unswitch past a switch with a constant
920*0b57cec5SDimitry Andric       // condition. This should be removed prior to running this pass by
921*0b57cec5SDimitry Andric       // simplify-cfg.
922*0b57cec5SDimitry Andric       if (isa<Constant>(SI->getCondition()))
923*0b57cec5SDimitry Andric         return Changed;
924*0b57cec5SDimitry Andric 
925*0b57cec5SDimitry Andric       if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
926*0b57cec5SDimitry Andric         // Couldn't unswitch this one so we're done.
927*0b57cec5SDimitry Andric         return Changed;
928*0b57cec5SDimitry Andric 
929*0b57cec5SDimitry Andric       // Mark that we managed to unswitch something.
930*0b57cec5SDimitry Andric       Changed = true;
931*0b57cec5SDimitry Andric 
932*0b57cec5SDimitry Andric       // If unswitching turned the terminator into an unconditional branch then
933*0b57cec5SDimitry Andric       // we can continue. The unswitching logic specifically works to fold any
934*0b57cec5SDimitry Andric       // cases it can into an unconditional branch to make it easier to
935*0b57cec5SDimitry Andric       // recognize here.
936*0b57cec5SDimitry Andric       auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
937*0b57cec5SDimitry Andric       if (!BI || BI->isConditional())
938*0b57cec5SDimitry Andric         return Changed;
939*0b57cec5SDimitry Andric 
940*0b57cec5SDimitry Andric       CurrentBB = BI->getSuccessor(0);
941*0b57cec5SDimitry Andric       continue;
942*0b57cec5SDimitry Andric     }
943*0b57cec5SDimitry Andric 
944*0b57cec5SDimitry Andric     auto *BI = dyn_cast<BranchInst>(CurrentTerm);
945*0b57cec5SDimitry Andric     if (!BI)
946*0b57cec5SDimitry Andric       // We do not understand other terminator instructions.
947*0b57cec5SDimitry Andric       return Changed;
948*0b57cec5SDimitry Andric 
949*0b57cec5SDimitry Andric     // Don't bother trying to unswitch past an unconditional branch or a branch
950*0b57cec5SDimitry Andric     // with a constant value. These should be removed by simplify-cfg prior to
951*0b57cec5SDimitry Andric     // running this pass.
952*0b57cec5SDimitry Andric     if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
953*0b57cec5SDimitry Andric       return Changed;
954*0b57cec5SDimitry Andric 
955*0b57cec5SDimitry Andric     // Found a trivial condition candidate: non-foldable conditional branch. If
956*0b57cec5SDimitry Andric     // we fail to unswitch this, we can't do anything else that is trivial.
957*0b57cec5SDimitry Andric     if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
958*0b57cec5SDimitry Andric       return Changed;
959*0b57cec5SDimitry Andric 
960*0b57cec5SDimitry Andric     // Mark that we managed to unswitch something.
961*0b57cec5SDimitry Andric     Changed = true;
962*0b57cec5SDimitry Andric 
963*0b57cec5SDimitry Andric     // If we only unswitched some of the conditions feeding the branch, we won't
964*0b57cec5SDimitry Andric     // have collapsed it to a single successor.
965*0b57cec5SDimitry Andric     BI = cast<BranchInst>(CurrentBB->getTerminator());
966*0b57cec5SDimitry Andric     if (BI->isConditional())
967*0b57cec5SDimitry Andric       return Changed;
968*0b57cec5SDimitry Andric 
969*0b57cec5SDimitry Andric     // Follow the newly unconditional branch into its successor.
970*0b57cec5SDimitry Andric     CurrentBB = BI->getSuccessor(0);
971*0b57cec5SDimitry Andric 
972*0b57cec5SDimitry Andric     // When continuing, if we exit the loop or reach a previous visited block,
973*0b57cec5SDimitry Andric     // then we can not reach any trivial condition candidates (unfoldable
974*0b57cec5SDimitry Andric     // branch instructions or switch instructions) and no unswitch can happen.
975*0b57cec5SDimitry Andric   } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
976*0b57cec5SDimitry Andric 
977*0b57cec5SDimitry Andric   return Changed;
978*0b57cec5SDimitry Andric }
979*0b57cec5SDimitry Andric 
980*0b57cec5SDimitry Andric /// Build the cloned blocks for an unswitched copy of the given loop.
981*0b57cec5SDimitry Andric ///
982*0b57cec5SDimitry Andric /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
983*0b57cec5SDimitry Andric /// after the split block (`SplitBB`) that will be used to select between the
984*0b57cec5SDimitry Andric /// cloned and original loop.
985*0b57cec5SDimitry Andric ///
986*0b57cec5SDimitry Andric /// This routine handles cloning all of the necessary loop blocks and exit
987*0b57cec5SDimitry Andric /// blocks including rewriting their instructions and the relevant PHI nodes.
988*0b57cec5SDimitry Andric /// Any loop blocks or exit blocks which are dominated by a different successor
989*0b57cec5SDimitry Andric /// than the one for this clone of the loop blocks can be trivially skipped. We
990*0b57cec5SDimitry Andric /// use the `DominatingSucc` map to determine whether a block satisfies that
991*0b57cec5SDimitry Andric /// property with a simple map lookup.
992*0b57cec5SDimitry Andric ///
993*0b57cec5SDimitry Andric /// It also correctly creates the unconditional branch in the cloned
994*0b57cec5SDimitry Andric /// unswitched parent block to only point at the unswitched successor.
995*0b57cec5SDimitry Andric ///
996*0b57cec5SDimitry Andric /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
997*0b57cec5SDimitry Andric /// block splitting is correctly reflected in `LoopInfo`, essentially all of
998*0b57cec5SDimitry Andric /// the cloned blocks (and their loops) are left without full `LoopInfo`
999*0b57cec5SDimitry Andric /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
1000*0b57cec5SDimitry Andric /// blocks to them but doesn't create the cloned `DominatorTree` structure and
1001*0b57cec5SDimitry Andric /// instead the caller must recompute an accurate DT. It *does* correctly
1002*0b57cec5SDimitry Andric /// update the `AssumptionCache` provided in `AC`.
1003*0b57cec5SDimitry Andric static BasicBlock *buildClonedLoopBlocks(
1004*0b57cec5SDimitry Andric     Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
1005*0b57cec5SDimitry Andric     ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
1006*0b57cec5SDimitry Andric     BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
1007*0b57cec5SDimitry Andric     const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
1008*0b57cec5SDimitry Andric     ValueToValueMapTy &VMap,
1009*0b57cec5SDimitry Andric     SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
1010*0b57cec5SDimitry Andric     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
1011*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> NewBlocks;
1012*0b57cec5SDimitry Andric   NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
1013*0b57cec5SDimitry Andric 
1014*0b57cec5SDimitry Andric   // We will need to clone a bunch of blocks, wrap up the clone operation in
1015*0b57cec5SDimitry Andric   // a helper.
1016*0b57cec5SDimitry Andric   auto CloneBlock = [&](BasicBlock *OldBB) {
1017*0b57cec5SDimitry Andric     // Clone the basic block and insert it before the new preheader.
1018*0b57cec5SDimitry Andric     BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
1019*0b57cec5SDimitry Andric     NewBB->moveBefore(LoopPH);
1020*0b57cec5SDimitry Andric 
1021*0b57cec5SDimitry Andric     // Record this block and the mapping.
1022*0b57cec5SDimitry Andric     NewBlocks.push_back(NewBB);
1023*0b57cec5SDimitry Andric     VMap[OldBB] = NewBB;
1024*0b57cec5SDimitry Andric 
1025*0b57cec5SDimitry Andric     return NewBB;
1026*0b57cec5SDimitry Andric   };
1027*0b57cec5SDimitry Andric 
1028*0b57cec5SDimitry Andric   // We skip cloning blocks when they have a dominating succ that is not the
1029*0b57cec5SDimitry Andric   // succ we are cloning for.
1030*0b57cec5SDimitry Andric   auto SkipBlock = [&](BasicBlock *BB) {
1031*0b57cec5SDimitry Andric     auto It = DominatingSucc.find(BB);
1032*0b57cec5SDimitry Andric     return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
1033*0b57cec5SDimitry Andric   };
1034*0b57cec5SDimitry Andric 
1035*0b57cec5SDimitry Andric   // First, clone the preheader.
1036*0b57cec5SDimitry Andric   auto *ClonedPH = CloneBlock(LoopPH);
1037*0b57cec5SDimitry Andric 
1038*0b57cec5SDimitry Andric   // Then clone all the loop blocks, skipping the ones that aren't necessary.
1039*0b57cec5SDimitry Andric   for (auto *LoopBB : L.blocks())
1040*0b57cec5SDimitry Andric     if (!SkipBlock(LoopBB))
1041*0b57cec5SDimitry Andric       CloneBlock(LoopBB);
1042*0b57cec5SDimitry Andric 
1043*0b57cec5SDimitry Andric   // Split all the loop exit edges so that when we clone the exit blocks, if
1044*0b57cec5SDimitry Andric   // any of the exit blocks are *also* a preheader for some other loop, we
1045*0b57cec5SDimitry Andric   // don't create multiple predecessors entering the loop header.
1046*0b57cec5SDimitry Andric   for (auto *ExitBB : ExitBlocks) {
1047*0b57cec5SDimitry Andric     if (SkipBlock(ExitBB))
1048*0b57cec5SDimitry Andric       continue;
1049*0b57cec5SDimitry Andric 
1050*0b57cec5SDimitry Andric     // When we are going to clone an exit, we don't need to clone all the
1051*0b57cec5SDimitry Andric     // instructions in the exit block and we want to ensure we have an easy
1052*0b57cec5SDimitry Andric     // place to merge the CFG, so split the exit first. This is always safe to
1053*0b57cec5SDimitry Andric     // do because there cannot be any non-loop predecessors of a loop exit in
1054*0b57cec5SDimitry Andric     // loop simplified form.
1055*0b57cec5SDimitry Andric     auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
1056*0b57cec5SDimitry Andric 
1057*0b57cec5SDimitry Andric     // Rearrange the names to make it easier to write test cases by having the
1058*0b57cec5SDimitry Andric     // exit block carry the suffix rather than the merge block carrying the
1059*0b57cec5SDimitry Andric     // suffix.
1060*0b57cec5SDimitry Andric     MergeBB->takeName(ExitBB);
1061*0b57cec5SDimitry Andric     ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1062*0b57cec5SDimitry Andric 
1063*0b57cec5SDimitry Andric     // Now clone the original exit block.
1064*0b57cec5SDimitry Andric     auto *ClonedExitBB = CloneBlock(ExitBB);
1065*0b57cec5SDimitry Andric     assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1066*0b57cec5SDimitry Andric            "Exit block should have been split to have one successor!");
1067*0b57cec5SDimitry Andric     assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1068*0b57cec5SDimitry Andric            "Cloned exit block has the wrong successor!");
1069*0b57cec5SDimitry Andric 
1070*0b57cec5SDimitry Andric     // Remap any cloned instructions and create a merge phi node for them.
1071*0b57cec5SDimitry Andric     for (auto ZippedInsts : llvm::zip_first(
1072*0b57cec5SDimitry Andric              llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1073*0b57cec5SDimitry Andric              llvm::make_range(ClonedExitBB->begin(),
1074*0b57cec5SDimitry Andric                               std::prev(ClonedExitBB->end())))) {
1075*0b57cec5SDimitry Andric       Instruction &I = std::get<0>(ZippedInsts);
1076*0b57cec5SDimitry Andric       Instruction &ClonedI = std::get<1>(ZippedInsts);
1077*0b57cec5SDimitry Andric 
1078*0b57cec5SDimitry Andric       // The only instructions in the exit block should be PHI nodes and
1079*0b57cec5SDimitry Andric       // potentially a landing pad.
1080*0b57cec5SDimitry Andric       assert(
1081*0b57cec5SDimitry Andric           (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1082*0b57cec5SDimitry Andric           "Bad instruction in exit block!");
1083*0b57cec5SDimitry Andric       // We should have a value map between the instruction and its clone.
1084*0b57cec5SDimitry Andric       assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1085*0b57cec5SDimitry Andric 
1086*0b57cec5SDimitry Andric       auto *MergePN =
1087*0b57cec5SDimitry Andric           PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1088*0b57cec5SDimitry Andric                           &*MergeBB->getFirstInsertionPt());
1089*0b57cec5SDimitry Andric       I.replaceAllUsesWith(MergePN);
1090*0b57cec5SDimitry Andric       MergePN->addIncoming(&I, ExitBB);
1091*0b57cec5SDimitry Andric       MergePN->addIncoming(&ClonedI, ClonedExitBB);
1092*0b57cec5SDimitry Andric     }
1093*0b57cec5SDimitry Andric   }
1094*0b57cec5SDimitry Andric 
1095*0b57cec5SDimitry Andric   // Rewrite the instructions in the cloned blocks to refer to the instructions
1096*0b57cec5SDimitry Andric   // in the cloned blocks. We have to do this as a second pass so that we have
1097*0b57cec5SDimitry Andric   // everything available. Also, we have inserted new instructions which may
1098*0b57cec5SDimitry Andric   // include assume intrinsics, so we update the assumption cache while
1099*0b57cec5SDimitry Andric   // processing this.
1100*0b57cec5SDimitry Andric   for (auto *ClonedBB : NewBlocks)
1101*0b57cec5SDimitry Andric     for (Instruction &I : *ClonedBB) {
1102*0b57cec5SDimitry Andric       RemapInstruction(&I, VMap,
1103*0b57cec5SDimitry Andric                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1104*0b57cec5SDimitry Andric       if (auto *II = dyn_cast<IntrinsicInst>(&I))
1105*0b57cec5SDimitry Andric         if (II->getIntrinsicID() == Intrinsic::assume)
1106*0b57cec5SDimitry Andric           AC.registerAssumption(II);
1107*0b57cec5SDimitry Andric     }
1108*0b57cec5SDimitry Andric 
1109*0b57cec5SDimitry Andric   // Update any PHI nodes in the cloned successors of the skipped blocks to not
1110*0b57cec5SDimitry Andric   // have spurious incoming values.
1111*0b57cec5SDimitry Andric   for (auto *LoopBB : L.blocks())
1112*0b57cec5SDimitry Andric     if (SkipBlock(LoopBB))
1113*0b57cec5SDimitry Andric       for (auto *SuccBB : successors(LoopBB))
1114*0b57cec5SDimitry Andric         if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1115*0b57cec5SDimitry Andric           for (PHINode &PN : ClonedSuccBB->phis())
1116*0b57cec5SDimitry Andric             PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1117*0b57cec5SDimitry Andric 
1118*0b57cec5SDimitry Andric   // Remove the cloned parent as a predecessor of any successor we ended up
1119*0b57cec5SDimitry Andric   // cloning other than the unswitched one.
1120*0b57cec5SDimitry Andric   auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1121*0b57cec5SDimitry Andric   for (auto *SuccBB : successors(ParentBB)) {
1122*0b57cec5SDimitry Andric     if (SuccBB == UnswitchedSuccBB)
1123*0b57cec5SDimitry Andric       continue;
1124*0b57cec5SDimitry Andric 
1125*0b57cec5SDimitry Andric     auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1126*0b57cec5SDimitry Andric     if (!ClonedSuccBB)
1127*0b57cec5SDimitry Andric       continue;
1128*0b57cec5SDimitry Andric 
1129*0b57cec5SDimitry Andric     ClonedSuccBB->removePredecessor(ClonedParentBB,
1130*0b57cec5SDimitry Andric                                     /*KeepOneInputPHIs*/ true);
1131*0b57cec5SDimitry Andric   }
1132*0b57cec5SDimitry Andric 
1133*0b57cec5SDimitry Andric   // Replace the cloned branch with an unconditional branch to the cloned
1134*0b57cec5SDimitry Andric   // unswitched successor.
1135*0b57cec5SDimitry Andric   auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1136*0b57cec5SDimitry Andric   ClonedParentBB->getTerminator()->eraseFromParent();
1137*0b57cec5SDimitry Andric   BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1138*0b57cec5SDimitry Andric 
1139*0b57cec5SDimitry Andric   // If there are duplicate entries in the PHI nodes because of multiple edges
1140*0b57cec5SDimitry Andric   // to the unswitched successor, we need to nuke all but one as we replaced it
1141*0b57cec5SDimitry Andric   // with a direct branch.
1142*0b57cec5SDimitry Andric   for (PHINode &PN : ClonedSuccBB->phis()) {
1143*0b57cec5SDimitry Andric     bool Found = false;
1144*0b57cec5SDimitry Andric     // Loop over the incoming operands backwards so we can easily delete as we
1145*0b57cec5SDimitry Andric     // go without invalidating the index.
1146*0b57cec5SDimitry Andric     for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1147*0b57cec5SDimitry Andric       if (PN.getIncomingBlock(i) != ClonedParentBB)
1148*0b57cec5SDimitry Andric         continue;
1149*0b57cec5SDimitry Andric       if (!Found) {
1150*0b57cec5SDimitry Andric         Found = true;
1151*0b57cec5SDimitry Andric         continue;
1152*0b57cec5SDimitry Andric       }
1153*0b57cec5SDimitry Andric       PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1154*0b57cec5SDimitry Andric     }
1155*0b57cec5SDimitry Andric   }
1156*0b57cec5SDimitry Andric 
1157*0b57cec5SDimitry Andric   // Record the domtree updates for the new blocks.
1158*0b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 4> SuccSet;
1159*0b57cec5SDimitry Andric   for (auto *ClonedBB : NewBlocks) {
1160*0b57cec5SDimitry Andric     for (auto *SuccBB : successors(ClonedBB))
1161*0b57cec5SDimitry Andric       if (SuccSet.insert(SuccBB).second)
1162*0b57cec5SDimitry Andric         DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1163*0b57cec5SDimitry Andric     SuccSet.clear();
1164*0b57cec5SDimitry Andric   }
1165*0b57cec5SDimitry Andric 
1166*0b57cec5SDimitry Andric   return ClonedPH;
1167*0b57cec5SDimitry Andric }
1168*0b57cec5SDimitry Andric 
1169*0b57cec5SDimitry Andric /// Recursively clone the specified loop and all of its children.
1170*0b57cec5SDimitry Andric ///
1171*0b57cec5SDimitry Andric /// The target parent loop for the clone should be provided, or can be null if
1172*0b57cec5SDimitry Andric /// the clone is a top-level loop. While cloning, all the blocks are mapped
1173*0b57cec5SDimitry Andric /// with the provided value map. The entire original loop must be present in
1174*0b57cec5SDimitry Andric /// the value map. The cloned loop is returned.
1175*0b57cec5SDimitry Andric static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1176*0b57cec5SDimitry Andric                            const ValueToValueMapTy &VMap, LoopInfo &LI) {
1177*0b57cec5SDimitry Andric   auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1178*0b57cec5SDimitry Andric     assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1179*0b57cec5SDimitry Andric     ClonedL.reserveBlocks(OrigL.getNumBlocks());
1180*0b57cec5SDimitry Andric     for (auto *BB : OrigL.blocks()) {
1181*0b57cec5SDimitry Andric       auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1182*0b57cec5SDimitry Andric       ClonedL.addBlockEntry(ClonedBB);
1183*0b57cec5SDimitry Andric       if (LI.getLoopFor(BB) == &OrigL)
1184*0b57cec5SDimitry Andric         LI.changeLoopFor(ClonedBB, &ClonedL);
1185*0b57cec5SDimitry Andric     }
1186*0b57cec5SDimitry Andric   };
1187*0b57cec5SDimitry Andric 
1188*0b57cec5SDimitry Andric   // We specially handle the first loop because it may get cloned into
1189*0b57cec5SDimitry Andric   // a different parent and because we most commonly are cloning leaf loops.
1190*0b57cec5SDimitry Andric   Loop *ClonedRootL = LI.AllocateLoop();
1191*0b57cec5SDimitry Andric   if (RootParentL)
1192*0b57cec5SDimitry Andric     RootParentL->addChildLoop(ClonedRootL);
1193*0b57cec5SDimitry Andric   else
1194*0b57cec5SDimitry Andric     LI.addTopLevelLoop(ClonedRootL);
1195*0b57cec5SDimitry Andric   AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1196*0b57cec5SDimitry Andric 
1197*0b57cec5SDimitry Andric   if (OrigRootL.empty())
1198*0b57cec5SDimitry Andric     return ClonedRootL;
1199*0b57cec5SDimitry Andric 
1200*0b57cec5SDimitry Andric   // If we have a nest, we can quickly clone the entire loop nest using an
1201*0b57cec5SDimitry Andric   // iterative approach because it is a tree. We keep the cloned parent in the
1202*0b57cec5SDimitry Andric   // data structure to avoid repeatedly querying through a map to find it.
1203*0b57cec5SDimitry Andric   SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1204*0b57cec5SDimitry Andric   // Build up the loops to clone in reverse order as we'll clone them from the
1205*0b57cec5SDimitry Andric   // back.
1206*0b57cec5SDimitry Andric   for (Loop *ChildL : llvm::reverse(OrigRootL))
1207*0b57cec5SDimitry Andric     LoopsToClone.push_back({ClonedRootL, ChildL});
1208*0b57cec5SDimitry Andric   do {
1209*0b57cec5SDimitry Andric     Loop *ClonedParentL, *L;
1210*0b57cec5SDimitry Andric     std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1211*0b57cec5SDimitry Andric     Loop *ClonedL = LI.AllocateLoop();
1212*0b57cec5SDimitry Andric     ClonedParentL->addChildLoop(ClonedL);
1213*0b57cec5SDimitry Andric     AddClonedBlocksToLoop(*L, *ClonedL);
1214*0b57cec5SDimitry Andric     for (Loop *ChildL : llvm::reverse(*L))
1215*0b57cec5SDimitry Andric       LoopsToClone.push_back({ClonedL, ChildL});
1216*0b57cec5SDimitry Andric   } while (!LoopsToClone.empty());
1217*0b57cec5SDimitry Andric 
1218*0b57cec5SDimitry Andric   return ClonedRootL;
1219*0b57cec5SDimitry Andric }
1220*0b57cec5SDimitry Andric 
1221*0b57cec5SDimitry Andric /// Build the cloned loops of an original loop from unswitching.
1222*0b57cec5SDimitry Andric ///
1223*0b57cec5SDimitry Andric /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1224*0b57cec5SDimitry Andric /// operation. We need to re-verify that there even is a loop (as the backedge
1225*0b57cec5SDimitry Andric /// may not have been cloned), and even if there are remaining backedges the
1226*0b57cec5SDimitry Andric /// backedge set may be different. However, we know that each child loop is
1227*0b57cec5SDimitry Andric /// undisturbed, we only need to find where to place each child loop within
1228*0b57cec5SDimitry Andric /// either any parent loop or within a cloned version of the original loop.
1229*0b57cec5SDimitry Andric ///
1230*0b57cec5SDimitry Andric /// Because child loops may end up cloned outside of any cloned version of the
1231*0b57cec5SDimitry Andric /// original loop, multiple cloned sibling loops may be created. All of them
1232*0b57cec5SDimitry Andric /// are returned so that the newly introduced loop nest roots can be
1233*0b57cec5SDimitry Andric /// identified.
1234*0b57cec5SDimitry Andric static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1235*0b57cec5SDimitry Andric                              const ValueToValueMapTy &VMap, LoopInfo &LI,
1236*0b57cec5SDimitry Andric                              SmallVectorImpl<Loop *> &NonChildClonedLoops) {
1237*0b57cec5SDimitry Andric   Loop *ClonedL = nullptr;
1238*0b57cec5SDimitry Andric 
1239*0b57cec5SDimitry Andric   auto *OrigPH = OrigL.getLoopPreheader();
1240*0b57cec5SDimitry Andric   auto *OrigHeader = OrigL.getHeader();
1241*0b57cec5SDimitry Andric 
1242*0b57cec5SDimitry Andric   auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1243*0b57cec5SDimitry Andric   auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1244*0b57cec5SDimitry Andric 
1245*0b57cec5SDimitry Andric   // We need to know the loops of the cloned exit blocks to even compute the
1246*0b57cec5SDimitry Andric   // accurate parent loop. If we only clone exits to some parent of the
1247*0b57cec5SDimitry Andric   // original parent, we want to clone into that outer loop. We also keep track
1248*0b57cec5SDimitry Andric   // of the loops that our cloned exit blocks participate in.
1249*0b57cec5SDimitry Andric   Loop *ParentL = nullptr;
1250*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1251*0b57cec5SDimitry Andric   SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1252*0b57cec5SDimitry Andric   ClonedExitsInLoops.reserve(ExitBlocks.size());
1253*0b57cec5SDimitry Andric   for (auto *ExitBB : ExitBlocks)
1254*0b57cec5SDimitry Andric     if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1255*0b57cec5SDimitry Andric       if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1256*0b57cec5SDimitry Andric         ExitLoopMap[ClonedExitBB] = ExitL;
1257*0b57cec5SDimitry Andric         ClonedExitsInLoops.push_back(ClonedExitBB);
1258*0b57cec5SDimitry Andric         if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1259*0b57cec5SDimitry Andric           ParentL = ExitL;
1260*0b57cec5SDimitry Andric       }
1261*0b57cec5SDimitry Andric   assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1262*0b57cec5SDimitry Andric           ParentL->contains(OrigL.getParentLoop())) &&
1263*0b57cec5SDimitry Andric          "The computed parent loop should always contain (or be) the parent of "
1264*0b57cec5SDimitry Andric          "the original loop.");
1265*0b57cec5SDimitry Andric 
1266*0b57cec5SDimitry Andric   // We build the set of blocks dominated by the cloned header from the set of
1267*0b57cec5SDimitry Andric   // cloned blocks out of the original loop. While not all of these will
1268*0b57cec5SDimitry Andric   // necessarily be in the cloned loop, it is enough to establish that they
1269*0b57cec5SDimitry Andric   // aren't in unreachable cycles, etc.
1270*0b57cec5SDimitry Andric   SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1271*0b57cec5SDimitry Andric   for (auto *BB : OrigL.blocks())
1272*0b57cec5SDimitry Andric     if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1273*0b57cec5SDimitry Andric       ClonedLoopBlocks.insert(ClonedBB);
1274*0b57cec5SDimitry Andric 
1275*0b57cec5SDimitry Andric   // Rebuild the set of blocks that will end up in the cloned loop. We may have
1276*0b57cec5SDimitry Andric   // skipped cloning some region of this loop which can in turn skip some of
1277*0b57cec5SDimitry Andric   // the backedges so we have to rebuild the blocks in the loop based on the
1278*0b57cec5SDimitry Andric   // backedges that remain after cloning.
1279*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> Worklist;
1280*0b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1281*0b57cec5SDimitry Andric   for (auto *Pred : predecessors(ClonedHeader)) {
1282*0b57cec5SDimitry Andric     // The only possible non-loop header predecessor is the preheader because
1283*0b57cec5SDimitry Andric     // we know we cloned the loop in simplified form.
1284*0b57cec5SDimitry Andric     if (Pred == ClonedPH)
1285*0b57cec5SDimitry Andric       continue;
1286*0b57cec5SDimitry Andric 
1287*0b57cec5SDimitry Andric     // Because the loop was in simplified form, the only non-loop predecessor
1288*0b57cec5SDimitry Andric     // should be the preheader.
1289*0b57cec5SDimitry Andric     assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1290*0b57cec5SDimitry Andric                                            "header other than the preheader "
1291*0b57cec5SDimitry Andric                                            "that is not part of the loop!");
1292*0b57cec5SDimitry Andric 
1293*0b57cec5SDimitry Andric     // Insert this block into the loop set and on the first visit (and if it
1294*0b57cec5SDimitry Andric     // isn't the header we're currently walking) put it into the worklist to
1295*0b57cec5SDimitry Andric     // recurse through.
1296*0b57cec5SDimitry Andric     if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1297*0b57cec5SDimitry Andric       Worklist.push_back(Pred);
1298*0b57cec5SDimitry Andric   }
1299*0b57cec5SDimitry Andric 
1300*0b57cec5SDimitry Andric   // If we had any backedges then there *is* a cloned loop. Put the header into
1301*0b57cec5SDimitry Andric   // the loop set and then walk the worklist backwards to find all the blocks
1302*0b57cec5SDimitry Andric   // that remain within the loop after cloning.
1303*0b57cec5SDimitry Andric   if (!BlocksInClonedLoop.empty()) {
1304*0b57cec5SDimitry Andric     BlocksInClonedLoop.insert(ClonedHeader);
1305*0b57cec5SDimitry Andric 
1306*0b57cec5SDimitry Andric     while (!Worklist.empty()) {
1307*0b57cec5SDimitry Andric       BasicBlock *BB = Worklist.pop_back_val();
1308*0b57cec5SDimitry Andric       assert(BlocksInClonedLoop.count(BB) &&
1309*0b57cec5SDimitry Andric              "Didn't put block into the loop set!");
1310*0b57cec5SDimitry Andric 
1311*0b57cec5SDimitry Andric       // Insert any predecessors that are in the possible set into the cloned
1312*0b57cec5SDimitry Andric       // set, and if the insert is successful, add them to the worklist. Note
1313*0b57cec5SDimitry Andric       // that we filter on the blocks that are definitely reachable via the
1314*0b57cec5SDimitry Andric       // backedge to the loop header so we may prune out dead code within the
1315*0b57cec5SDimitry Andric       // cloned loop.
1316*0b57cec5SDimitry Andric       for (auto *Pred : predecessors(BB))
1317*0b57cec5SDimitry Andric         if (ClonedLoopBlocks.count(Pred) &&
1318*0b57cec5SDimitry Andric             BlocksInClonedLoop.insert(Pred).second)
1319*0b57cec5SDimitry Andric           Worklist.push_back(Pred);
1320*0b57cec5SDimitry Andric     }
1321*0b57cec5SDimitry Andric 
1322*0b57cec5SDimitry Andric     ClonedL = LI.AllocateLoop();
1323*0b57cec5SDimitry Andric     if (ParentL) {
1324*0b57cec5SDimitry Andric       ParentL->addBasicBlockToLoop(ClonedPH, LI);
1325*0b57cec5SDimitry Andric       ParentL->addChildLoop(ClonedL);
1326*0b57cec5SDimitry Andric     } else {
1327*0b57cec5SDimitry Andric       LI.addTopLevelLoop(ClonedL);
1328*0b57cec5SDimitry Andric     }
1329*0b57cec5SDimitry Andric     NonChildClonedLoops.push_back(ClonedL);
1330*0b57cec5SDimitry Andric 
1331*0b57cec5SDimitry Andric     ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1332*0b57cec5SDimitry Andric     // We don't want to just add the cloned loop blocks based on how we
1333*0b57cec5SDimitry Andric     // discovered them. The original order of blocks was carefully built in
1334*0b57cec5SDimitry Andric     // a way that doesn't rely on predecessor ordering. Rather than re-invent
1335*0b57cec5SDimitry Andric     // that logic, we just re-walk the original blocks (and those of the child
1336*0b57cec5SDimitry Andric     // loops) and filter them as we add them into the cloned loop.
1337*0b57cec5SDimitry Andric     for (auto *BB : OrigL.blocks()) {
1338*0b57cec5SDimitry Andric       auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1339*0b57cec5SDimitry Andric       if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1340*0b57cec5SDimitry Andric         continue;
1341*0b57cec5SDimitry Andric 
1342*0b57cec5SDimitry Andric       // Directly add the blocks that are only in this loop.
1343*0b57cec5SDimitry Andric       if (LI.getLoopFor(BB) == &OrigL) {
1344*0b57cec5SDimitry Andric         ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1345*0b57cec5SDimitry Andric         continue;
1346*0b57cec5SDimitry Andric       }
1347*0b57cec5SDimitry Andric 
1348*0b57cec5SDimitry Andric       // We want to manually add it to this loop and parents.
1349*0b57cec5SDimitry Andric       // Registering it with LoopInfo will happen when we clone the top
1350*0b57cec5SDimitry Andric       // loop for this block.
1351*0b57cec5SDimitry Andric       for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1352*0b57cec5SDimitry Andric         PL->addBlockEntry(ClonedBB);
1353*0b57cec5SDimitry Andric     }
1354*0b57cec5SDimitry Andric 
1355*0b57cec5SDimitry Andric     // Now add each child loop whose header remains within the cloned loop. All
1356*0b57cec5SDimitry Andric     // of the blocks within the loop must satisfy the same constraints as the
1357*0b57cec5SDimitry Andric     // header so once we pass the header checks we can just clone the entire
1358*0b57cec5SDimitry Andric     // child loop nest.
1359*0b57cec5SDimitry Andric     for (Loop *ChildL : OrigL) {
1360*0b57cec5SDimitry Andric       auto *ClonedChildHeader =
1361*0b57cec5SDimitry Andric           cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1362*0b57cec5SDimitry Andric       if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1363*0b57cec5SDimitry Andric         continue;
1364*0b57cec5SDimitry Andric 
1365*0b57cec5SDimitry Andric #ifndef NDEBUG
1366*0b57cec5SDimitry Andric       // We should never have a cloned child loop header but fail to have
1367*0b57cec5SDimitry Andric       // all of the blocks for that child loop.
1368*0b57cec5SDimitry Andric       for (auto *ChildLoopBB : ChildL->blocks())
1369*0b57cec5SDimitry Andric         assert(BlocksInClonedLoop.count(
1370*0b57cec5SDimitry Andric                    cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1371*0b57cec5SDimitry Andric                "Child cloned loop has a header within the cloned outer "
1372*0b57cec5SDimitry Andric                "loop but not all of its blocks!");
1373*0b57cec5SDimitry Andric #endif
1374*0b57cec5SDimitry Andric 
1375*0b57cec5SDimitry Andric       cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1376*0b57cec5SDimitry Andric     }
1377*0b57cec5SDimitry Andric   }
1378*0b57cec5SDimitry Andric 
1379*0b57cec5SDimitry Andric   // Now that we've handled all the components of the original loop that were
1380*0b57cec5SDimitry Andric   // cloned into a new loop, we still need to handle anything from the original
1381*0b57cec5SDimitry Andric   // loop that wasn't in a cloned loop.
1382*0b57cec5SDimitry Andric 
1383*0b57cec5SDimitry Andric   // Figure out what blocks are left to place within any loop nest containing
1384*0b57cec5SDimitry Andric   // the unswitched loop. If we never formed a loop, the cloned PH is one of
1385*0b57cec5SDimitry Andric   // them.
1386*0b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1387*0b57cec5SDimitry Andric   if (BlocksInClonedLoop.empty())
1388*0b57cec5SDimitry Andric     UnloopedBlockSet.insert(ClonedPH);
1389*0b57cec5SDimitry Andric   for (auto *ClonedBB : ClonedLoopBlocks)
1390*0b57cec5SDimitry Andric     if (!BlocksInClonedLoop.count(ClonedBB))
1391*0b57cec5SDimitry Andric       UnloopedBlockSet.insert(ClonedBB);
1392*0b57cec5SDimitry Andric 
1393*0b57cec5SDimitry Andric   // Copy the cloned exits and sort them in ascending loop depth, we'll work
1394*0b57cec5SDimitry Andric   // backwards across these to process them inside out. The order shouldn't
1395*0b57cec5SDimitry Andric   // matter as we're just trying to build up the map from inside-out; we use
1396*0b57cec5SDimitry Andric   // the map in a more stably ordered way below.
1397*0b57cec5SDimitry Andric   auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
1398*0b57cec5SDimitry Andric   llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1399*0b57cec5SDimitry Andric     return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1400*0b57cec5SDimitry Andric            ExitLoopMap.lookup(RHS)->getLoopDepth();
1401*0b57cec5SDimitry Andric   });
1402*0b57cec5SDimitry Andric 
1403*0b57cec5SDimitry Andric   // Populate the existing ExitLoopMap with everything reachable from each
1404*0b57cec5SDimitry Andric   // exit, starting from the inner most exit.
1405*0b57cec5SDimitry Andric   while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1406*0b57cec5SDimitry Andric     assert(Worklist.empty() && "Didn't clear worklist!");
1407*0b57cec5SDimitry Andric 
1408*0b57cec5SDimitry Andric     BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1409*0b57cec5SDimitry Andric     Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1410*0b57cec5SDimitry Andric 
1411*0b57cec5SDimitry Andric     // Walk the CFG back until we hit the cloned PH adding everything reachable
1412*0b57cec5SDimitry Andric     // and in the unlooped set to this exit block's loop.
1413*0b57cec5SDimitry Andric     Worklist.push_back(ExitBB);
1414*0b57cec5SDimitry Andric     do {
1415*0b57cec5SDimitry Andric       BasicBlock *BB = Worklist.pop_back_val();
1416*0b57cec5SDimitry Andric       // We can stop recursing at the cloned preheader (if we get there).
1417*0b57cec5SDimitry Andric       if (BB == ClonedPH)
1418*0b57cec5SDimitry Andric         continue;
1419*0b57cec5SDimitry Andric 
1420*0b57cec5SDimitry Andric       for (BasicBlock *PredBB : predecessors(BB)) {
1421*0b57cec5SDimitry Andric         // If this pred has already been moved to our set or is part of some
1422*0b57cec5SDimitry Andric         // (inner) loop, no update needed.
1423*0b57cec5SDimitry Andric         if (!UnloopedBlockSet.erase(PredBB)) {
1424*0b57cec5SDimitry Andric           assert(
1425*0b57cec5SDimitry Andric               (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1426*0b57cec5SDimitry Andric               "Predecessor not mapped to a loop!");
1427*0b57cec5SDimitry Andric           continue;
1428*0b57cec5SDimitry Andric         }
1429*0b57cec5SDimitry Andric 
1430*0b57cec5SDimitry Andric         // We just insert into the loop set here. We'll add these blocks to the
1431*0b57cec5SDimitry Andric         // exit loop after we build up the set in an order that doesn't rely on
1432*0b57cec5SDimitry Andric         // predecessor order (which in turn relies on use list order).
1433*0b57cec5SDimitry Andric         bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1434*0b57cec5SDimitry Andric         (void)Inserted;
1435*0b57cec5SDimitry Andric         assert(Inserted && "Should only visit an unlooped block once!");
1436*0b57cec5SDimitry Andric 
1437*0b57cec5SDimitry Andric         // And recurse through to its predecessors.
1438*0b57cec5SDimitry Andric         Worklist.push_back(PredBB);
1439*0b57cec5SDimitry Andric       }
1440*0b57cec5SDimitry Andric     } while (!Worklist.empty());
1441*0b57cec5SDimitry Andric   }
1442*0b57cec5SDimitry Andric 
1443*0b57cec5SDimitry Andric   // Now that the ExitLoopMap gives as  mapping for all the non-looping cloned
1444*0b57cec5SDimitry Andric   // blocks to their outer loops, walk the cloned blocks and the cloned exits
1445*0b57cec5SDimitry Andric   // in their original order adding them to the correct loop.
1446*0b57cec5SDimitry Andric 
1447*0b57cec5SDimitry Andric   // We need a stable insertion order. We use the order of the original loop
1448*0b57cec5SDimitry Andric   // order and map into the correct parent loop.
1449*0b57cec5SDimitry Andric   for (auto *BB : llvm::concat<BasicBlock *const>(
1450*0b57cec5SDimitry Andric            makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1451*0b57cec5SDimitry Andric     if (Loop *OuterL = ExitLoopMap.lookup(BB))
1452*0b57cec5SDimitry Andric       OuterL->addBasicBlockToLoop(BB, LI);
1453*0b57cec5SDimitry Andric 
1454*0b57cec5SDimitry Andric #ifndef NDEBUG
1455*0b57cec5SDimitry Andric   for (auto &BBAndL : ExitLoopMap) {
1456*0b57cec5SDimitry Andric     auto *BB = BBAndL.first;
1457*0b57cec5SDimitry Andric     auto *OuterL = BBAndL.second;
1458*0b57cec5SDimitry Andric     assert(LI.getLoopFor(BB) == OuterL &&
1459*0b57cec5SDimitry Andric            "Failed to put all blocks into outer loops!");
1460*0b57cec5SDimitry Andric   }
1461*0b57cec5SDimitry Andric #endif
1462*0b57cec5SDimitry Andric 
1463*0b57cec5SDimitry Andric   // Now that all the blocks are placed into the correct containing loop in the
1464*0b57cec5SDimitry Andric   // absence of child loops, find all the potentially cloned child loops and
1465*0b57cec5SDimitry Andric   // clone them into whatever outer loop we placed their header into.
1466*0b57cec5SDimitry Andric   for (Loop *ChildL : OrigL) {
1467*0b57cec5SDimitry Andric     auto *ClonedChildHeader =
1468*0b57cec5SDimitry Andric         cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1469*0b57cec5SDimitry Andric     if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1470*0b57cec5SDimitry Andric       continue;
1471*0b57cec5SDimitry Andric 
1472*0b57cec5SDimitry Andric #ifndef NDEBUG
1473*0b57cec5SDimitry Andric     for (auto *ChildLoopBB : ChildL->blocks())
1474*0b57cec5SDimitry Andric       assert(VMap.count(ChildLoopBB) &&
1475*0b57cec5SDimitry Andric              "Cloned a child loop header but not all of that loops blocks!");
1476*0b57cec5SDimitry Andric #endif
1477*0b57cec5SDimitry Andric 
1478*0b57cec5SDimitry Andric     NonChildClonedLoops.push_back(cloneLoopNest(
1479*0b57cec5SDimitry Andric         *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1480*0b57cec5SDimitry Andric   }
1481*0b57cec5SDimitry Andric }
1482*0b57cec5SDimitry Andric 
1483*0b57cec5SDimitry Andric static void
1484*0b57cec5SDimitry Andric deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1485*0b57cec5SDimitry Andric                        ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1486*0b57cec5SDimitry Andric                        DominatorTree &DT, MemorySSAUpdater *MSSAU) {
1487*0b57cec5SDimitry Andric   // Find all the dead clones, and remove them from their successors.
1488*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> DeadBlocks;
1489*0b57cec5SDimitry Andric   for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1490*0b57cec5SDimitry Andric     for (auto &VMap : VMaps)
1491*0b57cec5SDimitry Andric       if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1492*0b57cec5SDimitry Andric         if (!DT.isReachableFromEntry(ClonedBB)) {
1493*0b57cec5SDimitry Andric           for (BasicBlock *SuccBB : successors(ClonedBB))
1494*0b57cec5SDimitry Andric             SuccBB->removePredecessor(ClonedBB);
1495*0b57cec5SDimitry Andric           DeadBlocks.push_back(ClonedBB);
1496*0b57cec5SDimitry Andric         }
1497*0b57cec5SDimitry Andric 
1498*0b57cec5SDimitry Andric   // Remove all MemorySSA in the dead blocks
1499*0b57cec5SDimitry Andric   if (MSSAU) {
1500*0b57cec5SDimitry Andric     SmallSetVector<BasicBlock *, 8> DeadBlockSet(DeadBlocks.begin(),
1501*0b57cec5SDimitry Andric                                                  DeadBlocks.end());
1502*0b57cec5SDimitry Andric     MSSAU->removeBlocks(DeadBlockSet);
1503*0b57cec5SDimitry Andric   }
1504*0b57cec5SDimitry Andric 
1505*0b57cec5SDimitry Andric   // Drop any remaining references to break cycles.
1506*0b57cec5SDimitry Andric   for (BasicBlock *BB : DeadBlocks)
1507*0b57cec5SDimitry Andric     BB->dropAllReferences();
1508*0b57cec5SDimitry Andric   // Erase them from the IR.
1509*0b57cec5SDimitry Andric   for (BasicBlock *BB : DeadBlocks)
1510*0b57cec5SDimitry Andric     BB->eraseFromParent();
1511*0b57cec5SDimitry Andric }
1512*0b57cec5SDimitry Andric 
1513*0b57cec5SDimitry Andric static void deleteDeadBlocksFromLoop(Loop &L,
1514*0b57cec5SDimitry Andric                                      SmallVectorImpl<BasicBlock *> &ExitBlocks,
1515*0b57cec5SDimitry Andric                                      DominatorTree &DT, LoopInfo &LI,
1516*0b57cec5SDimitry Andric                                      MemorySSAUpdater *MSSAU) {
1517*0b57cec5SDimitry Andric   // Find all the dead blocks tied to this loop, and remove them from their
1518*0b57cec5SDimitry Andric   // successors.
1519*0b57cec5SDimitry Andric   SmallSetVector<BasicBlock *, 8> DeadBlockSet;
1520*0b57cec5SDimitry Andric 
1521*0b57cec5SDimitry Andric   // Start with loop/exit blocks and get a transitive closure of reachable dead
1522*0b57cec5SDimitry Andric   // blocks.
1523*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
1524*0b57cec5SDimitry Andric                                                 ExitBlocks.end());
1525*0b57cec5SDimitry Andric   DeathCandidates.append(L.blocks().begin(), L.blocks().end());
1526*0b57cec5SDimitry Andric   while (!DeathCandidates.empty()) {
1527*0b57cec5SDimitry Andric     auto *BB = DeathCandidates.pop_back_val();
1528*0b57cec5SDimitry Andric     if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
1529*0b57cec5SDimitry Andric       for (BasicBlock *SuccBB : successors(BB)) {
1530*0b57cec5SDimitry Andric         SuccBB->removePredecessor(BB);
1531*0b57cec5SDimitry Andric         DeathCandidates.push_back(SuccBB);
1532*0b57cec5SDimitry Andric       }
1533*0b57cec5SDimitry Andric       DeadBlockSet.insert(BB);
1534*0b57cec5SDimitry Andric     }
1535*0b57cec5SDimitry Andric   }
1536*0b57cec5SDimitry Andric 
1537*0b57cec5SDimitry Andric   // Remove all MemorySSA in the dead blocks
1538*0b57cec5SDimitry Andric   if (MSSAU)
1539*0b57cec5SDimitry Andric     MSSAU->removeBlocks(DeadBlockSet);
1540*0b57cec5SDimitry Andric 
1541*0b57cec5SDimitry Andric   // Filter out the dead blocks from the exit blocks list so that it can be
1542*0b57cec5SDimitry Andric   // used in the caller.
1543*0b57cec5SDimitry Andric   llvm::erase_if(ExitBlocks,
1544*0b57cec5SDimitry Andric                  [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1545*0b57cec5SDimitry Andric 
1546*0b57cec5SDimitry Andric   // Walk from this loop up through its parents removing all of the dead blocks.
1547*0b57cec5SDimitry Andric   for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
1548*0b57cec5SDimitry Andric     for (auto *BB : DeadBlockSet)
1549*0b57cec5SDimitry Andric       ParentL->getBlocksSet().erase(BB);
1550*0b57cec5SDimitry Andric     llvm::erase_if(ParentL->getBlocksVector(),
1551*0b57cec5SDimitry Andric                    [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1552*0b57cec5SDimitry Andric   }
1553*0b57cec5SDimitry Andric 
1554*0b57cec5SDimitry Andric   // Now delete the dead child loops. This raw delete will clear them
1555*0b57cec5SDimitry Andric   // recursively.
1556*0b57cec5SDimitry Andric   llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
1557*0b57cec5SDimitry Andric     if (!DeadBlockSet.count(ChildL->getHeader()))
1558*0b57cec5SDimitry Andric       return false;
1559*0b57cec5SDimitry Andric 
1560*0b57cec5SDimitry Andric     assert(llvm::all_of(ChildL->blocks(),
1561*0b57cec5SDimitry Andric                         [&](BasicBlock *ChildBB) {
1562*0b57cec5SDimitry Andric                           return DeadBlockSet.count(ChildBB);
1563*0b57cec5SDimitry Andric                         }) &&
1564*0b57cec5SDimitry Andric            "If the child loop header is dead all blocks in the child loop must "
1565*0b57cec5SDimitry Andric            "be dead as well!");
1566*0b57cec5SDimitry Andric     LI.destroy(ChildL);
1567*0b57cec5SDimitry Andric     return true;
1568*0b57cec5SDimitry Andric   });
1569*0b57cec5SDimitry Andric 
1570*0b57cec5SDimitry Andric   // Remove the loop mappings for the dead blocks and drop all the references
1571*0b57cec5SDimitry Andric   // from these blocks to others to handle cyclic references as we start
1572*0b57cec5SDimitry Andric   // deleting the blocks themselves.
1573*0b57cec5SDimitry Andric   for (auto *BB : DeadBlockSet) {
1574*0b57cec5SDimitry Andric     // Check that the dominator tree has already been updated.
1575*0b57cec5SDimitry Andric     assert(!DT.getNode(BB) && "Should already have cleared domtree!");
1576*0b57cec5SDimitry Andric     LI.changeLoopFor(BB, nullptr);
15775ffd83dbSDimitry Andric     // Drop all uses of the instructions to make sure we won't have dangling
15785ffd83dbSDimitry Andric     // uses in other blocks.
15795ffd83dbSDimitry Andric     for (auto &I : *BB)
15805ffd83dbSDimitry Andric       if (!I.use_empty())
15815ffd83dbSDimitry Andric         I.replaceAllUsesWith(UndefValue::get(I.getType()));
1582*0b57cec5SDimitry Andric     BB->dropAllReferences();
1583*0b57cec5SDimitry Andric   }
1584*0b57cec5SDimitry Andric 
1585*0b57cec5SDimitry Andric   // Actually delete the blocks now that they've been fully unhooked from the
1586*0b57cec5SDimitry Andric   // IR.
1587*0b57cec5SDimitry Andric   for (auto *BB : DeadBlockSet)
1588*0b57cec5SDimitry Andric     BB->eraseFromParent();
1589*0b57cec5SDimitry Andric }
1590*0b57cec5SDimitry Andric 
1591*0b57cec5SDimitry Andric /// Recompute the set of blocks in a loop after unswitching.
1592*0b57cec5SDimitry Andric ///
1593*0b57cec5SDimitry Andric /// This walks from the original headers predecessors to rebuild the loop. We
1594*0b57cec5SDimitry Andric /// take advantage of the fact that new blocks can't have been added, and so we
1595*0b57cec5SDimitry Andric /// filter by the original loop's blocks. This also handles potentially
1596*0b57cec5SDimitry Andric /// unreachable code that we don't want to explore but might be found examining
1597*0b57cec5SDimitry Andric /// the predecessors of the header.
1598*0b57cec5SDimitry Andric ///
1599*0b57cec5SDimitry Andric /// If the original loop is no longer a loop, this will return an empty set. If
1600*0b57cec5SDimitry Andric /// it remains a loop, all the blocks within it will be added to the set
1601*0b57cec5SDimitry Andric /// (including those blocks in inner loops).
1602*0b57cec5SDimitry Andric static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1603*0b57cec5SDimitry Andric                                                                  LoopInfo &LI) {
1604*0b57cec5SDimitry Andric   SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1605*0b57cec5SDimitry Andric 
1606*0b57cec5SDimitry Andric   auto *PH = L.getLoopPreheader();
1607*0b57cec5SDimitry Andric   auto *Header = L.getHeader();
1608*0b57cec5SDimitry Andric 
1609*0b57cec5SDimitry Andric   // A worklist to use while walking backwards from the header.
1610*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> Worklist;
1611*0b57cec5SDimitry Andric 
1612*0b57cec5SDimitry Andric   // First walk the predecessors of the header to find the backedges. This will
1613*0b57cec5SDimitry Andric   // form the basis of our walk.
1614*0b57cec5SDimitry Andric   for (auto *Pred : predecessors(Header)) {
1615*0b57cec5SDimitry Andric     // Skip the preheader.
1616*0b57cec5SDimitry Andric     if (Pred == PH)
1617*0b57cec5SDimitry Andric       continue;
1618*0b57cec5SDimitry Andric 
1619*0b57cec5SDimitry Andric     // Because the loop was in simplified form, the only non-loop predecessor
1620*0b57cec5SDimitry Andric     // is the preheader.
1621*0b57cec5SDimitry Andric     assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1622*0b57cec5SDimitry Andric                                "than the preheader that is not part of the "
1623*0b57cec5SDimitry Andric                                "loop!");
1624*0b57cec5SDimitry Andric 
1625*0b57cec5SDimitry Andric     // Insert this block into the loop set and on the first visit and, if it
1626*0b57cec5SDimitry Andric     // isn't the header we're currently walking, put it into the worklist to
1627*0b57cec5SDimitry Andric     // recurse through.
1628*0b57cec5SDimitry Andric     if (LoopBlockSet.insert(Pred).second && Pred != Header)
1629*0b57cec5SDimitry Andric       Worklist.push_back(Pred);
1630*0b57cec5SDimitry Andric   }
1631*0b57cec5SDimitry Andric 
1632*0b57cec5SDimitry Andric   // If no backedges were found, we're done.
1633*0b57cec5SDimitry Andric   if (LoopBlockSet.empty())
1634*0b57cec5SDimitry Andric     return LoopBlockSet;
1635*0b57cec5SDimitry Andric 
1636*0b57cec5SDimitry Andric   // We found backedges, recurse through them to identify the loop blocks.
1637*0b57cec5SDimitry Andric   while (!Worklist.empty()) {
1638*0b57cec5SDimitry Andric     BasicBlock *BB = Worklist.pop_back_val();
1639*0b57cec5SDimitry Andric     assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1640*0b57cec5SDimitry Andric 
1641*0b57cec5SDimitry Andric     // No need to walk past the header.
1642*0b57cec5SDimitry Andric     if (BB == Header)
1643*0b57cec5SDimitry Andric       continue;
1644*0b57cec5SDimitry Andric 
1645*0b57cec5SDimitry Andric     // Because we know the inner loop structure remains valid we can use the
1646*0b57cec5SDimitry Andric     // loop structure to jump immediately across the entire nested loop.
1647*0b57cec5SDimitry Andric     // Further, because it is in loop simplified form, we can directly jump
1648*0b57cec5SDimitry Andric     // to its preheader afterward.
1649*0b57cec5SDimitry Andric     if (Loop *InnerL = LI.getLoopFor(BB))
1650*0b57cec5SDimitry Andric       if (InnerL != &L) {
1651*0b57cec5SDimitry Andric         assert(L.contains(InnerL) &&
1652*0b57cec5SDimitry Andric                "Should not reach a loop *outside* this loop!");
1653*0b57cec5SDimitry Andric         // The preheader is the only possible predecessor of the loop so
1654*0b57cec5SDimitry Andric         // insert it into the set and check whether it was already handled.
1655*0b57cec5SDimitry Andric         auto *InnerPH = InnerL->getLoopPreheader();
1656*0b57cec5SDimitry Andric         assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1657*0b57cec5SDimitry Andric                                       "but not contain the inner loop "
1658*0b57cec5SDimitry Andric                                       "preheader!");
1659*0b57cec5SDimitry Andric         if (!LoopBlockSet.insert(InnerPH).second)
1660*0b57cec5SDimitry Andric           // The only way to reach the preheader is through the loop body
1661*0b57cec5SDimitry Andric           // itself so if it has been visited the loop is already handled.
1662*0b57cec5SDimitry Andric           continue;
1663*0b57cec5SDimitry Andric 
1664*0b57cec5SDimitry Andric         // Insert all of the blocks (other than those already present) into
1665*0b57cec5SDimitry Andric         // the loop set. We expect at least the block that led us to find the
1666*0b57cec5SDimitry Andric         // inner loop to be in the block set, but we may also have other loop
1667*0b57cec5SDimitry Andric         // blocks if they were already enqueued as predecessors of some other
1668*0b57cec5SDimitry Andric         // outer loop block.
1669*0b57cec5SDimitry Andric         for (auto *InnerBB : InnerL->blocks()) {
1670*0b57cec5SDimitry Andric           if (InnerBB == BB) {
1671*0b57cec5SDimitry Andric             assert(LoopBlockSet.count(InnerBB) &&
1672*0b57cec5SDimitry Andric                    "Block should already be in the set!");
1673*0b57cec5SDimitry Andric             continue;
1674*0b57cec5SDimitry Andric           }
1675*0b57cec5SDimitry Andric 
1676*0b57cec5SDimitry Andric           LoopBlockSet.insert(InnerBB);
1677*0b57cec5SDimitry Andric         }
1678*0b57cec5SDimitry Andric 
1679*0b57cec5SDimitry Andric         // Add the preheader to the worklist so we will continue past the
1680*0b57cec5SDimitry Andric         // loop body.
1681*0b57cec5SDimitry Andric         Worklist.push_back(InnerPH);
1682*0b57cec5SDimitry Andric         continue;
1683*0b57cec5SDimitry Andric       }
1684*0b57cec5SDimitry Andric 
1685*0b57cec5SDimitry Andric     // Insert any predecessors that were in the original loop into the new
1686*0b57cec5SDimitry Andric     // set, and if the insert is successful, add them to the worklist.
1687*0b57cec5SDimitry Andric     for (auto *Pred : predecessors(BB))
1688*0b57cec5SDimitry Andric       if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1689*0b57cec5SDimitry Andric         Worklist.push_back(Pred);
1690*0b57cec5SDimitry Andric   }
1691*0b57cec5SDimitry Andric 
1692*0b57cec5SDimitry Andric   assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1693*0b57cec5SDimitry Andric 
1694*0b57cec5SDimitry Andric   // We've found all the blocks participating in the loop, return our completed
1695*0b57cec5SDimitry Andric   // set.
1696*0b57cec5SDimitry Andric   return LoopBlockSet;
1697*0b57cec5SDimitry Andric }
1698*0b57cec5SDimitry Andric 
1699*0b57cec5SDimitry Andric /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1700*0b57cec5SDimitry Andric ///
1701*0b57cec5SDimitry Andric /// The removal may have removed some child loops entirely but cannot have
1702*0b57cec5SDimitry Andric /// disturbed any remaining child loops. However, they may need to be hoisted
1703*0b57cec5SDimitry Andric /// to the parent loop (or to be top-level loops). The original loop may be
1704*0b57cec5SDimitry Andric /// completely removed.
1705*0b57cec5SDimitry Andric ///
1706*0b57cec5SDimitry Andric /// The sibling loops resulting from this update are returned. If the original
1707*0b57cec5SDimitry Andric /// loop remains a valid loop, it will be the first entry in this list with all
1708*0b57cec5SDimitry Andric /// of the newly sibling loops following it.
1709*0b57cec5SDimitry Andric ///
1710*0b57cec5SDimitry Andric /// Returns true if the loop remains a loop after unswitching, and false if it
1711*0b57cec5SDimitry Andric /// is no longer a loop after unswitching (and should not continue to be
1712*0b57cec5SDimitry Andric /// referenced).
1713*0b57cec5SDimitry Andric static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1714*0b57cec5SDimitry Andric                                      LoopInfo &LI,
1715*0b57cec5SDimitry Andric                                      SmallVectorImpl<Loop *> &HoistedLoops) {
1716*0b57cec5SDimitry Andric   auto *PH = L.getLoopPreheader();
1717*0b57cec5SDimitry Andric 
1718*0b57cec5SDimitry Andric   // Compute the actual parent loop from the exit blocks. Because we may have
1719*0b57cec5SDimitry Andric   // pruned some exits the loop may be different from the original parent.
1720*0b57cec5SDimitry Andric   Loop *ParentL = nullptr;
1721*0b57cec5SDimitry Andric   SmallVector<Loop *, 4> ExitLoops;
1722*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> ExitsInLoops;
1723*0b57cec5SDimitry Andric   ExitsInLoops.reserve(ExitBlocks.size());
1724*0b57cec5SDimitry Andric   for (auto *ExitBB : ExitBlocks)
1725*0b57cec5SDimitry Andric     if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1726*0b57cec5SDimitry Andric       ExitLoops.push_back(ExitL);
1727*0b57cec5SDimitry Andric       ExitsInLoops.push_back(ExitBB);
1728*0b57cec5SDimitry Andric       if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1729*0b57cec5SDimitry Andric         ParentL = ExitL;
1730*0b57cec5SDimitry Andric     }
1731*0b57cec5SDimitry Andric 
1732*0b57cec5SDimitry Andric   // Recompute the blocks participating in this loop. This may be empty if it
1733*0b57cec5SDimitry Andric   // is no longer a loop.
1734*0b57cec5SDimitry Andric   auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1735*0b57cec5SDimitry Andric 
1736*0b57cec5SDimitry Andric   // If we still have a loop, we need to re-set the loop's parent as the exit
1737*0b57cec5SDimitry Andric   // block set changing may have moved it within the loop nest. Note that this
1738*0b57cec5SDimitry Andric   // can only happen when this loop has a parent as it can only hoist the loop
1739*0b57cec5SDimitry Andric   // *up* the nest.
1740*0b57cec5SDimitry Andric   if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1741*0b57cec5SDimitry Andric     // Remove this loop's (original) blocks from all of the intervening loops.
1742*0b57cec5SDimitry Andric     for (Loop *IL = L.getParentLoop(); IL != ParentL;
1743*0b57cec5SDimitry Andric          IL = IL->getParentLoop()) {
1744*0b57cec5SDimitry Andric       IL->getBlocksSet().erase(PH);
1745*0b57cec5SDimitry Andric       for (auto *BB : L.blocks())
1746*0b57cec5SDimitry Andric         IL->getBlocksSet().erase(BB);
1747*0b57cec5SDimitry Andric       llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1748*0b57cec5SDimitry Andric         return BB == PH || L.contains(BB);
1749*0b57cec5SDimitry Andric       });
1750*0b57cec5SDimitry Andric     }
1751*0b57cec5SDimitry Andric 
1752*0b57cec5SDimitry Andric     LI.changeLoopFor(PH, ParentL);
1753*0b57cec5SDimitry Andric     L.getParentLoop()->removeChildLoop(&L);
1754*0b57cec5SDimitry Andric     if (ParentL)
1755*0b57cec5SDimitry Andric       ParentL->addChildLoop(&L);
1756*0b57cec5SDimitry Andric     else
1757*0b57cec5SDimitry Andric       LI.addTopLevelLoop(&L);
1758*0b57cec5SDimitry Andric   }
1759*0b57cec5SDimitry Andric 
1760*0b57cec5SDimitry Andric   // Now we update all the blocks which are no longer within the loop.
1761*0b57cec5SDimitry Andric   auto &Blocks = L.getBlocksVector();
1762*0b57cec5SDimitry Andric   auto BlocksSplitI =
1763*0b57cec5SDimitry Andric       LoopBlockSet.empty()
1764*0b57cec5SDimitry Andric           ? Blocks.begin()
1765*0b57cec5SDimitry Andric           : std::stable_partition(
1766*0b57cec5SDimitry Andric                 Blocks.begin(), Blocks.end(),
1767*0b57cec5SDimitry Andric                 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1768*0b57cec5SDimitry Andric 
1769*0b57cec5SDimitry Andric   // Before we erase the list of unlooped blocks, build a set of them.
1770*0b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1771*0b57cec5SDimitry Andric   if (LoopBlockSet.empty())
1772*0b57cec5SDimitry Andric     UnloopedBlocks.insert(PH);
1773*0b57cec5SDimitry Andric 
1774*0b57cec5SDimitry Andric   // Now erase these blocks from the loop.
1775*0b57cec5SDimitry Andric   for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1776*0b57cec5SDimitry Andric     L.getBlocksSet().erase(BB);
1777*0b57cec5SDimitry Andric   Blocks.erase(BlocksSplitI, Blocks.end());
1778*0b57cec5SDimitry Andric 
1779*0b57cec5SDimitry Andric   // Sort the exits in ascending loop depth, we'll work backwards across these
1780*0b57cec5SDimitry Andric   // to process them inside out.
1781*0b57cec5SDimitry Andric   llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1782*0b57cec5SDimitry Andric     return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1783*0b57cec5SDimitry Andric   });
1784*0b57cec5SDimitry Andric 
1785*0b57cec5SDimitry Andric   // We'll build up a set for each exit loop.
1786*0b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1787*0b57cec5SDimitry Andric   Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1788*0b57cec5SDimitry Andric 
1789*0b57cec5SDimitry Andric   auto RemoveUnloopedBlocksFromLoop =
1790*0b57cec5SDimitry Andric       [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1791*0b57cec5SDimitry Andric         for (auto *BB : UnloopedBlocks)
1792*0b57cec5SDimitry Andric           L.getBlocksSet().erase(BB);
1793*0b57cec5SDimitry Andric         llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1794*0b57cec5SDimitry Andric           return UnloopedBlocks.count(BB);
1795*0b57cec5SDimitry Andric         });
1796*0b57cec5SDimitry Andric       };
1797*0b57cec5SDimitry Andric 
1798*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> Worklist;
1799*0b57cec5SDimitry Andric   while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1800*0b57cec5SDimitry Andric     assert(Worklist.empty() && "Didn't clear worklist!");
1801*0b57cec5SDimitry Andric     assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1802*0b57cec5SDimitry Andric 
1803*0b57cec5SDimitry Andric     // Grab the next exit block, in decreasing loop depth order.
1804*0b57cec5SDimitry Andric     BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1805*0b57cec5SDimitry Andric     Loop &ExitL = *LI.getLoopFor(ExitBB);
1806*0b57cec5SDimitry Andric     assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1807*0b57cec5SDimitry Andric 
1808*0b57cec5SDimitry Andric     // Erase all of the unlooped blocks from the loops between the previous
1809*0b57cec5SDimitry Andric     // exit loop and this exit loop. This works because the ExitInLoops list is
1810*0b57cec5SDimitry Andric     // sorted in increasing order of loop depth and thus we visit loops in
1811*0b57cec5SDimitry Andric     // decreasing order of loop depth.
1812*0b57cec5SDimitry Andric     for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1813*0b57cec5SDimitry Andric       RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1814*0b57cec5SDimitry Andric 
1815*0b57cec5SDimitry Andric     // Walk the CFG back until we hit the cloned PH adding everything reachable
1816*0b57cec5SDimitry Andric     // and in the unlooped set to this exit block's loop.
1817*0b57cec5SDimitry Andric     Worklist.push_back(ExitBB);
1818*0b57cec5SDimitry Andric     do {
1819*0b57cec5SDimitry Andric       BasicBlock *BB = Worklist.pop_back_val();
1820*0b57cec5SDimitry Andric       // We can stop recursing at the cloned preheader (if we get there).
1821*0b57cec5SDimitry Andric       if (BB == PH)
1822*0b57cec5SDimitry Andric         continue;
1823*0b57cec5SDimitry Andric 
1824*0b57cec5SDimitry Andric       for (BasicBlock *PredBB : predecessors(BB)) {
1825*0b57cec5SDimitry Andric         // If this pred has already been moved to our set or is part of some
1826*0b57cec5SDimitry Andric         // (inner) loop, no update needed.
1827*0b57cec5SDimitry Andric         if (!UnloopedBlocks.erase(PredBB)) {
1828*0b57cec5SDimitry Andric           assert((NewExitLoopBlocks.count(PredBB) ||
1829*0b57cec5SDimitry Andric                   ExitL.contains(LI.getLoopFor(PredBB))) &&
1830*0b57cec5SDimitry Andric                  "Predecessor not in a nested loop (or already visited)!");
1831*0b57cec5SDimitry Andric           continue;
1832*0b57cec5SDimitry Andric         }
1833*0b57cec5SDimitry Andric 
1834*0b57cec5SDimitry Andric         // We just insert into the loop set here. We'll add these blocks to the
1835*0b57cec5SDimitry Andric         // exit loop after we build up the set in a deterministic order rather
1836*0b57cec5SDimitry Andric         // than the predecessor-influenced visit order.
1837*0b57cec5SDimitry Andric         bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1838*0b57cec5SDimitry Andric         (void)Inserted;
1839*0b57cec5SDimitry Andric         assert(Inserted && "Should only visit an unlooped block once!");
1840*0b57cec5SDimitry Andric 
1841*0b57cec5SDimitry Andric         // And recurse through to its predecessors.
1842*0b57cec5SDimitry Andric         Worklist.push_back(PredBB);
1843*0b57cec5SDimitry Andric       }
1844*0b57cec5SDimitry Andric     } while (!Worklist.empty());
1845*0b57cec5SDimitry Andric 
1846*0b57cec5SDimitry Andric     // If blocks in this exit loop were directly part of the original loop (as
1847*0b57cec5SDimitry Andric     // opposed to a child loop) update the map to point to this exit loop. This
1848*0b57cec5SDimitry Andric     // just updates a map and so the fact that the order is unstable is fine.
1849*0b57cec5SDimitry Andric     for (auto *BB : NewExitLoopBlocks)
1850*0b57cec5SDimitry Andric       if (Loop *BBL = LI.getLoopFor(BB))
1851*0b57cec5SDimitry Andric         if (BBL == &L || !L.contains(BBL))
1852*0b57cec5SDimitry Andric           LI.changeLoopFor(BB, &ExitL);
1853*0b57cec5SDimitry Andric 
1854*0b57cec5SDimitry Andric     // We will remove the remaining unlooped blocks from this loop in the next
1855*0b57cec5SDimitry Andric     // iteration or below.
1856*0b57cec5SDimitry Andric     NewExitLoopBlocks.clear();
1857*0b57cec5SDimitry Andric   }
1858*0b57cec5SDimitry Andric 
1859*0b57cec5SDimitry Andric   // Any remaining unlooped blocks are no longer part of any loop unless they
1860*0b57cec5SDimitry Andric   // are part of some child loop.
1861*0b57cec5SDimitry Andric   for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1862*0b57cec5SDimitry Andric     RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1863*0b57cec5SDimitry Andric   for (auto *BB : UnloopedBlocks)
1864*0b57cec5SDimitry Andric     if (Loop *BBL = LI.getLoopFor(BB))
1865*0b57cec5SDimitry Andric       if (BBL == &L || !L.contains(BBL))
1866*0b57cec5SDimitry Andric         LI.changeLoopFor(BB, nullptr);
1867*0b57cec5SDimitry Andric 
1868*0b57cec5SDimitry Andric   // Sink all the child loops whose headers are no longer in the loop set to
1869*0b57cec5SDimitry Andric   // the parent (or to be top level loops). We reach into the loop and directly
1870*0b57cec5SDimitry Andric   // update its subloop vector to make this batch update efficient.
1871*0b57cec5SDimitry Andric   auto &SubLoops = L.getSubLoopsVector();
1872*0b57cec5SDimitry Andric   auto SubLoopsSplitI =
1873*0b57cec5SDimitry Andric       LoopBlockSet.empty()
1874*0b57cec5SDimitry Andric           ? SubLoops.begin()
1875*0b57cec5SDimitry Andric           : std::stable_partition(
1876*0b57cec5SDimitry Andric                 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1877*0b57cec5SDimitry Andric                   return LoopBlockSet.count(SubL->getHeader());
1878*0b57cec5SDimitry Andric                 });
1879*0b57cec5SDimitry Andric   for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1880*0b57cec5SDimitry Andric     HoistedLoops.push_back(HoistedL);
1881*0b57cec5SDimitry Andric     HoistedL->setParentLoop(nullptr);
1882*0b57cec5SDimitry Andric 
1883*0b57cec5SDimitry Andric     // To compute the new parent of this hoisted loop we look at where we
1884*0b57cec5SDimitry Andric     // placed the preheader above. We can't lookup the header itself because we
1885*0b57cec5SDimitry Andric     // retained the mapping from the header to the hoisted loop. But the
1886*0b57cec5SDimitry Andric     // preheader and header should have the exact same new parent computed
1887*0b57cec5SDimitry Andric     // based on the set of exit blocks from the original loop as the preheader
1888*0b57cec5SDimitry Andric     // is a predecessor of the header and so reached in the reverse walk. And
1889*0b57cec5SDimitry Andric     // because the loops were all in simplified form the preheader of the
1890*0b57cec5SDimitry Andric     // hoisted loop can't be part of some *other* loop.
1891*0b57cec5SDimitry Andric     if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1892*0b57cec5SDimitry Andric       NewParentL->addChildLoop(HoistedL);
1893*0b57cec5SDimitry Andric     else
1894*0b57cec5SDimitry Andric       LI.addTopLevelLoop(HoistedL);
1895*0b57cec5SDimitry Andric   }
1896*0b57cec5SDimitry Andric   SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1897*0b57cec5SDimitry Andric 
1898*0b57cec5SDimitry Andric   // Actually delete the loop if nothing remained within it.
1899*0b57cec5SDimitry Andric   if (Blocks.empty()) {
1900*0b57cec5SDimitry Andric     assert(SubLoops.empty() &&
1901*0b57cec5SDimitry Andric            "Failed to remove all subloops from the original loop!");
1902*0b57cec5SDimitry Andric     if (Loop *ParentL = L.getParentLoop())
1903*0b57cec5SDimitry Andric       ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1904*0b57cec5SDimitry Andric     else
1905*0b57cec5SDimitry Andric       LI.removeLoop(llvm::find(LI, &L));
1906*0b57cec5SDimitry Andric     LI.destroy(&L);
1907*0b57cec5SDimitry Andric     return false;
1908*0b57cec5SDimitry Andric   }
1909*0b57cec5SDimitry Andric 
1910*0b57cec5SDimitry Andric   return true;
1911*0b57cec5SDimitry Andric }
1912*0b57cec5SDimitry Andric 
1913*0b57cec5SDimitry Andric /// Helper to visit a dominator subtree, invoking a callable on each node.
1914*0b57cec5SDimitry Andric ///
1915*0b57cec5SDimitry Andric /// Returning false at any point will stop walking past that node of the tree.
1916*0b57cec5SDimitry Andric template <typename CallableT>
1917*0b57cec5SDimitry Andric void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1918*0b57cec5SDimitry Andric   SmallVector<DomTreeNode *, 4> DomWorklist;
1919*0b57cec5SDimitry Andric   DomWorklist.push_back(DT[BB]);
1920*0b57cec5SDimitry Andric #ifndef NDEBUG
1921*0b57cec5SDimitry Andric   SmallPtrSet<DomTreeNode *, 4> Visited;
1922*0b57cec5SDimitry Andric   Visited.insert(DT[BB]);
1923*0b57cec5SDimitry Andric #endif
1924*0b57cec5SDimitry Andric   do {
1925*0b57cec5SDimitry Andric     DomTreeNode *N = DomWorklist.pop_back_val();
1926*0b57cec5SDimitry Andric 
1927*0b57cec5SDimitry Andric     // Visit this node.
1928*0b57cec5SDimitry Andric     if (!Callable(N->getBlock()))
1929*0b57cec5SDimitry Andric       continue;
1930*0b57cec5SDimitry Andric 
1931*0b57cec5SDimitry Andric     // Accumulate the child nodes.
1932*0b57cec5SDimitry Andric     for (DomTreeNode *ChildN : *N) {
1933*0b57cec5SDimitry Andric       assert(Visited.insert(ChildN).second &&
1934*0b57cec5SDimitry Andric              "Cannot visit a node twice when walking a tree!");
1935*0b57cec5SDimitry Andric       DomWorklist.push_back(ChildN);
1936*0b57cec5SDimitry Andric     }
1937*0b57cec5SDimitry Andric   } while (!DomWorklist.empty());
1938*0b57cec5SDimitry Andric }
1939*0b57cec5SDimitry Andric 
1940*0b57cec5SDimitry Andric static void unswitchNontrivialInvariants(
1941*0b57cec5SDimitry Andric     Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
1942*0b57cec5SDimitry Andric     SmallVectorImpl<BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI,
1943*0b57cec5SDimitry Andric     AssumptionCache &AC, function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
1944*0b57cec5SDimitry Andric     ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
1945*0b57cec5SDimitry Andric   auto *ParentBB = TI.getParent();
1946*0b57cec5SDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(&TI);
1947*0b57cec5SDimitry Andric   SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
1948*0b57cec5SDimitry Andric 
1949*0b57cec5SDimitry Andric   // We can only unswitch switches, conditional branches with an invariant
1950*0b57cec5SDimitry Andric   // condition, or combining invariant conditions with an instruction.
19518bcb0991SDimitry Andric   assert((SI || (BI && BI->isConditional())) &&
1952*0b57cec5SDimitry Andric          "Can only unswitch switches and conditional branch!");
1953*0b57cec5SDimitry Andric   bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
1954*0b57cec5SDimitry Andric   if (FullUnswitch)
1955*0b57cec5SDimitry Andric     assert(Invariants.size() == 1 &&
1956*0b57cec5SDimitry Andric            "Cannot have other invariants with full unswitching!");
1957*0b57cec5SDimitry Andric   else
1958*0b57cec5SDimitry Andric     assert(isa<Instruction>(BI->getCondition()) &&
1959*0b57cec5SDimitry Andric            "Partial unswitching requires an instruction as the condition!");
1960*0b57cec5SDimitry Andric 
1961*0b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
1962*0b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
1963*0b57cec5SDimitry Andric 
1964*0b57cec5SDimitry Andric   // Constant and BBs tracking the cloned and continuing successor. When we are
1965*0b57cec5SDimitry Andric   // unswitching the entire condition, this can just be trivially chosen to
1966*0b57cec5SDimitry Andric   // unswitch towards `true`. However, when we are unswitching a set of
1967*0b57cec5SDimitry Andric   // invariants combined with `and` or `or`, the combining operation determines
1968*0b57cec5SDimitry Andric   // the best direction to unswitch: we want to unswitch the direction that will
1969*0b57cec5SDimitry Andric   // collapse the branch.
1970*0b57cec5SDimitry Andric   bool Direction = true;
1971*0b57cec5SDimitry Andric   int ClonedSucc = 0;
1972*0b57cec5SDimitry Andric   if (!FullUnswitch) {
1973*0b57cec5SDimitry Andric     if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1974*0b57cec5SDimitry Andric       assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1975*0b57cec5SDimitry Andric                  Instruction::And &&
1976*0b57cec5SDimitry Andric              "Only `or` and `and` instructions can combine invariants being "
1977*0b57cec5SDimitry Andric              "unswitched.");
1978*0b57cec5SDimitry Andric       Direction = false;
1979*0b57cec5SDimitry Andric       ClonedSucc = 1;
1980*0b57cec5SDimitry Andric     }
1981*0b57cec5SDimitry Andric   }
1982*0b57cec5SDimitry Andric 
1983*0b57cec5SDimitry Andric   BasicBlock *RetainedSuccBB =
1984*0b57cec5SDimitry Andric       BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1985*0b57cec5SDimitry Andric   SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1986*0b57cec5SDimitry Andric   if (BI)
1987*0b57cec5SDimitry Andric     UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1988*0b57cec5SDimitry Andric   else
1989*0b57cec5SDimitry Andric     for (auto Case : SI->cases())
1990*0b57cec5SDimitry Andric       if (Case.getCaseSuccessor() != RetainedSuccBB)
1991*0b57cec5SDimitry Andric         UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
1992*0b57cec5SDimitry Andric 
1993*0b57cec5SDimitry Andric   assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1994*0b57cec5SDimitry Andric          "Should not unswitch the same successor we are retaining!");
1995*0b57cec5SDimitry Andric 
1996*0b57cec5SDimitry Andric   // The branch should be in this exact loop. Any inner loop's invariant branch
1997*0b57cec5SDimitry Andric   // should be handled by unswitching that inner loop. The caller of this
1998*0b57cec5SDimitry Andric   // routine should filter out any candidates that remain (but were skipped for
1999*0b57cec5SDimitry Andric   // whatever reason).
2000*0b57cec5SDimitry Andric   assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
2001*0b57cec5SDimitry Andric 
2002*0b57cec5SDimitry Andric   // Compute the parent loop now before we start hacking on things.
2003*0b57cec5SDimitry Andric   Loop *ParentL = L.getParentLoop();
2004*0b57cec5SDimitry Andric   // Get blocks in RPO order for MSSA update, before changing the CFG.
2005*0b57cec5SDimitry Andric   LoopBlocksRPO LBRPO(&L);
2006*0b57cec5SDimitry Andric   if (MSSAU)
2007*0b57cec5SDimitry Andric     LBRPO.perform(&LI);
2008*0b57cec5SDimitry Andric 
2009*0b57cec5SDimitry Andric   // Compute the outer-most loop containing one of our exit blocks. This is the
2010*0b57cec5SDimitry Andric   // furthest up our loopnest which can be mutated, which we will use below to
2011*0b57cec5SDimitry Andric   // update things.
2012*0b57cec5SDimitry Andric   Loop *OuterExitL = &L;
2013*0b57cec5SDimitry Andric   for (auto *ExitBB : ExitBlocks) {
2014*0b57cec5SDimitry Andric     Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
2015*0b57cec5SDimitry Andric     if (!NewOuterExitL) {
2016*0b57cec5SDimitry Andric       // We exited the entire nest with this block, so we're done.
2017*0b57cec5SDimitry Andric       OuterExitL = nullptr;
2018*0b57cec5SDimitry Andric       break;
2019*0b57cec5SDimitry Andric     }
2020*0b57cec5SDimitry Andric     if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
2021*0b57cec5SDimitry Andric       OuterExitL = NewOuterExitL;
2022*0b57cec5SDimitry Andric   }
2023*0b57cec5SDimitry Andric 
2024*0b57cec5SDimitry Andric   // At this point, we're definitely going to unswitch something so invalidate
2025*0b57cec5SDimitry Andric   // any cached information in ScalarEvolution for the outer most loop
2026*0b57cec5SDimitry Andric   // containing an exit block and all nested loops.
2027*0b57cec5SDimitry Andric   if (SE) {
2028*0b57cec5SDimitry Andric     if (OuterExitL)
2029*0b57cec5SDimitry Andric       SE->forgetLoop(OuterExitL);
2030*0b57cec5SDimitry Andric     else
2031*0b57cec5SDimitry Andric       SE->forgetTopmostLoop(&L);
2032*0b57cec5SDimitry Andric   }
2033*0b57cec5SDimitry Andric 
2034*0b57cec5SDimitry Andric   // If the edge from this terminator to a successor dominates that successor,
2035*0b57cec5SDimitry Andric   // store a map from each block in its dominator subtree to it. This lets us
2036*0b57cec5SDimitry Andric   // tell when cloning for a particular successor if a block is dominated by
2037*0b57cec5SDimitry Andric   // some *other* successor with a single data structure. We use this to
2038*0b57cec5SDimitry Andric   // significantly reduce cloning.
2039*0b57cec5SDimitry Andric   SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
2040*0b57cec5SDimitry Andric   for (auto *SuccBB : llvm::concat<BasicBlock *const>(
2041*0b57cec5SDimitry Andric            makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
2042*0b57cec5SDimitry Andric     if (SuccBB->getUniquePredecessor() ||
2043*0b57cec5SDimitry Andric         llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2044*0b57cec5SDimitry Andric           return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
2045*0b57cec5SDimitry Andric         }))
2046*0b57cec5SDimitry Andric       visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
2047*0b57cec5SDimitry Andric         DominatingSucc[BB] = SuccBB;
2048*0b57cec5SDimitry Andric         return true;
2049*0b57cec5SDimitry Andric       });
2050*0b57cec5SDimitry Andric 
2051*0b57cec5SDimitry Andric   // Split the preheader, so that we know that there is a safe place to insert
2052*0b57cec5SDimitry Andric   // the conditional branch. We will change the preheader to have a conditional
2053*0b57cec5SDimitry Andric   // branch on LoopCond. The original preheader will become the split point
2054*0b57cec5SDimitry Andric   // between the unswitched versions, and we will have a new preheader for the
2055*0b57cec5SDimitry Andric   // original loop.
2056*0b57cec5SDimitry Andric   BasicBlock *SplitBB = L.getLoopPreheader();
2057*0b57cec5SDimitry Andric   BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
2058*0b57cec5SDimitry Andric 
2059*0b57cec5SDimitry Andric   // Keep track of the dominator tree updates needed.
2060*0b57cec5SDimitry Andric   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2061*0b57cec5SDimitry Andric 
2062*0b57cec5SDimitry Andric   // Clone the loop for each unswitched successor.
2063*0b57cec5SDimitry Andric   SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
2064*0b57cec5SDimitry Andric   VMaps.reserve(UnswitchedSuccBBs.size());
2065*0b57cec5SDimitry Andric   SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
2066*0b57cec5SDimitry Andric   for (auto *SuccBB : UnswitchedSuccBBs) {
2067*0b57cec5SDimitry Andric     VMaps.emplace_back(new ValueToValueMapTy());
2068*0b57cec5SDimitry Andric     ClonedPHs[SuccBB] = buildClonedLoopBlocks(
2069*0b57cec5SDimitry Andric         L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2070*0b57cec5SDimitry Andric         DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
2071*0b57cec5SDimitry Andric   }
2072*0b57cec5SDimitry Andric 
2073*0b57cec5SDimitry Andric   // The stitching of the branched code back together depends on whether we're
2074*0b57cec5SDimitry Andric   // doing full unswitching or not with the exception that we always want to
2075*0b57cec5SDimitry Andric   // nuke the initial terminator placed in the split block.
2076*0b57cec5SDimitry Andric   SplitBB->getTerminator()->eraseFromParent();
2077*0b57cec5SDimitry Andric   if (FullUnswitch) {
2078*0b57cec5SDimitry Andric     // Splice the terminator from the original loop and rewrite its
2079*0b57cec5SDimitry Andric     // successors.
2080*0b57cec5SDimitry Andric     SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2081*0b57cec5SDimitry Andric 
2082*0b57cec5SDimitry Andric     // Keep a clone of the terminator for MSSA updates.
2083*0b57cec5SDimitry Andric     Instruction *NewTI = TI.clone();
2084*0b57cec5SDimitry Andric     ParentBB->getInstList().push_back(NewTI);
2085*0b57cec5SDimitry Andric 
2086*0b57cec5SDimitry Andric     // First wire up the moved terminator to the preheaders.
2087*0b57cec5SDimitry Andric     if (BI) {
2088*0b57cec5SDimitry Andric       BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2089*0b57cec5SDimitry Andric       BI->setSuccessor(ClonedSucc, ClonedPH);
2090*0b57cec5SDimitry Andric       BI->setSuccessor(1 - ClonedSucc, LoopPH);
2091*0b57cec5SDimitry Andric       DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2092*0b57cec5SDimitry Andric     } else {
2093*0b57cec5SDimitry Andric       assert(SI && "Must either be a branch or switch!");
2094*0b57cec5SDimitry Andric 
2095*0b57cec5SDimitry Andric       // Walk the cases and directly update their successors.
2096*0b57cec5SDimitry Andric       assert(SI->getDefaultDest() == RetainedSuccBB &&
2097*0b57cec5SDimitry Andric              "Not retaining default successor!");
2098*0b57cec5SDimitry Andric       SI->setDefaultDest(LoopPH);
2099*0b57cec5SDimitry Andric       for (auto &Case : SI->cases())
2100*0b57cec5SDimitry Andric         if (Case.getCaseSuccessor() == RetainedSuccBB)
2101*0b57cec5SDimitry Andric           Case.setSuccessor(LoopPH);
2102*0b57cec5SDimitry Andric         else
2103*0b57cec5SDimitry Andric           Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2104*0b57cec5SDimitry Andric 
2105*0b57cec5SDimitry Andric       // We need to use the set to populate domtree updates as even when there
2106*0b57cec5SDimitry Andric       // are multiple cases pointing at the same successor we only want to
2107*0b57cec5SDimitry Andric       // remove and insert one edge in the domtree.
2108*0b57cec5SDimitry Andric       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2109*0b57cec5SDimitry Andric         DTUpdates.push_back(
2110*0b57cec5SDimitry Andric             {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2111*0b57cec5SDimitry Andric     }
2112*0b57cec5SDimitry Andric 
2113*0b57cec5SDimitry Andric     if (MSSAU) {
2114*0b57cec5SDimitry Andric       DT.applyUpdates(DTUpdates);
2115*0b57cec5SDimitry Andric       DTUpdates.clear();
2116*0b57cec5SDimitry Andric 
2117*0b57cec5SDimitry Andric       // Remove all but one edge to the retained block and all unswitched
2118*0b57cec5SDimitry Andric       // blocks. This is to avoid having duplicate entries in the cloned Phis,
2119*0b57cec5SDimitry Andric       // when we know we only keep a single edge for each case.
2120*0b57cec5SDimitry Andric       MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2121*0b57cec5SDimitry Andric       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2122*0b57cec5SDimitry Andric         MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2123*0b57cec5SDimitry Andric 
2124*0b57cec5SDimitry Andric       for (auto &VMap : VMaps)
2125*0b57cec5SDimitry Andric         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2126*0b57cec5SDimitry Andric                                    /*IgnoreIncomingWithNoClones=*/true);
2127*0b57cec5SDimitry Andric       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2128*0b57cec5SDimitry Andric 
2129*0b57cec5SDimitry Andric       // Remove all edges to unswitched blocks.
2130*0b57cec5SDimitry Andric       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2131*0b57cec5SDimitry Andric         MSSAU->removeEdge(ParentBB, SuccBB);
2132*0b57cec5SDimitry Andric     }
2133*0b57cec5SDimitry Andric 
2134*0b57cec5SDimitry Andric     // Now unhook the successor relationship as we'll be replacing
2135*0b57cec5SDimitry Andric     // the terminator with a direct branch. This is much simpler for branches
2136*0b57cec5SDimitry Andric     // than switches so we handle those first.
2137*0b57cec5SDimitry Andric     if (BI) {
2138*0b57cec5SDimitry Andric       // Remove the parent as a predecessor of the unswitched successor.
2139*0b57cec5SDimitry Andric       assert(UnswitchedSuccBBs.size() == 1 &&
2140*0b57cec5SDimitry Andric              "Only one possible unswitched block for a branch!");
2141*0b57cec5SDimitry Andric       BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2142*0b57cec5SDimitry Andric       UnswitchedSuccBB->removePredecessor(ParentBB,
2143*0b57cec5SDimitry Andric                                           /*KeepOneInputPHIs*/ true);
2144*0b57cec5SDimitry Andric       DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2145*0b57cec5SDimitry Andric     } else {
2146*0b57cec5SDimitry Andric       // Note that we actually want to remove the parent block as a predecessor
2147*0b57cec5SDimitry Andric       // of *every* case successor. The case successor is either unswitched,
2148*0b57cec5SDimitry Andric       // completely eliminating an edge from the parent to that successor, or it
2149*0b57cec5SDimitry Andric       // is a duplicate edge to the retained successor as the retained successor
2150*0b57cec5SDimitry Andric       // is always the default successor and as we'll replace this with a direct
2151*0b57cec5SDimitry Andric       // branch we no longer need the duplicate entries in the PHI nodes.
2152*0b57cec5SDimitry Andric       SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2153*0b57cec5SDimitry Andric       assert(NewSI->getDefaultDest() == RetainedSuccBB &&
2154*0b57cec5SDimitry Andric              "Not retaining default successor!");
2155*0b57cec5SDimitry Andric       for (auto &Case : NewSI->cases())
2156*0b57cec5SDimitry Andric         Case.getCaseSuccessor()->removePredecessor(
2157*0b57cec5SDimitry Andric             ParentBB,
2158*0b57cec5SDimitry Andric             /*KeepOneInputPHIs*/ true);
2159*0b57cec5SDimitry Andric 
2160*0b57cec5SDimitry Andric       // We need to use the set to populate domtree updates as even when there
2161*0b57cec5SDimitry Andric       // are multiple cases pointing at the same successor we only want to
2162*0b57cec5SDimitry Andric       // remove and insert one edge in the domtree.
2163*0b57cec5SDimitry Andric       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2164*0b57cec5SDimitry Andric         DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
2165*0b57cec5SDimitry Andric     }
2166*0b57cec5SDimitry Andric 
2167*0b57cec5SDimitry Andric     // After MSSAU update, remove the cloned terminator instruction NewTI.
2168*0b57cec5SDimitry Andric     ParentBB->getTerminator()->eraseFromParent();
2169*0b57cec5SDimitry Andric 
2170*0b57cec5SDimitry Andric     // Create a new unconditional branch to the continuing block (as opposed to
2171*0b57cec5SDimitry Andric     // the one cloned).
2172*0b57cec5SDimitry Andric     BranchInst::Create(RetainedSuccBB, ParentBB);
2173*0b57cec5SDimitry Andric   } else {
2174*0b57cec5SDimitry Andric     assert(BI && "Only branches have partial unswitching.");
2175*0b57cec5SDimitry Andric     assert(UnswitchedSuccBBs.size() == 1 &&
2176*0b57cec5SDimitry Andric            "Only one possible unswitched block for a branch!");
2177*0b57cec5SDimitry Andric     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2178*0b57cec5SDimitry Andric     // When doing a partial unswitch, we have to do a bit more work to build up
2179*0b57cec5SDimitry Andric     // the branch in the split block.
2180*0b57cec5SDimitry Andric     buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
2181*0b57cec5SDimitry Andric                                           *ClonedPH, *LoopPH);
2182*0b57cec5SDimitry Andric     DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
21838bcb0991SDimitry Andric 
21848bcb0991SDimitry Andric     if (MSSAU) {
21858bcb0991SDimitry Andric       DT.applyUpdates(DTUpdates);
21868bcb0991SDimitry Andric       DTUpdates.clear();
21878bcb0991SDimitry Andric 
21888bcb0991SDimitry Andric       // Perform MSSA cloning updates.
21898bcb0991SDimitry Andric       for (auto &VMap : VMaps)
21908bcb0991SDimitry Andric         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
21918bcb0991SDimitry Andric                                    /*IgnoreIncomingWithNoClones=*/true);
21928bcb0991SDimitry Andric       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
21938bcb0991SDimitry Andric     }
2194*0b57cec5SDimitry Andric   }
2195*0b57cec5SDimitry Andric 
2196*0b57cec5SDimitry Andric   // Apply the updates accumulated above to get an up-to-date dominator tree.
2197*0b57cec5SDimitry Andric   DT.applyUpdates(DTUpdates);
2198*0b57cec5SDimitry Andric 
2199*0b57cec5SDimitry Andric   // Now that we have an accurate dominator tree, first delete the dead cloned
2200*0b57cec5SDimitry Andric   // blocks so that we can accurately build any cloned loops. It is important to
2201*0b57cec5SDimitry Andric   // not delete the blocks from the original loop yet because we still want to
2202*0b57cec5SDimitry Andric   // reference the original loop to understand the cloned loop's structure.
2203*0b57cec5SDimitry Andric   deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
2204*0b57cec5SDimitry Andric 
2205*0b57cec5SDimitry Andric   // Build the cloned loop structure itself. This may be substantially
2206*0b57cec5SDimitry Andric   // different from the original structure due to the simplified CFG. This also
2207*0b57cec5SDimitry Andric   // handles inserting all the cloned blocks into the correct loops.
2208*0b57cec5SDimitry Andric   SmallVector<Loop *, 4> NonChildClonedLoops;
2209*0b57cec5SDimitry Andric   for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2210*0b57cec5SDimitry Andric     buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
2211*0b57cec5SDimitry Andric 
2212*0b57cec5SDimitry Andric   // Now that our cloned loops have been built, we can update the original loop.
2213*0b57cec5SDimitry Andric   // First we delete the dead blocks from it and then we rebuild the loop
2214*0b57cec5SDimitry Andric   // structure taking these deletions into account.
2215*0b57cec5SDimitry Andric   deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU);
2216*0b57cec5SDimitry Andric 
2217*0b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
2218*0b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
2219*0b57cec5SDimitry Andric 
2220*0b57cec5SDimitry Andric   SmallVector<Loop *, 4> HoistedLoops;
2221*0b57cec5SDimitry Andric   bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2222*0b57cec5SDimitry Andric 
2223*0b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
2224*0b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
2225*0b57cec5SDimitry Andric 
2226*0b57cec5SDimitry Andric   // This transformation has a high risk of corrupting the dominator tree, and
2227*0b57cec5SDimitry Andric   // the below steps to rebuild loop structures will result in hard to debug
2228*0b57cec5SDimitry Andric   // errors in that case so verify that the dominator tree is sane first.
2229*0b57cec5SDimitry Andric   // FIXME: Remove this when the bugs stop showing up and rely on existing
2230*0b57cec5SDimitry Andric   // verification steps.
2231*0b57cec5SDimitry Andric   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2232*0b57cec5SDimitry Andric 
2233*0b57cec5SDimitry Andric   if (BI) {
2234*0b57cec5SDimitry Andric     // If we unswitched a branch which collapses the condition to a known
2235*0b57cec5SDimitry Andric     // constant we want to replace all the uses of the invariants within both
2236*0b57cec5SDimitry Andric     // the original and cloned blocks. We do this here so that we can use the
2237*0b57cec5SDimitry Andric     // now updated dominator tree to identify which side the users are on.
2238*0b57cec5SDimitry Andric     assert(UnswitchedSuccBBs.size() == 1 &&
2239*0b57cec5SDimitry Andric            "Only one possible unswitched block for a branch!");
2240*0b57cec5SDimitry Andric     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2241*0b57cec5SDimitry Andric 
2242*0b57cec5SDimitry Andric     // When considering multiple partially-unswitched invariants
2243*0b57cec5SDimitry Andric     // we cant just go replace them with constants in both branches.
2244*0b57cec5SDimitry Andric     //
2245*0b57cec5SDimitry Andric     // For 'AND' we infer that true branch ("continue") means true
2246*0b57cec5SDimitry Andric     // for each invariant operand.
2247*0b57cec5SDimitry Andric     // For 'OR' we can infer that false branch ("continue") means false
2248*0b57cec5SDimitry Andric     // for each invariant operand.
2249*0b57cec5SDimitry Andric     // So it happens that for multiple-partial case we dont replace
2250*0b57cec5SDimitry Andric     // in the unswitched branch.
2251*0b57cec5SDimitry Andric     bool ReplaceUnswitched = FullUnswitch || (Invariants.size() == 1);
2252*0b57cec5SDimitry Andric 
2253*0b57cec5SDimitry Andric     ConstantInt *UnswitchedReplacement =
2254*0b57cec5SDimitry Andric         Direction ? ConstantInt::getTrue(BI->getContext())
2255*0b57cec5SDimitry Andric                   : ConstantInt::getFalse(BI->getContext());
2256*0b57cec5SDimitry Andric     ConstantInt *ContinueReplacement =
2257*0b57cec5SDimitry Andric         Direction ? ConstantInt::getFalse(BI->getContext())
2258*0b57cec5SDimitry Andric                   : ConstantInt::getTrue(BI->getContext());
2259*0b57cec5SDimitry Andric     for (Value *Invariant : Invariants)
2260*0b57cec5SDimitry Andric       for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2261*0b57cec5SDimitry Andric            UI != UE;) {
2262*0b57cec5SDimitry Andric         // Grab the use and walk past it so we can clobber it in the use list.
2263*0b57cec5SDimitry Andric         Use *U = &*UI++;
2264*0b57cec5SDimitry Andric         Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2265*0b57cec5SDimitry Andric         if (!UserI)
2266*0b57cec5SDimitry Andric           continue;
2267*0b57cec5SDimitry Andric 
2268*0b57cec5SDimitry Andric         // Replace it with the 'continue' side if in the main loop body, and the
2269*0b57cec5SDimitry Andric         // unswitched if in the cloned blocks.
2270*0b57cec5SDimitry Andric         if (DT.dominates(LoopPH, UserI->getParent()))
2271*0b57cec5SDimitry Andric           U->set(ContinueReplacement);
2272*0b57cec5SDimitry Andric         else if (ReplaceUnswitched &&
2273*0b57cec5SDimitry Andric                  DT.dominates(ClonedPH, UserI->getParent()))
2274*0b57cec5SDimitry Andric           U->set(UnswitchedReplacement);
2275*0b57cec5SDimitry Andric       }
2276*0b57cec5SDimitry Andric   }
2277*0b57cec5SDimitry Andric 
2278*0b57cec5SDimitry Andric   // We can change which blocks are exit blocks of all the cloned sibling
2279*0b57cec5SDimitry Andric   // loops, the current loop, and any parent loops which shared exit blocks
2280*0b57cec5SDimitry Andric   // with the current loop. As a consequence, we need to re-form LCSSA for
2281*0b57cec5SDimitry Andric   // them. But we shouldn't need to re-form LCSSA for any child loops.
2282*0b57cec5SDimitry Andric   // FIXME: This could be made more efficient by tracking which exit blocks are
2283*0b57cec5SDimitry Andric   // new, and focusing on them, but that isn't likely to be necessary.
2284*0b57cec5SDimitry Andric   //
2285*0b57cec5SDimitry Andric   // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2286*0b57cec5SDimitry Andric   // loop nest and update every loop that could have had its exits changed. We
2287*0b57cec5SDimitry Andric   // also need to cover any intervening loops. We add all of these loops to
2288*0b57cec5SDimitry Andric   // a list and sort them by loop depth to achieve this without updating
2289*0b57cec5SDimitry Andric   // unnecessary loops.
2290*0b57cec5SDimitry Andric   auto UpdateLoop = [&](Loop &UpdateL) {
2291*0b57cec5SDimitry Andric #ifndef NDEBUG
2292*0b57cec5SDimitry Andric     UpdateL.verifyLoop();
2293*0b57cec5SDimitry Andric     for (Loop *ChildL : UpdateL) {
2294*0b57cec5SDimitry Andric       ChildL->verifyLoop();
2295*0b57cec5SDimitry Andric       assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2296*0b57cec5SDimitry Andric              "Perturbed a child loop's LCSSA form!");
2297*0b57cec5SDimitry Andric     }
2298*0b57cec5SDimitry Andric #endif
2299*0b57cec5SDimitry Andric     // First build LCSSA for this loop so that we can preserve it when
2300*0b57cec5SDimitry Andric     // forming dedicated exits. We don't want to perturb some other loop's
2301*0b57cec5SDimitry Andric     // LCSSA while doing that CFG edit.
2302480093f4SDimitry Andric     formLCSSA(UpdateL, DT, &LI, SE);
2303*0b57cec5SDimitry Andric 
2304*0b57cec5SDimitry Andric     // For loops reached by this loop's original exit blocks we may
2305*0b57cec5SDimitry Andric     // introduced new, non-dedicated exits. At least try to re-form dedicated
2306*0b57cec5SDimitry Andric     // exits for these loops. This may fail if they couldn't have dedicated
2307*0b57cec5SDimitry Andric     // exits to start with.
2308*0b57cec5SDimitry Andric     formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
2309*0b57cec5SDimitry Andric   };
2310*0b57cec5SDimitry Andric 
2311*0b57cec5SDimitry Andric   // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2312*0b57cec5SDimitry Andric   // and we can do it in any order as they don't nest relative to each other.
2313*0b57cec5SDimitry Andric   //
2314*0b57cec5SDimitry Andric   // Also check if any of the loops we have updated have become top-level loops
2315*0b57cec5SDimitry Andric   // as that will necessitate widening the outer loop scope.
2316*0b57cec5SDimitry Andric   for (Loop *UpdatedL :
2317*0b57cec5SDimitry Andric        llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2318*0b57cec5SDimitry Andric     UpdateLoop(*UpdatedL);
2319*0b57cec5SDimitry Andric     if (!UpdatedL->getParentLoop())
2320*0b57cec5SDimitry Andric       OuterExitL = nullptr;
2321*0b57cec5SDimitry Andric   }
2322*0b57cec5SDimitry Andric   if (IsStillLoop) {
2323*0b57cec5SDimitry Andric     UpdateLoop(L);
2324*0b57cec5SDimitry Andric     if (!L.getParentLoop())
2325*0b57cec5SDimitry Andric       OuterExitL = nullptr;
2326*0b57cec5SDimitry Andric   }
2327*0b57cec5SDimitry Andric 
2328*0b57cec5SDimitry Andric   // If the original loop had exit blocks, walk up through the outer most loop
2329*0b57cec5SDimitry Andric   // of those exit blocks to update LCSSA and form updated dedicated exits.
2330*0b57cec5SDimitry Andric   if (OuterExitL != &L)
2331*0b57cec5SDimitry Andric     for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2332*0b57cec5SDimitry Andric          OuterL = OuterL->getParentLoop())
2333*0b57cec5SDimitry Andric       UpdateLoop(*OuterL);
2334*0b57cec5SDimitry Andric 
2335*0b57cec5SDimitry Andric #ifndef NDEBUG
2336*0b57cec5SDimitry Andric   // Verify the entire loop structure to catch any incorrect updates before we
2337*0b57cec5SDimitry Andric   // progress in the pass pipeline.
2338*0b57cec5SDimitry Andric   LI.verify(DT);
2339*0b57cec5SDimitry Andric #endif
2340*0b57cec5SDimitry Andric 
2341*0b57cec5SDimitry Andric   // Now that we've unswitched something, make callbacks to report the changes.
2342*0b57cec5SDimitry Andric   // For that we need to merge together the updated loops and the cloned loops
2343*0b57cec5SDimitry Andric   // and check whether the original loop survived.
2344*0b57cec5SDimitry Andric   SmallVector<Loop *, 4> SibLoops;
2345*0b57cec5SDimitry Andric   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2346*0b57cec5SDimitry Andric     if (UpdatedL->getParentLoop() == ParentL)
2347*0b57cec5SDimitry Andric       SibLoops.push_back(UpdatedL);
2348*0b57cec5SDimitry Andric   UnswitchCB(IsStillLoop, SibLoops);
2349*0b57cec5SDimitry Andric 
2350*0b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
2351*0b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
2352*0b57cec5SDimitry Andric 
2353*0b57cec5SDimitry Andric   if (BI)
2354*0b57cec5SDimitry Andric     ++NumBranches;
2355*0b57cec5SDimitry Andric   else
2356*0b57cec5SDimitry Andric     ++NumSwitches;
2357*0b57cec5SDimitry Andric }
2358*0b57cec5SDimitry Andric 
2359*0b57cec5SDimitry Andric /// Recursively compute the cost of a dominator subtree based on the per-block
2360*0b57cec5SDimitry Andric /// cost map provided.
2361*0b57cec5SDimitry Andric ///
2362*0b57cec5SDimitry Andric /// The recursive computation is memozied into the provided DT-indexed cost map
2363*0b57cec5SDimitry Andric /// to allow querying it for most nodes in the domtree without it becoming
2364*0b57cec5SDimitry Andric /// quadratic.
2365*0b57cec5SDimitry Andric static int
2366*0b57cec5SDimitry Andric computeDomSubtreeCost(DomTreeNode &N,
2367*0b57cec5SDimitry Andric                       const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2368*0b57cec5SDimitry Andric                       SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2369*0b57cec5SDimitry Andric   // Don't accumulate cost (or recurse through) blocks not in our block cost
2370*0b57cec5SDimitry Andric   // map and thus not part of the duplication cost being considered.
2371*0b57cec5SDimitry Andric   auto BBCostIt = BBCostMap.find(N.getBlock());
2372*0b57cec5SDimitry Andric   if (BBCostIt == BBCostMap.end())
2373*0b57cec5SDimitry Andric     return 0;
2374*0b57cec5SDimitry Andric 
2375*0b57cec5SDimitry Andric   // Lookup this node to see if we already computed its cost.
2376*0b57cec5SDimitry Andric   auto DTCostIt = DTCostMap.find(&N);
2377*0b57cec5SDimitry Andric   if (DTCostIt != DTCostMap.end())
2378*0b57cec5SDimitry Andric     return DTCostIt->second;
2379*0b57cec5SDimitry Andric 
2380*0b57cec5SDimitry Andric   // If not, we have to compute it. We can't use insert above and update
2381*0b57cec5SDimitry Andric   // because computing the cost may insert more things into the map.
2382*0b57cec5SDimitry Andric   int Cost = std::accumulate(
2383*0b57cec5SDimitry Andric       N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2384*0b57cec5SDimitry Andric         return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2385*0b57cec5SDimitry Andric       });
2386*0b57cec5SDimitry Andric   bool Inserted = DTCostMap.insert({&N, Cost}).second;
2387*0b57cec5SDimitry Andric   (void)Inserted;
2388*0b57cec5SDimitry Andric   assert(Inserted && "Should not insert a node while visiting children!");
2389*0b57cec5SDimitry Andric   return Cost;
2390*0b57cec5SDimitry Andric }
2391*0b57cec5SDimitry Andric 
2392*0b57cec5SDimitry Andric /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2393*0b57cec5SDimitry Andric /// making the following replacement:
2394*0b57cec5SDimitry Andric ///
2395*0b57cec5SDimitry Andric ///   --code before guard--
2396*0b57cec5SDimitry Andric ///   call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
2397*0b57cec5SDimitry Andric ///   --code after guard--
2398*0b57cec5SDimitry Andric ///
2399*0b57cec5SDimitry Andric /// into
2400*0b57cec5SDimitry Andric ///
2401*0b57cec5SDimitry Andric ///   --code before guard--
2402*0b57cec5SDimitry Andric ///   br i1 %cond, label %guarded, label %deopt
2403*0b57cec5SDimitry Andric ///
2404*0b57cec5SDimitry Andric /// guarded:
2405*0b57cec5SDimitry Andric ///   --code after guard--
2406*0b57cec5SDimitry Andric ///
2407*0b57cec5SDimitry Andric /// deopt:
2408*0b57cec5SDimitry Andric ///   call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2409*0b57cec5SDimitry Andric ///   unreachable
2410*0b57cec5SDimitry Andric ///
2411*0b57cec5SDimitry Andric /// It also makes all relevant DT and LI updates, so that all structures are in
2412*0b57cec5SDimitry Andric /// valid state after this transform.
2413*0b57cec5SDimitry Andric static BranchInst *
2414*0b57cec5SDimitry Andric turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2415*0b57cec5SDimitry Andric                     SmallVectorImpl<BasicBlock *> &ExitBlocks,
2416*0b57cec5SDimitry Andric                     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
2417*0b57cec5SDimitry Andric   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2418*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2419*0b57cec5SDimitry Andric   BasicBlock *CheckBB = GI->getParent();
2420*0b57cec5SDimitry Andric 
2421*0b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
2422*0b57cec5SDimitry Andric      MSSAU->getMemorySSA()->verifyMemorySSA();
2423*0b57cec5SDimitry Andric 
2424*0b57cec5SDimitry Andric   // Remove all CheckBB's successors from DomTree. A block can be seen among
2425*0b57cec5SDimitry Andric   // successors more than once, but for DomTree it should be added only once.
2426*0b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 4> Successors;
2427*0b57cec5SDimitry Andric   for (auto *Succ : successors(CheckBB))
2428*0b57cec5SDimitry Andric     if (Successors.insert(Succ).second)
2429*0b57cec5SDimitry Andric       DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2430*0b57cec5SDimitry Andric 
2431*0b57cec5SDimitry Andric   Instruction *DeoptBlockTerm =
2432*0b57cec5SDimitry Andric       SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2433*0b57cec5SDimitry Andric   BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2434*0b57cec5SDimitry Andric   // SplitBlockAndInsertIfThen inserts control flow that branches to
2435*0b57cec5SDimitry Andric   // DeoptBlockTerm if the condition is true.  We want the opposite.
2436*0b57cec5SDimitry Andric   CheckBI->swapSuccessors();
2437*0b57cec5SDimitry Andric 
2438*0b57cec5SDimitry Andric   BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2439*0b57cec5SDimitry Andric   GuardedBlock->setName("guarded");
2440*0b57cec5SDimitry Andric   CheckBI->getSuccessor(1)->setName("deopt");
2441*0b57cec5SDimitry Andric   BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
2442*0b57cec5SDimitry Andric 
2443*0b57cec5SDimitry Andric   // We now have a new exit block.
2444*0b57cec5SDimitry Andric   ExitBlocks.push_back(CheckBI->getSuccessor(1));
2445*0b57cec5SDimitry Andric 
2446*0b57cec5SDimitry Andric   if (MSSAU)
2447*0b57cec5SDimitry Andric     MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2448*0b57cec5SDimitry Andric 
2449*0b57cec5SDimitry Andric   GI->moveBefore(DeoptBlockTerm);
2450*0b57cec5SDimitry Andric   GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2451*0b57cec5SDimitry Andric 
2452*0b57cec5SDimitry Andric   // Add new successors of CheckBB into DomTree.
2453*0b57cec5SDimitry Andric   for (auto *Succ : successors(CheckBB))
2454*0b57cec5SDimitry Andric     DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2455*0b57cec5SDimitry Andric 
2456*0b57cec5SDimitry Andric   // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2457*0b57cec5SDimitry Andric   // successors.
2458*0b57cec5SDimitry Andric   for (auto *Succ : Successors)
2459*0b57cec5SDimitry Andric     DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2460*0b57cec5SDimitry Andric 
2461*0b57cec5SDimitry Andric   // Make proper changes to DT.
2462*0b57cec5SDimitry Andric   DT.applyUpdates(DTUpdates);
2463*0b57cec5SDimitry Andric   // Inform LI of a new loop block.
2464*0b57cec5SDimitry Andric   L.addBasicBlockToLoop(GuardedBlock, LI);
2465*0b57cec5SDimitry Andric 
2466*0b57cec5SDimitry Andric   if (MSSAU) {
2467*0b57cec5SDimitry Andric     MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2468480093f4SDimitry Andric     MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::BeforeTerminator);
2469*0b57cec5SDimitry Andric     if (VerifyMemorySSA)
2470*0b57cec5SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
2471*0b57cec5SDimitry Andric   }
2472*0b57cec5SDimitry Andric 
2473*0b57cec5SDimitry Andric   ++NumGuards;
2474*0b57cec5SDimitry Andric   return CheckBI;
2475*0b57cec5SDimitry Andric }
2476*0b57cec5SDimitry Andric 
2477*0b57cec5SDimitry Andric /// Cost multiplier is a way to limit potentially exponential behavior
2478*0b57cec5SDimitry Andric /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2479*0b57cec5SDimitry Andric /// candidates available. Also accounting for the number of "sibling" loops with
2480*0b57cec5SDimitry Andric /// the idea to account for previous unswitches that already happened on this
2481*0b57cec5SDimitry Andric /// cluster of loops. There was an attempt to keep this formula simple,
2482*0b57cec5SDimitry Andric /// just enough to limit the worst case behavior. Even if it is not that simple
2483*0b57cec5SDimitry Andric /// now it is still not an attempt to provide a detailed heuristic size
2484*0b57cec5SDimitry Andric /// prediction.
2485*0b57cec5SDimitry Andric ///
2486*0b57cec5SDimitry Andric /// TODO: Make a proper accounting of "explosion" effect for all kinds of
2487*0b57cec5SDimitry Andric /// unswitch candidates, making adequate predictions instead of wild guesses.
2488*0b57cec5SDimitry Andric /// That requires knowing not just the number of "remaining" candidates but
2489*0b57cec5SDimitry Andric /// also costs of unswitching for each of these candidates.
24905ffd83dbSDimitry Andric static int CalculateUnswitchCostMultiplier(
2491*0b57cec5SDimitry Andric     Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
2492*0b57cec5SDimitry Andric     ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
2493*0b57cec5SDimitry Andric         UnswitchCandidates) {
2494*0b57cec5SDimitry Andric 
2495*0b57cec5SDimitry Andric   // Guards and other exiting conditions do not contribute to exponential
2496*0b57cec5SDimitry Andric   // explosion as soon as they dominate the latch (otherwise there might be
2497*0b57cec5SDimitry Andric   // another path to the latch remaining that does not allow to eliminate the
2498*0b57cec5SDimitry Andric   // loop copy on unswitch).
2499*0b57cec5SDimitry Andric   BasicBlock *Latch = L.getLoopLatch();
2500*0b57cec5SDimitry Andric   BasicBlock *CondBlock = TI.getParent();
2501*0b57cec5SDimitry Andric   if (DT.dominates(CondBlock, Latch) &&
2502*0b57cec5SDimitry Andric       (isGuard(&TI) ||
2503*0b57cec5SDimitry Andric        llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
2504*0b57cec5SDimitry Andric          return L.contains(SuccBB);
2505*0b57cec5SDimitry Andric        }) <= 1)) {
2506*0b57cec5SDimitry Andric     NumCostMultiplierSkipped++;
2507*0b57cec5SDimitry Andric     return 1;
2508*0b57cec5SDimitry Andric   }
2509*0b57cec5SDimitry Andric 
2510*0b57cec5SDimitry Andric   auto *ParentL = L.getParentLoop();
2511*0b57cec5SDimitry Andric   int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2512*0b57cec5SDimitry Andric                                : std::distance(LI.begin(), LI.end()));
2513*0b57cec5SDimitry Andric   // Count amount of clones that all the candidates might cause during
2514*0b57cec5SDimitry Andric   // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2515*0b57cec5SDimitry Andric   int UnswitchedClones = 0;
2516*0b57cec5SDimitry Andric   for (auto Candidate : UnswitchCandidates) {
2517*0b57cec5SDimitry Andric     Instruction *CI = Candidate.first;
2518*0b57cec5SDimitry Andric     BasicBlock *CondBlock = CI->getParent();
2519*0b57cec5SDimitry Andric     bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2520*0b57cec5SDimitry Andric     if (isGuard(CI)) {
2521*0b57cec5SDimitry Andric       if (!SkipExitingSuccessors)
2522*0b57cec5SDimitry Andric         UnswitchedClones++;
2523*0b57cec5SDimitry Andric       continue;
2524*0b57cec5SDimitry Andric     }
2525*0b57cec5SDimitry Andric     int NonExitingSuccessors = llvm::count_if(
2526*0b57cec5SDimitry Andric         successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
2527*0b57cec5SDimitry Andric           return !SkipExitingSuccessors || L.contains(SuccBB);
2528*0b57cec5SDimitry Andric         });
2529*0b57cec5SDimitry Andric     UnswitchedClones += Log2_32(NonExitingSuccessors);
2530*0b57cec5SDimitry Andric   }
2531*0b57cec5SDimitry Andric 
2532*0b57cec5SDimitry Andric   // Ignore up to the "unscaled candidates" number of unswitch candidates
2533*0b57cec5SDimitry Andric   // when calculating the power-of-two scaling of the cost. The main idea
2534*0b57cec5SDimitry Andric   // with this control is to allow a small number of unswitches to happen
2535*0b57cec5SDimitry Andric   // and rely more on siblings multiplier (see below) when the number
2536*0b57cec5SDimitry Andric   // of candidates is small.
2537*0b57cec5SDimitry Andric   unsigned ClonesPower =
2538*0b57cec5SDimitry Andric       std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
2539*0b57cec5SDimitry Andric 
2540*0b57cec5SDimitry Andric   // Allowing top-level loops to spread a bit more than nested ones.
2541*0b57cec5SDimitry Andric   int SiblingsMultiplier =
2542*0b57cec5SDimitry Andric       std::max((ParentL ? SiblingsCount
2543*0b57cec5SDimitry Andric                         : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
2544*0b57cec5SDimitry Andric                1);
2545*0b57cec5SDimitry Andric   // Compute the cost multiplier in a way that won't overflow by saturating
2546*0b57cec5SDimitry Andric   // at an upper bound.
2547*0b57cec5SDimitry Andric   int CostMultiplier;
2548*0b57cec5SDimitry Andric   if (ClonesPower > Log2_32(UnswitchThreshold) ||
2549*0b57cec5SDimitry Andric       SiblingsMultiplier > UnswitchThreshold)
2550*0b57cec5SDimitry Andric     CostMultiplier = UnswitchThreshold;
2551*0b57cec5SDimitry Andric   else
2552*0b57cec5SDimitry Andric     CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2553*0b57cec5SDimitry Andric                               (int)UnswitchThreshold);
2554*0b57cec5SDimitry Andric 
2555*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Computed multiplier  " << CostMultiplier
2556*0b57cec5SDimitry Andric                     << " (siblings " << SiblingsMultiplier << " * clones "
2557*0b57cec5SDimitry Andric                     << (1 << ClonesPower) << ")"
2558*0b57cec5SDimitry Andric                     << " for unswitch candidate: " << TI << "\n");
2559*0b57cec5SDimitry Andric   return CostMultiplier;
2560*0b57cec5SDimitry Andric }
2561*0b57cec5SDimitry Andric 
2562*0b57cec5SDimitry Andric static bool
2563*0b57cec5SDimitry Andric unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2564*0b57cec5SDimitry Andric                       AssumptionCache &AC, TargetTransformInfo &TTI,
2565*0b57cec5SDimitry Andric                       function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2566*0b57cec5SDimitry Andric                       ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
2567*0b57cec5SDimitry Andric   // Collect all invariant conditions within this loop (as opposed to an inner
2568*0b57cec5SDimitry Andric   // loop which would be handled when visiting that inner loop).
2569*0b57cec5SDimitry Andric   SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
2570*0b57cec5SDimitry Andric       UnswitchCandidates;
2571*0b57cec5SDimitry Andric 
2572*0b57cec5SDimitry Andric   // Whether or not we should also collect guards in the loop.
2573*0b57cec5SDimitry Andric   bool CollectGuards = false;
2574*0b57cec5SDimitry Andric   if (UnswitchGuards) {
2575*0b57cec5SDimitry Andric     auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2576*0b57cec5SDimitry Andric         Intrinsic::getName(Intrinsic::experimental_guard));
2577*0b57cec5SDimitry Andric     if (GuardDecl && !GuardDecl->use_empty())
2578*0b57cec5SDimitry Andric       CollectGuards = true;
2579*0b57cec5SDimitry Andric   }
2580*0b57cec5SDimitry Andric 
2581*0b57cec5SDimitry Andric   for (auto *BB : L.blocks()) {
2582*0b57cec5SDimitry Andric     if (LI.getLoopFor(BB) != &L)
2583*0b57cec5SDimitry Andric       continue;
2584*0b57cec5SDimitry Andric 
2585*0b57cec5SDimitry Andric     if (CollectGuards)
2586*0b57cec5SDimitry Andric       for (auto &I : *BB)
2587*0b57cec5SDimitry Andric         if (isGuard(&I)) {
2588*0b57cec5SDimitry Andric           auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2589*0b57cec5SDimitry Andric           // TODO: Support AND, OR conditions and partial unswitching.
2590*0b57cec5SDimitry Andric           if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2591*0b57cec5SDimitry Andric             UnswitchCandidates.push_back({&I, {Cond}});
2592*0b57cec5SDimitry Andric         }
2593*0b57cec5SDimitry Andric 
2594*0b57cec5SDimitry Andric     if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2595*0b57cec5SDimitry Andric       // We can only consider fully loop-invariant switch conditions as we need
2596*0b57cec5SDimitry Andric       // to completely eliminate the switch after unswitching.
2597*0b57cec5SDimitry Andric       if (!isa<Constant>(SI->getCondition()) &&
2598*0b57cec5SDimitry Andric           L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor())
2599*0b57cec5SDimitry Andric         UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2600*0b57cec5SDimitry Andric       continue;
2601*0b57cec5SDimitry Andric     }
2602*0b57cec5SDimitry Andric 
2603*0b57cec5SDimitry Andric     auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2604*0b57cec5SDimitry Andric     if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2605*0b57cec5SDimitry Andric         BI->getSuccessor(0) == BI->getSuccessor(1))
2606*0b57cec5SDimitry Andric       continue;
2607*0b57cec5SDimitry Andric 
2608*0b57cec5SDimitry Andric     if (L.isLoopInvariant(BI->getCondition())) {
2609*0b57cec5SDimitry Andric       UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2610*0b57cec5SDimitry Andric       continue;
2611*0b57cec5SDimitry Andric     }
2612*0b57cec5SDimitry Andric 
2613*0b57cec5SDimitry Andric     Instruction &CondI = *cast<Instruction>(BI->getCondition());
2614*0b57cec5SDimitry Andric     if (CondI.getOpcode() != Instruction::And &&
2615*0b57cec5SDimitry Andric       CondI.getOpcode() != Instruction::Or)
2616*0b57cec5SDimitry Andric       continue;
2617*0b57cec5SDimitry Andric 
2618*0b57cec5SDimitry Andric     TinyPtrVector<Value *> Invariants =
2619*0b57cec5SDimitry Andric         collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2620*0b57cec5SDimitry Andric     if (Invariants.empty())
2621*0b57cec5SDimitry Andric       continue;
2622*0b57cec5SDimitry Andric 
2623*0b57cec5SDimitry Andric     UnswitchCandidates.push_back({BI, std::move(Invariants)});
2624*0b57cec5SDimitry Andric   }
2625*0b57cec5SDimitry Andric 
2626*0b57cec5SDimitry Andric   // If we didn't find any candidates, we're done.
2627*0b57cec5SDimitry Andric   if (UnswitchCandidates.empty())
2628*0b57cec5SDimitry Andric     return false;
2629*0b57cec5SDimitry Andric 
2630*0b57cec5SDimitry Andric   // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2631*0b57cec5SDimitry Andric   // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2632*0b57cec5SDimitry Andric   // irreducible control flow into reducible control flow and introduce new
2633*0b57cec5SDimitry Andric   // loops "out of thin air". If we ever discover important use cases for doing
2634*0b57cec5SDimitry Andric   // this, we can add support to loop unswitch, but it is a lot of complexity
2635*0b57cec5SDimitry Andric   // for what seems little or no real world benefit.
2636*0b57cec5SDimitry Andric   LoopBlocksRPO RPOT(&L);
2637*0b57cec5SDimitry Andric   RPOT.perform(&LI);
2638*0b57cec5SDimitry Andric   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
2639*0b57cec5SDimitry Andric     return false;
2640*0b57cec5SDimitry Andric 
2641*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 4> ExitBlocks;
2642*0b57cec5SDimitry Andric   L.getUniqueExitBlocks(ExitBlocks);
2643*0b57cec5SDimitry Andric 
2644*0b57cec5SDimitry Andric   // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
2645*0b57cec5SDimitry Andric   // don't know how to split those exit blocks.
2646*0b57cec5SDimitry Andric   // FIXME: We should teach SplitBlock to handle this and remove this
2647*0b57cec5SDimitry Andric   // restriction.
2648*0b57cec5SDimitry Andric   for (auto *ExitBB : ExitBlocks)
2649*0b57cec5SDimitry Andric     if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) {
2650*0b57cec5SDimitry Andric       dbgs() << "Cannot unswitch because of cleanuppad in exit block\n";
2651*0b57cec5SDimitry Andric       return false;
2652*0b57cec5SDimitry Andric     }
2653*0b57cec5SDimitry Andric 
2654*0b57cec5SDimitry Andric   LLVM_DEBUG(
2655*0b57cec5SDimitry Andric       dbgs() << "Considering " << UnswitchCandidates.size()
2656*0b57cec5SDimitry Andric              << " non-trivial loop invariant conditions for unswitching.\n");
2657*0b57cec5SDimitry Andric 
2658*0b57cec5SDimitry Andric   // Given that unswitching these terminators will require duplicating parts of
2659*0b57cec5SDimitry Andric   // the loop, so we need to be able to model that cost. Compute the ephemeral
2660*0b57cec5SDimitry Andric   // values and set up a data structure to hold per-BB costs. We cache each
2661*0b57cec5SDimitry Andric   // block's cost so that we don't recompute this when considering different
2662*0b57cec5SDimitry Andric   // subsets of the loop for duplication during unswitching.
2663*0b57cec5SDimitry Andric   SmallPtrSet<const Value *, 4> EphValues;
2664*0b57cec5SDimitry Andric   CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2665*0b57cec5SDimitry Andric   SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2666*0b57cec5SDimitry Andric 
2667*0b57cec5SDimitry Andric   // Compute the cost of each block, as well as the total loop cost. Also, bail
2668*0b57cec5SDimitry Andric   // out if we see instructions which are incompatible with loop unswitching
2669*0b57cec5SDimitry Andric   // (convergent, noduplicate, or cross-basic-block tokens).
2670*0b57cec5SDimitry Andric   // FIXME: We might be able to safely handle some of these in non-duplicated
2671*0b57cec5SDimitry Andric   // regions.
2672*0b57cec5SDimitry Andric   int LoopCost = 0;
2673*0b57cec5SDimitry Andric   for (auto *BB : L.blocks()) {
2674*0b57cec5SDimitry Andric     int Cost = 0;
2675*0b57cec5SDimitry Andric     for (auto &I : *BB) {
2676*0b57cec5SDimitry Andric       if (EphValues.count(&I))
2677*0b57cec5SDimitry Andric         continue;
2678*0b57cec5SDimitry Andric 
2679*0b57cec5SDimitry Andric       if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
2680*0b57cec5SDimitry Andric         return false;
26815ffd83dbSDimitry Andric       if (auto *CB = dyn_cast<CallBase>(&I))
26825ffd83dbSDimitry Andric         if (CB->isConvergent() || CB->cannotDuplicate())
2683*0b57cec5SDimitry Andric           return false;
2684*0b57cec5SDimitry Andric 
26855ffd83dbSDimitry Andric       Cost += TTI.getUserCost(&I, TargetTransformInfo::TCK_CodeSize);
2686*0b57cec5SDimitry Andric     }
2687*0b57cec5SDimitry Andric     assert(Cost >= 0 && "Must not have negative costs!");
2688*0b57cec5SDimitry Andric     LoopCost += Cost;
2689*0b57cec5SDimitry Andric     assert(LoopCost >= 0 && "Must not have negative loop costs!");
2690*0b57cec5SDimitry Andric     BBCostMap[BB] = Cost;
2691*0b57cec5SDimitry Andric   }
2692*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Total loop cost: " << LoopCost << "\n");
2693*0b57cec5SDimitry Andric 
2694*0b57cec5SDimitry Andric   // Now we find the best candidate by searching for the one with the following
2695*0b57cec5SDimitry Andric   // properties in order:
2696*0b57cec5SDimitry Andric   //
2697*0b57cec5SDimitry Andric   // 1) An unswitching cost below the threshold
2698*0b57cec5SDimitry Andric   // 2) The smallest number of duplicated unswitch candidates (to avoid
2699*0b57cec5SDimitry Andric   //    creating redundant subsequent unswitching)
2700*0b57cec5SDimitry Andric   // 3) The smallest cost after unswitching.
2701*0b57cec5SDimitry Andric   //
2702*0b57cec5SDimitry Andric   // We prioritize reducing fanout of unswitch candidates provided the cost
2703*0b57cec5SDimitry Andric   // remains below the threshold because this has a multiplicative effect.
2704*0b57cec5SDimitry Andric   //
2705*0b57cec5SDimitry Andric   // This requires memoizing each dominator subtree to avoid redundant work.
2706*0b57cec5SDimitry Andric   //
2707*0b57cec5SDimitry Andric   // FIXME: Need to actually do the number of candidates part above.
2708*0b57cec5SDimitry Andric   SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2709*0b57cec5SDimitry Andric   // Given a terminator which might be unswitched, computes the non-duplicated
2710*0b57cec5SDimitry Andric   // cost for that terminator.
2711*0b57cec5SDimitry Andric   auto ComputeUnswitchedCost = [&](Instruction &TI, bool FullUnswitch) {
2712*0b57cec5SDimitry Andric     BasicBlock &BB = *TI.getParent();
2713*0b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 4> Visited;
2714*0b57cec5SDimitry Andric 
2715*0b57cec5SDimitry Andric     int Cost = LoopCost;
2716*0b57cec5SDimitry Andric     for (BasicBlock *SuccBB : successors(&BB)) {
2717*0b57cec5SDimitry Andric       // Don't count successors more than once.
2718*0b57cec5SDimitry Andric       if (!Visited.insert(SuccBB).second)
2719*0b57cec5SDimitry Andric         continue;
2720*0b57cec5SDimitry Andric 
2721*0b57cec5SDimitry Andric       // If this is a partial unswitch candidate, then it must be a conditional
2722*0b57cec5SDimitry Andric       // branch with a condition of either `or` or `and`. In that case, one of
2723*0b57cec5SDimitry Andric       // the successors is necessarily duplicated, so don't even try to remove
2724*0b57cec5SDimitry Andric       // its cost.
2725*0b57cec5SDimitry Andric       if (!FullUnswitch) {
2726*0b57cec5SDimitry Andric         auto &BI = cast<BranchInst>(TI);
2727*0b57cec5SDimitry Andric         if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2728*0b57cec5SDimitry Andric             Instruction::And) {
2729*0b57cec5SDimitry Andric           if (SuccBB == BI.getSuccessor(1))
2730*0b57cec5SDimitry Andric             continue;
2731*0b57cec5SDimitry Andric         } else {
2732*0b57cec5SDimitry Andric           assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2733*0b57cec5SDimitry Andric                      Instruction::Or &&
2734*0b57cec5SDimitry Andric                  "Only `and` and `or` conditions can result in a partial "
2735*0b57cec5SDimitry Andric                  "unswitch!");
2736*0b57cec5SDimitry Andric           if (SuccBB == BI.getSuccessor(0))
2737*0b57cec5SDimitry Andric             continue;
2738*0b57cec5SDimitry Andric         }
2739*0b57cec5SDimitry Andric       }
2740*0b57cec5SDimitry Andric 
2741*0b57cec5SDimitry Andric       // This successor's domtree will not need to be duplicated after
2742*0b57cec5SDimitry Andric       // unswitching if the edge to the successor dominates it (and thus the
2743*0b57cec5SDimitry Andric       // entire tree). This essentially means there is no other path into this
2744*0b57cec5SDimitry Andric       // subtree and so it will end up live in only one clone of the loop.
2745*0b57cec5SDimitry Andric       if (SuccBB->getUniquePredecessor() ||
2746*0b57cec5SDimitry Andric           llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2747*0b57cec5SDimitry Andric             return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2748*0b57cec5SDimitry Andric           })) {
2749*0b57cec5SDimitry Andric         Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2750*0b57cec5SDimitry Andric         assert(Cost >= 0 &&
2751*0b57cec5SDimitry Andric                "Non-duplicated cost should never exceed total loop cost!");
2752*0b57cec5SDimitry Andric       }
2753*0b57cec5SDimitry Andric     }
2754*0b57cec5SDimitry Andric 
2755*0b57cec5SDimitry Andric     // Now scale the cost by the number of unique successors minus one. We
2756*0b57cec5SDimitry Andric     // subtract one because there is already at least one copy of the entire
2757*0b57cec5SDimitry Andric     // loop. This is computing the new cost of unswitching a condition.
2758*0b57cec5SDimitry Andric     // Note that guards always have 2 unique successors that are implicit and
2759*0b57cec5SDimitry Andric     // will be materialized if we decide to unswitch it.
2760*0b57cec5SDimitry Andric     int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2761*0b57cec5SDimitry Andric     assert(SuccessorsCount > 1 &&
2762*0b57cec5SDimitry Andric            "Cannot unswitch a condition without multiple distinct successors!");
2763*0b57cec5SDimitry Andric     return Cost * (SuccessorsCount - 1);
2764*0b57cec5SDimitry Andric   };
2765*0b57cec5SDimitry Andric   Instruction *BestUnswitchTI = nullptr;
27668bcb0991SDimitry Andric   int BestUnswitchCost = 0;
2767*0b57cec5SDimitry Andric   ArrayRef<Value *> BestUnswitchInvariants;
2768*0b57cec5SDimitry Andric   for (auto &TerminatorAndInvariants : UnswitchCandidates) {
2769*0b57cec5SDimitry Andric     Instruction &TI = *TerminatorAndInvariants.first;
2770*0b57cec5SDimitry Andric     ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2771*0b57cec5SDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(&TI);
2772*0b57cec5SDimitry Andric     int CandidateCost = ComputeUnswitchedCost(
2773*0b57cec5SDimitry Andric         TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2774*0b57cec5SDimitry Andric                                      Invariants[0] == BI->getCondition()));
2775*0b57cec5SDimitry Andric     // Calculate cost multiplier which is a tool to limit potentially
2776*0b57cec5SDimitry Andric     // exponential behavior of loop-unswitch.
2777*0b57cec5SDimitry Andric     if (EnableUnswitchCostMultiplier) {
2778*0b57cec5SDimitry Andric       int CostMultiplier =
27795ffd83dbSDimitry Andric           CalculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
2780*0b57cec5SDimitry Andric       assert(
2781*0b57cec5SDimitry Andric           (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
2782*0b57cec5SDimitry Andric           "cost multiplier needs to be in the range of 1..UnswitchThreshold");
2783*0b57cec5SDimitry Andric       CandidateCost *= CostMultiplier;
2784*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
2785*0b57cec5SDimitry Andric                         << " (multiplier: " << CostMultiplier << ")"
2786*0b57cec5SDimitry Andric                         << " for unswitch candidate: " << TI << "\n");
2787*0b57cec5SDimitry Andric     } else {
2788*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
2789*0b57cec5SDimitry Andric                         << " for unswitch candidate: " << TI << "\n");
2790*0b57cec5SDimitry Andric     }
2791*0b57cec5SDimitry Andric 
2792*0b57cec5SDimitry Andric     if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2793*0b57cec5SDimitry Andric       BestUnswitchTI = &TI;
2794*0b57cec5SDimitry Andric       BestUnswitchCost = CandidateCost;
2795*0b57cec5SDimitry Andric       BestUnswitchInvariants = Invariants;
2796*0b57cec5SDimitry Andric     }
2797*0b57cec5SDimitry Andric   }
27988bcb0991SDimitry Andric   assert(BestUnswitchTI && "Failed to find loop unswitch candidate");
2799*0b57cec5SDimitry Andric 
2800*0b57cec5SDimitry Andric   if (BestUnswitchCost >= UnswitchThreshold) {
2801*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2802*0b57cec5SDimitry Andric                       << BestUnswitchCost << "\n");
2803*0b57cec5SDimitry Andric     return false;
2804*0b57cec5SDimitry Andric   }
2805*0b57cec5SDimitry Andric 
2806*0b57cec5SDimitry Andric   // If the best candidate is a guard, turn it into a branch.
2807*0b57cec5SDimitry Andric   if (isGuard(BestUnswitchTI))
2808*0b57cec5SDimitry Andric     BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
2809*0b57cec5SDimitry Andric                                          ExitBlocks, DT, LI, MSSAU);
2810*0b57cec5SDimitry Andric 
2811*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Unswitching non-trivial (cost = "
2812*0b57cec5SDimitry Andric                     << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2813*0b57cec5SDimitry Andric                     << "\n");
2814*0b57cec5SDimitry Andric   unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
2815*0b57cec5SDimitry Andric                                ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU);
2816*0b57cec5SDimitry Andric   return true;
2817*0b57cec5SDimitry Andric }
2818*0b57cec5SDimitry Andric 
2819*0b57cec5SDimitry Andric /// Unswitch control flow predicated on loop invariant conditions.
2820*0b57cec5SDimitry Andric ///
2821*0b57cec5SDimitry Andric /// This first hoists all branches or switches which are trivial (IE, do not
2822*0b57cec5SDimitry Andric /// require duplicating any part of the loop) out of the loop body. It then
2823*0b57cec5SDimitry Andric /// looks at other loop invariant control flows and tries to unswitch those as
2824*0b57cec5SDimitry Andric /// well by cloning the loop if the result is small enough.
2825*0b57cec5SDimitry Andric ///
2826*0b57cec5SDimitry Andric /// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2827*0b57cec5SDimitry Andric /// updated based on the unswitch.
2828*0b57cec5SDimitry Andric /// The `MSSA` analysis is also updated if valid (i.e. its use is enabled).
2829*0b57cec5SDimitry Andric ///
2830*0b57cec5SDimitry Andric /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2831*0b57cec5SDimitry Andric /// true, we will attempt to do non-trivial unswitching as well as trivial
2832*0b57cec5SDimitry Andric /// unswitching.
2833*0b57cec5SDimitry Andric ///
2834*0b57cec5SDimitry Andric /// The `UnswitchCB` callback provided will be run after unswitching is
2835*0b57cec5SDimitry Andric /// complete, with the first parameter set to `true` if the provided loop
2836*0b57cec5SDimitry Andric /// remains a loop, and a list of new sibling loops created.
2837*0b57cec5SDimitry Andric ///
2838*0b57cec5SDimitry Andric /// If `SE` is non-null, we will update that analysis based on the unswitching
2839*0b57cec5SDimitry Andric /// done.
2840*0b57cec5SDimitry Andric static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2841*0b57cec5SDimitry Andric                          AssumptionCache &AC, TargetTransformInfo &TTI,
2842*0b57cec5SDimitry Andric                          bool NonTrivial,
2843*0b57cec5SDimitry Andric                          function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2844*0b57cec5SDimitry Andric                          ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
2845*0b57cec5SDimitry Andric   assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2846*0b57cec5SDimitry Andric          "Loops must be in LCSSA form before unswitching.");
2847*0b57cec5SDimitry Andric   bool Changed = false;
2848*0b57cec5SDimitry Andric 
2849*0b57cec5SDimitry Andric   // Must be in loop simplified form: we need a preheader and dedicated exits.
2850*0b57cec5SDimitry Andric   if (!L.isLoopSimplifyForm())
2851*0b57cec5SDimitry Andric     return false;
2852*0b57cec5SDimitry Andric 
2853*0b57cec5SDimitry Andric   // Try trivial unswitch first before loop over other basic blocks in the loop.
2854*0b57cec5SDimitry Andric   if (unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
2855*0b57cec5SDimitry Andric     // If we unswitched successfully we will want to clean up the loop before
2856*0b57cec5SDimitry Andric     // processing it further so just mark it as unswitched and return.
2857*0b57cec5SDimitry Andric     UnswitchCB(/*CurrentLoopValid*/ true, {});
2858*0b57cec5SDimitry Andric     return true;
2859*0b57cec5SDimitry Andric   }
2860*0b57cec5SDimitry Andric 
2861*0b57cec5SDimitry Andric   // If we're not doing non-trivial unswitching, we're done. We both accept
2862*0b57cec5SDimitry Andric   // a parameter but also check a local flag that can be used for testing
2863*0b57cec5SDimitry Andric   // a debugging.
2864*0b57cec5SDimitry Andric   if (!NonTrivial && !EnableNonTrivialUnswitch)
2865*0b57cec5SDimitry Andric     return false;
2866*0b57cec5SDimitry Andric 
2867*0b57cec5SDimitry Andric   // For non-trivial unswitching, because it often creates new loops, we rely on
2868*0b57cec5SDimitry Andric   // the pass manager to iterate on the loops rather than trying to immediately
2869*0b57cec5SDimitry Andric   // reach a fixed point. There is no substantial advantage to iterating
2870*0b57cec5SDimitry Andric   // internally, and if any of the new loops are simplified enough to contain
2871*0b57cec5SDimitry Andric   // trivial unswitching we want to prefer those.
2872*0b57cec5SDimitry Andric 
2873*0b57cec5SDimitry Andric   // Try to unswitch the best invariant condition. We prefer this full unswitch to
2874*0b57cec5SDimitry Andric   // a partial unswitch when possible below the threshold.
2875*0b57cec5SDimitry Andric   if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE, MSSAU))
2876*0b57cec5SDimitry Andric     return true;
2877*0b57cec5SDimitry Andric 
2878*0b57cec5SDimitry Andric   // No other opportunities to unswitch.
2879*0b57cec5SDimitry Andric   return Changed;
2880*0b57cec5SDimitry Andric }
2881*0b57cec5SDimitry Andric 
2882*0b57cec5SDimitry Andric PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2883*0b57cec5SDimitry Andric                                               LoopStandardAnalysisResults &AR,
2884*0b57cec5SDimitry Andric                                               LPMUpdater &U) {
2885*0b57cec5SDimitry Andric   Function &F = *L.getHeader()->getParent();
2886*0b57cec5SDimitry Andric   (void)F;
2887*0b57cec5SDimitry Andric 
2888*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2889*0b57cec5SDimitry Andric                     << "\n");
2890*0b57cec5SDimitry Andric 
2891*0b57cec5SDimitry Andric   // Save the current loop name in a variable so that we can report it even
2892*0b57cec5SDimitry Andric   // after it has been deleted.
28935ffd83dbSDimitry Andric   std::string LoopName = std::string(L.getName());
2894*0b57cec5SDimitry Andric 
2895*0b57cec5SDimitry Andric   auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2896*0b57cec5SDimitry Andric                                         ArrayRef<Loop *> NewLoops) {
2897*0b57cec5SDimitry Andric     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2898*0b57cec5SDimitry Andric     if (!NewLoops.empty())
2899*0b57cec5SDimitry Andric       U.addSiblingLoops(NewLoops);
2900*0b57cec5SDimitry Andric 
2901*0b57cec5SDimitry Andric     // If the current loop remains valid, we should revisit it to catch any
2902*0b57cec5SDimitry Andric     // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2903*0b57cec5SDimitry Andric     if (CurrentLoopValid)
2904*0b57cec5SDimitry Andric       U.revisitCurrentLoop();
2905*0b57cec5SDimitry Andric     else
2906*0b57cec5SDimitry Andric       U.markLoopAsDeleted(L, LoopName);
2907*0b57cec5SDimitry Andric   };
2908*0b57cec5SDimitry Andric 
2909*0b57cec5SDimitry Andric   Optional<MemorySSAUpdater> MSSAU;
2910*0b57cec5SDimitry Andric   if (AR.MSSA) {
2911*0b57cec5SDimitry Andric     MSSAU = MemorySSAUpdater(AR.MSSA);
2912*0b57cec5SDimitry Andric     if (VerifyMemorySSA)
2913*0b57cec5SDimitry Andric       AR.MSSA->verifyMemorySSA();
2914*0b57cec5SDimitry Andric   }
2915*0b57cec5SDimitry Andric   if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
2916*0b57cec5SDimitry Andric                     &AR.SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
2917*0b57cec5SDimitry Andric     return PreservedAnalyses::all();
2918*0b57cec5SDimitry Andric 
2919*0b57cec5SDimitry Andric   if (AR.MSSA && VerifyMemorySSA)
2920*0b57cec5SDimitry Andric     AR.MSSA->verifyMemorySSA();
2921*0b57cec5SDimitry Andric 
2922*0b57cec5SDimitry Andric   // Historically this pass has had issues with the dominator tree so verify it
2923*0b57cec5SDimitry Andric   // in asserts builds.
2924*0b57cec5SDimitry Andric   assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
2925*0b57cec5SDimitry Andric 
2926*0b57cec5SDimitry Andric   auto PA = getLoopPassPreservedAnalyses();
29278bcb0991SDimitry Andric   if (AR.MSSA)
2928*0b57cec5SDimitry Andric     PA.preserve<MemorySSAAnalysis>();
2929*0b57cec5SDimitry Andric   return PA;
2930*0b57cec5SDimitry Andric }
2931*0b57cec5SDimitry Andric 
2932*0b57cec5SDimitry Andric namespace {
2933*0b57cec5SDimitry Andric 
2934*0b57cec5SDimitry Andric class SimpleLoopUnswitchLegacyPass : public LoopPass {
2935*0b57cec5SDimitry Andric   bool NonTrivial;
2936*0b57cec5SDimitry Andric 
2937*0b57cec5SDimitry Andric public:
2938*0b57cec5SDimitry Andric   static char ID; // Pass ID, replacement for typeid
2939*0b57cec5SDimitry Andric 
2940*0b57cec5SDimitry Andric   explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2941*0b57cec5SDimitry Andric       : LoopPass(ID), NonTrivial(NonTrivial) {
2942*0b57cec5SDimitry Andric     initializeSimpleLoopUnswitchLegacyPassPass(
2943*0b57cec5SDimitry Andric         *PassRegistry::getPassRegistry());
2944*0b57cec5SDimitry Andric   }
2945*0b57cec5SDimitry Andric 
2946*0b57cec5SDimitry Andric   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2947*0b57cec5SDimitry Andric 
2948*0b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
2949*0b57cec5SDimitry Andric     AU.addRequired<AssumptionCacheTracker>();
2950*0b57cec5SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
2951*0b57cec5SDimitry Andric     if (EnableMSSALoopDependency) {
2952*0b57cec5SDimitry Andric       AU.addRequired<MemorySSAWrapperPass>();
2953*0b57cec5SDimitry Andric       AU.addPreserved<MemorySSAWrapperPass>();
2954*0b57cec5SDimitry Andric     }
2955*0b57cec5SDimitry Andric     getLoopAnalysisUsage(AU);
2956*0b57cec5SDimitry Andric   }
2957*0b57cec5SDimitry Andric };
2958*0b57cec5SDimitry Andric 
2959*0b57cec5SDimitry Andric } // end anonymous namespace
2960*0b57cec5SDimitry Andric 
2961*0b57cec5SDimitry Andric bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2962*0b57cec5SDimitry Andric   if (skipLoop(L))
2963*0b57cec5SDimitry Andric     return false;
2964*0b57cec5SDimitry Andric 
2965*0b57cec5SDimitry Andric   Function &F = *L->getHeader()->getParent();
2966*0b57cec5SDimitry Andric 
2967*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2968*0b57cec5SDimitry Andric                     << "\n");
2969*0b57cec5SDimitry Andric 
2970*0b57cec5SDimitry Andric   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2971*0b57cec5SDimitry Andric   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2972*0b57cec5SDimitry Andric   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2973*0b57cec5SDimitry Andric   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2974*0b57cec5SDimitry Andric   MemorySSA *MSSA = nullptr;
2975*0b57cec5SDimitry Andric   Optional<MemorySSAUpdater> MSSAU;
2976*0b57cec5SDimitry Andric   if (EnableMSSALoopDependency) {
2977*0b57cec5SDimitry Andric     MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
2978*0b57cec5SDimitry Andric     MSSAU = MemorySSAUpdater(MSSA);
2979*0b57cec5SDimitry Andric   }
2980*0b57cec5SDimitry Andric 
2981*0b57cec5SDimitry Andric   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2982*0b57cec5SDimitry Andric   auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2983*0b57cec5SDimitry Andric 
2984*0b57cec5SDimitry Andric   auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2985*0b57cec5SDimitry Andric                                ArrayRef<Loop *> NewLoops) {
2986*0b57cec5SDimitry Andric     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2987*0b57cec5SDimitry Andric     for (auto *NewL : NewLoops)
2988*0b57cec5SDimitry Andric       LPM.addLoop(*NewL);
2989*0b57cec5SDimitry Andric 
2990*0b57cec5SDimitry Andric     // If the current loop remains valid, re-add it to the queue. This is
2991*0b57cec5SDimitry Andric     // a little wasteful as we'll finish processing the current loop as well,
2992*0b57cec5SDimitry Andric     // but it is the best we can do in the old PM.
2993*0b57cec5SDimitry Andric     if (CurrentLoopValid)
2994*0b57cec5SDimitry Andric       LPM.addLoop(*L);
2995*0b57cec5SDimitry Andric     else
2996*0b57cec5SDimitry Andric       LPM.markLoopAsDeleted(*L);
2997*0b57cec5SDimitry Andric   };
2998*0b57cec5SDimitry Andric 
2999*0b57cec5SDimitry Andric   if (MSSA && VerifyMemorySSA)
3000*0b57cec5SDimitry Andric     MSSA->verifyMemorySSA();
3001*0b57cec5SDimitry Andric 
3002*0b57cec5SDimitry Andric   bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE,
3003*0b57cec5SDimitry Andric                               MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
3004*0b57cec5SDimitry Andric 
3005*0b57cec5SDimitry Andric   if (MSSA && VerifyMemorySSA)
3006*0b57cec5SDimitry Andric     MSSA->verifyMemorySSA();
3007*0b57cec5SDimitry Andric 
3008*0b57cec5SDimitry Andric   // Historically this pass has had issues with the dominator tree so verify it
3009*0b57cec5SDimitry Andric   // in asserts builds.
3010*0b57cec5SDimitry Andric   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
3011*0b57cec5SDimitry Andric 
3012*0b57cec5SDimitry Andric   return Changed;
3013*0b57cec5SDimitry Andric }
3014*0b57cec5SDimitry Andric 
3015*0b57cec5SDimitry Andric char SimpleLoopUnswitchLegacyPass::ID = 0;
3016*0b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
3017*0b57cec5SDimitry Andric                       "Simple unswitch loops", false, false)
3018*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3019*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3020*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
3021*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopPass)
3022*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3023*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
3024*0b57cec5SDimitry Andric INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
3025*0b57cec5SDimitry Andric                     "Simple unswitch loops", false, false)
3026*0b57cec5SDimitry Andric 
3027*0b57cec5SDimitry Andric Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
3028*0b57cec5SDimitry Andric   return new SimpleLoopUnswitchLegacyPass(NonTrivial);
3029*0b57cec5SDimitry Andric }
3030