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