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