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