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