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/MemorySSA.h" 28 #include "llvm/Analysis/MemorySSAUpdater.h" 29 #include "llvm/Analysis/MustExecute.h" 30 #include "llvm/Analysis/ProfileSummaryInfo.h" 31 #include "llvm/Analysis/ScalarEvolution.h" 32 #include "llvm/Analysis/TargetTransformInfo.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/IR/BasicBlock.h" 35 #include "llvm/IR/Constant.h" 36 #include "llvm/IR/Constants.h" 37 #include "llvm/IR/Dominators.h" 38 #include "llvm/IR/Function.h" 39 #include "llvm/IR/IRBuilder.h" 40 #include "llvm/IR/InstrTypes.h" 41 #include "llvm/IR/Instruction.h" 42 #include "llvm/IR/Instructions.h" 43 #include "llvm/IR/IntrinsicInst.h" 44 #include "llvm/IR/Module.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/Support/Casting.h" 50 #include "llvm/Support/CommandLine.h" 51 #include "llvm/Support/Debug.h" 52 #include "llvm/Support/ErrorHandling.h" 53 #include "llvm/Support/GenericDomTree.h" 54 #include "llvm/Support/InstructionCost.h" 55 #include "llvm/Support/raw_ostream.h" 56 #include "llvm/Transforms/Scalar/LoopPassManager.h" 57 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 58 #include "llvm/Transforms/Utils/Cloning.h" 59 #include "llvm/Transforms/Utils/Local.h" 60 #include "llvm/Transforms/Utils/LoopUtils.h" 61 #include "llvm/Transforms/Utils/ValueMapper.h" 62 #include <algorithm> 63 #include <cassert> 64 #include <iterator> 65 #include <numeric> 66 #include <optional> 67 #include <utility> 68 69 #define DEBUG_TYPE "simple-loop-unswitch" 70 71 using namespace llvm; 72 using namespace llvm::PatternMatch; 73 74 STATISTIC(NumBranches, "Number of branches unswitched"); 75 STATISTIC(NumSwitches, "Number of switches unswitched"); 76 STATISTIC(NumSelects, "Number of selects turned into branches for unswitching"); 77 STATISTIC(NumGuards, "Number of guards turned into branches for unswitching"); 78 STATISTIC(NumTrivial, "Number of unswitches that are trivial"); 79 STATISTIC( 80 NumCostMultiplierSkipped, 81 "Number of unswitch candidates that had their cost multiplier skipped"); 82 STATISTIC(NumInvariantConditionsInjected, 83 "Number of invariant conditions injected and unswitched"); 84 85 static cl::opt<bool> EnableNonTrivialUnswitch( 86 "enable-nontrivial-unswitch", cl::init(false), cl::Hidden, 87 cl::desc("Forcibly enables non-trivial loop unswitching rather than " 88 "following the configuration passed into the pass.")); 89 90 static cl::opt<int> 91 UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden, 92 cl::desc("The cost threshold for unswitching a loop.")); 93 94 static cl::opt<bool> EnableUnswitchCostMultiplier( 95 "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden, 96 cl::desc("Enable unswitch cost multiplier that prohibits exponential " 97 "explosion in nontrivial unswitch.")); 98 static cl::opt<int> UnswitchSiblingsToplevelDiv( 99 "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden, 100 cl::desc("Toplevel siblings divisor for cost multiplier.")); 101 static cl::opt<int> UnswitchNumInitialUnscaledCandidates( 102 "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden, 103 cl::desc("Number of unswitch candidates that are ignored when calculating " 104 "cost multiplier.")); 105 static cl::opt<bool> UnswitchGuards( 106 "simple-loop-unswitch-guards", cl::init(true), cl::Hidden, 107 cl::desc("If enabled, simple loop unswitching will also consider " 108 "llvm.experimental.guard intrinsics as unswitch candidates.")); 109 static cl::opt<bool> DropNonTrivialImplicitNullChecks( 110 "simple-loop-unswitch-drop-non-trivial-implicit-null-checks", 111 cl::init(false), cl::Hidden, 112 cl::desc("If enabled, drop make.implicit metadata in unswitched implicit " 113 "null checks to save time analyzing if we can keep it.")); 114 static cl::opt<unsigned> 115 MSSAThreshold("simple-loop-unswitch-memoryssa-threshold", 116 cl::desc("Max number of memory uses to explore during " 117 "partial unswitching analysis"), 118 cl::init(100), cl::Hidden); 119 static cl::opt<bool> FreezeLoopUnswitchCond( 120 "freeze-loop-unswitch-cond", cl::init(true), cl::Hidden, 121 cl::desc("If enabled, the freeze instruction will be added to condition " 122 "of loop unswitch to prevent miscompilation.")); 123 124 static cl::opt<bool> InjectInvariantConditions( 125 "simple-loop-unswitch-inject-invariant-conditions", cl::Hidden, 126 cl::desc("Whether we should inject new invariants and unswitch them to " 127 "eliminate some existing (non-invariant) conditions."), 128 cl::init(true)); 129 130 static cl::opt<unsigned> InjectInvariantConditionHotnesThreshold( 131 "simple-loop-unswitch-inject-invariant-condition-hotness-threshold", 132 cl::Hidden, cl::desc("Only try to inject loop invariant conditions and " 133 "unswitch on them to eliminate branches that are " 134 "not-taken 1/<this option> times or less."), 135 cl::init(16)); 136 137 AnalysisKey ShouldRunExtraSimpleLoopUnswitch::Key; 138 namespace { 139 struct CompareDesc { 140 BranchInst *Term; 141 Value *Invariant; 142 BasicBlock *InLoopSucc; 143 144 CompareDesc(BranchInst *Term, Value *Invariant, BasicBlock *InLoopSucc) 145 : Term(Term), Invariant(Invariant), InLoopSucc(InLoopSucc) {} 146 }; 147 148 struct InjectedInvariant { 149 ICmpInst::Predicate Pred; 150 Value *LHS; 151 Value *RHS; 152 BasicBlock *InLoopSucc; 153 154 InjectedInvariant(ICmpInst::Predicate Pred, Value *LHS, Value *RHS, 155 BasicBlock *InLoopSucc) 156 : Pred(Pred), LHS(LHS), RHS(RHS), InLoopSucc(InLoopSucc) {} 157 }; 158 159 struct NonTrivialUnswitchCandidate { 160 Instruction *TI = nullptr; 161 TinyPtrVector<Value *> Invariants; 162 std::optional<InstructionCost> Cost; 163 std::optional<InjectedInvariant> PendingInjection; 164 NonTrivialUnswitchCandidate( 165 Instruction *TI, ArrayRef<Value *> Invariants, 166 std::optional<InstructionCost> Cost = std::nullopt, 167 std::optional<InjectedInvariant> PendingInjection = std::nullopt) 168 : TI(TI), Invariants(Invariants), Cost(Cost), 169 PendingInjection(PendingInjection) {}; 170 171 bool hasPendingInjection() const { return PendingInjection.has_value(); } 172 }; 173 } // end anonymous namespace. 174 175 // Helper to skip (select x, true, false), which matches both a logical AND and 176 // OR and can confuse code that tries to determine if \p Cond is either a 177 // logical AND or OR but not both. 178 static Value *skipTrivialSelect(Value *Cond) { 179 Value *CondNext; 180 while (match(Cond, m_Select(m_Value(CondNext), m_One(), m_Zero()))) 181 Cond = CondNext; 182 return Cond; 183 } 184 185 /// Collect all of the loop invariant input values transitively used by the 186 /// homogeneous instruction graph from a given root. 187 /// 188 /// This essentially walks from a root recursively through loop variant operands 189 /// which have perform the same logical operation (AND or OR) and finds all 190 /// inputs which are loop invariant. For some operations these can be 191 /// re-associated and unswitched out of the loop entirely. 192 static TinyPtrVector<Value *> 193 collectHomogenousInstGraphLoopInvariants(const Loop &L, Instruction &Root, 194 const LoopInfo &LI) { 195 assert(!L.isLoopInvariant(&Root) && 196 "Only need to walk the graph if root itself is not invariant."); 197 TinyPtrVector<Value *> Invariants; 198 199 bool IsRootAnd = match(&Root, m_LogicalAnd()); 200 bool IsRootOr = match(&Root, m_LogicalOr()); 201 202 // Build a worklist and recurse through operators collecting invariants. 203 SmallVector<Instruction *, 4> Worklist; 204 SmallPtrSet<Instruction *, 8> Visited; 205 Worklist.push_back(&Root); 206 Visited.insert(&Root); 207 do { 208 Instruction &I = *Worklist.pop_back_val(); 209 for (Value *OpV : I.operand_values()) { 210 // Skip constants as unswitching isn't interesting for them. 211 if (isa<Constant>(OpV)) 212 continue; 213 214 // Add it to our result if loop invariant. 215 if (L.isLoopInvariant(OpV)) { 216 Invariants.push_back(OpV); 217 continue; 218 } 219 220 // If not an instruction with the same opcode, nothing we can do. 221 Instruction *OpI = dyn_cast<Instruction>(skipTrivialSelect(OpV)); 222 223 if (OpI && ((IsRootAnd && match(OpI, m_LogicalAnd())) || 224 (IsRootOr && match(OpI, m_LogicalOr())))) { 225 // Visit this operand. 226 if (Visited.insert(OpI).second) 227 Worklist.push_back(OpI); 228 } 229 } 230 } while (!Worklist.empty()); 231 232 return Invariants; 233 } 234 235 static void replaceLoopInvariantUses(const Loop &L, Value *Invariant, 236 Constant &Replacement) { 237 assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?"); 238 239 // Replace uses of LIC in the loop with the given constant. 240 // We use make_early_inc_range as set invalidates the iterator. 241 for (Use &U : llvm::make_early_inc_range(Invariant->uses())) { 242 Instruction *UserI = dyn_cast<Instruction>(U.getUser()); 243 244 // Replace this use within the loop body. 245 if (UserI && L.contains(UserI)) 246 U.set(&Replacement); 247 } 248 } 249 250 /// Check that all the LCSSA PHI nodes in the loop exit block have trivial 251 /// incoming values along this edge. 252 static bool areLoopExitPHIsLoopInvariant(const Loop &L, 253 const BasicBlock &ExitingBB, 254 const BasicBlock &ExitBB) { 255 for (const Instruction &I : ExitBB) { 256 auto *PN = dyn_cast<PHINode>(&I); 257 if (!PN) 258 // No more PHIs to check. 259 return true; 260 261 // If the incoming value for this edge isn't loop invariant the unswitch 262 // won't be trivial. 263 if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB))) 264 return false; 265 } 266 llvm_unreachable("Basic blocks should never be empty!"); 267 } 268 269 /// Copy a set of loop invariant values \p ToDuplicate and insert them at the 270 /// end of \p BB and conditionally branch on the copied condition. We only 271 /// branch on a single value. 272 static void buildPartialUnswitchConditionalBranch( 273 BasicBlock &BB, ArrayRef<Value *> Invariants, bool Direction, 274 BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, bool InsertFreeze, 275 const Instruction *I, AssumptionCache *AC, const DominatorTree &DT) { 276 IRBuilder<> IRB(&BB); 277 278 SmallVector<Value *> FrozenInvariants; 279 for (Value *Inv : Invariants) { 280 if (InsertFreeze && !isGuaranteedNotToBeUndefOrPoison(Inv, AC, I, &DT)) 281 Inv = IRB.CreateFreeze(Inv, Inv->getName() + ".fr"); 282 FrozenInvariants.push_back(Inv); 283 } 284 285 Value *Cond = Direction ? IRB.CreateOr(FrozenInvariants) 286 : IRB.CreateAnd(FrozenInvariants); 287 IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc, 288 Direction ? &NormalSucc : &UnswitchedSucc); 289 } 290 291 /// Copy a set of loop invariant values, and conditionally branch on them. 292 static void buildPartialInvariantUnswitchConditionalBranch( 293 BasicBlock &BB, ArrayRef<Value *> ToDuplicate, bool Direction, 294 BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, Loop &L, 295 MemorySSAUpdater *MSSAU) { 296 ValueToValueMapTy VMap; 297 for (auto *Val : reverse(ToDuplicate)) { 298 Instruction *Inst = cast<Instruction>(Val); 299 Instruction *NewInst = Inst->clone(); 300 NewInst->insertInto(&BB, BB.end()); 301 RemapInstruction(NewInst, VMap, 302 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 303 VMap[Val] = NewInst; 304 305 if (!MSSAU) 306 continue; 307 308 MemorySSA *MSSA = MSSAU->getMemorySSA(); 309 if (auto *MemUse = 310 dyn_cast_or_null<MemoryUse>(MSSA->getMemoryAccess(Inst))) { 311 auto *DefiningAccess = MemUse->getDefiningAccess(); 312 // Get the first defining access before the loop. 313 while (L.contains(DefiningAccess->getBlock())) { 314 // If the defining access is a MemoryPhi, get the incoming 315 // value for the pre-header as defining access. 316 if (auto *MemPhi = dyn_cast<MemoryPhi>(DefiningAccess)) 317 DefiningAccess = 318 MemPhi->getIncomingValueForBlock(L.getLoopPreheader()); 319 else 320 DefiningAccess = cast<MemoryDef>(DefiningAccess)->getDefiningAccess(); 321 } 322 MSSAU->createMemoryAccessInBB(NewInst, DefiningAccess, 323 NewInst->getParent(), 324 MemorySSA::BeforeTerminator); 325 } 326 } 327 328 IRBuilder<> IRB(&BB); 329 Value *Cond = VMap[ToDuplicate[0]]; 330 IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc, 331 Direction ? &NormalSucc : &UnswitchedSucc); 332 } 333 334 /// Rewrite the PHI nodes in an unswitched loop exit basic block. 335 /// 336 /// Requires that the loop exit and unswitched basic block are the same, and 337 /// that the exiting block was a unique predecessor of that block. Rewrites the 338 /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial 339 /// PHI nodes from the old preheader that now contains the unswitched 340 /// terminator. 341 static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB, 342 BasicBlock &OldExitingBB, 343 BasicBlock &OldPH) { 344 for (PHINode &PN : UnswitchedBB.phis()) { 345 // When the loop exit is directly unswitched we just need to update the 346 // incoming basic block. We loop to handle weird cases with repeated 347 // incoming blocks, but expect to typically only have one operand here. 348 for (auto i : seq<int>(0, PN.getNumOperands())) { 349 assert(PN.getIncomingBlock(i) == &OldExitingBB && 350 "Found incoming block different from unique predecessor!"); 351 PN.setIncomingBlock(i, &OldPH); 352 } 353 } 354 } 355 356 /// Rewrite the PHI nodes in the loop exit basic block and the split off 357 /// unswitched block. 358 /// 359 /// Because the exit block remains an exit from the loop, this rewrites the 360 /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI 361 /// nodes into the unswitched basic block to select between the value in the 362 /// old preheader and the loop exit. 363 static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB, 364 BasicBlock &UnswitchedBB, 365 BasicBlock &OldExitingBB, 366 BasicBlock &OldPH, 367 bool FullUnswitch) { 368 assert(&ExitBB != &UnswitchedBB && 369 "Must have different loop exit and unswitched blocks!"); 370 BasicBlock::iterator InsertPt = UnswitchedBB.begin(); 371 for (PHINode &PN : ExitBB.phis()) { 372 auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2, 373 PN.getName() + ".split"); 374 NewPN->insertBefore(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->begin(), &DT, &LI, MSSAU, "", false); 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 BI.moveBefore(*OldPH, OldPH->end()); 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->begin(), &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->begin(), &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->begin(), &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 BasicBlock::iterator InsertPt = MergeBB->getFirstInsertionPt(); 1249 1250 auto *MergePN = 1251 PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi"); 1252 MergePN->insertBefore(InsertPt); 1253 MergePN->setDebugLoc(InsertPt->getDebugLoc()); 1254 I.replaceAllUsesWith(MergePN); 1255 MergePN->addIncoming(&I, ExitBB); 1256 MergePN->addIncoming(&ClonedI, ClonedExitBB); 1257 } 1258 } 1259 1260 // Rewrite the instructions in the cloned blocks to refer to the instructions 1261 // in the cloned blocks. We have to do this as a second pass so that we have 1262 // everything available. Also, we have inserted new instructions which may 1263 // include assume intrinsics, so we update the assumption cache while 1264 // processing this. 1265 Module *M = ClonedPH->getParent()->getParent(); 1266 for (auto *ClonedBB : NewBlocks) 1267 for (Instruction &I : *ClonedBB) { 1268 RemapDbgRecordRange(M, I.getDbgRecordRange(), VMap, 1269 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 1270 RemapInstruction(&I, VMap, 1271 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 1272 if (auto *II = dyn_cast<AssumeInst>(&I)) 1273 AC.registerAssumption(II); 1274 } 1275 1276 // Update any PHI nodes in the cloned successors of the skipped blocks to not 1277 // have spurious incoming values. 1278 for (auto *LoopBB : L.blocks()) 1279 if (SkipBlock(LoopBB)) 1280 for (auto *SuccBB : successors(LoopBB)) 1281 if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB))) 1282 for (PHINode &PN : ClonedSuccBB->phis()) 1283 PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false); 1284 1285 // Remove the cloned parent as a predecessor of any successor we ended up 1286 // cloning other than the unswitched one. 1287 auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB)); 1288 for (auto *SuccBB : successors(ParentBB)) { 1289 if (SuccBB == UnswitchedSuccBB) 1290 continue; 1291 1292 auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)); 1293 if (!ClonedSuccBB) 1294 continue; 1295 1296 ClonedSuccBB->removePredecessor(ClonedParentBB, 1297 /*KeepOneInputPHIs*/ true); 1298 } 1299 1300 // Replace the cloned branch with an unconditional branch to the cloned 1301 // unswitched successor. 1302 auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB)); 1303 Instruction *ClonedTerminator = ClonedParentBB->getTerminator(); 1304 // Trivial Simplification. If Terminator is a conditional branch and 1305 // condition becomes dead - erase it. 1306 Value *ClonedConditionToErase = nullptr; 1307 if (auto *BI = dyn_cast<BranchInst>(ClonedTerminator)) 1308 ClonedConditionToErase = BI->getCondition(); 1309 else if (auto *SI = dyn_cast<SwitchInst>(ClonedTerminator)) 1310 ClonedConditionToErase = SI->getCondition(); 1311 1312 Instruction *BI = BranchInst::Create(ClonedSuccBB, ClonedParentBB); 1313 BI->setDebugLoc(ClonedTerminator->getDebugLoc()); 1314 ClonedTerminator->eraseFromParent(); 1315 1316 if (ClonedConditionToErase) 1317 RecursivelyDeleteTriviallyDeadInstructions(ClonedConditionToErase, nullptr, 1318 MSSAU); 1319 1320 // If there are duplicate entries in the PHI nodes because of multiple edges 1321 // to the unswitched successor, we need to nuke all but one as we replaced it 1322 // with a direct branch. 1323 for (PHINode &PN : ClonedSuccBB->phis()) { 1324 bool Found = false; 1325 // Loop over the incoming operands backwards so we can easily delete as we 1326 // go without invalidating the index. 1327 for (int i = PN.getNumOperands() - 1; i >= 0; --i) { 1328 if (PN.getIncomingBlock(i) != ClonedParentBB) 1329 continue; 1330 if (!Found) { 1331 Found = true; 1332 continue; 1333 } 1334 PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false); 1335 } 1336 } 1337 1338 // Record the domtree updates for the new blocks. 1339 SmallPtrSet<BasicBlock *, 4> SuccSet; 1340 for (auto *ClonedBB : NewBlocks) { 1341 for (auto *SuccBB : successors(ClonedBB)) 1342 if (SuccSet.insert(SuccBB).second) 1343 DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB}); 1344 SuccSet.clear(); 1345 } 1346 1347 return ClonedPH; 1348 } 1349 1350 /// Recursively clone the specified loop and all of its children. 1351 /// 1352 /// The target parent loop for the clone should be provided, or can be null if 1353 /// the clone is a top-level loop. While cloning, all the blocks are mapped 1354 /// with the provided value map. The entire original loop must be present in 1355 /// the value map. The cloned loop is returned. 1356 static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL, 1357 const ValueToValueMapTy &VMap, LoopInfo &LI) { 1358 auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) { 1359 assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!"); 1360 ClonedL.reserveBlocks(OrigL.getNumBlocks()); 1361 for (auto *BB : OrigL.blocks()) { 1362 auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB)); 1363 ClonedL.addBlockEntry(ClonedBB); 1364 if (LI.getLoopFor(BB) == &OrigL) 1365 LI.changeLoopFor(ClonedBB, &ClonedL); 1366 } 1367 }; 1368 1369 // We specially handle the first loop because it may get cloned into 1370 // a different parent and because we most commonly are cloning leaf loops. 1371 Loop *ClonedRootL = LI.AllocateLoop(); 1372 if (RootParentL) 1373 RootParentL->addChildLoop(ClonedRootL); 1374 else 1375 LI.addTopLevelLoop(ClonedRootL); 1376 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL); 1377 1378 if (OrigRootL.isInnermost()) 1379 return ClonedRootL; 1380 1381 // If we have a nest, we can quickly clone the entire loop nest using an 1382 // iterative approach because it is a tree. We keep the cloned parent in the 1383 // data structure to avoid repeatedly querying through a map to find it. 1384 SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone; 1385 // Build up the loops to clone in reverse order as we'll clone them from the 1386 // back. 1387 for (Loop *ChildL : llvm::reverse(OrigRootL)) 1388 LoopsToClone.push_back({ClonedRootL, ChildL}); 1389 do { 1390 Loop *ClonedParentL, *L; 1391 std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val(); 1392 Loop *ClonedL = LI.AllocateLoop(); 1393 ClonedParentL->addChildLoop(ClonedL); 1394 AddClonedBlocksToLoop(*L, *ClonedL); 1395 for (Loop *ChildL : llvm::reverse(*L)) 1396 LoopsToClone.push_back({ClonedL, ChildL}); 1397 } while (!LoopsToClone.empty()); 1398 1399 return ClonedRootL; 1400 } 1401 1402 /// Build the cloned loops of an original loop from unswitching. 1403 /// 1404 /// Because unswitching simplifies the CFG of the loop, this isn't a trivial 1405 /// operation. We need to re-verify that there even is a loop (as the backedge 1406 /// may not have been cloned), and even if there are remaining backedges the 1407 /// backedge set may be different. However, we know that each child loop is 1408 /// undisturbed, we only need to find where to place each child loop within 1409 /// either any parent loop or within a cloned version of the original loop. 1410 /// 1411 /// Because child loops may end up cloned outside of any cloned version of the 1412 /// original loop, multiple cloned sibling loops may be created. All of them 1413 /// are returned so that the newly introduced loop nest roots can be 1414 /// identified. 1415 static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks, 1416 const ValueToValueMapTy &VMap, LoopInfo &LI, 1417 SmallVectorImpl<Loop *> &NonChildClonedLoops) { 1418 Loop *ClonedL = nullptr; 1419 1420 auto *OrigPH = OrigL.getLoopPreheader(); 1421 auto *OrigHeader = OrigL.getHeader(); 1422 1423 auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH)); 1424 auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader)); 1425 1426 // We need to know the loops of the cloned exit blocks to even compute the 1427 // accurate parent loop. If we only clone exits to some parent of the 1428 // original parent, we want to clone into that outer loop. We also keep track 1429 // of the loops that our cloned exit blocks participate in. 1430 Loop *ParentL = nullptr; 1431 SmallVector<BasicBlock *, 4> ClonedExitsInLoops; 1432 SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap; 1433 ClonedExitsInLoops.reserve(ExitBlocks.size()); 1434 for (auto *ExitBB : ExitBlocks) 1435 if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB))) 1436 if (Loop *ExitL = LI.getLoopFor(ExitBB)) { 1437 ExitLoopMap[ClonedExitBB] = ExitL; 1438 ClonedExitsInLoops.push_back(ClonedExitBB); 1439 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL))) 1440 ParentL = ExitL; 1441 } 1442 assert((!ParentL || ParentL == OrigL.getParentLoop() || 1443 ParentL->contains(OrigL.getParentLoop())) && 1444 "The computed parent loop should always contain (or be) the parent of " 1445 "the original loop."); 1446 1447 // We build the set of blocks dominated by the cloned header from the set of 1448 // cloned blocks out of the original loop. While not all of these will 1449 // necessarily be in the cloned loop, it is enough to establish that they 1450 // aren't in unreachable cycles, etc. 1451 SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks; 1452 for (auto *BB : OrigL.blocks()) 1453 if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB))) 1454 ClonedLoopBlocks.insert(ClonedBB); 1455 1456 // Rebuild the set of blocks that will end up in the cloned loop. We may have 1457 // skipped cloning some region of this loop which can in turn skip some of 1458 // the backedges so we have to rebuild the blocks in the loop based on the 1459 // backedges that remain after cloning. 1460 SmallVector<BasicBlock *, 16> Worklist; 1461 SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop; 1462 for (auto *Pred : predecessors(ClonedHeader)) { 1463 // The only possible non-loop header predecessor is the preheader because 1464 // we know we cloned the loop in simplified form. 1465 if (Pred == ClonedPH) 1466 continue; 1467 1468 // Because the loop was in simplified form, the only non-loop predecessor 1469 // should be the preheader. 1470 assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop " 1471 "header other than the preheader " 1472 "that is not part of the loop!"); 1473 1474 // Insert this block into the loop set and on the first visit (and if it 1475 // isn't the header we're currently walking) put it into the worklist to 1476 // recurse through. 1477 if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader) 1478 Worklist.push_back(Pred); 1479 } 1480 1481 // If we had any backedges then there *is* a cloned loop. Put the header into 1482 // the loop set and then walk the worklist backwards to find all the blocks 1483 // that remain within the loop after cloning. 1484 if (!BlocksInClonedLoop.empty()) { 1485 BlocksInClonedLoop.insert(ClonedHeader); 1486 1487 while (!Worklist.empty()) { 1488 BasicBlock *BB = Worklist.pop_back_val(); 1489 assert(BlocksInClonedLoop.count(BB) && 1490 "Didn't put block into the loop set!"); 1491 1492 // Insert any predecessors that are in the possible set into the cloned 1493 // set, and if the insert is successful, add them to the worklist. Note 1494 // that we filter on the blocks that are definitely reachable via the 1495 // backedge to the loop header so we may prune out dead code within the 1496 // cloned loop. 1497 for (auto *Pred : predecessors(BB)) 1498 if (ClonedLoopBlocks.count(Pred) && 1499 BlocksInClonedLoop.insert(Pred).second) 1500 Worklist.push_back(Pred); 1501 } 1502 1503 ClonedL = LI.AllocateLoop(); 1504 if (ParentL) { 1505 ParentL->addBasicBlockToLoop(ClonedPH, LI); 1506 ParentL->addChildLoop(ClonedL); 1507 } else { 1508 LI.addTopLevelLoop(ClonedL); 1509 } 1510 NonChildClonedLoops.push_back(ClonedL); 1511 1512 ClonedL->reserveBlocks(BlocksInClonedLoop.size()); 1513 // We don't want to just add the cloned loop blocks based on how we 1514 // discovered them. The original order of blocks was carefully built in 1515 // a way that doesn't rely on predecessor ordering. Rather than re-invent 1516 // that logic, we just re-walk the original blocks (and those of the child 1517 // loops) and filter them as we add them into the cloned loop. 1518 for (auto *BB : OrigL.blocks()) { 1519 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)); 1520 if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB)) 1521 continue; 1522 1523 // Directly add the blocks that are only in this loop. 1524 if (LI.getLoopFor(BB) == &OrigL) { 1525 ClonedL->addBasicBlockToLoop(ClonedBB, LI); 1526 continue; 1527 } 1528 1529 // We want to manually add it to this loop and parents. 1530 // Registering it with LoopInfo will happen when we clone the top 1531 // loop for this block. 1532 for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop()) 1533 PL->addBlockEntry(ClonedBB); 1534 } 1535 1536 // Now add each child loop whose header remains within the cloned loop. All 1537 // of the blocks within the loop must satisfy the same constraints as the 1538 // header so once we pass the header checks we can just clone the entire 1539 // child loop nest. 1540 for (Loop *ChildL : OrigL) { 1541 auto *ClonedChildHeader = 1542 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader())); 1543 if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader)) 1544 continue; 1545 1546 #ifndef NDEBUG 1547 // We should never have a cloned child loop header but fail to have 1548 // all of the blocks for that child loop. 1549 for (auto *ChildLoopBB : ChildL->blocks()) 1550 assert(BlocksInClonedLoop.count( 1551 cast<BasicBlock>(VMap.lookup(ChildLoopBB))) && 1552 "Child cloned loop has a header within the cloned outer " 1553 "loop but not all of its blocks!"); 1554 #endif 1555 1556 cloneLoopNest(*ChildL, ClonedL, VMap, LI); 1557 } 1558 } 1559 1560 // Now that we've handled all the components of the original loop that were 1561 // cloned into a new loop, we still need to handle anything from the original 1562 // loop that wasn't in a cloned loop. 1563 1564 // Figure out what blocks are left to place within any loop nest containing 1565 // the unswitched loop. If we never formed a loop, the cloned PH is one of 1566 // them. 1567 SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet; 1568 if (BlocksInClonedLoop.empty()) 1569 UnloopedBlockSet.insert(ClonedPH); 1570 for (auto *ClonedBB : ClonedLoopBlocks) 1571 if (!BlocksInClonedLoop.count(ClonedBB)) 1572 UnloopedBlockSet.insert(ClonedBB); 1573 1574 // Copy the cloned exits and sort them in ascending loop depth, we'll work 1575 // backwards across these to process them inside out. The order shouldn't 1576 // matter as we're just trying to build up the map from inside-out; we use 1577 // the map in a more stably ordered way below. 1578 auto OrderedClonedExitsInLoops = ClonedExitsInLoops; 1579 llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) { 1580 return ExitLoopMap.lookup(LHS)->getLoopDepth() < 1581 ExitLoopMap.lookup(RHS)->getLoopDepth(); 1582 }); 1583 1584 // Populate the existing ExitLoopMap with everything reachable from each 1585 // exit, starting from the inner most exit. 1586 while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) { 1587 assert(Worklist.empty() && "Didn't clear worklist!"); 1588 1589 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val(); 1590 Loop *ExitL = ExitLoopMap.lookup(ExitBB); 1591 1592 // Walk the CFG back until we hit the cloned PH adding everything reachable 1593 // and in the unlooped set to this exit block's loop. 1594 Worklist.push_back(ExitBB); 1595 do { 1596 BasicBlock *BB = Worklist.pop_back_val(); 1597 // We can stop recursing at the cloned preheader (if we get there). 1598 if (BB == ClonedPH) 1599 continue; 1600 1601 for (BasicBlock *PredBB : predecessors(BB)) { 1602 // If this pred has already been moved to our set or is part of some 1603 // (inner) loop, no update needed. 1604 if (!UnloopedBlockSet.erase(PredBB)) { 1605 assert( 1606 (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) && 1607 "Predecessor not mapped to a loop!"); 1608 continue; 1609 } 1610 1611 // We just insert into the loop set here. We'll add these blocks to the 1612 // exit loop after we build up the set in an order that doesn't rely on 1613 // predecessor order (which in turn relies on use list order). 1614 bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second; 1615 (void)Inserted; 1616 assert(Inserted && "Should only visit an unlooped block once!"); 1617 1618 // And recurse through to its predecessors. 1619 Worklist.push_back(PredBB); 1620 } 1621 } while (!Worklist.empty()); 1622 } 1623 1624 // Now that the ExitLoopMap gives as mapping for all the non-looping cloned 1625 // blocks to their outer loops, walk the cloned blocks and the cloned exits 1626 // in their original order adding them to the correct loop. 1627 1628 // We need a stable insertion order. We use the order of the original loop 1629 // order and map into the correct parent loop. 1630 for (auto *BB : llvm::concat<BasicBlock *const>( 1631 ArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops)) 1632 if (Loop *OuterL = ExitLoopMap.lookup(BB)) 1633 OuterL->addBasicBlockToLoop(BB, LI); 1634 1635 #ifndef NDEBUG 1636 for (auto &BBAndL : ExitLoopMap) { 1637 auto *BB = BBAndL.first; 1638 auto *OuterL = BBAndL.second; 1639 assert(LI.getLoopFor(BB) == OuterL && 1640 "Failed to put all blocks into outer loops!"); 1641 } 1642 #endif 1643 1644 // Now that all the blocks are placed into the correct containing loop in the 1645 // absence of child loops, find all the potentially cloned child loops and 1646 // clone them into whatever outer loop we placed their header into. 1647 for (Loop *ChildL : OrigL) { 1648 auto *ClonedChildHeader = 1649 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader())); 1650 if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader)) 1651 continue; 1652 1653 #ifndef NDEBUG 1654 for (auto *ChildLoopBB : ChildL->blocks()) 1655 assert(VMap.count(ChildLoopBB) && 1656 "Cloned a child loop header but not all of that loops blocks!"); 1657 #endif 1658 1659 NonChildClonedLoops.push_back(cloneLoopNest( 1660 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI)); 1661 } 1662 } 1663 1664 static void 1665 deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks, 1666 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, 1667 DominatorTree &DT, MemorySSAUpdater *MSSAU) { 1668 // Find all the dead clones, and remove them from their successors. 1669 SmallVector<BasicBlock *, 16> DeadBlocks; 1670 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks)) 1671 for (const auto &VMap : VMaps) 1672 if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB))) 1673 if (!DT.isReachableFromEntry(ClonedBB)) { 1674 for (BasicBlock *SuccBB : successors(ClonedBB)) 1675 SuccBB->removePredecessor(ClonedBB); 1676 DeadBlocks.push_back(ClonedBB); 1677 } 1678 1679 // Remove all MemorySSA in the dead blocks 1680 if (MSSAU) { 1681 SmallSetVector<BasicBlock *, 8> DeadBlockSet(DeadBlocks.begin(), 1682 DeadBlocks.end()); 1683 MSSAU->removeBlocks(DeadBlockSet); 1684 } 1685 1686 // Drop any remaining references to break cycles. 1687 for (BasicBlock *BB : DeadBlocks) 1688 BB->dropAllReferences(); 1689 // Erase them from the IR. 1690 for (BasicBlock *BB : DeadBlocks) 1691 BB->eraseFromParent(); 1692 } 1693 1694 static void deleteDeadBlocksFromLoop(Loop &L, 1695 SmallVectorImpl<BasicBlock *> &ExitBlocks, 1696 DominatorTree &DT, LoopInfo &LI, 1697 MemorySSAUpdater *MSSAU, 1698 ScalarEvolution *SE, 1699 LPMUpdater &LoopUpdater) { 1700 // Find all the dead blocks tied to this loop, and remove them from their 1701 // successors. 1702 SmallSetVector<BasicBlock *, 8> DeadBlockSet; 1703 1704 // Start with loop/exit blocks and get a transitive closure of reachable dead 1705 // blocks. 1706 SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(), 1707 ExitBlocks.end()); 1708 DeathCandidates.append(L.blocks().begin(), L.blocks().end()); 1709 while (!DeathCandidates.empty()) { 1710 auto *BB = DeathCandidates.pop_back_val(); 1711 if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) { 1712 for (BasicBlock *SuccBB : successors(BB)) { 1713 SuccBB->removePredecessor(BB); 1714 DeathCandidates.push_back(SuccBB); 1715 } 1716 DeadBlockSet.insert(BB); 1717 } 1718 } 1719 1720 // Remove all MemorySSA in the dead blocks 1721 if (MSSAU) 1722 MSSAU->removeBlocks(DeadBlockSet); 1723 1724 // Filter out the dead blocks from the exit blocks list so that it can be 1725 // used in the caller. 1726 llvm::erase_if(ExitBlocks, 1727 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); }); 1728 1729 // Walk from this loop up through its parents removing all of the dead blocks. 1730 for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) { 1731 for (auto *BB : DeadBlockSet) 1732 ParentL->getBlocksSet().erase(BB); 1733 llvm::erase_if(ParentL->getBlocksVector(), 1734 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); }); 1735 } 1736 1737 // Now delete the dead child loops. This raw delete will clear them 1738 // recursively. 1739 llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) { 1740 if (!DeadBlockSet.count(ChildL->getHeader())) 1741 return false; 1742 1743 assert(llvm::all_of(ChildL->blocks(), 1744 [&](BasicBlock *ChildBB) { 1745 return DeadBlockSet.count(ChildBB); 1746 }) && 1747 "If the child loop header is dead all blocks in the child loop must " 1748 "be dead as well!"); 1749 LoopUpdater.markLoopAsDeleted(*ChildL, ChildL->getName()); 1750 if (SE) 1751 SE->forgetBlockAndLoopDispositions(); 1752 LI.destroy(ChildL); 1753 return true; 1754 }); 1755 1756 // Remove the loop mappings for the dead blocks and drop all the references 1757 // from these blocks to others to handle cyclic references as we start 1758 // deleting the blocks themselves. 1759 for (auto *BB : DeadBlockSet) { 1760 // Check that the dominator tree has already been updated. 1761 assert(!DT.getNode(BB) && "Should already have cleared domtree!"); 1762 LI.changeLoopFor(BB, nullptr); 1763 // Drop all uses of the instructions to make sure we won't have dangling 1764 // uses in other blocks. 1765 for (auto &I : *BB) 1766 if (!I.use_empty()) 1767 I.replaceAllUsesWith(PoisonValue::get(I.getType())); 1768 BB->dropAllReferences(); 1769 } 1770 1771 // Actually delete the blocks now that they've been fully unhooked from the 1772 // IR. 1773 for (auto *BB : DeadBlockSet) 1774 BB->eraseFromParent(); 1775 } 1776 1777 /// Recompute the set of blocks in a loop after unswitching. 1778 /// 1779 /// This walks from the original headers predecessors to rebuild the loop. We 1780 /// take advantage of the fact that new blocks can't have been added, and so we 1781 /// filter by the original loop's blocks. This also handles potentially 1782 /// unreachable code that we don't want to explore but might be found examining 1783 /// the predecessors of the header. 1784 /// 1785 /// If the original loop is no longer a loop, this will return an empty set. If 1786 /// it remains a loop, all the blocks within it will be added to the set 1787 /// (including those blocks in inner loops). 1788 static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L, 1789 LoopInfo &LI) { 1790 SmallPtrSet<const BasicBlock *, 16> LoopBlockSet; 1791 1792 auto *PH = L.getLoopPreheader(); 1793 auto *Header = L.getHeader(); 1794 1795 // A worklist to use while walking backwards from the header. 1796 SmallVector<BasicBlock *, 16> Worklist; 1797 1798 // First walk the predecessors of the header to find the backedges. This will 1799 // form the basis of our walk. 1800 for (auto *Pred : predecessors(Header)) { 1801 // Skip the preheader. 1802 if (Pred == PH) 1803 continue; 1804 1805 // Because the loop was in simplified form, the only non-loop predecessor 1806 // is the preheader. 1807 assert(L.contains(Pred) && "Found a predecessor of the loop header other " 1808 "than the preheader that is not part of the " 1809 "loop!"); 1810 1811 // Insert this block into the loop set and on the first visit and, if it 1812 // isn't the header we're currently walking, put it into the worklist to 1813 // recurse through. 1814 if (LoopBlockSet.insert(Pred).second && Pred != Header) 1815 Worklist.push_back(Pred); 1816 } 1817 1818 // If no backedges were found, we're done. 1819 if (LoopBlockSet.empty()) 1820 return LoopBlockSet; 1821 1822 // We found backedges, recurse through them to identify the loop blocks. 1823 while (!Worklist.empty()) { 1824 BasicBlock *BB = Worklist.pop_back_val(); 1825 assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!"); 1826 1827 // No need to walk past the header. 1828 if (BB == Header) 1829 continue; 1830 1831 // Because we know the inner loop structure remains valid we can use the 1832 // loop structure to jump immediately across the entire nested loop. 1833 // Further, because it is in loop simplified form, we can directly jump 1834 // to its preheader afterward. 1835 if (Loop *InnerL = LI.getLoopFor(BB)) 1836 if (InnerL != &L) { 1837 assert(L.contains(InnerL) && 1838 "Should not reach a loop *outside* this loop!"); 1839 // The preheader is the only possible predecessor of the loop so 1840 // insert it into the set and check whether it was already handled. 1841 auto *InnerPH = InnerL->getLoopPreheader(); 1842 assert(L.contains(InnerPH) && "Cannot contain an inner loop block " 1843 "but not contain the inner loop " 1844 "preheader!"); 1845 if (!LoopBlockSet.insert(InnerPH).second) 1846 // The only way to reach the preheader is through the loop body 1847 // itself so if it has been visited the loop is already handled. 1848 continue; 1849 1850 // Insert all of the blocks (other than those already present) into 1851 // the loop set. We expect at least the block that led us to find the 1852 // inner loop to be in the block set, but we may also have other loop 1853 // blocks if they were already enqueued as predecessors of some other 1854 // outer loop block. 1855 for (auto *InnerBB : InnerL->blocks()) { 1856 if (InnerBB == BB) { 1857 assert(LoopBlockSet.count(InnerBB) && 1858 "Block should already be in the set!"); 1859 continue; 1860 } 1861 1862 LoopBlockSet.insert(InnerBB); 1863 } 1864 1865 // Add the preheader to the worklist so we will continue past the 1866 // loop body. 1867 Worklist.push_back(InnerPH); 1868 continue; 1869 } 1870 1871 // Insert any predecessors that were in the original loop into the new 1872 // set, and if the insert is successful, add them to the worklist. 1873 for (auto *Pred : predecessors(BB)) 1874 if (L.contains(Pred) && LoopBlockSet.insert(Pred).second) 1875 Worklist.push_back(Pred); 1876 } 1877 1878 assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!"); 1879 1880 // We've found all the blocks participating in the loop, return our completed 1881 // set. 1882 return LoopBlockSet; 1883 } 1884 1885 /// Rebuild a loop after unswitching removes some subset of blocks and edges. 1886 /// 1887 /// The removal may have removed some child loops entirely but cannot have 1888 /// disturbed any remaining child loops. However, they may need to be hoisted 1889 /// to the parent loop (or to be top-level loops). The original loop may be 1890 /// completely removed. 1891 /// 1892 /// The sibling loops resulting from this update are returned. If the original 1893 /// loop remains a valid loop, it will be the first entry in this list with all 1894 /// of the newly sibling loops following it. 1895 /// 1896 /// Returns true if the loop remains a loop after unswitching, and false if it 1897 /// is no longer a loop after unswitching (and should not continue to be 1898 /// referenced). 1899 static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks, 1900 LoopInfo &LI, 1901 SmallVectorImpl<Loop *> &HoistedLoops, 1902 ScalarEvolution *SE) { 1903 auto *PH = L.getLoopPreheader(); 1904 1905 // Compute the actual parent loop from the exit blocks. Because we may have 1906 // pruned some exits the loop may be different from the original parent. 1907 Loop *ParentL = nullptr; 1908 SmallVector<Loop *, 4> ExitLoops; 1909 SmallVector<BasicBlock *, 4> ExitsInLoops; 1910 ExitsInLoops.reserve(ExitBlocks.size()); 1911 for (auto *ExitBB : ExitBlocks) 1912 if (Loop *ExitL = LI.getLoopFor(ExitBB)) { 1913 ExitLoops.push_back(ExitL); 1914 ExitsInLoops.push_back(ExitBB); 1915 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL))) 1916 ParentL = ExitL; 1917 } 1918 1919 // Recompute the blocks participating in this loop. This may be empty if it 1920 // is no longer a loop. 1921 auto LoopBlockSet = recomputeLoopBlockSet(L, LI); 1922 1923 // If we still have a loop, we need to re-set the loop's parent as the exit 1924 // block set changing may have moved it within the loop nest. Note that this 1925 // can only happen when this loop has a parent as it can only hoist the loop 1926 // *up* the nest. 1927 if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) { 1928 // Remove this loop's (original) blocks from all of the intervening loops. 1929 for (Loop *IL = L.getParentLoop(); IL != ParentL; 1930 IL = IL->getParentLoop()) { 1931 IL->getBlocksSet().erase(PH); 1932 for (auto *BB : L.blocks()) 1933 IL->getBlocksSet().erase(BB); 1934 llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) { 1935 return BB == PH || L.contains(BB); 1936 }); 1937 } 1938 1939 LI.changeLoopFor(PH, ParentL); 1940 L.getParentLoop()->removeChildLoop(&L); 1941 if (ParentL) 1942 ParentL->addChildLoop(&L); 1943 else 1944 LI.addTopLevelLoop(&L); 1945 } 1946 1947 // Now we update all the blocks which are no longer within the loop. 1948 auto &Blocks = L.getBlocksVector(); 1949 auto BlocksSplitI = 1950 LoopBlockSet.empty() 1951 ? Blocks.begin() 1952 : std::stable_partition( 1953 Blocks.begin(), Blocks.end(), 1954 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); }); 1955 1956 // Before we erase the list of unlooped blocks, build a set of them. 1957 SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end()); 1958 if (LoopBlockSet.empty()) 1959 UnloopedBlocks.insert(PH); 1960 1961 // Now erase these blocks from the loop. 1962 for (auto *BB : make_range(BlocksSplitI, Blocks.end())) 1963 L.getBlocksSet().erase(BB); 1964 Blocks.erase(BlocksSplitI, Blocks.end()); 1965 1966 // Sort the exits in ascending loop depth, we'll work backwards across these 1967 // to process them inside out. 1968 llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) { 1969 return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS); 1970 }); 1971 1972 // We'll build up a set for each exit loop. 1973 SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks; 1974 Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop. 1975 1976 auto RemoveUnloopedBlocksFromLoop = 1977 [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) { 1978 for (auto *BB : UnloopedBlocks) 1979 L.getBlocksSet().erase(BB); 1980 llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) { 1981 return UnloopedBlocks.count(BB); 1982 }); 1983 }; 1984 1985 SmallVector<BasicBlock *, 16> Worklist; 1986 while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) { 1987 assert(Worklist.empty() && "Didn't clear worklist!"); 1988 assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!"); 1989 1990 // Grab the next exit block, in decreasing loop depth order. 1991 BasicBlock *ExitBB = ExitsInLoops.pop_back_val(); 1992 Loop &ExitL = *LI.getLoopFor(ExitBB); 1993 assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!"); 1994 1995 // Erase all of the unlooped blocks from the loops between the previous 1996 // exit loop and this exit loop. This works because the ExitInLoops list is 1997 // sorted in increasing order of loop depth and thus we visit loops in 1998 // decreasing order of loop depth. 1999 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop()) 2000 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks); 2001 2002 // Walk the CFG back until we hit the cloned PH adding everything reachable 2003 // and in the unlooped set to this exit block's loop. 2004 Worklist.push_back(ExitBB); 2005 do { 2006 BasicBlock *BB = Worklist.pop_back_val(); 2007 // We can stop recursing at the cloned preheader (if we get there). 2008 if (BB == PH) 2009 continue; 2010 2011 for (BasicBlock *PredBB : predecessors(BB)) { 2012 // If this pred has already been moved to our set or is part of some 2013 // (inner) loop, no update needed. 2014 if (!UnloopedBlocks.erase(PredBB)) { 2015 assert((NewExitLoopBlocks.count(PredBB) || 2016 ExitL.contains(LI.getLoopFor(PredBB))) && 2017 "Predecessor not in a nested loop (or already visited)!"); 2018 continue; 2019 } 2020 2021 // We just insert into the loop set here. We'll add these blocks to the 2022 // exit loop after we build up the set in a deterministic order rather 2023 // than the predecessor-influenced visit order. 2024 bool Inserted = NewExitLoopBlocks.insert(PredBB).second; 2025 (void)Inserted; 2026 assert(Inserted && "Should only visit an unlooped block once!"); 2027 2028 // And recurse through to its predecessors. 2029 Worklist.push_back(PredBB); 2030 } 2031 } while (!Worklist.empty()); 2032 2033 // If blocks in this exit loop were directly part of the original loop (as 2034 // opposed to a child loop) update the map to point to this exit loop. This 2035 // just updates a map and so the fact that the order is unstable is fine. 2036 for (auto *BB : NewExitLoopBlocks) 2037 if (Loop *BBL = LI.getLoopFor(BB)) 2038 if (BBL == &L || !L.contains(BBL)) 2039 LI.changeLoopFor(BB, &ExitL); 2040 2041 // We will remove the remaining unlooped blocks from this loop in the next 2042 // iteration or below. 2043 NewExitLoopBlocks.clear(); 2044 } 2045 2046 // Any remaining unlooped blocks are no longer part of any loop unless they 2047 // are part of some child loop. 2048 for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop()) 2049 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks); 2050 for (auto *BB : UnloopedBlocks) 2051 if (Loop *BBL = LI.getLoopFor(BB)) 2052 if (BBL == &L || !L.contains(BBL)) 2053 LI.changeLoopFor(BB, nullptr); 2054 2055 // Sink all the child loops whose headers are no longer in the loop set to 2056 // the parent (or to be top level loops). We reach into the loop and directly 2057 // update its subloop vector to make this batch update efficient. 2058 auto &SubLoops = L.getSubLoopsVector(); 2059 auto SubLoopsSplitI = 2060 LoopBlockSet.empty() 2061 ? SubLoops.begin() 2062 : std::stable_partition( 2063 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) { 2064 return LoopBlockSet.count(SubL->getHeader()); 2065 }); 2066 for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) { 2067 HoistedLoops.push_back(HoistedL); 2068 HoistedL->setParentLoop(nullptr); 2069 2070 // To compute the new parent of this hoisted loop we look at where we 2071 // placed the preheader above. We can't lookup the header itself because we 2072 // retained the mapping from the header to the hoisted loop. But the 2073 // preheader and header should have the exact same new parent computed 2074 // based on the set of exit blocks from the original loop as the preheader 2075 // is a predecessor of the header and so reached in the reverse walk. And 2076 // because the loops were all in simplified form the preheader of the 2077 // hoisted loop can't be part of some *other* loop. 2078 if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader())) 2079 NewParentL->addChildLoop(HoistedL); 2080 else 2081 LI.addTopLevelLoop(HoistedL); 2082 } 2083 SubLoops.erase(SubLoopsSplitI, SubLoops.end()); 2084 2085 // Actually delete the loop if nothing remained within it. 2086 if (Blocks.empty()) { 2087 assert(SubLoops.empty() && 2088 "Failed to remove all subloops from the original loop!"); 2089 if (Loop *ParentL = L.getParentLoop()) 2090 ParentL->removeChildLoop(llvm::find(*ParentL, &L)); 2091 else 2092 LI.removeLoop(llvm::find(LI, &L)); 2093 // markLoopAsDeleted for L should be triggered by the caller (it is 2094 // typically done within postUnswitch). 2095 if (SE) 2096 SE->forgetBlockAndLoopDispositions(); 2097 LI.destroy(&L); 2098 return false; 2099 } 2100 2101 return true; 2102 } 2103 2104 /// Helper to visit a dominator subtree, invoking a callable on each node. 2105 /// 2106 /// Returning false at any point will stop walking past that node of the tree. 2107 template <typename CallableT> 2108 void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) { 2109 SmallVector<DomTreeNode *, 4> DomWorklist; 2110 DomWorklist.push_back(DT[BB]); 2111 #ifndef NDEBUG 2112 SmallPtrSet<DomTreeNode *, 4> Visited; 2113 Visited.insert(DT[BB]); 2114 #endif 2115 do { 2116 DomTreeNode *N = DomWorklist.pop_back_val(); 2117 2118 // Visit this node. 2119 if (!Callable(N->getBlock())) 2120 continue; 2121 2122 // Accumulate the child nodes. 2123 for (DomTreeNode *ChildN : *N) { 2124 assert(Visited.insert(ChildN).second && 2125 "Cannot visit a node twice when walking a tree!"); 2126 DomWorklist.push_back(ChildN); 2127 } 2128 } while (!DomWorklist.empty()); 2129 } 2130 2131 void postUnswitch(Loop &L, LPMUpdater &U, StringRef LoopName, 2132 bool CurrentLoopValid, bool PartiallyInvariant, 2133 bool InjectedCondition, ArrayRef<Loop *> NewLoops) { 2134 // If we did a non-trivial unswitch, we have added new (cloned) loops. 2135 if (!NewLoops.empty()) 2136 U.addSiblingLoops(NewLoops); 2137 2138 // If the current loop remains valid, we should revisit it to catch any 2139 // other unswitch opportunities. Otherwise, we need to mark it as deleted. 2140 if (CurrentLoopValid) { 2141 if (PartiallyInvariant) { 2142 // Mark the new loop as partially unswitched, to avoid unswitching on 2143 // the same condition again. 2144 auto &Context = L.getHeader()->getContext(); 2145 MDNode *DisableUnswitchMD = MDNode::get( 2146 Context, 2147 MDString::get(Context, "llvm.loop.unswitch.partial.disable")); 2148 MDNode *NewLoopID = makePostTransformationMetadata( 2149 Context, L.getLoopID(), {"llvm.loop.unswitch.partial"}, 2150 {DisableUnswitchMD}); 2151 L.setLoopID(NewLoopID); 2152 } else if (InjectedCondition) { 2153 // Do the same for injection of invariant conditions. 2154 auto &Context = L.getHeader()->getContext(); 2155 MDNode *DisableUnswitchMD = MDNode::get( 2156 Context, 2157 MDString::get(Context, "llvm.loop.unswitch.injection.disable")); 2158 MDNode *NewLoopID = makePostTransformationMetadata( 2159 Context, L.getLoopID(), {"llvm.loop.unswitch.injection"}, 2160 {DisableUnswitchMD}); 2161 L.setLoopID(NewLoopID); 2162 } else 2163 U.revisitCurrentLoop(); 2164 } else 2165 U.markLoopAsDeleted(L, LoopName); 2166 } 2167 2168 static void unswitchNontrivialInvariants( 2169 Loop &L, Instruction &TI, ArrayRef<Value *> Invariants, 2170 IVConditionInfo &PartialIVInfo, DominatorTree &DT, LoopInfo &LI, 2171 AssumptionCache &AC, ScalarEvolution *SE, MemorySSAUpdater *MSSAU, 2172 LPMUpdater &LoopUpdater, bool InsertFreeze, bool InjectedCondition) { 2173 auto *ParentBB = TI.getParent(); 2174 BranchInst *BI = dyn_cast<BranchInst>(&TI); 2175 SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI); 2176 2177 // Save the current loop name in a variable so that we can report it even 2178 // after it has been deleted. 2179 std::string LoopName(L.getName()); 2180 2181 // We can only unswitch switches, conditional branches with an invariant 2182 // condition, or combining invariant conditions with an instruction or 2183 // partially invariant instructions. 2184 assert((SI || (BI && BI->isConditional())) && 2185 "Can only unswitch switches and conditional branch!"); 2186 bool PartiallyInvariant = !PartialIVInfo.InstToDuplicate.empty(); 2187 bool FullUnswitch = 2188 SI || (skipTrivialSelect(BI->getCondition()) == Invariants[0] && 2189 !PartiallyInvariant); 2190 if (FullUnswitch) 2191 assert(Invariants.size() == 1 && 2192 "Cannot have other invariants with full unswitching!"); 2193 else 2194 assert(isa<Instruction>(skipTrivialSelect(BI->getCondition())) && 2195 "Partial unswitching requires an instruction as the condition!"); 2196 2197 if (MSSAU && VerifyMemorySSA) 2198 MSSAU->getMemorySSA()->verifyMemorySSA(); 2199 2200 // Constant and BBs tracking the cloned and continuing successor. When we are 2201 // unswitching the entire condition, this can just be trivially chosen to 2202 // unswitch towards `true`. However, when we are unswitching a set of 2203 // invariants combined with `and` or `or` or partially invariant instructions, 2204 // the combining operation determines the best direction to unswitch: we want 2205 // to unswitch the direction that will collapse the branch. 2206 bool Direction = true; 2207 int ClonedSucc = 0; 2208 if (!FullUnswitch) { 2209 Value *Cond = skipTrivialSelect(BI->getCondition()); 2210 (void)Cond; 2211 assert(((match(Cond, m_LogicalAnd()) ^ match(Cond, m_LogicalOr())) || 2212 PartiallyInvariant) && 2213 "Only `or`, `and`, an `select`, partially invariant instructions " 2214 "can combine invariants being unswitched."); 2215 if (!match(Cond, m_LogicalOr())) { 2216 if (match(Cond, m_LogicalAnd()) || 2217 (PartiallyInvariant && !PartialIVInfo.KnownValue->isOneValue())) { 2218 Direction = false; 2219 ClonedSucc = 1; 2220 } 2221 } 2222 } 2223 2224 BasicBlock *RetainedSuccBB = 2225 BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest(); 2226 SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs; 2227 if (BI) 2228 UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc)); 2229 else 2230 for (auto Case : SI->cases()) 2231 if (Case.getCaseSuccessor() != RetainedSuccBB) 2232 UnswitchedSuccBBs.insert(Case.getCaseSuccessor()); 2233 2234 assert(!UnswitchedSuccBBs.count(RetainedSuccBB) && 2235 "Should not unswitch the same successor we are retaining!"); 2236 2237 // The branch should be in this exact loop. Any inner loop's invariant branch 2238 // should be handled by unswitching that inner loop. The caller of this 2239 // routine should filter out any candidates that remain (but were skipped for 2240 // whatever reason). 2241 assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!"); 2242 2243 // Compute the parent loop now before we start hacking on things. 2244 Loop *ParentL = L.getParentLoop(); 2245 // Get blocks in RPO order for MSSA update, before changing the CFG. 2246 LoopBlocksRPO LBRPO(&L); 2247 if (MSSAU) 2248 LBRPO.perform(&LI); 2249 2250 // Compute the outer-most loop containing one of our exit blocks. This is the 2251 // furthest up our loopnest which can be mutated, which we will use below to 2252 // update things. 2253 Loop *OuterExitL = &L; 2254 SmallVector<BasicBlock *, 4> ExitBlocks; 2255 L.getUniqueExitBlocks(ExitBlocks); 2256 for (auto *ExitBB : ExitBlocks) { 2257 // ExitBB can be an exit block for several levels in the loop nest. Make 2258 // sure we find the top most. 2259 Loop *NewOuterExitL = getTopMostExitingLoop(ExitBB, LI); 2260 if (!NewOuterExitL) { 2261 // We exited the entire nest with this block, so we're done. 2262 OuterExitL = nullptr; 2263 break; 2264 } 2265 if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL)) 2266 OuterExitL = NewOuterExitL; 2267 } 2268 2269 // At this point, we're definitely going to unswitch something so invalidate 2270 // any cached information in ScalarEvolution for the outer most loop 2271 // containing an exit block and all nested loops. 2272 if (SE) { 2273 if (OuterExitL) 2274 SE->forgetLoop(OuterExitL); 2275 else 2276 SE->forgetTopmostLoop(&L); 2277 SE->forgetBlockAndLoopDispositions(); 2278 } 2279 2280 // If the edge from this terminator to a successor dominates that successor, 2281 // store a map from each block in its dominator subtree to it. This lets us 2282 // tell when cloning for a particular successor if a block is dominated by 2283 // some *other* successor with a single data structure. We use this to 2284 // significantly reduce cloning. 2285 SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc; 2286 for (auto *SuccBB : llvm::concat<BasicBlock *const>(ArrayRef(RetainedSuccBB), 2287 UnswitchedSuccBBs)) 2288 if (SuccBB->getUniquePredecessor() || 2289 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) { 2290 return PredBB == ParentBB || DT.dominates(SuccBB, PredBB); 2291 })) 2292 visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) { 2293 DominatingSucc[BB] = SuccBB; 2294 return true; 2295 }); 2296 2297 // Split the preheader, so that we know that there is a safe place to insert 2298 // the conditional branch. We will change the preheader to have a conditional 2299 // branch on LoopCond. The original preheader will become the split point 2300 // between the unswitched versions, and we will have a new preheader for the 2301 // original loop. 2302 BasicBlock *SplitBB = L.getLoopPreheader(); 2303 BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU); 2304 2305 // Keep track of the dominator tree updates needed. 2306 SmallVector<DominatorTree::UpdateType, 4> DTUpdates; 2307 2308 // Clone the loop for each unswitched successor. 2309 SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps; 2310 VMaps.reserve(UnswitchedSuccBBs.size()); 2311 SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs; 2312 for (auto *SuccBB : UnswitchedSuccBBs) { 2313 VMaps.emplace_back(new ValueToValueMapTy()); 2314 ClonedPHs[SuccBB] = buildClonedLoopBlocks( 2315 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB, 2316 DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU, SE); 2317 } 2318 2319 // Drop metadata if we may break its semantics by moving this instr into the 2320 // split block. 2321 if (TI.getMetadata(LLVMContext::MD_make_implicit)) { 2322 if (DropNonTrivialImplicitNullChecks) 2323 // Do not spend time trying to understand if we can keep it, just drop it 2324 // to save compile time. 2325 TI.setMetadata(LLVMContext::MD_make_implicit, nullptr); 2326 else { 2327 // It is only legal to preserve make.implicit metadata if we are 2328 // guaranteed no reach implicit null check after following this branch. 2329 ICFLoopSafetyInfo SafetyInfo; 2330 SafetyInfo.computeLoopSafetyInfo(&L); 2331 if (!SafetyInfo.isGuaranteedToExecute(TI, &DT, &L)) 2332 TI.setMetadata(LLVMContext::MD_make_implicit, nullptr); 2333 } 2334 } 2335 2336 // The stitching of the branched code back together depends on whether we're 2337 // doing full unswitching or not with the exception that we always want to 2338 // nuke the initial terminator placed in the split block. 2339 SplitBB->getTerminator()->eraseFromParent(); 2340 if (FullUnswitch) { 2341 // Keep a clone of the terminator for MSSA updates. 2342 Instruction *NewTI = TI.clone(); 2343 NewTI->insertInto(ParentBB, ParentBB->end()); 2344 2345 // Splice the terminator from the original loop and rewrite its 2346 // successors. 2347 TI.moveBefore(*SplitBB, SplitBB->end()); 2348 TI.dropLocation(); 2349 2350 // First wire up the moved terminator to the preheaders. 2351 if (BI) { 2352 BasicBlock *ClonedPH = ClonedPHs.begin()->second; 2353 BI->setSuccessor(ClonedSucc, ClonedPH); 2354 BI->setSuccessor(1 - ClonedSucc, LoopPH); 2355 Value *Cond = skipTrivialSelect(BI->getCondition()); 2356 if (InsertFreeze) { 2357 // We don't give any debug location to the new freeze, because the 2358 // BI (`dyn_cast<BranchInst>(TI)`) is an in-loop instruction hoisted 2359 // out of the loop. 2360 Cond = new FreezeInst(Cond, Cond->getName() + ".fr", BI->getIterator()); 2361 } 2362 BI->setCondition(Cond); 2363 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH}); 2364 } else { 2365 assert(SI && "Must either be a branch or switch!"); 2366 2367 // Walk the cases and directly update their successors. 2368 assert(SI->getDefaultDest() == RetainedSuccBB && 2369 "Not retaining default successor!"); 2370 SI->setDefaultDest(LoopPH); 2371 for (const auto &Case : SI->cases()) 2372 if (Case.getCaseSuccessor() == RetainedSuccBB) 2373 Case.setSuccessor(LoopPH); 2374 else 2375 Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second); 2376 2377 if (InsertFreeze) 2378 SI->setCondition(new FreezeInst(SI->getCondition(), 2379 SI->getCondition()->getName() + ".fr", 2380 SI->getIterator())); 2381 2382 // We need to use the set to populate domtree updates as even when there 2383 // are multiple cases pointing at the same successor we only want to 2384 // remove and insert one edge in the domtree. 2385 for (BasicBlock *SuccBB : UnswitchedSuccBBs) 2386 DTUpdates.push_back( 2387 {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second}); 2388 } 2389 2390 if (MSSAU) { 2391 DT.applyUpdates(DTUpdates); 2392 DTUpdates.clear(); 2393 2394 // Remove all but one edge to the retained block and all unswitched 2395 // blocks. This is to avoid having duplicate entries in the cloned Phis, 2396 // when we know we only keep a single edge for each case. 2397 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB); 2398 for (BasicBlock *SuccBB : UnswitchedSuccBBs) 2399 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB); 2400 2401 for (auto &VMap : VMaps) 2402 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap, 2403 /*IgnoreIncomingWithNoClones=*/true); 2404 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT); 2405 2406 // Remove all edges to unswitched blocks. 2407 for (BasicBlock *SuccBB : UnswitchedSuccBBs) 2408 MSSAU->removeEdge(ParentBB, SuccBB); 2409 } 2410 2411 // Now unhook the successor relationship as we'll be replacing 2412 // the terminator with a direct branch. This is much simpler for branches 2413 // than switches so we handle those first. 2414 if (BI) { 2415 // Remove the parent as a predecessor of the unswitched successor. 2416 assert(UnswitchedSuccBBs.size() == 1 && 2417 "Only one possible unswitched block for a branch!"); 2418 BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin(); 2419 UnswitchedSuccBB->removePredecessor(ParentBB, 2420 /*KeepOneInputPHIs*/ true); 2421 DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB}); 2422 } else { 2423 // Note that we actually want to remove the parent block as a predecessor 2424 // of *every* case successor. The case successor is either unswitched, 2425 // completely eliminating an edge from the parent to that successor, or it 2426 // is a duplicate edge to the retained successor as the retained successor 2427 // is always the default successor and as we'll replace this with a direct 2428 // branch we no longer need the duplicate entries in the PHI nodes. 2429 SwitchInst *NewSI = cast<SwitchInst>(NewTI); 2430 assert(NewSI->getDefaultDest() == RetainedSuccBB && 2431 "Not retaining default successor!"); 2432 for (const auto &Case : NewSI->cases()) 2433 Case.getCaseSuccessor()->removePredecessor( 2434 ParentBB, 2435 /*KeepOneInputPHIs*/ true); 2436 2437 // We need to use the set to populate domtree updates as even when there 2438 // are multiple cases pointing at the same successor we only want to 2439 // remove and insert one edge in the domtree. 2440 for (BasicBlock *SuccBB : UnswitchedSuccBBs) 2441 DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB}); 2442 } 2443 2444 // Create a new unconditional branch to the continuing block (as opposed to 2445 // the one cloned). 2446 Instruction *NewBI = BranchInst::Create(RetainedSuccBB, ParentBB); 2447 NewBI->setDebugLoc(NewTI->getDebugLoc()); 2448 2449 // After MSSAU update, remove the cloned terminator instruction NewTI. 2450 NewTI->eraseFromParent(); 2451 } else { 2452 assert(BI && "Only branches have partial unswitching."); 2453 assert(UnswitchedSuccBBs.size() == 1 && 2454 "Only one possible unswitched block for a branch!"); 2455 BasicBlock *ClonedPH = ClonedPHs.begin()->second; 2456 // When doing a partial unswitch, we have to do a bit more work to build up 2457 // the branch in the split block. 2458 if (PartiallyInvariant) 2459 buildPartialInvariantUnswitchConditionalBranch( 2460 *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH, L, MSSAU); 2461 else { 2462 buildPartialUnswitchConditionalBranch( 2463 *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH, 2464 FreezeLoopUnswitchCond, BI, &AC, DT); 2465 } 2466 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH}); 2467 2468 if (MSSAU) { 2469 DT.applyUpdates(DTUpdates); 2470 DTUpdates.clear(); 2471 2472 // Perform MSSA cloning updates. 2473 for (auto &VMap : VMaps) 2474 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap, 2475 /*IgnoreIncomingWithNoClones=*/true); 2476 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT); 2477 } 2478 } 2479 2480 // Apply the updates accumulated above to get an up-to-date dominator tree. 2481 DT.applyUpdates(DTUpdates); 2482 2483 // Now that we have an accurate dominator tree, first delete the dead cloned 2484 // blocks so that we can accurately build any cloned loops. It is important to 2485 // not delete the blocks from the original loop yet because we still want to 2486 // reference the original loop to understand the cloned loop's structure. 2487 deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU); 2488 2489 // Build the cloned loop structure itself. This may be substantially 2490 // different from the original structure due to the simplified CFG. This also 2491 // handles inserting all the cloned blocks into the correct loops. 2492 SmallVector<Loop *, 4> NonChildClonedLoops; 2493 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps) 2494 buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops); 2495 2496 // Now that our cloned loops have been built, we can update the original loop. 2497 // First we delete the dead blocks from it and then we rebuild the loop 2498 // structure taking these deletions into account. 2499 deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU, SE, LoopUpdater); 2500 2501 if (MSSAU && VerifyMemorySSA) 2502 MSSAU->getMemorySSA()->verifyMemorySSA(); 2503 2504 SmallVector<Loop *, 4> HoistedLoops; 2505 bool IsStillLoop = 2506 rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops, SE); 2507 2508 if (MSSAU && VerifyMemorySSA) 2509 MSSAU->getMemorySSA()->verifyMemorySSA(); 2510 2511 // This transformation has a high risk of corrupting the dominator tree, and 2512 // the below steps to rebuild loop structures will result in hard to debug 2513 // errors in that case so verify that the dominator tree is sane first. 2514 // FIXME: Remove this when the bugs stop showing up and rely on existing 2515 // verification steps. 2516 assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 2517 2518 if (BI && !PartiallyInvariant) { 2519 // If we unswitched a branch which collapses the condition to a known 2520 // constant we want to replace all the uses of the invariants within both 2521 // the original and cloned blocks. We do this here so that we can use the 2522 // now updated dominator tree to identify which side the users are on. 2523 assert(UnswitchedSuccBBs.size() == 1 && 2524 "Only one possible unswitched block for a branch!"); 2525 BasicBlock *ClonedPH = ClonedPHs.begin()->second; 2526 2527 // When considering multiple partially-unswitched invariants 2528 // we cant just go replace them with constants in both branches. 2529 // 2530 // For 'AND' we infer that true branch ("continue") means true 2531 // for each invariant operand. 2532 // For 'OR' we can infer that false branch ("continue") means false 2533 // for each invariant operand. 2534 // So it happens that for multiple-partial case we dont replace 2535 // in the unswitched branch. 2536 bool ReplaceUnswitched = 2537 FullUnswitch || (Invariants.size() == 1) || PartiallyInvariant; 2538 2539 ConstantInt *UnswitchedReplacement = 2540 Direction ? ConstantInt::getTrue(BI->getContext()) 2541 : ConstantInt::getFalse(BI->getContext()); 2542 ConstantInt *ContinueReplacement = 2543 Direction ? ConstantInt::getFalse(BI->getContext()) 2544 : ConstantInt::getTrue(BI->getContext()); 2545 for (Value *Invariant : Invariants) { 2546 assert(!isa<Constant>(Invariant) && 2547 "Should not be replacing constant values!"); 2548 // Use make_early_inc_range here as set invalidates the iterator. 2549 for (Use &U : llvm::make_early_inc_range(Invariant->uses())) { 2550 Instruction *UserI = dyn_cast<Instruction>(U.getUser()); 2551 if (!UserI) 2552 continue; 2553 2554 // Replace it with the 'continue' side if in the main loop body, and the 2555 // unswitched if in the cloned blocks. 2556 if (DT.dominates(LoopPH, UserI->getParent())) 2557 U.set(ContinueReplacement); 2558 else if (ReplaceUnswitched && 2559 DT.dominates(ClonedPH, UserI->getParent())) 2560 U.set(UnswitchedReplacement); 2561 } 2562 } 2563 } 2564 2565 // We can change which blocks are exit blocks of all the cloned sibling 2566 // loops, the current loop, and any parent loops which shared exit blocks 2567 // with the current loop. As a consequence, we need to re-form LCSSA for 2568 // them. But we shouldn't need to re-form LCSSA for any child loops. 2569 // FIXME: This could be made more efficient by tracking which exit blocks are 2570 // new, and focusing on them, but that isn't likely to be necessary. 2571 // 2572 // In order to reasonably rebuild LCSSA we need to walk inside-out across the 2573 // loop nest and update every loop that could have had its exits changed. We 2574 // also need to cover any intervening loops. We add all of these loops to 2575 // a list and sort them by loop depth to achieve this without updating 2576 // unnecessary loops. 2577 auto UpdateLoop = [&](Loop &UpdateL) { 2578 #ifndef NDEBUG 2579 UpdateL.verifyLoop(); 2580 for (Loop *ChildL : UpdateL) { 2581 ChildL->verifyLoop(); 2582 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) && 2583 "Perturbed a child loop's LCSSA form!"); 2584 } 2585 #endif 2586 // First build LCSSA for this loop so that we can preserve it when 2587 // forming dedicated exits. We don't want to perturb some other loop's 2588 // LCSSA while doing that CFG edit. 2589 formLCSSA(UpdateL, DT, &LI, SE); 2590 2591 // For loops reached by this loop's original exit blocks we may 2592 // introduced new, non-dedicated exits. At least try to re-form dedicated 2593 // exits for these loops. This may fail if they couldn't have dedicated 2594 // exits to start with. 2595 formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true); 2596 }; 2597 2598 // For non-child cloned loops and hoisted loops, we just need to update LCSSA 2599 // and we can do it in any order as they don't nest relative to each other. 2600 // 2601 // Also check if any of the loops we have updated have become top-level loops 2602 // as that will necessitate widening the outer loop scope. 2603 for (Loop *UpdatedL : 2604 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) { 2605 UpdateLoop(*UpdatedL); 2606 if (UpdatedL->isOutermost()) 2607 OuterExitL = nullptr; 2608 } 2609 if (IsStillLoop) { 2610 UpdateLoop(L); 2611 if (L.isOutermost()) 2612 OuterExitL = nullptr; 2613 } 2614 2615 // If the original loop had exit blocks, walk up through the outer most loop 2616 // of those exit blocks to update LCSSA and form updated dedicated exits. 2617 if (OuterExitL != &L) 2618 for (Loop *OuterL = ParentL; OuterL != OuterExitL; 2619 OuterL = OuterL->getParentLoop()) 2620 UpdateLoop(*OuterL); 2621 2622 #ifndef NDEBUG 2623 // Verify the entire loop structure to catch any incorrect updates before we 2624 // progress in the pass pipeline. 2625 LI.verify(DT); 2626 #endif 2627 2628 // Now that we've unswitched something, make callbacks to report the changes. 2629 // For that we need to merge together the updated loops and the cloned loops 2630 // and check whether the original loop survived. 2631 SmallVector<Loop *, 4> SibLoops; 2632 for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) 2633 if (UpdatedL->getParentLoop() == ParentL) 2634 SibLoops.push_back(UpdatedL); 2635 postUnswitch(L, LoopUpdater, LoopName, IsStillLoop, PartiallyInvariant, 2636 InjectedCondition, SibLoops); 2637 2638 if (MSSAU && VerifyMemorySSA) 2639 MSSAU->getMemorySSA()->verifyMemorySSA(); 2640 2641 if (BI) 2642 ++NumBranches; 2643 else 2644 ++NumSwitches; 2645 } 2646 2647 /// Recursively compute the cost of a dominator subtree based on the per-block 2648 /// cost map provided. 2649 /// 2650 /// The recursive computation is memozied into the provided DT-indexed cost map 2651 /// to allow querying it for most nodes in the domtree without it becoming 2652 /// quadratic. 2653 static InstructionCost computeDomSubtreeCost( 2654 DomTreeNode &N, 2655 const SmallDenseMap<BasicBlock *, InstructionCost, 4> &BBCostMap, 2656 SmallDenseMap<DomTreeNode *, InstructionCost, 4> &DTCostMap) { 2657 // Don't accumulate cost (or recurse through) blocks not in our block cost 2658 // map and thus not part of the duplication cost being considered. 2659 auto BBCostIt = BBCostMap.find(N.getBlock()); 2660 if (BBCostIt == BBCostMap.end()) 2661 return 0; 2662 2663 // Lookup this node to see if we already computed its cost. 2664 auto DTCostIt = DTCostMap.find(&N); 2665 if (DTCostIt != DTCostMap.end()) 2666 return DTCostIt->second; 2667 2668 // If not, we have to compute it. We can't use insert above and update 2669 // because computing the cost may insert more things into the map. 2670 InstructionCost Cost = std::accumulate( 2671 N.begin(), N.end(), BBCostIt->second, 2672 [&](InstructionCost Sum, DomTreeNode *ChildN) -> InstructionCost { 2673 return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap); 2674 }); 2675 bool Inserted = DTCostMap.insert({&N, Cost}).second; 2676 (void)Inserted; 2677 assert(Inserted && "Should not insert a node while visiting children!"); 2678 return Cost; 2679 } 2680 2681 /// Turns a select instruction into implicit control flow branch, 2682 /// making the following replacement: 2683 /// 2684 /// head: 2685 /// --code before select-- 2686 /// select %cond, %trueval, %falseval 2687 /// --code after select-- 2688 /// 2689 /// into 2690 /// 2691 /// head: 2692 /// --code before select-- 2693 /// br i1 %cond, label %then, label %tail 2694 /// 2695 /// then: 2696 /// br %tail 2697 /// 2698 /// tail: 2699 /// phi [ %trueval, %then ], [ %falseval, %head] 2700 /// unreachable 2701 /// 2702 /// It also makes all relevant DT and LI updates, so that all structures are in 2703 /// valid state after this transform. 2704 static BranchInst *turnSelectIntoBranch(SelectInst *SI, DominatorTree &DT, 2705 LoopInfo &LI, MemorySSAUpdater *MSSAU, 2706 AssumptionCache *AC) { 2707 LLVM_DEBUG(dbgs() << "Turning " << *SI << " into a branch.\n"); 2708 BasicBlock *HeadBB = SI->getParent(); 2709 2710 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 2711 SplitBlockAndInsertIfThen(SI->getCondition(), SI, false, 2712 SI->getMetadata(LLVMContext::MD_prof), &DTU, &LI); 2713 auto *CondBr = cast<BranchInst>(HeadBB->getTerminator()); 2714 BasicBlock *ThenBB = CondBr->getSuccessor(0), 2715 *TailBB = CondBr->getSuccessor(1); 2716 if (MSSAU) 2717 MSSAU->moveAllAfterSpliceBlocks(HeadBB, TailBB, SI); 2718 2719 PHINode *Phi = 2720 PHINode::Create(SI->getType(), 2, "unswitched.select", SI->getIterator()); 2721 Phi->addIncoming(SI->getTrueValue(), ThenBB); 2722 Phi->addIncoming(SI->getFalseValue(), HeadBB); 2723 Phi->setDebugLoc(SI->getDebugLoc()); 2724 SI->replaceAllUsesWith(Phi); 2725 SI->eraseFromParent(); 2726 2727 if (MSSAU && VerifyMemorySSA) 2728 MSSAU->getMemorySSA()->verifyMemorySSA(); 2729 2730 ++NumSelects; 2731 return CondBr; 2732 } 2733 2734 /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch, 2735 /// making the following replacement: 2736 /// 2737 /// --code before guard-- 2738 /// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ] 2739 /// --code after guard-- 2740 /// 2741 /// into 2742 /// 2743 /// --code before guard-- 2744 /// br i1 %cond, label %guarded, label %deopt 2745 /// 2746 /// guarded: 2747 /// --code after guard-- 2748 /// 2749 /// deopt: 2750 /// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ] 2751 /// unreachable 2752 /// 2753 /// It also makes all relevant DT and LI updates, so that all structures are in 2754 /// valid state after this transform. 2755 static BranchInst *turnGuardIntoBranch(IntrinsicInst *GI, Loop &L, 2756 DominatorTree &DT, LoopInfo &LI, 2757 MemorySSAUpdater *MSSAU) { 2758 SmallVector<DominatorTree::UpdateType, 4> DTUpdates; 2759 LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n"); 2760 BasicBlock *CheckBB = GI->getParent(); 2761 2762 if (MSSAU && VerifyMemorySSA) 2763 MSSAU->getMemorySSA()->verifyMemorySSA(); 2764 2765 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 2766 Instruction *DeoptBlockTerm = 2767 SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true, 2768 GI->getMetadata(LLVMContext::MD_prof), &DTU, &LI); 2769 BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator()); 2770 // SplitBlockAndInsertIfThen inserts control flow that branches to 2771 // DeoptBlockTerm if the condition is true. We want the opposite. 2772 CheckBI->swapSuccessors(); 2773 2774 BasicBlock *GuardedBlock = CheckBI->getSuccessor(0); 2775 GuardedBlock->setName("guarded"); 2776 CheckBI->getSuccessor(1)->setName("deopt"); 2777 BasicBlock *DeoptBlock = CheckBI->getSuccessor(1); 2778 2779 if (MSSAU) 2780 MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI); 2781 2782 GI->moveBefore(DeoptBlockTerm); 2783 GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext())); 2784 2785 if (MSSAU) { 2786 MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI)); 2787 MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::BeforeTerminator); 2788 if (VerifyMemorySSA) 2789 MSSAU->getMemorySSA()->verifyMemorySSA(); 2790 } 2791 2792 if (VerifyLoopInfo) 2793 LI.verify(DT); 2794 ++NumGuards; 2795 return CheckBI; 2796 } 2797 2798 /// Cost multiplier is a way to limit potentially exponential behavior 2799 /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch 2800 /// candidates available. Also accounting for the number of "sibling" loops with 2801 /// the idea to account for previous unswitches that already happened on this 2802 /// cluster of loops. There was an attempt to keep this formula simple, 2803 /// just enough to limit the worst case behavior. Even if it is not that simple 2804 /// now it is still not an attempt to provide a detailed heuristic size 2805 /// prediction. 2806 /// 2807 /// TODO: Make a proper accounting of "explosion" effect for all kinds of 2808 /// unswitch candidates, making adequate predictions instead of wild guesses. 2809 /// That requires knowing not just the number of "remaining" candidates but 2810 /// also costs of unswitching for each of these candidates. 2811 static int CalculateUnswitchCostMultiplier( 2812 const Instruction &TI, const Loop &L, const LoopInfo &LI, 2813 const DominatorTree &DT, 2814 ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates) { 2815 2816 // Guards and other exiting conditions do not contribute to exponential 2817 // explosion as soon as they dominate the latch (otherwise there might be 2818 // another path to the latch remaining that does not allow to eliminate the 2819 // loop copy on unswitch). 2820 const BasicBlock *Latch = L.getLoopLatch(); 2821 const BasicBlock *CondBlock = TI.getParent(); 2822 if (DT.dominates(CondBlock, Latch) && 2823 (isGuard(&TI) || 2824 (TI.isTerminator() && 2825 llvm::count_if(successors(&TI), [&L](const BasicBlock *SuccBB) { 2826 return L.contains(SuccBB); 2827 }) <= 1))) { 2828 NumCostMultiplierSkipped++; 2829 return 1; 2830 } 2831 2832 auto *ParentL = L.getParentLoop(); 2833 int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size() 2834 : std::distance(LI.begin(), LI.end())); 2835 // Count amount of clones that all the candidates might cause during 2836 // unswitching. Branch/guard/select counts as 1, switch counts as log2 of its 2837 // cases. 2838 int UnswitchedClones = 0; 2839 for (const auto &Candidate : UnswitchCandidates) { 2840 const Instruction *CI = Candidate.TI; 2841 const BasicBlock *CondBlock = CI->getParent(); 2842 bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch); 2843 if (isa<SelectInst>(CI)) { 2844 UnswitchedClones++; 2845 continue; 2846 } 2847 if (isGuard(CI)) { 2848 if (!SkipExitingSuccessors) 2849 UnswitchedClones++; 2850 continue; 2851 } 2852 int NonExitingSuccessors = 2853 llvm::count_if(successors(CondBlock), 2854 [SkipExitingSuccessors, &L](const BasicBlock *SuccBB) { 2855 return !SkipExitingSuccessors || L.contains(SuccBB); 2856 }); 2857 UnswitchedClones += Log2_32(NonExitingSuccessors); 2858 } 2859 2860 // Ignore up to the "unscaled candidates" number of unswitch candidates 2861 // when calculating the power-of-two scaling of the cost. The main idea 2862 // with this control is to allow a small number of unswitches to happen 2863 // and rely more on siblings multiplier (see below) when the number 2864 // of candidates is small. 2865 unsigned ClonesPower = 2866 std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0); 2867 2868 // Allowing top-level loops to spread a bit more than nested ones. 2869 int SiblingsMultiplier = 2870 std::max((ParentL ? SiblingsCount 2871 : SiblingsCount / (int)UnswitchSiblingsToplevelDiv), 2872 1); 2873 // Compute the cost multiplier in a way that won't overflow by saturating 2874 // at an upper bound. 2875 int CostMultiplier; 2876 if (ClonesPower > Log2_32(UnswitchThreshold) || 2877 SiblingsMultiplier > UnswitchThreshold) 2878 CostMultiplier = UnswitchThreshold; 2879 else 2880 CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower), 2881 (int)UnswitchThreshold); 2882 2883 LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier 2884 << " (siblings " << SiblingsMultiplier << " * clones " 2885 << (1 << ClonesPower) << ")" 2886 << " for unswitch candidate: " << TI << "\n"); 2887 return CostMultiplier; 2888 } 2889 2890 static bool collectUnswitchCandidates( 2891 SmallVectorImpl<NonTrivialUnswitchCandidate> &UnswitchCandidates, 2892 IVConditionInfo &PartialIVInfo, Instruction *&PartialIVCondBranch, 2893 const Loop &L, const LoopInfo &LI, AAResults &AA, 2894 const MemorySSAUpdater *MSSAU) { 2895 assert(UnswitchCandidates.empty() && "Should be!"); 2896 2897 auto AddUnswitchCandidatesForInst = [&](Instruction *I, Value *Cond) { 2898 Cond = skipTrivialSelect(Cond); 2899 if (isa<Constant>(Cond)) 2900 return; 2901 if (L.isLoopInvariant(Cond)) { 2902 UnswitchCandidates.push_back({I, {Cond}}); 2903 return; 2904 } 2905 if (match(Cond, m_CombineOr(m_LogicalAnd(), m_LogicalOr()))) { 2906 TinyPtrVector<Value *> Invariants = 2907 collectHomogenousInstGraphLoopInvariants( 2908 L, *static_cast<Instruction *>(Cond), LI); 2909 if (!Invariants.empty()) 2910 UnswitchCandidates.push_back({I, std::move(Invariants)}); 2911 } 2912 }; 2913 2914 // Whether or not we should also collect guards in the loop. 2915 bool CollectGuards = false; 2916 if (UnswitchGuards) { 2917 auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction( 2918 Intrinsic::getName(Intrinsic::experimental_guard)); 2919 if (GuardDecl && !GuardDecl->use_empty()) 2920 CollectGuards = true; 2921 } 2922 2923 for (auto *BB : L.blocks()) { 2924 if (LI.getLoopFor(BB) != &L) 2925 continue; 2926 2927 for (auto &I : *BB) { 2928 if (auto *SI = dyn_cast<SelectInst>(&I)) { 2929 auto *Cond = SI->getCondition(); 2930 // Do not unswitch vector selects and logical and/or selects 2931 if (Cond->getType()->isIntegerTy(1) && !SI->getType()->isIntegerTy(1)) 2932 AddUnswitchCandidatesForInst(SI, Cond); 2933 } else if (CollectGuards && isGuard(&I)) { 2934 auto *Cond = 2935 skipTrivialSelect(cast<IntrinsicInst>(&I)->getArgOperand(0)); 2936 // TODO: Support AND, OR conditions and partial unswitching. 2937 if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond)) 2938 UnswitchCandidates.push_back({&I, {Cond}}); 2939 } 2940 } 2941 2942 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 2943 // We can only consider fully loop-invariant switch conditions as we need 2944 // to completely eliminate the switch after unswitching. 2945 if (!isa<Constant>(SI->getCondition()) && 2946 L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor()) 2947 UnswitchCandidates.push_back({SI, {SI->getCondition()}}); 2948 continue; 2949 } 2950 2951 auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 2952 if (!BI || !BI->isConditional() || 2953 BI->getSuccessor(0) == BI->getSuccessor(1)) 2954 continue; 2955 2956 AddUnswitchCandidatesForInst(BI, BI->getCondition()); 2957 } 2958 2959 if (MSSAU && !findOptionMDForLoop(&L, "llvm.loop.unswitch.partial.disable") && 2960 !any_of(UnswitchCandidates, [&L](auto &TerminatorAndInvariants) { 2961 return TerminatorAndInvariants.TI == L.getHeader()->getTerminator(); 2962 })) { 2963 MemorySSA *MSSA = MSSAU->getMemorySSA(); 2964 if (auto Info = hasPartialIVCondition(L, MSSAThreshold, *MSSA, AA)) { 2965 LLVM_DEBUG( 2966 dbgs() << "simple-loop-unswitch: Found partially invariant condition " 2967 << *Info->InstToDuplicate[0] << "\n"); 2968 PartialIVInfo = *Info; 2969 PartialIVCondBranch = L.getHeader()->getTerminator(); 2970 TinyPtrVector<Value *> ValsToDuplicate; 2971 llvm::append_range(ValsToDuplicate, Info->InstToDuplicate); 2972 UnswitchCandidates.push_back( 2973 {L.getHeader()->getTerminator(), std::move(ValsToDuplicate)}); 2974 } 2975 } 2976 return !UnswitchCandidates.empty(); 2977 } 2978 2979 /// Tries to canonicalize condition described by: 2980 /// 2981 /// br (LHS pred RHS), label IfTrue, label IfFalse 2982 /// 2983 /// into its equivalent where `Pred` is something that we support for injected 2984 /// invariants (so far it is limited to ult), LHS in canonicalized form is 2985 /// non-invariant and RHS is an invariant. 2986 static void canonicalizeForInvariantConditionInjection( 2987 ICmpInst::Predicate &Pred, Value *&LHS, Value *&RHS, BasicBlock *&IfTrue, 2988 BasicBlock *&IfFalse, const Loop &L) { 2989 if (!L.contains(IfTrue)) { 2990 Pred = ICmpInst::getInversePredicate(Pred); 2991 std::swap(IfTrue, IfFalse); 2992 } 2993 2994 // Move loop-invariant argument to RHS position. 2995 if (L.isLoopInvariant(LHS)) { 2996 Pred = ICmpInst::getSwappedPredicate(Pred); 2997 std::swap(LHS, RHS); 2998 } 2999 3000 if (Pred == ICmpInst::ICMP_SGE && match(RHS, m_Zero())) { 3001 // Turn "x >=s 0" into "x <u UMIN_INT" 3002 Pred = ICmpInst::ICMP_ULT; 3003 RHS = ConstantInt::get( 3004 RHS->getContext(), 3005 APInt::getSignedMinValue(RHS->getType()->getIntegerBitWidth())); 3006 } 3007 } 3008 3009 /// Returns true, if predicate described by ( \p Pred, \p LHS, \p RHS ) 3010 /// succeeding into blocks ( \p IfTrue, \p IfFalse) can be optimized by 3011 /// injecting a loop-invariant condition. 3012 static bool shouldTryInjectInvariantCondition( 3013 const ICmpInst::Predicate Pred, const Value *LHS, const Value *RHS, 3014 const BasicBlock *IfTrue, const BasicBlock *IfFalse, const Loop &L) { 3015 if (L.isLoopInvariant(LHS) || !L.isLoopInvariant(RHS)) 3016 return false; 3017 // TODO: Support other predicates. 3018 if (Pred != ICmpInst::ICMP_ULT) 3019 return false; 3020 // TODO: Support non-loop-exiting branches? 3021 if (!L.contains(IfTrue) || L.contains(IfFalse)) 3022 return false; 3023 // FIXME: For some reason this causes problems with MSSA updates, need to 3024 // investigate why. So far, just don't unswitch latch. 3025 if (L.getHeader() == IfTrue) 3026 return false; 3027 return true; 3028 } 3029 3030 /// Returns true, if metadata on \p BI allows us to optimize branching into \p 3031 /// TakenSucc via injection of invariant conditions. The branch should be not 3032 /// enough and not previously unswitched, the information about this comes from 3033 /// the metadata. 3034 bool shouldTryInjectBasingOnMetadata(const BranchInst *BI, 3035 const BasicBlock *TakenSucc) { 3036 SmallVector<uint32_t> Weights; 3037 if (!extractBranchWeights(*BI, Weights)) 3038 return false; 3039 unsigned T = InjectInvariantConditionHotnesThreshold; 3040 BranchProbability LikelyTaken(T - 1, T); 3041 3042 assert(Weights.size() == 2 && "Unexpected profile data!"); 3043 size_t Idx = BI->getSuccessor(0) == TakenSucc ? 0 : 1; 3044 auto Num = Weights[Idx]; 3045 auto Denom = Weights[0] + Weights[1]; 3046 // Degenerate or overflowed metadata. 3047 if (Denom == 0 || Num > Denom) 3048 return false; 3049 BranchProbability ActualTaken(Num, Denom); 3050 if (LikelyTaken > ActualTaken) 3051 return false; 3052 return true; 3053 } 3054 3055 /// Materialize pending invariant condition of the given candidate into IR. The 3056 /// injected loop-invariant condition implies the original loop-variant branch 3057 /// condition, so the materialization turns 3058 /// 3059 /// loop_block: 3060 /// ... 3061 /// br i1 %variant_cond, label InLoopSucc, label OutOfLoopSucc 3062 /// 3063 /// into 3064 /// 3065 /// preheader: 3066 /// %invariant_cond = LHS pred RHS 3067 /// ... 3068 /// loop_block: 3069 /// br i1 %invariant_cond, label InLoopSucc, label OriginalCheck 3070 /// OriginalCheck: 3071 /// br i1 %variant_cond, label InLoopSucc, label OutOfLoopSucc 3072 /// ... 3073 static NonTrivialUnswitchCandidate 3074 injectPendingInvariantConditions(NonTrivialUnswitchCandidate Candidate, Loop &L, 3075 DominatorTree &DT, LoopInfo &LI, 3076 AssumptionCache &AC, MemorySSAUpdater *MSSAU) { 3077 assert(Candidate.hasPendingInjection() && "Nothing to inject!"); 3078 BasicBlock *Preheader = L.getLoopPreheader(); 3079 assert(Preheader && "Loop is not in simplified form?"); 3080 assert(LI.getLoopFor(Candidate.TI->getParent()) == &L && 3081 "Unswitching branch of inner loop!"); 3082 3083 auto Pred = Candidate.PendingInjection->Pred; 3084 auto *LHS = Candidate.PendingInjection->LHS; 3085 auto *RHS = Candidate.PendingInjection->RHS; 3086 auto *InLoopSucc = Candidate.PendingInjection->InLoopSucc; 3087 auto *TI = cast<BranchInst>(Candidate.TI); 3088 auto *BB = Candidate.TI->getParent(); 3089 auto *OutOfLoopSucc = InLoopSucc == TI->getSuccessor(0) ? TI->getSuccessor(1) 3090 : TI->getSuccessor(0); 3091 // FIXME: Remove this once limitation on successors is lifted. 3092 assert(L.contains(InLoopSucc) && "Not supported yet!"); 3093 assert(!L.contains(OutOfLoopSucc) && "Not supported yet!"); 3094 auto &Ctx = BB->getContext(); 3095 3096 IRBuilder<> Builder(Preheader->getTerminator()); 3097 assert(ICmpInst::isUnsigned(Pred) && "Not supported yet!"); 3098 if (LHS->getType() != RHS->getType()) { 3099 if (LHS->getType()->getIntegerBitWidth() < 3100 RHS->getType()->getIntegerBitWidth()) 3101 LHS = Builder.CreateZExt(LHS, RHS->getType(), LHS->getName() + ".wide"); 3102 else 3103 RHS = Builder.CreateZExt(RHS, LHS->getType(), RHS->getName() + ".wide"); 3104 } 3105 // Do not use builder here: CreateICmp may simplify this into a constant and 3106 // unswitching will break. Better optimize it away later. 3107 auto *InjectedCond = 3108 ICmpInst::Create(Instruction::ICmp, Pred, LHS, RHS, "injected.cond", 3109 Preheader->getTerminator()->getIterator()); 3110 3111 BasicBlock *CheckBlock = BasicBlock::Create(Ctx, BB->getName() + ".check", 3112 BB->getParent(), InLoopSucc); 3113 Builder.SetInsertPoint(TI); 3114 auto *InvariantBr = 3115 Builder.CreateCondBr(InjectedCond, InLoopSucc, CheckBlock); 3116 3117 Builder.SetInsertPoint(CheckBlock); 3118 Builder.CreateCondBr(TI->getCondition(), TI->getSuccessor(0), 3119 TI->getSuccessor(1)); 3120 TI->eraseFromParent(); 3121 3122 // Fixup phis. 3123 for (auto &I : *InLoopSucc) { 3124 auto *PN = dyn_cast<PHINode>(&I); 3125 if (!PN) 3126 break; 3127 auto *Inc = PN->getIncomingValueForBlock(BB); 3128 PN->addIncoming(Inc, CheckBlock); 3129 } 3130 OutOfLoopSucc->replacePhiUsesWith(BB, CheckBlock); 3131 3132 SmallVector<DominatorTree::UpdateType, 4> DTUpdates = { 3133 { DominatorTree::Insert, BB, CheckBlock }, 3134 { DominatorTree::Insert, CheckBlock, InLoopSucc }, 3135 { DominatorTree::Insert, CheckBlock, OutOfLoopSucc }, 3136 { DominatorTree::Delete, BB, OutOfLoopSucc } 3137 }; 3138 3139 DT.applyUpdates(DTUpdates); 3140 if (MSSAU) 3141 MSSAU->applyUpdates(DTUpdates, DT); 3142 L.addBasicBlockToLoop(CheckBlock, LI); 3143 3144 #ifndef NDEBUG 3145 DT.verify(); 3146 LI.verify(DT); 3147 if (MSSAU && VerifyMemorySSA) 3148 MSSAU->getMemorySSA()->verifyMemorySSA(); 3149 #endif 3150 3151 // TODO: In fact, cost of unswitching a new invariant candidate is *slightly* 3152 // higher because we have just inserted a new block. Need to think how to 3153 // adjust the cost of injected candidates when it was first computed. 3154 LLVM_DEBUG(dbgs() << "Injected a new loop-invariant branch " << *InvariantBr 3155 << " and considering it for unswitching."); 3156 ++NumInvariantConditionsInjected; 3157 return NonTrivialUnswitchCandidate(InvariantBr, { InjectedCond }, 3158 Candidate.Cost); 3159 } 3160 3161 /// Given chain of loop branch conditions looking like: 3162 /// br (Variant < Invariant1) 3163 /// br (Variant < Invariant2) 3164 /// br (Variant < Invariant3) 3165 /// ... 3166 /// collect set of invariant conditions on which we want to unswitch, which 3167 /// look like: 3168 /// Invariant1 <= Invariant2 3169 /// Invariant2 <= Invariant3 3170 /// ... 3171 /// Though they might not immediately exist in the IR, we can still inject them. 3172 static bool insertCandidatesWithPendingInjections( 3173 SmallVectorImpl<NonTrivialUnswitchCandidate> &UnswitchCandidates, Loop &L, 3174 ICmpInst::Predicate Pred, ArrayRef<CompareDesc> Compares, 3175 const DominatorTree &DT) { 3176 3177 assert(ICmpInst::isRelational(Pred)); 3178 assert(ICmpInst::isStrictPredicate(Pred)); 3179 if (Compares.size() < 2) 3180 return false; 3181 ICmpInst::Predicate NonStrictPred = ICmpInst::getNonStrictPredicate(Pred); 3182 for (auto Prev = Compares.begin(), Next = Compares.begin() + 1; 3183 Next != Compares.end(); ++Prev, ++Next) { 3184 Value *LHS = Next->Invariant; 3185 Value *RHS = Prev->Invariant; 3186 BasicBlock *InLoopSucc = Prev->InLoopSucc; 3187 InjectedInvariant ToInject(NonStrictPred, LHS, RHS, InLoopSucc); 3188 NonTrivialUnswitchCandidate Candidate(Prev->Term, { LHS, RHS }, 3189 std::nullopt, std::move(ToInject)); 3190 UnswitchCandidates.push_back(std::move(Candidate)); 3191 } 3192 return true; 3193 } 3194 3195 /// Collect unswitch candidates by invariant conditions that are not immediately 3196 /// present in the loop. However, they can be injected into the code if we 3197 /// decide it's profitable. 3198 /// An example of such conditions is following: 3199 /// 3200 /// for (...) { 3201 /// x = load ... 3202 /// if (! x <u C1) break; 3203 /// if (! x <u C2) break; 3204 /// <do something> 3205 /// } 3206 /// 3207 /// We can unswitch by condition "C1 <=u C2". If that is true, then "x <u C1 <= 3208 /// C2" automatically implies "x <u C2", so we can get rid of one of 3209 /// loop-variant checks in unswitched loop version. 3210 static bool collectUnswitchCandidatesWithInjections( 3211 SmallVectorImpl<NonTrivialUnswitchCandidate> &UnswitchCandidates, 3212 IVConditionInfo &PartialIVInfo, Instruction *&PartialIVCondBranch, Loop &L, 3213 const DominatorTree &DT, const LoopInfo &LI, AAResults &AA, 3214 const MemorySSAUpdater *MSSAU) { 3215 if (!InjectInvariantConditions) 3216 return false; 3217 3218 if (!DT.isReachableFromEntry(L.getHeader())) 3219 return false; 3220 auto *Latch = L.getLoopLatch(); 3221 // Need to have a single latch and a preheader. 3222 if (!Latch) 3223 return false; 3224 assert(L.getLoopPreheader() && "Must have a preheader!"); 3225 3226 DenseMap<Value *, SmallVector<CompareDesc, 4> > CandidatesULT; 3227 // Traverse the conditions that dominate latch (and therefore dominate each 3228 // other). 3229 for (auto *DTN = DT.getNode(Latch); L.contains(DTN->getBlock()); 3230 DTN = DTN->getIDom()) { 3231 ICmpInst::Predicate Pred; 3232 Value *LHS = nullptr, *RHS = nullptr; 3233 BasicBlock *IfTrue = nullptr, *IfFalse = nullptr; 3234 auto *BB = DTN->getBlock(); 3235 // Ignore inner loops. 3236 if (LI.getLoopFor(BB) != &L) 3237 continue; 3238 auto *Term = BB->getTerminator(); 3239 if (!match(Term, m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), 3240 m_BasicBlock(IfTrue), m_BasicBlock(IfFalse)))) 3241 continue; 3242 if (!LHS->getType()->isIntegerTy()) 3243 continue; 3244 canonicalizeForInvariantConditionInjection(Pred, LHS, RHS, IfTrue, IfFalse, 3245 L); 3246 if (!shouldTryInjectInvariantCondition(Pred, LHS, RHS, IfTrue, IfFalse, L)) 3247 continue; 3248 if (!shouldTryInjectBasingOnMetadata(cast<BranchInst>(Term), IfTrue)) 3249 continue; 3250 // Strip ZEXT for unsigned predicate. 3251 // TODO: once signed predicates are supported, also strip SEXT. 3252 CompareDesc Desc(cast<BranchInst>(Term), RHS, IfTrue); 3253 while (auto *Zext = dyn_cast<ZExtInst>(LHS)) 3254 LHS = Zext->getOperand(0); 3255 CandidatesULT[LHS].push_back(Desc); 3256 } 3257 3258 bool Found = false; 3259 for (auto &It : CandidatesULT) 3260 Found |= insertCandidatesWithPendingInjections( 3261 UnswitchCandidates, L, ICmpInst::ICMP_ULT, It.second, DT); 3262 return Found; 3263 } 3264 3265 static bool isSafeForNoNTrivialUnswitching(Loop &L, LoopInfo &LI) { 3266 if (!L.isSafeToClone()) 3267 return false; 3268 for (auto *BB : L.blocks()) 3269 for (auto &I : *BB) { 3270 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB)) 3271 return false; 3272 if (auto *CB = dyn_cast<CallBase>(&I)) { 3273 assert(!CB->cannotDuplicate() && "Checked by L.isSafeToClone()."); 3274 if (CB->isConvergent()) 3275 return false; 3276 } 3277 } 3278 3279 // Check if there are irreducible CFG cycles in this loop. If so, we cannot 3280 // easily unswitch non-trivial edges out of the loop. Doing so might turn the 3281 // irreducible control flow into reducible control flow and introduce new 3282 // loops "out of thin air". If we ever discover important use cases for doing 3283 // this, we can add support to loop unswitch, but it is a lot of complexity 3284 // for what seems little or no real world benefit. 3285 LoopBlocksRPO RPOT(&L); 3286 RPOT.perform(&LI); 3287 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI)) 3288 return false; 3289 3290 SmallVector<BasicBlock *, 4> ExitBlocks; 3291 L.getUniqueExitBlocks(ExitBlocks); 3292 // We cannot unswitch if exit blocks contain a cleanuppad/catchswitch 3293 // instruction as we don't know how to split those exit blocks. 3294 // FIXME: We should teach SplitBlock to handle this and remove this 3295 // restriction. 3296 for (auto *ExitBB : ExitBlocks) { 3297 auto *I = ExitBB->getFirstNonPHI(); 3298 if (isa<CleanupPadInst>(I) || isa<CatchSwitchInst>(I)) { 3299 LLVM_DEBUG(dbgs() << "Cannot unswitch because of cleanuppad/catchswitch " 3300 "in exit block\n"); 3301 return false; 3302 } 3303 } 3304 3305 return true; 3306 } 3307 3308 static NonTrivialUnswitchCandidate findBestNonTrivialUnswitchCandidate( 3309 ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates, const Loop &L, 3310 const DominatorTree &DT, const LoopInfo &LI, AssumptionCache &AC, 3311 const TargetTransformInfo &TTI, const IVConditionInfo &PartialIVInfo) { 3312 // Given that unswitching these terminators will require duplicating parts of 3313 // the loop, so we need to be able to model that cost. Compute the ephemeral 3314 // values and set up a data structure to hold per-BB costs. We cache each 3315 // block's cost so that we don't recompute this when considering different 3316 // subsets of the loop for duplication during unswitching. 3317 SmallPtrSet<const Value *, 4> EphValues; 3318 CodeMetrics::collectEphemeralValues(&L, &AC, EphValues); 3319 SmallDenseMap<BasicBlock *, InstructionCost, 4> BBCostMap; 3320 3321 // Compute the cost of each block, as well as the total loop cost. Also, bail 3322 // out if we see instructions which are incompatible with loop unswitching 3323 // (convergent, noduplicate, or cross-basic-block tokens). 3324 // FIXME: We might be able to safely handle some of these in non-duplicated 3325 // regions. 3326 TargetTransformInfo::TargetCostKind CostKind = 3327 L.getHeader()->getParent()->hasMinSize() 3328 ? TargetTransformInfo::TCK_CodeSize 3329 : TargetTransformInfo::TCK_SizeAndLatency; 3330 InstructionCost LoopCost = 0; 3331 for (auto *BB : L.blocks()) { 3332 InstructionCost Cost = 0; 3333 for (auto &I : *BB) { 3334 if (EphValues.count(&I)) 3335 continue; 3336 Cost += TTI.getInstructionCost(&I, CostKind); 3337 } 3338 assert(Cost >= 0 && "Must not have negative costs!"); 3339 LoopCost += Cost; 3340 assert(LoopCost >= 0 && "Must not have negative loop costs!"); 3341 BBCostMap[BB] = Cost; 3342 } 3343 LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n"); 3344 3345 // Now we find the best candidate by searching for the one with the following 3346 // properties in order: 3347 // 3348 // 1) An unswitching cost below the threshold 3349 // 2) The smallest number of duplicated unswitch candidates (to avoid 3350 // creating redundant subsequent unswitching) 3351 // 3) The smallest cost after unswitching. 3352 // 3353 // We prioritize reducing fanout of unswitch candidates provided the cost 3354 // remains below the threshold because this has a multiplicative effect. 3355 // 3356 // This requires memoizing each dominator subtree to avoid redundant work. 3357 // 3358 // FIXME: Need to actually do the number of candidates part above. 3359 SmallDenseMap<DomTreeNode *, InstructionCost, 4> DTCostMap; 3360 // Given a terminator which might be unswitched, computes the non-duplicated 3361 // cost for that terminator. 3362 auto ComputeUnswitchedCost = [&](Instruction &TI, 3363 bool FullUnswitch) -> InstructionCost { 3364 // Unswitching selects unswitches the entire loop. 3365 if (isa<SelectInst>(TI)) 3366 return LoopCost; 3367 3368 BasicBlock &BB = *TI.getParent(); 3369 SmallPtrSet<BasicBlock *, 4> Visited; 3370 3371 InstructionCost Cost = 0; 3372 for (BasicBlock *SuccBB : successors(&BB)) { 3373 // Don't count successors more than once. 3374 if (!Visited.insert(SuccBB).second) 3375 continue; 3376 3377 // If this is a partial unswitch candidate, then it must be a conditional 3378 // branch with a condition of either `or`, `and`, their corresponding 3379 // select forms or partially invariant instructions. In that case, one of 3380 // the successors is necessarily duplicated, so don't even try to remove 3381 // its cost. 3382 if (!FullUnswitch) { 3383 auto &BI = cast<BranchInst>(TI); 3384 Value *Cond = skipTrivialSelect(BI.getCondition()); 3385 if (match(Cond, m_LogicalAnd())) { 3386 if (SuccBB == BI.getSuccessor(1)) 3387 continue; 3388 } else if (match(Cond, m_LogicalOr())) { 3389 if (SuccBB == BI.getSuccessor(0)) 3390 continue; 3391 } else if ((PartialIVInfo.KnownValue->isOneValue() && 3392 SuccBB == BI.getSuccessor(0)) || 3393 (!PartialIVInfo.KnownValue->isOneValue() && 3394 SuccBB == BI.getSuccessor(1))) 3395 continue; 3396 } 3397 3398 // This successor's domtree will not need to be duplicated after 3399 // unswitching if the edge to the successor dominates it (and thus the 3400 // entire tree). This essentially means there is no other path into this 3401 // subtree and so it will end up live in only one clone of the loop. 3402 if (SuccBB->getUniquePredecessor() || 3403 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) { 3404 return PredBB == &BB || DT.dominates(SuccBB, PredBB); 3405 })) { 3406 Cost += computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap); 3407 assert(Cost <= LoopCost && 3408 "Non-duplicated cost should never exceed total loop cost!"); 3409 } 3410 } 3411 3412 // Now scale the cost by the number of unique successors minus one. We 3413 // subtract one because there is already at least one copy of the entire 3414 // loop. This is computing the new cost of unswitching a condition. 3415 // Note that guards always have 2 unique successors that are implicit and 3416 // will be materialized if we decide to unswitch it. 3417 int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size(); 3418 assert(SuccessorsCount > 1 && 3419 "Cannot unswitch a condition without multiple distinct successors!"); 3420 return (LoopCost - Cost) * (SuccessorsCount - 1); 3421 }; 3422 3423 std::optional<NonTrivialUnswitchCandidate> Best; 3424 for (auto &Candidate : UnswitchCandidates) { 3425 Instruction &TI = *Candidate.TI; 3426 ArrayRef<Value *> Invariants = Candidate.Invariants; 3427 BranchInst *BI = dyn_cast<BranchInst>(&TI); 3428 bool FullUnswitch = 3429 !BI || Candidate.hasPendingInjection() || 3430 (Invariants.size() == 1 && 3431 Invariants[0] == skipTrivialSelect(BI->getCondition())); 3432 InstructionCost CandidateCost = ComputeUnswitchedCost(TI, FullUnswitch); 3433 // Calculate cost multiplier which is a tool to limit potentially 3434 // exponential behavior of loop-unswitch. 3435 if (EnableUnswitchCostMultiplier) { 3436 int CostMultiplier = 3437 CalculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates); 3438 assert( 3439 (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) && 3440 "cost multiplier needs to be in the range of 1..UnswitchThreshold"); 3441 CandidateCost *= CostMultiplier; 3442 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost 3443 << " (multiplier: " << CostMultiplier << ")" 3444 << " for unswitch candidate: " << TI << "\n"); 3445 } else { 3446 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost 3447 << " for unswitch candidate: " << TI << "\n"); 3448 } 3449 3450 if (!Best || CandidateCost < Best->Cost) { 3451 Best = Candidate; 3452 Best->Cost = CandidateCost; 3453 } 3454 } 3455 assert(Best && "Must be!"); 3456 return *Best; 3457 } 3458 3459 // Insert a freeze on an unswitched branch if all is true: 3460 // 1. freeze-loop-unswitch-cond option is true 3461 // 2. The branch may not execute in the loop pre-transformation. If a branch may 3462 // not execute and could cause UB, it would always cause UB if it is hoisted outside 3463 // of the loop. Insert a freeze to prevent this case. 3464 // 3. The branch condition may be poison or undef 3465 static bool shouldInsertFreeze(Loop &L, Instruction &TI, DominatorTree &DT, 3466 AssumptionCache &AC) { 3467 assert(isa<BranchInst>(TI) || isa<SwitchInst>(TI)); 3468 if (!FreezeLoopUnswitchCond) 3469 return false; 3470 3471 ICFLoopSafetyInfo SafetyInfo; 3472 SafetyInfo.computeLoopSafetyInfo(&L); 3473 if (SafetyInfo.isGuaranteedToExecute(TI, &DT, &L)) 3474 return false; 3475 3476 Value *Cond; 3477 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) 3478 Cond = skipTrivialSelect(BI->getCondition()); 3479 else 3480 Cond = skipTrivialSelect(cast<SwitchInst>(&TI)->getCondition()); 3481 return !isGuaranteedNotToBeUndefOrPoison( 3482 Cond, &AC, L.getLoopPreheader()->getTerminator(), &DT); 3483 } 3484 3485 static bool unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI, 3486 AssumptionCache &AC, AAResults &AA, 3487 TargetTransformInfo &TTI, ScalarEvolution *SE, 3488 MemorySSAUpdater *MSSAU, 3489 LPMUpdater &LoopUpdater) { 3490 // Collect all invariant conditions within this loop (as opposed to an inner 3491 // loop which would be handled when visiting that inner loop). 3492 SmallVector<NonTrivialUnswitchCandidate, 4> UnswitchCandidates; 3493 IVConditionInfo PartialIVInfo; 3494 Instruction *PartialIVCondBranch = nullptr; 3495 collectUnswitchCandidates(UnswitchCandidates, PartialIVInfo, 3496 PartialIVCondBranch, L, LI, AA, MSSAU); 3497 if (!findOptionMDForLoop(&L, "llvm.loop.unswitch.injection.disable")) 3498 collectUnswitchCandidatesWithInjections(UnswitchCandidates, PartialIVInfo, 3499 PartialIVCondBranch, L, DT, LI, AA, 3500 MSSAU); 3501 // If we didn't find any candidates, we're done. 3502 if (UnswitchCandidates.empty()) 3503 return false; 3504 3505 LLVM_DEBUG( 3506 dbgs() << "Considering " << UnswitchCandidates.size() 3507 << " non-trivial loop invariant conditions for unswitching.\n"); 3508 3509 NonTrivialUnswitchCandidate Best = findBestNonTrivialUnswitchCandidate( 3510 UnswitchCandidates, L, DT, LI, AC, TTI, PartialIVInfo); 3511 3512 assert(Best.TI && "Failed to find loop unswitch candidate"); 3513 assert(Best.Cost && "Failed to compute cost"); 3514 3515 if (*Best.Cost >= UnswitchThreshold) { 3516 LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: " << *Best.Cost 3517 << "\n"); 3518 return false; 3519 } 3520 3521 bool InjectedCondition = false; 3522 if (Best.hasPendingInjection()) { 3523 Best = injectPendingInvariantConditions(Best, L, DT, LI, AC, MSSAU); 3524 InjectedCondition = true; 3525 } 3526 assert(!Best.hasPendingInjection() && 3527 "All injections should have been done by now!"); 3528 3529 if (Best.TI != PartialIVCondBranch) 3530 PartialIVInfo.InstToDuplicate.clear(); 3531 3532 bool InsertFreeze; 3533 if (auto *SI = dyn_cast<SelectInst>(Best.TI)) { 3534 // If the best candidate is a select, turn it into a branch. Select 3535 // instructions with a poison conditional do not propagate poison, but 3536 // branching on poison causes UB. Insert a freeze on the select 3537 // conditional to prevent UB after turning the select into a branch. 3538 InsertFreeze = !isGuaranteedNotToBeUndefOrPoison( 3539 SI->getCondition(), &AC, L.getLoopPreheader()->getTerminator(), &DT); 3540 Best.TI = turnSelectIntoBranch(SI, DT, LI, MSSAU, &AC); 3541 } else { 3542 // If the best candidate is a guard, turn it into a branch. 3543 if (isGuard(Best.TI)) 3544 Best.TI = 3545 turnGuardIntoBranch(cast<IntrinsicInst>(Best.TI), L, DT, LI, MSSAU); 3546 InsertFreeze = shouldInsertFreeze(L, *Best.TI, DT, AC); 3547 } 3548 3549 LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = " << Best.Cost 3550 << ") terminator: " << *Best.TI << "\n"); 3551 unswitchNontrivialInvariants(L, *Best.TI, Best.Invariants, PartialIVInfo, DT, 3552 LI, AC, SE, MSSAU, LoopUpdater, InsertFreeze, 3553 InjectedCondition); 3554 return true; 3555 } 3556 3557 /// Unswitch control flow predicated on loop invariant conditions. 3558 /// 3559 /// This first hoists all branches or switches which are trivial (IE, do not 3560 /// require duplicating any part of the loop) out of the loop body. It then 3561 /// looks at other loop invariant control flows and tries to unswitch those as 3562 /// well by cloning the loop if the result is small enough. 3563 /// 3564 /// The `DT`, `LI`, `AC`, `AA`, `TTI` parameters are required analyses that are 3565 /// also updated based on the unswitch. The `MSSA` analysis is also updated if 3566 /// valid (i.e. its use is enabled). 3567 /// 3568 /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is 3569 /// true, we will attempt to do non-trivial unswitching as well as trivial 3570 /// unswitching. 3571 /// 3572 /// The `postUnswitch` function will be run after unswitching is complete 3573 /// with information on whether or not the provided loop remains a loop and 3574 /// a list of new sibling loops created. 3575 /// 3576 /// If `SE` is non-null, we will update that analysis based on the unswitching 3577 /// done. 3578 static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, 3579 AssumptionCache &AC, AAResults &AA, 3580 TargetTransformInfo &TTI, bool Trivial, 3581 bool NonTrivial, ScalarEvolution *SE, 3582 MemorySSAUpdater *MSSAU, ProfileSummaryInfo *PSI, 3583 BlockFrequencyInfo *BFI, LPMUpdater &LoopUpdater) { 3584 assert(L.isRecursivelyLCSSAForm(DT, LI) && 3585 "Loops must be in LCSSA form before unswitching."); 3586 3587 // Must be in loop simplified form: we need a preheader and dedicated exits. 3588 if (!L.isLoopSimplifyForm()) 3589 return false; 3590 3591 // Try trivial unswitch first before loop over other basic blocks in the loop. 3592 if (Trivial && unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) { 3593 // If we unswitched successfully we will want to clean up the loop before 3594 // processing it further so just mark it as unswitched and return. 3595 postUnswitch(L, LoopUpdater, L.getName(), 3596 /*CurrentLoopValid*/ true, /*PartiallyInvariant*/ false, 3597 /*InjectedCondition*/ false, {}); 3598 return true; 3599 } 3600 3601 const Function *F = L.getHeader()->getParent(); 3602 3603 // Check whether we should continue with non-trivial conditions. 3604 // EnableNonTrivialUnswitch: Global variable that forces non-trivial 3605 // unswitching for testing and debugging. 3606 // NonTrivial: Parameter that enables non-trivial unswitching for this 3607 // invocation of the transform. But this should be allowed only 3608 // for targets without branch divergence. 3609 // 3610 // FIXME: If divergence analysis becomes available to a loop 3611 // transform, we should allow unswitching for non-trivial uniform 3612 // branches even on targets that have divergence. 3613 // https://bugs.llvm.org/show_bug.cgi?id=48819 3614 bool ContinueWithNonTrivial = 3615 EnableNonTrivialUnswitch || (NonTrivial && !TTI.hasBranchDivergence(F)); 3616 if (!ContinueWithNonTrivial) 3617 return false; 3618 3619 // Skip non-trivial unswitching for optsize functions. 3620 if (F->hasOptSize()) 3621 return false; 3622 3623 // Returns true if Loop L's loop nest is cold, i.e. if the headers of L, 3624 // of the loops L is nested in, and of the loops nested in L are all cold. 3625 auto IsLoopNestCold = [&](const Loop *L) { 3626 // Check L and all of its parent loops. 3627 auto *Parent = L; 3628 while (Parent) { 3629 if (!PSI->isColdBlock(Parent->getHeader(), BFI)) 3630 return false; 3631 Parent = Parent->getParentLoop(); 3632 } 3633 // Next check all loops nested within L. 3634 SmallVector<const Loop *, 4> Worklist; 3635 Worklist.insert(Worklist.end(), L->getSubLoops().begin(), 3636 L->getSubLoops().end()); 3637 while (!Worklist.empty()) { 3638 auto *CurLoop = Worklist.pop_back_val(); 3639 if (!PSI->isColdBlock(CurLoop->getHeader(), BFI)) 3640 return false; 3641 Worklist.insert(Worklist.end(), CurLoop->getSubLoops().begin(), 3642 CurLoop->getSubLoops().end()); 3643 } 3644 return true; 3645 }; 3646 3647 // Skip cold loops in cold loop nests, as unswitching them brings little 3648 // benefit but increases the code size 3649 if (PSI && PSI->hasProfileSummary() && BFI && IsLoopNestCold(&L)) { 3650 LLVM_DEBUG(dbgs() << " Skip cold loop: " << L << "\n"); 3651 return false; 3652 } 3653 3654 // Perform legality checks. 3655 if (!isSafeForNoNTrivialUnswitching(L, LI)) 3656 return false; 3657 3658 // For non-trivial unswitching, because it often creates new loops, we rely on 3659 // the pass manager to iterate on the loops rather than trying to immediately 3660 // reach a fixed point. There is no substantial advantage to iterating 3661 // internally, and if any of the new loops are simplified enough to contain 3662 // trivial unswitching we want to prefer those. 3663 3664 // Try to unswitch the best invariant condition. We prefer this full unswitch to 3665 // a partial unswitch when possible below the threshold. 3666 if (unswitchBestCondition(L, DT, LI, AC, AA, TTI, SE, MSSAU, LoopUpdater)) 3667 return true; 3668 3669 // No other opportunities to unswitch. 3670 return false; 3671 } 3672 3673 PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM, 3674 LoopStandardAnalysisResults &AR, 3675 LPMUpdater &U) { 3676 Function &F = *L.getHeader()->getParent(); 3677 (void)F; 3678 ProfileSummaryInfo *PSI = nullptr; 3679 if (auto OuterProxy = 3680 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR) 3681 .getCachedResult<ModuleAnalysisManagerFunctionProxy>(F)) 3682 PSI = OuterProxy->getCachedResult<ProfileSummaryAnalysis>(*F.getParent()); 3683 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L 3684 << "\n"); 3685 3686 std::optional<MemorySSAUpdater> MSSAU; 3687 if (AR.MSSA) { 3688 MSSAU = MemorySSAUpdater(AR.MSSA); 3689 if (VerifyMemorySSA) 3690 AR.MSSA->verifyMemorySSA(); 3691 } 3692 if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.AA, AR.TTI, Trivial, NonTrivial, 3693 &AR.SE, MSSAU ? &*MSSAU : nullptr, PSI, AR.BFI, U)) 3694 return PreservedAnalyses::all(); 3695 3696 if (AR.MSSA && VerifyMemorySSA) 3697 AR.MSSA->verifyMemorySSA(); 3698 3699 // Historically this pass has had issues with the dominator tree so verify it 3700 // in asserts builds. 3701 assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast)); 3702 3703 auto PA = getLoopPassPreservedAnalyses(); 3704 if (AR.MSSA) 3705 PA.preserve<MemorySSAAnalysis>(); 3706 return PA; 3707 } 3708 3709 void SimpleLoopUnswitchPass::printPipeline( 3710 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) { 3711 static_cast<PassInfoMixin<SimpleLoopUnswitchPass> *>(this)->printPipeline( 3712 OS, MapClassName2PassName); 3713 3714 OS << '<'; 3715 OS << (NonTrivial ? "" : "no-") << "nontrivial;"; 3716 OS << (Trivial ? "" : "no-") << "trivial"; 3717 OS << '>'; 3718 } 3719