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