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