1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass implements a simple loop unroller. It works best when loops have 11 // been canonicalized by the -indvars pass, allowing it to determine the trip 12 // counts of loops easily. 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/Analysis/AssumptionCache.h" 18 #include "llvm/Analysis/CodeMetrics.h" 19 #include "llvm/Analysis/GlobalsModRef.h" 20 #include "llvm/Analysis/InstructionSimplify.h" 21 #include "llvm/Analysis/LoopPass.h" 22 #include "llvm/Analysis/LoopUnrollAnalyzer.h" 23 #include "llvm/Analysis/OptimizationDiagnosticInfo.h" 24 #include "llvm/Analysis/ProfileSummaryInfo.h" 25 #include "llvm/Analysis/ScalarEvolution.h" 26 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/InstVisitor.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Transforms/Scalar.h" 36 #include "llvm/Transforms/Scalar/LoopPassManager.h" 37 #include "llvm/Transforms/Utils/LoopUtils.h" 38 #include "llvm/Transforms/Utils/UnrollLoop.h" 39 #include <climits> 40 #include <utility> 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "loop-unroll" 45 46 static cl::opt<unsigned> 47 UnrollThreshold("unroll-threshold", cl::Hidden, 48 cl::desc("The cost threshold for loop unrolling")); 49 50 static cl::opt<unsigned> UnrollPartialThreshold( 51 "unroll-partial-threshold", cl::Hidden, 52 cl::desc("The cost threshold for partial loop unrolling")); 53 54 static cl::opt<unsigned> UnrollMaxPercentThresholdBoost( 55 "unroll-max-percent-threshold-boost", cl::init(400), cl::Hidden, 56 cl::desc("The maximum 'boost' (represented as a percentage >= 100) applied " 57 "to the threshold when aggressively unrolling a loop due to the " 58 "dynamic cost savings. If completely unrolling a loop will reduce " 59 "the total runtime from X to Y, we boost the loop unroll " 60 "threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, " 61 "X/Y). This limit avoids excessive code bloat.")); 62 63 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze( 64 "unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden, 65 cl::desc("Don't allow loop unrolling to simulate more than this number of" 66 "iterations when checking full unroll profitability")); 67 68 static cl::opt<unsigned> UnrollCount( 69 "unroll-count", cl::Hidden, 70 cl::desc("Use this unroll count for all loops including those with " 71 "unroll_count pragma values, for testing purposes")); 72 73 static cl::opt<unsigned> UnrollMaxCount( 74 "unroll-max-count", cl::Hidden, 75 cl::desc("Set the max unroll count for partial and runtime unrolling, for" 76 "testing purposes")); 77 78 static cl::opt<unsigned> UnrollFullMaxCount( 79 "unroll-full-max-count", cl::Hidden, 80 cl::desc( 81 "Set the max unroll count for full unrolling, for testing purposes")); 82 83 static cl::opt<bool> 84 UnrollAllowPartial("unroll-allow-partial", cl::Hidden, 85 cl::desc("Allows loops to be partially unrolled until " 86 "-unroll-threshold loop size is reached.")); 87 88 static cl::opt<bool> UnrollAllowRemainder( 89 "unroll-allow-remainder", cl::Hidden, 90 cl::desc("Allow generation of a loop remainder (extra iterations) " 91 "when unrolling a loop.")); 92 93 static cl::opt<bool> 94 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden, 95 cl::desc("Unroll loops with run-time trip counts")); 96 97 static cl::opt<unsigned> UnrollMaxUpperBound( 98 "unroll-max-upperbound", cl::init(8), cl::Hidden, 99 cl::desc( 100 "The max of trip count upper bound that is considered in unrolling")); 101 102 static cl::opt<unsigned> PragmaUnrollThreshold( 103 "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden, 104 cl::desc("Unrolled size limit for loops with an unroll(full) or " 105 "unroll_count pragma.")); 106 107 static cl::opt<unsigned> FlatLoopTripCountThreshold( 108 "flat-loop-tripcount-threshold", cl::init(5), cl::Hidden, 109 cl::desc("If the runtime tripcount for the loop is lower than the " 110 "threshold, the loop is considered as flat and will be less " 111 "aggressively unrolled.")); 112 113 static cl::opt<bool> 114 UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, 115 cl::desc("Allows loops to be peeled when the dynamic " 116 "trip count is known to be low.")); 117 118 static cl::opt<bool> UnrollUnrollRemainder( 119 "unroll-remainder", cl::Hidden, 120 cl::desc("Allow the loop remainder to be unrolled.")); 121 122 // This option isn't ever intended to be enabled, it serves to allow 123 // experiments to check the assumptions about when this kind of revisit is 124 // necessary. 125 static cl::opt<bool> UnrollRevisitChildLoops( 126 "unroll-revisit-child-loops", cl::Hidden, 127 cl::desc("Enqueue and re-visit child loops in the loop PM after unrolling. " 128 "This shouldn't typically be needed as child loops (or their " 129 "clones) were already visited.")); 130 131 /// A magic value for use with the Threshold parameter to indicate 132 /// that the loop unroll should be performed regardless of how much 133 /// code expansion would result. 134 static const unsigned NoThreshold = UINT_MAX; 135 136 /// Gather the various unrolling parameters based on the defaults, compiler 137 /// flags, TTI overrides and user specified parameters. 138 static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences( 139 Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, int OptLevel, 140 Optional<unsigned> UserThreshold, Optional<unsigned> UserCount, 141 Optional<bool> UserAllowPartial, Optional<bool> UserRuntime, 142 Optional<bool> UserUpperBound, Optional<bool> UserAllowPeeling) { 143 TargetTransformInfo::UnrollingPreferences UP; 144 145 // Set up the defaults 146 UP.Threshold = OptLevel > 2 ? 300 : 150; 147 UP.MaxPercentThresholdBoost = 400; 148 UP.OptSizeThreshold = 0; 149 UP.PartialThreshold = 150; 150 UP.PartialOptSizeThreshold = 0; 151 UP.Count = 0; 152 UP.PeelCount = 0; 153 UP.DefaultUnrollRuntimeCount = 8; 154 UP.MaxCount = UINT_MAX; 155 UP.FullUnrollMaxCount = UINT_MAX; 156 UP.BEInsns = 2; 157 UP.Partial = false; 158 UP.Runtime = false; 159 UP.AllowRemainder = true; 160 UP.UnrollRemainder = false; 161 UP.AllowExpensiveTripCount = false; 162 UP.Force = false; 163 UP.UpperBound = false; 164 UP.AllowPeeling = true; 165 166 // Override with any target specific settings 167 TTI.getUnrollingPreferences(L, SE, UP); 168 169 // Apply size attributes 170 if (L->getHeader()->getParent()->optForSize()) { 171 UP.Threshold = UP.OptSizeThreshold; 172 UP.PartialThreshold = UP.PartialOptSizeThreshold; 173 } 174 175 // Apply any user values specified by cl::opt 176 if (UnrollThreshold.getNumOccurrences() > 0) 177 UP.Threshold = UnrollThreshold; 178 if (UnrollPartialThreshold.getNumOccurrences() > 0) 179 UP.PartialThreshold = UnrollPartialThreshold; 180 if (UnrollMaxPercentThresholdBoost.getNumOccurrences() > 0) 181 UP.MaxPercentThresholdBoost = UnrollMaxPercentThresholdBoost; 182 if (UnrollMaxCount.getNumOccurrences() > 0) 183 UP.MaxCount = UnrollMaxCount; 184 if (UnrollFullMaxCount.getNumOccurrences() > 0) 185 UP.FullUnrollMaxCount = UnrollFullMaxCount; 186 if (UnrollAllowPartial.getNumOccurrences() > 0) 187 UP.Partial = UnrollAllowPartial; 188 if (UnrollAllowRemainder.getNumOccurrences() > 0) 189 UP.AllowRemainder = UnrollAllowRemainder; 190 if (UnrollRuntime.getNumOccurrences() > 0) 191 UP.Runtime = UnrollRuntime; 192 if (UnrollMaxUpperBound == 0) 193 UP.UpperBound = false; 194 if (UnrollAllowPeeling.getNumOccurrences() > 0) 195 UP.AllowPeeling = UnrollAllowPeeling; 196 if (UnrollUnrollRemainder.getNumOccurrences() > 0) 197 UP.UnrollRemainder = UnrollUnrollRemainder; 198 199 // Apply user values provided by argument 200 if (UserThreshold.hasValue()) { 201 UP.Threshold = *UserThreshold; 202 UP.PartialThreshold = *UserThreshold; 203 } 204 if (UserCount.hasValue()) 205 UP.Count = *UserCount; 206 if (UserAllowPartial.hasValue()) 207 UP.Partial = *UserAllowPartial; 208 if (UserRuntime.hasValue()) 209 UP.Runtime = *UserRuntime; 210 if (UserUpperBound.hasValue()) 211 UP.UpperBound = *UserUpperBound; 212 if (UserAllowPeeling.hasValue()) 213 UP.AllowPeeling = *UserAllowPeeling; 214 215 return UP; 216 } 217 218 namespace { 219 /// A struct to densely store the state of an instruction after unrolling at 220 /// each iteration. 221 /// 222 /// This is designed to work like a tuple of <Instruction *, int> for the 223 /// purposes of hashing and lookup, but to be able to associate two boolean 224 /// states with each key. 225 struct UnrolledInstState { 226 Instruction *I; 227 int Iteration : 30; 228 unsigned IsFree : 1; 229 unsigned IsCounted : 1; 230 }; 231 232 /// Hashing and equality testing for a set of the instruction states. 233 struct UnrolledInstStateKeyInfo { 234 typedef DenseMapInfo<Instruction *> PtrInfo; 235 typedef DenseMapInfo<std::pair<Instruction *, int>> PairInfo; 236 static inline UnrolledInstState getEmptyKey() { 237 return {PtrInfo::getEmptyKey(), 0, 0, 0}; 238 } 239 static inline UnrolledInstState getTombstoneKey() { 240 return {PtrInfo::getTombstoneKey(), 0, 0, 0}; 241 } 242 static inline unsigned getHashValue(const UnrolledInstState &S) { 243 return PairInfo::getHashValue({S.I, S.Iteration}); 244 } 245 static inline bool isEqual(const UnrolledInstState &LHS, 246 const UnrolledInstState &RHS) { 247 return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration}); 248 } 249 }; 250 } 251 252 namespace { 253 struct EstimatedUnrollCost { 254 /// \brief The estimated cost after unrolling. 255 unsigned UnrolledCost; 256 257 /// \brief The estimated dynamic cost of executing the instructions in the 258 /// rolled form. 259 unsigned RolledDynamicCost; 260 }; 261 } 262 263 /// \brief Figure out if the loop is worth full unrolling. 264 /// 265 /// Complete loop unrolling can make some loads constant, and we need to know 266 /// if that would expose any further optimization opportunities. This routine 267 /// estimates this optimization. It computes cost of unrolled loop 268 /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By 269 /// dynamic cost we mean that we won't count costs of blocks that are known not 270 /// to be executed (i.e. if we have a branch in the loop and we know that at the 271 /// given iteration its condition would be resolved to true, we won't add up the 272 /// cost of the 'false'-block). 273 /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If 274 /// the analysis failed (no benefits expected from the unrolling, or the loop is 275 /// too big to analyze), the returned value is None. 276 static Optional<EstimatedUnrollCost> 277 analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT, 278 ScalarEvolution &SE, const TargetTransformInfo &TTI, 279 unsigned MaxUnrolledLoopSize) { 280 // We want to be able to scale offsets by the trip count and add more offsets 281 // to them without checking for overflows, and we already don't want to 282 // analyze *massive* trip counts, so we force the max to be reasonably small. 283 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) && 284 "The unroll iterations max is too large!"); 285 286 // Only analyze inner loops. We can't properly estimate cost of nested loops 287 // and we won't visit inner loops again anyway. 288 if (!L->empty()) 289 return None; 290 291 // Don't simulate loops with a big or unknown tripcount 292 if (!UnrollMaxIterationsCountToAnalyze || !TripCount || 293 TripCount > UnrollMaxIterationsCountToAnalyze) 294 return None; 295 296 SmallSetVector<BasicBlock *, 16> BBWorklist; 297 SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist; 298 DenseMap<Value *, Constant *> SimplifiedValues; 299 SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues; 300 301 // The estimated cost of the unrolled form of the loop. We try to estimate 302 // this by simplifying as much as we can while computing the estimate. 303 unsigned UnrolledCost = 0; 304 305 // We also track the estimated dynamic (that is, actually executed) cost in 306 // the rolled form. This helps identify cases when the savings from unrolling 307 // aren't just exposing dead control flows, but actual reduced dynamic 308 // instructions due to the simplifications which we expect to occur after 309 // unrolling. 310 unsigned RolledDynamicCost = 0; 311 312 // We track the simplification of each instruction in each iteration. We use 313 // this to recursively merge costs into the unrolled cost on-demand so that 314 // we don't count the cost of any dead code. This is essentially a map from 315 // <instruction, int> to <bool, bool>, but stored as a densely packed struct. 316 DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap; 317 318 // A small worklist used to accumulate cost of instructions from each 319 // observable and reached root in the loop. 320 SmallVector<Instruction *, 16> CostWorklist; 321 322 // PHI-used worklist used between iterations while accumulating cost. 323 SmallVector<Instruction *, 4> PHIUsedList; 324 325 // Helper function to accumulate cost for instructions in the loop. 326 auto AddCostRecursively = [&](Instruction &RootI, int Iteration) { 327 assert(Iteration >= 0 && "Cannot have a negative iteration!"); 328 assert(CostWorklist.empty() && "Must start with an empty cost list"); 329 assert(PHIUsedList.empty() && "Must start with an empty phi used list"); 330 CostWorklist.push_back(&RootI); 331 for (;; --Iteration) { 332 do { 333 Instruction *I = CostWorklist.pop_back_val(); 334 335 // InstCostMap only uses I and Iteration as a key, the other two values 336 // don't matter here. 337 auto CostIter = InstCostMap.find({I, Iteration, 0, 0}); 338 if (CostIter == InstCostMap.end()) 339 // If an input to a PHI node comes from a dead path through the loop 340 // we may have no cost data for it here. What that actually means is 341 // that it is free. 342 continue; 343 auto &Cost = *CostIter; 344 if (Cost.IsCounted) 345 // Already counted this instruction. 346 continue; 347 348 // Mark that we are counting the cost of this instruction now. 349 Cost.IsCounted = true; 350 351 // If this is a PHI node in the loop header, just add it to the PHI set. 352 if (auto *PhiI = dyn_cast<PHINode>(I)) 353 if (PhiI->getParent() == L->getHeader()) { 354 assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they " 355 "inherently simplify during unrolling."); 356 if (Iteration == 0) 357 continue; 358 359 // Push the incoming value from the backedge into the PHI used list 360 // if it is an in-loop instruction. We'll use this to populate the 361 // cost worklist for the next iteration (as we count backwards). 362 if (auto *OpI = dyn_cast<Instruction>( 363 PhiI->getIncomingValueForBlock(L->getLoopLatch()))) 364 if (L->contains(OpI)) 365 PHIUsedList.push_back(OpI); 366 continue; 367 } 368 369 // First accumulate the cost of this instruction. 370 if (!Cost.IsFree) { 371 UnrolledCost += TTI.getUserCost(I); 372 DEBUG(dbgs() << "Adding cost of instruction (iteration " << Iteration 373 << "): "); 374 DEBUG(I->dump()); 375 } 376 377 // We must count the cost of every operand which is not free, 378 // recursively. If we reach a loop PHI node, simply add it to the set 379 // to be considered on the next iteration (backwards!). 380 for (Value *Op : I->operands()) { 381 // Check whether this operand is free due to being a constant or 382 // outside the loop. 383 auto *OpI = dyn_cast<Instruction>(Op); 384 if (!OpI || !L->contains(OpI)) 385 continue; 386 387 // Otherwise accumulate its cost. 388 CostWorklist.push_back(OpI); 389 } 390 } while (!CostWorklist.empty()); 391 392 if (PHIUsedList.empty()) 393 // We've exhausted the search. 394 break; 395 396 assert(Iteration > 0 && 397 "Cannot track PHI-used values past the first iteration!"); 398 CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end()); 399 PHIUsedList.clear(); 400 } 401 }; 402 403 // Ensure that we don't violate the loop structure invariants relied on by 404 // this analysis. 405 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first."); 406 assert(L->isLCSSAForm(DT) && 407 "Must have loops in LCSSA form to track live-out values."); 408 409 DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n"); 410 411 // Simulate execution of each iteration of the loop counting instructions, 412 // which would be simplified. 413 // Since the same load will take different values on different iterations, 414 // we literally have to go through all loop's iterations. 415 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) { 416 DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n"); 417 418 // Prepare for the iteration by collecting any simplified entry or backedge 419 // inputs. 420 for (Instruction &I : *L->getHeader()) { 421 auto *PHI = dyn_cast<PHINode>(&I); 422 if (!PHI) 423 break; 424 425 // The loop header PHI nodes must have exactly two input: one from the 426 // loop preheader and one from the loop latch. 427 assert( 428 PHI->getNumIncomingValues() == 2 && 429 "Must have an incoming value only for the preheader and the latch."); 430 431 Value *V = PHI->getIncomingValueForBlock( 432 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch()); 433 Constant *C = dyn_cast<Constant>(V); 434 if (Iteration != 0 && !C) 435 C = SimplifiedValues.lookup(V); 436 if (C) 437 SimplifiedInputValues.push_back({PHI, C}); 438 } 439 440 // Now clear and re-populate the map for the next iteration. 441 SimplifiedValues.clear(); 442 while (!SimplifiedInputValues.empty()) 443 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val()); 444 445 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L); 446 447 BBWorklist.clear(); 448 BBWorklist.insert(L->getHeader()); 449 // Note that we *must not* cache the size, this loop grows the worklist. 450 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 451 BasicBlock *BB = BBWorklist[Idx]; 452 453 // Visit all instructions in the given basic block and try to simplify 454 // it. We don't change the actual IR, just count optimization 455 // opportunities. 456 for (Instruction &I : *BB) { 457 if (isa<DbgInfoIntrinsic>(I)) 458 continue; 459 460 // Track this instruction's expected baseline cost when executing the 461 // rolled loop form. 462 RolledDynamicCost += TTI.getUserCost(&I); 463 464 // Visit the instruction to analyze its loop cost after unrolling, 465 // and if the visitor returns true, mark the instruction as free after 466 // unrolling and continue. 467 bool IsFree = Analyzer.visit(I); 468 bool Inserted = InstCostMap.insert({&I, (int)Iteration, 469 (unsigned)IsFree, 470 /*IsCounted*/ false}).second; 471 (void)Inserted; 472 assert(Inserted && "Cannot have a state for an unvisited instruction!"); 473 474 if (IsFree) 475 continue; 476 477 // Can't properly model a cost of a call. 478 // FIXME: With a proper cost model we should be able to do it. 479 if(isa<CallInst>(&I)) 480 return None; 481 482 // If the instruction might have a side-effect recursively account for 483 // the cost of it and all the instructions leading up to it. 484 if (I.mayHaveSideEffects()) 485 AddCostRecursively(I, Iteration); 486 487 // If unrolled body turns out to be too big, bail out. 488 if (UnrolledCost > MaxUnrolledLoopSize) { 489 DEBUG(dbgs() << " Exceeded threshold.. exiting.\n" 490 << " UnrolledCost: " << UnrolledCost 491 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize 492 << "\n"); 493 return None; 494 } 495 } 496 497 TerminatorInst *TI = BB->getTerminator(); 498 499 // Add in the live successors by first checking whether we have terminator 500 // that may be simplified based on the values simplified by this call. 501 BasicBlock *KnownSucc = nullptr; 502 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 503 if (BI->isConditional()) { 504 if (Constant *SimpleCond = 505 SimplifiedValues.lookup(BI->getCondition())) { 506 // Just take the first successor if condition is undef 507 if (isa<UndefValue>(SimpleCond)) 508 KnownSucc = BI->getSuccessor(0); 509 else if (ConstantInt *SimpleCondVal = 510 dyn_cast<ConstantInt>(SimpleCond)) 511 KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0); 512 } 513 } 514 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 515 if (Constant *SimpleCond = 516 SimplifiedValues.lookup(SI->getCondition())) { 517 // Just take the first successor if condition is undef 518 if (isa<UndefValue>(SimpleCond)) 519 KnownSucc = SI->getSuccessor(0); 520 else if (ConstantInt *SimpleCondVal = 521 dyn_cast<ConstantInt>(SimpleCond)) 522 KnownSucc = SI->findCaseValue(SimpleCondVal)->getCaseSuccessor(); 523 } 524 } 525 if (KnownSucc) { 526 if (L->contains(KnownSucc)) 527 BBWorklist.insert(KnownSucc); 528 else 529 ExitWorklist.insert({BB, KnownSucc}); 530 continue; 531 } 532 533 // Add BB's successors to the worklist. 534 for (BasicBlock *Succ : successors(BB)) 535 if (L->contains(Succ)) 536 BBWorklist.insert(Succ); 537 else 538 ExitWorklist.insert({BB, Succ}); 539 AddCostRecursively(*TI, Iteration); 540 } 541 542 // If we found no optimization opportunities on the first iteration, we 543 // won't find them on later ones too. 544 if (UnrolledCost == RolledDynamicCost) { 545 DEBUG(dbgs() << " No opportunities found.. exiting.\n" 546 << " UnrolledCost: " << UnrolledCost << "\n"); 547 return None; 548 } 549 } 550 551 while (!ExitWorklist.empty()) { 552 BasicBlock *ExitingBB, *ExitBB; 553 std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val(); 554 555 for (Instruction &I : *ExitBB) { 556 auto *PN = dyn_cast<PHINode>(&I); 557 if (!PN) 558 break; 559 560 Value *Op = PN->getIncomingValueForBlock(ExitingBB); 561 if (auto *OpI = dyn_cast<Instruction>(Op)) 562 if (L->contains(OpI)) 563 AddCostRecursively(*OpI, TripCount - 1); 564 } 565 } 566 567 DEBUG(dbgs() << "Analysis finished:\n" 568 << "UnrolledCost: " << UnrolledCost << ", " 569 << "RolledDynamicCost: " << RolledDynamicCost << "\n"); 570 return {{UnrolledCost, RolledDynamicCost}}; 571 } 572 573 /// ApproximateLoopSize - Approximate the size of the loop. 574 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, 575 bool &NotDuplicatable, bool &Convergent, 576 const TargetTransformInfo &TTI, 577 AssumptionCache *AC, unsigned BEInsns) { 578 SmallPtrSet<const Value *, 32> EphValues; 579 CodeMetrics::collectEphemeralValues(L, AC, EphValues); 580 581 CodeMetrics Metrics; 582 for (BasicBlock *BB : L->blocks()) 583 Metrics.analyzeBasicBlock(BB, TTI, EphValues); 584 NumCalls = Metrics.NumInlineCandidates; 585 NotDuplicatable = Metrics.notDuplicatable; 586 Convergent = Metrics.convergent; 587 588 unsigned LoopSize = Metrics.NumInsts; 589 590 // Don't allow an estimate of size zero. This would allows unrolling of loops 591 // with huge iteration counts, which is a compile time problem even if it's 592 // not a problem for code quality. Also, the code using this size may assume 593 // that each loop has at least three instructions (likely a conditional 594 // branch, a comparison feeding that branch, and some kind of loop increment 595 // feeding that comparison instruction). 596 LoopSize = std::max(LoopSize, BEInsns + 1); 597 598 return LoopSize; 599 } 600 601 // Returns the loop hint metadata node with the given name (for example, 602 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is 603 // returned. 604 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) { 605 if (MDNode *LoopID = L->getLoopID()) 606 return GetUnrollMetadata(LoopID, Name); 607 return nullptr; 608 } 609 610 // Returns true if the loop has an unroll(full) pragma. 611 static bool HasUnrollFullPragma(const Loop *L) { 612 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full"); 613 } 614 615 // Returns true if the loop has an unroll(enable) pragma. This metadata is used 616 // for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives. 617 static bool HasUnrollEnablePragma(const Loop *L) { 618 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable"); 619 } 620 621 // Returns true if the loop has an unroll(disable) pragma. 622 static bool HasUnrollDisablePragma(const Loop *L) { 623 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable"); 624 } 625 626 // Returns true if the loop has an runtime unroll(disable) pragma. 627 static bool HasRuntimeUnrollDisablePragma(const Loop *L) { 628 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable"); 629 } 630 631 // If loop has an unroll_count pragma return the (necessarily 632 // positive) value from the pragma. Otherwise return 0. 633 static unsigned UnrollCountPragmaValue(const Loop *L) { 634 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); 635 if (MD) { 636 assert(MD->getNumOperands() == 2 && 637 "Unroll count hint metadata should have two operands."); 638 unsigned Count = 639 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 640 assert(Count >= 1 && "Unroll count must be positive."); 641 return Count; 642 } 643 return 0; 644 } 645 646 // Remove existing unroll metadata and add unroll disable metadata to 647 // indicate the loop has already been unrolled. This prevents a loop 648 // from being unrolled more than is directed by a pragma if the loop 649 // unrolling pass is run more than once (which it generally is). 650 static void SetLoopAlreadyUnrolled(Loop *L) { 651 MDNode *LoopID = L->getLoopID(); 652 // First remove any existing loop unrolling metadata. 653 SmallVector<Metadata *, 4> MDs; 654 // Reserve first location for self reference to the LoopID metadata node. 655 MDs.push_back(nullptr); 656 657 if (LoopID) { 658 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 659 bool IsUnrollMetadata = false; 660 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 661 if (MD) { 662 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 663 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 664 } 665 if (!IsUnrollMetadata) 666 MDs.push_back(LoopID->getOperand(i)); 667 } 668 } 669 670 // Add unroll(disable) metadata to disable future unrolling. 671 LLVMContext &Context = L->getHeader()->getContext(); 672 SmallVector<Metadata *, 1> DisableOperands; 673 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 674 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 675 MDs.push_back(DisableNode); 676 677 MDNode *NewLoopID = MDNode::get(Context, MDs); 678 // Set operand 0 to refer to the loop id itself. 679 NewLoopID->replaceOperandWith(0, NewLoopID); 680 L->setLoopID(NewLoopID); 681 } 682 683 // Computes the boosting factor for complete unrolling. 684 // If fully unrolling the loop would save a lot of RolledDynamicCost, it would 685 // be beneficial to fully unroll the loop even if unrolledcost is large. We 686 // use (RolledDynamicCost / UnrolledCost) to model the unroll benefits to adjust 687 // the unroll threshold. 688 static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost, 689 unsigned MaxPercentThresholdBoost) { 690 if (Cost.RolledDynamicCost >= UINT_MAX / 100) 691 return 100; 692 else if (Cost.UnrolledCost != 0) 693 // The boosting factor is RolledDynamicCost / UnrolledCost 694 return std::min(100 * Cost.RolledDynamicCost / Cost.UnrolledCost, 695 MaxPercentThresholdBoost); 696 else 697 return MaxPercentThresholdBoost; 698 } 699 700 // Returns loop size estimation for unrolled loop. 701 static uint64_t getUnrolledLoopSize( 702 unsigned LoopSize, 703 TargetTransformInfo::UnrollingPreferences &UP) { 704 assert(LoopSize >= UP.BEInsns && "LoopSize should not be less than BEInsns!"); 705 return (uint64_t)(LoopSize - UP.BEInsns) * UP.Count + UP.BEInsns; 706 } 707 708 // Returns true if unroll count was set explicitly. 709 // Calculates unroll count and writes it to UP.Count. 710 static bool computeUnrollCount( 711 Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI, 712 ScalarEvolution &SE, OptimizationRemarkEmitter *ORE, unsigned &TripCount, 713 unsigned MaxTripCount, unsigned &TripMultiple, unsigned LoopSize, 714 TargetTransformInfo::UnrollingPreferences &UP, bool &UseUpperBound) { 715 // Check for explicit Count. 716 // 1st priority is unroll count set by "unroll-count" option. 717 bool UserUnrollCount = UnrollCount.getNumOccurrences() > 0; 718 if (UserUnrollCount) { 719 UP.Count = UnrollCount; 720 UP.AllowExpensiveTripCount = true; 721 UP.Force = true; 722 if (UP.AllowRemainder && getUnrolledLoopSize(LoopSize, UP) < UP.Threshold) 723 return true; 724 } 725 726 // 2nd priority is unroll count set by pragma. 727 unsigned PragmaCount = UnrollCountPragmaValue(L); 728 if (PragmaCount > 0) { 729 UP.Count = PragmaCount; 730 UP.Runtime = true; 731 UP.AllowExpensiveTripCount = true; 732 UP.Force = true; 733 if (UP.AllowRemainder && 734 getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold) 735 return true; 736 } 737 bool PragmaFullUnroll = HasUnrollFullPragma(L); 738 if (PragmaFullUnroll && TripCount != 0) { 739 UP.Count = TripCount; 740 if (getUnrolledLoopSize(LoopSize, UP) < PragmaUnrollThreshold) 741 return false; 742 } 743 744 bool PragmaEnableUnroll = HasUnrollEnablePragma(L); 745 bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll || 746 PragmaEnableUnroll || UserUnrollCount; 747 748 if (ExplicitUnroll && TripCount != 0) { 749 // If the loop has an unrolling pragma, we want to be more aggressive with 750 // unrolling limits. Set thresholds to at least the PragmaThreshold value 751 // which is larger than the default limits. 752 UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold); 753 UP.PartialThreshold = 754 std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold); 755 } 756 757 // 3rd priority is full unroll count. 758 // Full unroll makes sense only when TripCount or its upper bound could be 759 // statically calculated. 760 // Also we need to check if we exceed FullUnrollMaxCount. 761 // If using the upper bound to unroll, TripMultiple should be set to 1 because 762 // we do not know when loop may exit. 763 // MaxTripCount and ExactTripCount cannot both be non zero since we only 764 // compute the former when the latter is zero. 765 unsigned ExactTripCount = TripCount; 766 assert((ExactTripCount == 0 || MaxTripCount == 0) && 767 "ExtractTripCound and MaxTripCount cannot both be non zero."); 768 unsigned FullUnrollTripCount = ExactTripCount ? ExactTripCount : MaxTripCount; 769 UP.Count = FullUnrollTripCount; 770 if (FullUnrollTripCount && FullUnrollTripCount <= UP.FullUnrollMaxCount) { 771 // When computing the unrolled size, note that BEInsns are not replicated 772 // like the rest of the loop body. 773 if (getUnrolledLoopSize(LoopSize, UP) < UP.Threshold) { 774 UseUpperBound = (MaxTripCount == FullUnrollTripCount); 775 TripCount = FullUnrollTripCount; 776 TripMultiple = UP.UpperBound ? 1 : TripMultiple; 777 return ExplicitUnroll; 778 } else { 779 // The loop isn't that small, but we still can fully unroll it if that 780 // helps to remove a significant number of instructions. 781 // To check that, run additional analysis on the loop. 782 if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost( 783 L, FullUnrollTripCount, DT, SE, TTI, 784 UP.Threshold * UP.MaxPercentThresholdBoost / 100)) { 785 unsigned Boost = 786 getFullUnrollBoostingFactor(*Cost, UP.MaxPercentThresholdBoost); 787 if (Cost->UnrolledCost < UP.Threshold * Boost / 100) { 788 UseUpperBound = (MaxTripCount == FullUnrollTripCount); 789 TripCount = FullUnrollTripCount; 790 TripMultiple = UP.UpperBound ? 1 : TripMultiple; 791 return ExplicitUnroll; 792 } 793 } 794 } 795 } 796 797 // 4th priority is loop peeling 798 computePeelCount(L, LoopSize, UP, TripCount); 799 if (UP.PeelCount) { 800 UP.Runtime = false; 801 UP.Count = 1; 802 return ExplicitUnroll; 803 } 804 805 // 5th priority is partial unrolling. 806 // Try partial unroll only when TripCount could be staticaly calculated. 807 if (TripCount) { 808 UP.Partial |= ExplicitUnroll; 809 if (!UP.Partial) { 810 DEBUG(dbgs() << " will not try to unroll partially because " 811 << "-unroll-allow-partial not given\n"); 812 UP.Count = 0; 813 return false; 814 } 815 if (UP.Count == 0) 816 UP.Count = TripCount; 817 if (UP.PartialThreshold != NoThreshold) { 818 // Reduce unroll count to be modulo of TripCount for partial unrolling. 819 if (getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold) 820 UP.Count = 821 (std::max(UP.PartialThreshold, UP.BEInsns + 1) - UP.BEInsns) / 822 (LoopSize - UP.BEInsns); 823 if (UP.Count > UP.MaxCount) 824 UP.Count = UP.MaxCount; 825 while (UP.Count != 0 && TripCount % UP.Count != 0) 826 UP.Count--; 827 if (UP.AllowRemainder && UP.Count <= 1) { 828 // If there is no Count that is modulo of TripCount, set Count to 829 // largest power-of-two factor that satisfies the threshold limit. 830 // As we'll create fixup loop, do the type of unrolling only if 831 // remainder loop is allowed. 832 UP.Count = UP.DefaultUnrollRuntimeCount; 833 while (UP.Count != 0 && 834 getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold) 835 UP.Count >>= 1; 836 } 837 if (UP.Count < 2) { 838 if (PragmaEnableUnroll) 839 ORE->emit( 840 OptimizationRemarkMissed(DEBUG_TYPE, "UnrollAsDirectedTooLarge", 841 L->getStartLoc(), L->getHeader()) 842 << "Unable to unroll loop as directed by unroll(enable) pragma " 843 "because unrolled size is too large."); 844 UP.Count = 0; 845 } 846 } else { 847 UP.Count = TripCount; 848 } 849 if (UP.Count > UP.MaxCount) 850 UP.Count = UP.MaxCount; 851 if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount && 852 UP.Count != TripCount) 853 ORE->emit( 854 OptimizationRemarkMissed(DEBUG_TYPE, "FullUnrollAsDirectedTooLarge", 855 L->getStartLoc(), L->getHeader()) 856 << "Unable to fully unroll loop as directed by unroll pragma because " 857 "unrolled size is too large."); 858 return ExplicitUnroll; 859 } 860 assert(TripCount == 0 && 861 "All cases when TripCount is constant should be covered here."); 862 if (PragmaFullUnroll) 863 ORE->emit( 864 OptimizationRemarkMissed(DEBUG_TYPE, 865 "CantFullUnrollAsDirectedRuntimeTripCount", 866 L->getStartLoc(), L->getHeader()) 867 << "Unable to fully unroll loop as directed by unroll(full) pragma " 868 "because loop has a runtime trip count."); 869 870 // 6th priority is runtime unrolling. 871 // Don't unroll a runtime trip count loop when it is disabled. 872 if (HasRuntimeUnrollDisablePragma(L)) { 873 UP.Count = 0; 874 return false; 875 } 876 877 // Check if the runtime trip count is too small when profile is available. 878 if (L->getHeader()->getParent()->getEntryCount()) { 879 if (auto ProfileTripCount = getLoopEstimatedTripCount(L)) { 880 if (*ProfileTripCount < FlatLoopTripCountThreshold) 881 return false; 882 else 883 UP.AllowExpensiveTripCount = true; 884 } 885 } 886 887 // Reduce count based on the type of unrolling and the threshold values. 888 UP.Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount; 889 if (!UP.Runtime) { 890 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " 891 << "-unroll-runtime not given\n"); 892 UP.Count = 0; 893 return false; 894 } 895 if (UP.Count == 0) 896 UP.Count = UP.DefaultUnrollRuntimeCount; 897 898 // Reduce unroll count to be the largest power-of-two factor of 899 // the original count which satisfies the threshold limit. 900 while (UP.Count != 0 && 901 getUnrolledLoopSize(LoopSize, UP) > UP.PartialThreshold) 902 UP.Count >>= 1; 903 904 #ifndef NDEBUG 905 unsigned OrigCount = UP.Count; 906 #endif 907 908 if (!UP.AllowRemainder && UP.Count != 0 && (TripMultiple % UP.Count) != 0) { 909 while (UP.Count != 0 && TripMultiple % UP.Count != 0) 910 UP.Count >>= 1; 911 DEBUG(dbgs() << "Remainder loop is restricted (that could architecture " 912 "specific or because the loop contains a convergent " 913 "instruction), so unroll count must divide the trip " 914 "multiple, " 915 << TripMultiple << ". Reducing unroll count from " 916 << OrigCount << " to " << UP.Count << ".\n"); 917 using namespace ore; 918 if (PragmaCount > 0 && !UP.AllowRemainder) 919 ORE->emit( 920 OptimizationRemarkMissed(DEBUG_TYPE, 921 "DifferentUnrollCountFromDirected", 922 L->getStartLoc(), L->getHeader()) 923 << "Unable to unroll loop the number of times directed by " 924 "unroll_count pragma because remainder loop is restricted " 925 "(that could architecture specific or because the loop " 926 "contains a convergent instruction) and so must have an unroll " 927 "count that divides the loop trip multiple of " 928 << NV("TripMultiple", TripMultiple) << ". Unrolling instead " 929 << NV("UnrollCount", UP.Count) << " time(s)."); 930 } 931 932 if (UP.Count > UP.MaxCount) 933 UP.Count = UP.MaxCount; 934 DEBUG(dbgs() << " partially unrolling with count: " << UP.Count << "\n"); 935 if (UP.Count < 2) 936 UP.Count = 0; 937 return ExplicitUnroll; 938 } 939 940 static bool tryToUnrollLoop( 941 Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE, 942 const TargetTransformInfo &TTI, AssumptionCache &AC, 943 OptimizationRemarkEmitter &ORE, bool PreserveLCSSA, int OptLevel, 944 Optional<unsigned> ProvidedCount, Optional<unsigned> ProvidedThreshold, 945 Optional<bool> ProvidedAllowPartial, Optional<bool> ProvidedRuntime, 946 Optional<bool> ProvidedUpperBound, Optional<bool> ProvidedAllowPeeling) { 947 DEBUG(dbgs() << "Loop Unroll: F[" << L->getHeader()->getParent()->getName() 948 << "] Loop %" << L->getHeader()->getName() << "\n"); 949 if (HasUnrollDisablePragma(L)) 950 return false; 951 if (!L->isLoopSimplifyForm()) { 952 DEBUG( 953 dbgs() << " Not unrolling loop which is not in loop-simplify form.\n"); 954 return false; 955 } 956 957 unsigned NumInlineCandidates; 958 bool NotDuplicatable; 959 bool Convergent; 960 TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences( 961 L, SE, TTI, OptLevel, ProvidedThreshold, ProvidedCount, 962 ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound, 963 ProvidedAllowPeeling); 964 // Exit early if unrolling is disabled. 965 if (UP.Threshold == 0 && (!UP.Partial || UP.PartialThreshold == 0)) 966 return false; 967 unsigned LoopSize = ApproximateLoopSize( 968 L, NumInlineCandidates, NotDuplicatable, Convergent, TTI, &AC, UP.BEInsns); 969 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); 970 if (NotDuplicatable) { 971 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" 972 << " instructions.\n"); 973 return false; 974 } 975 if (NumInlineCandidates != 0) { 976 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); 977 return false; 978 } 979 980 // Find trip count and trip multiple if count is not available 981 unsigned TripCount = 0; 982 unsigned MaxTripCount = 0; 983 unsigned TripMultiple = 1; 984 // If there are multiple exiting blocks but one of them is the latch, use the 985 // latch for the trip count estimation. Otherwise insist on a single exiting 986 // block for the trip count estimation. 987 BasicBlock *ExitingBlock = L->getLoopLatch(); 988 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) 989 ExitingBlock = L->getExitingBlock(); 990 if (ExitingBlock) { 991 TripCount = SE.getSmallConstantTripCount(L, ExitingBlock); 992 TripMultiple = SE.getSmallConstantTripMultiple(L, ExitingBlock); 993 } 994 995 // If the loop contains a convergent operation, the prelude we'd add 996 // to do the first few instructions before we hit the unrolled loop 997 // is unsafe -- it adds a control-flow dependency to the convergent 998 // operation. Therefore restrict remainder loop (try unrollig without). 999 // 1000 // TODO: This is quite conservative. In practice, convergent_op() 1001 // is likely to be called unconditionally in the loop. In this 1002 // case, the program would be ill-formed (on most architectures) 1003 // unless n were the same on all threads in a thread group. 1004 // Assuming n is the same on all threads, any kind of unrolling is 1005 // safe. But currently llvm's notion of convergence isn't powerful 1006 // enough to express this. 1007 if (Convergent) 1008 UP.AllowRemainder = false; 1009 1010 // Try to find the trip count upper bound if we cannot find the exact trip 1011 // count. 1012 bool MaxOrZero = false; 1013 if (!TripCount) { 1014 MaxTripCount = SE.getSmallConstantMaxTripCount(L); 1015 MaxOrZero = SE.isBackedgeTakenCountMaxOrZero(L); 1016 // We can unroll by the upper bound amount if it's generally allowed or if 1017 // we know that the loop is executed either the upper bound or zero times. 1018 // (MaxOrZero unrolling keeps only the first loop test, so the number of 1019 // loop tests remains the same compared to the non-unrolled version, whereas 1020 // the generic upper bound unrolling keeps all but the last loop test so the 1021 // number of loop tests goes up which may end up being worse on targets with 1022 // constriained branch predictor resources so is controlled by an option.) 1023 // In addition we only unroll small upper bounds. 1024 if (!(UP.UpperBound || MaxOrZero) || MaxTripCount > UnrollMaxUpperBound) { 1025 MaxTripCount = 0; 1026 } 1027 } 1028 1029 // computeUnrollCount() decides whether it is beneficial to use upper bound to 1030 // fully unroll the loop. 1031 bool UseUpperBound = false; 1032 bool IsCountSetExplicitly = 1033 computeUnrollCount(L, TTI, DT, LI, SE, &ORE, TripCount, MaxTripCount, 1034 TripMultiple, LoopSize, UP, UseUpperBound); 1035 if (!UP.Count) 1036 return false; 1037 // Unroll factor (Count) must be less or equal to TripCount. 1038 if (TripCount && UP.Count > TripCount) 1039 UP.Count = TripCount; 1040 1041 // Unroll the loop. 1042 if (!UnrollLoop(L, UP.Count, TripCount, UP.Force, UP.Runtime, 1043 UP.AllowExpensiveTripCount, UseUpperBound, MaxOrZero, 1044 TripMultiple, UP.PeelCount, UP.UnrollRemainder, 1045 LI, &SE, &DT, &AC, &ORE, 1046 PreserveLCSSA)) 1047 return false; 1048 1049 // If loop has an unroll count pragma or unrolled by explicitly set count 1050 // mark loop as unrolled to prevent unrolling beyond that requested. 1051 // If the loop was peeled, we already "used up" the profile information 1052 // we had, so we don't want to unroll or peel again. 1053 if (IsCountSetExplicitly || UP.PeelCount) 1054 SetLoopAlreadyUnrolled(L); 1055 1056 return true; 1057 } 1058 1059 namespace { 1060 class LoopUnroll : public LoopPass { 1061 public: 1062 static char ID; // Pass ID, replacement for typeid 1063 LoopUnroll(int OptLevel = 2, Optional<unsigned> Threshold = None, 1064 Optional<unsigned> Count = None, 1065 Optional<bool> AllowPartial = None, Optional<bool> Runtime = None, 1066 Optional<bool> UpperBound = None, 1067 Optional<bool> AllowPeeling = None) 1068 : LoopPass(ID), OptLevel(OptLevel), ProvidedCount(std::move(Count)), 1069 ProvidedThreshold(Threshold), ProvidedAllowPartial(AllowPartial), 1070 ProvidedRuntime(Runtime), ProvidedUpperBound(UpperBound), 1071 ProvidedAllowPeeling(AllowPeeling) { 1072 initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); 1073 } 1074 1075 int OptLevel; 1076 Optional<unsigned> ProvidedCount; 1077 Optional<unsigned> ProvidedThreshold; 1078 Optional<bool> ProvidedAllowPartial; 1079 Optional<bool> ProvidedRuntime; 1080 Optional<bool> ProvidedUpperBound; 1081 Optional<bool> ProvidedAllowPeeling; 1082 1083 bool runOnLoop(Loop *L, LPPassManager &) override { 1084 if (skipLoop(L)) 1085 return false; 1086 1087 Function &F = *L->getHeader()->getParent(); 1088 1089 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1090 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1091 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1092 const TargetTransformInfo &TTI = 1093 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 1094 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1095 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 1096 // pass. Function analyses need to be preserved across loop transformations 1097 // but ORE cannot be preserved (see comment before the pass definition). 1098 OptimizationRemarkEmitter ORE(&F); 1099 bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 1100 1101 return tryToUnrollLoop(L, DT, LI, SE, TTI, AC, ORE, PreserveLCSSA, OptLevel, 1102 ProvidedCount, ProvidedThreshold, 1103 ProvidedAllowPartial, ProvidedRuntime, 1104 ProvidedUpperBound, ProvidedAllowPeeling); 1105 } 1106 1107 /// This transformation requires natural loop information & requires that 1108 /// loop preheaders be inserted into the CFG... 1109 /// 1110 void getAnalysisUsage(AnalysisUsage &AU) const override { 1111 AU.addRequired<AssumptionCacheTracker>(); 1112 AU.addRequired<TargetTransformInfoWrapperPass>(); 1113 // FIXME: Loop passes are required to preserve domtree, and for now we just 1114 // recreate dom info if anything gets unrolled. 1115 getLoopAnalysisUsage(AU); 1116 } 1117 }; 1118 } 1119 1120 char LoopUnroll::ID = 0; 1121 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 1122 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1123 INITIALIZE_PASS_DEPENDENCY(LoopPass) 1124 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1125 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 1126 1127 Pass *llvm::createLoopUnrollPass(int OptLevel, int Threshold, int Count, 1128 int AllowPartial, int Runtime, int UpperBound, 1129 int AllowPeeling) { 1130 // TODO: It would make more sense for this function to take the optionals 1131 // directly, but that's dangerous since it would silently break out of tree 1132 // callers. 1133 return new LoopUnroll( 1134 OptLevel, Threshold == -1 ? None : Optional<unsigned>(Threshold), 1135 Count == -1 ? None : Optional<unsigned>(Count), 1136 AllowPartial == -1 ? None : Optional<bool>(AllowPartial), 1137 Runtime == -1 ? None : Optional<bool>(Runtime), 1138 UpperBound == -1 ? None : Optional<bool>(UpperBound), 1139 AllowPeeling == -1 ? None : Optional<bool>(AllowPeeling)); 1140 } 1141 1142 Pass *llvm::createSimpleLoopUnrollPass(int OptLevel) { 1143 return llvm::createLoopUnrollPass(OptLevel, -1, -1, 0, 0, 0, 0); 1144 } 1145 1146 PreservedAnalyses LoopFullUnrollPass::run(Loop &L, LoopAnalysisManager &AM, 1147 LoopStandardAnalysisResults &AR, 1148 LPMUpdater &Updater) { 1149 const auto &FAM = 1150 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); 1151 Function *F = L.getHeader()->getParent(); 1152 1153 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F); 1154 // FIXME: This should probably be optional rather than required. 1155 if (!ORE) 1156 report_fatal_error( 1157 "LoopFullUnrollPass: OptimizationRemarkEmitterAnalysis not " 1158 "cached at a higher level"); 1159 1160 // Keep track of the previous loop structure so we can identify new loops 1161 // created by unrolling. 1162 Loop *ParentL = L.getParentLoop(); 1163 SmallPtrSet<Loop *, 4> OldLoops; 1164 if (ParentL) 1165 OldLoops.insert(ParentL->begin(), ParentL->end()); 1166 else 1167 OldLoops.insert(AR.LI.begin(), AR.LI.end()); 1168 1169 bool Changed = 1170 tryToUnrollLoop(&L, AR.DT, &AR.LI, AR.SE, AR.TTI, AR.AC, *ORE, 1171 /*PreserveLCSSA*/ true, OptLevel, /*Count*/ None, 1172 /*Threshold*/ None, /*AllowPartial*/ false, 1173 /*Runtime*/ false, /*UpperBound*/ false, 1174 /*AllowPeeling*/ false); 1175 if (!Changed) 1176 return PreservedAnalyses::all(); 1177 1178 // The parent must not be damaged by unrolling! 1179 #ifndef NDEBUG 1180 if (ParentL) 1181 ParentL->verifyLoop(); 1182 #endif 1183 1184 // Unrolling can do several things to introduce new loops into a loop nest: 1185 // - Full unrolling clones child loops within the current loop but then 1186 // removes the current loop making all of the children appear to be new 1187 // sibling loops. 1188 // 1189 // When a new loop appears as a sibling loop after fully unrolling, 1190 // its nesting structure has fundamentally changed and we want to revisit 1191 // it to reflect that. 1192 // 1193 // When unrolling has removed the current loop, we need to tell the 1194 // infrastructure that it is gone. 1195 // 1196 // Finally, we support a debugging/testing mode where we revisit child loops 1197 // as well. These are not expected to require further optimizations as either 1198 // they or the loop they were cloned from have been directly visited already. 1199 // But the debugging mode allows us to check this assumption. 1200 bool IsCurrentLoopValid = false; 1201 SmallVector<Loop *, 4> SibLoops; 1202 if (ParentL) 1203 SibLoops.append(ParentL->begin(), ParentL->end()); 1204 else 1205 SibLoops.append(AR.LI.begin(), AR.LI.end()); 1206 erase_if(SibLoops, [&](Loop *SibLoop) { 1207 if (SibLoop == &L) { 1208 IsCurrentLoopValid = true; 1209 return true; 1210 } 1211 1212 // Otherwise erase the loop from the list if it was in the old loops. 1213 return OldLoops.count(SibLoop) != 0; 1214 }); 1215 Updater.addSiblingLoops(SibLoops); 1216 1217 if (!IsCurrentLoopValid) { 1218 Updater.markLoopAsDeleted(L); 1219 } else { 1220 // We can only walk child loops if the current loop remained valid. 1221 if (UnrollRevisitChildLoops) { 1222 // Walk *all* of the child loops. 1223 SmallVector<Loop *, 4> ChildLoops(L.begin(), L.end()); 1224 Updater.addChildLoops(ChildLoops); 1225 } 1226 } 1227 1228 return getLoopPassPreservedAnalyses(); 1229 } 1230 1231 template <typename RangeT> 1232 static SmallVector<Loop *, 8> appendLoopsToWorklist(RangeT &&Loops) { 1233 SmallVector<Loop *, 8> Worklist; 1234 // We use an internal worklist to build up the preorder traversal without 1235 // recursion. 1236 SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist; 1237 1238 for (Loop *RootL : Loops) { 1239 assert(PreOrderLoops.empty() && "Must start with an empty preorder walk."); 1240 assert(PreOrderWorklist.empty() && 1241 "Must start with an empty preorder walk worklist."); 1242 PreOrderWorklist.push_back(RootL); 1243 do { 1244 Loop *L = PreOrderWorklist.pop_back_val(); 1245 PreOrderWorklist.append(L->begin(), L->end()); 1246 PreOrderLoops.push_back(L); 1247 } while (!PreOrderWorklist.empty()); 1248 1249 Worklist.append(PreOrderLoops.begin(), PreOrderLoops.end()); 1250 PreOrderLoops.clear(); 1251 } 1252 return Worklist; 1253 } 1254 1255 PreservedAnalyses LoopUnrollPass::run(Function &F, 1256 FunctionAnalysisManager &AM) { 1257 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F); 1258 auto &LI = AM.getResult<LoopAnalysis>(F); 1259 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 1260 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1261 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1262 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1263 1264 LoopAnalysisManager *LAM = nullptr; 1265 if (auto *LAMProxy = AM.getCachedResult<LoopAnalysisManagerFunctionProxy>(F)) 1266 LAM = &LAMProxy->getManager(); 1267 1268 const ModuleAnalysisManager &MAM = 1269 AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager(); 1270 ProfileSummaryInfo *PSI = 1271 MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent()); 1272 1273 bool Changed = false; 1274 1275 // The unroller requires loops to be in simplified form, and also needs LCSSA. 1276 // Since simplification may add new inner loops, it has to run before the 1277 // legality and profitability checks. This means running the loop unroller 1278 // will simplify all loops, regardless of whether anything end up being 1279 // unrolled. 1280 for (auto &L : LI) { 1281 Changed |= simplifyLoop(L, &DT, &LI, &SE, &AC, false /* PreserveLCSSA */); 1282 Changed |= formLCSSARecursively(*L, DT, &LI, &SE); 1283 } 1284 1285 SmallVector<Loop *, 8> Worklist = appendLoopsToWorklist(LI); 1286 1287 while (!Worklist.empty()) { 1288 // Because the LoopInfo stores the loops in RPO, we walk the worklist 1289 // from back to front so that we work forward across the CFG, which 1290 // for unrolling is only needed to get optimization remarks emitted in 1291 // a forward order. 1292 Loop &L = *Worklist.pop_back_val(); 1293 Loop *ParentL = L.getParentLoop(); 1294 1295 // The API here is quite complex to call, but there are only two interesting 1296 // states we support: partial and full (or "simple") unrolling. However, to 1297 // enable these things we actually pass "None" in for the optional to avoid 1298 // providing an explicit choice. 1299 Optional<bool> AllowPartialParam, RuntimeParam, UpperBoundParam, 1300 AllowPeeling; 1301 // Check if the profile summary indicates that the profiled application 1302 // has a huge working set size, in which case we disable peeling to avoid 1303 // bloating it further. 1304 if (PSI && PSI->hasHugeWorkingSetSize()) 1305 AllowPeeling = false; 1306 bool CurChanged = 1307 tryToUnrollLoop(&L, DT, &LI, SE, TTI, AC, ORE, 1308 /*PreserveLCSSA*/ true, OptLevel, /*Count*/ None, 1309 /*Threshold*/ None, AllowPartialParam, RuntimeParam, 1310 UpperBoundParam, AllowPeeling); 1311 Changed |= CurChanged; 1312 1313 // The parent must not be damaged by unrolling! 1314 #ifndef NDEBUG 1315 if (CurChanged && ParentL) 1316 ParentL->verifyLoop(); 1317 #endif 1318 1319 // Walk the parent or top-level loops after unrolling to check whether we 1320 // actually removed a loop, and if so clear any cached analysis results for 1321 // it. We have to do this immediately as the next unrolling could allocate 1322 // a new loop object that ends up with the same address as the deleted loop 1323 // object causing cache collisions. 1324 if (LAM) { 1325 bool IsCurLoopValid = 1326 ParentL 1327 ? llvm::any_of(*ParentL, [&](Loop *SibL) { return SibL == &L; }) 1328 : llvm::any_of(LI, [&](Loop *SibL) { return SibL == &L; }); 1329 if (!IsCurLoopValid) 1330 LAM->clear(L); 1331 } 1332 } 1333 1334 if (!Changed) 1335 return PreservedAnalyses::all(); 1336 1337 return getLoopPassPreservedAnalyses(); 1338 } 1339