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