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.h" 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/Analysis/GlobalsModRef.h" 18 #include "llvm/Analysis/AssumptionCache.h" 19 #include "llvm/Analysis/CodeMetrics.h" 20 #include "llvm/Analysis/InstructionSimplify.h" 21 #include "llvm/Analysis/LoopPass.h" 22 #include "llvm/Analysis/ScalarEvolution.h" 23 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 24 #include "llvm/Analysis/TargetTransformInfo.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/DiagnosticInfo.h" 27 #include "llvm/IR/Dominators.h" 28 #include "llvm/IR/InstVisitor.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/IR/Metadata.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/Transforms/Utils/UnrollLoop.h" 35 #include <climits> 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "loop-unroll" 40 41 static cl::opt<unsigned> 42 UnrollThreshold("unroll-threshold", cl::Hidden, 43 cl::desc("The baseline cost threshold for loop unrolling")); 44 45 static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold( 46 "unroll-percent-dynamic-cost-saved-threshold", cl::Hidden, 47 cl::desc("The percentage of estimated dynamic cost which must be saved by " 48 "unrolling to allow unrolling up to the max threshold.")); 49 50 static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount( 51 "unroll-dynamic-cost-savings-discount", cl::Hidden, 52 cl::desc("This is the amount discounted from the total unroll cost when " 53 "the unrolled form has a high dynamic cost savings (triggered by " 54 "the '-unroll-perecent-dynamic-cost-saved-threshold' flag).")); 55 56 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze( 57 "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden, 58 cl::desc("Don't allow loop unrolling to simulate more than this number of" 59 "iterations when checking full unroll profitability")); 60 61 static cl::opt<unsigned> 62 UnrollCount("unroll-count", cl::Hidden, 63 cl::desc("Use this unroll count for all loops including those with " 64 "unroll_count pragma values, for testing purposes")); 65 66 static cl::opt<bool> 67 UnrollAllowPartial("unroll-allow-partial", cl::Hidden, 68 cl::desc("Allows loops to be partially unrolled until " 69 "-unroll-threshold loop size is reached.")); 70 71 static cl::opt<bool> 72 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden, 73 cl::desc("Unroll loops with run-time trip counts")); 74 75 static cl::opt<unsigned> 76 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden, 77 cl::desc("Unrolled size limit for loops with an unroll(full) or " 78 "unroll_count pragma.")); 79 80 81 /// A magic value for use with the Threshold parameter to indicate 82 /// that the loop unroll should be performed regardless of how much 83 /// code expansion would result. 84 static const unsigned NoThreshold = UINT_MAX; 85 86 /// Default unroll count for loops with run-time trip count if 87 /// -unroll-count is not set 88 static const unsigned DefaultUnrollRuntimeCount = 8; 89 90 /// Gather the various unrolling parameters based on the defaults, compiler 91 /// flags, TTI overrides, pragmas, and user specified parameters. 92 static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences( 93 Loop *L, const TargetTransformInfo &TTI, Optional<unsigned> UserThreshold, 94 Optional<unsigned> UserCount, Optional<bool> UserAllowPartial, 95 Optional<bool> UserRuntime, unsigned PragmaCount, bool PragmaFullUnroll, 96 bool PragmaEnableUnroll, unsigned TripCount) { 97 TargetTransformInfo::UnrollingPreferences UP; 98 99 // Set up the defaults 100 UP.Threshold = 150; 101 UP.PercentDynamicCostSavedThreshold = 20; 102 UP.DynamicCostSavingsDiscount = 2000; 103 UP.OptSizeThreshold = 50; 104 UP.PartialThreshold = UP.Threshold; 105 UP.PartialOptSizeThreshold = UP.OptSizeThreshold; 106 UP.Count = 0; 107 UP.MaxCount = UINT_MAX; 108 UP.Partial = false; 109 UP.Runtime = false; 110 UP.AllowExpensiveTripCount = false; 111 112 // Override with any target specific settings 113 TTI.getUnrollingPreferences(L, UP); 114 115 // Apply size attributes 116 if (L->getHeader()->getParent()->optForSize()) { 117 UP.Threshold = UP.OptSizeThreshold; 118 UP.PartialThreshold = UP.PartialOptSizeThreshold; 119 } 120 121 // Apply unroll count pragmas 122 if (PragmaCount) 123 UP.Count = PragmaCount; 124 else if (PragmaFullUnroll) 125 UP.Count = TripCount; 126 127 // Apply any user values specified by cl::opt 128 if (UnrollThreshold.getNumOccurrences() > 0) { 129 UP.Threshold = UnrollThreshold; 130 UP.PartialThreshold = UnrollThreshold; 131 } 132 if (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0) 133 UP.PercentDynamicCostSavedThreshold = 134 UnrollPercentDynamicCostSavedThreshold; 135 if (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0) 136 UP.DynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount; 137 if (UnrollCount.getNumOccurrences() > 0) 138 UP.Count = UnrollCount; 139 if (UnrollAllowPartial.getNumOccurrences() > 0) 140 UP.Partial = UnrollAllowPartial; 141 if (UnrollRuntime.getNumOccurrences() > 0) 142 UP.Runtime = UnrollRuntime; 143 144 // Apply user values provided by argument 145 if (UserThreshold.hasValue()) { 146 UP.Threshold = *UserThreshold; 147 UP.PartialThreshold = *UserThreshold; 148 } 149 if (UserCount.hasValue()) 150 UP.Count = *UserCount; 151 if (UserAllowPartial.hasValue()) 152 UP.Partial = *UserAllowPartial; 153 if (UserRuntime.hasValue()) 154 UP.Runtime = *UserRuntime; 155 156 if (PragmaCount > 0 || 157 ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount != 0)) { 158 // If the loop has an unrolling pragma, we want to be more aggressive with 159 // unrolling limits. Set thresholds to at least the PragmaTheshold value 160 // which is larger than the default limits. 161 if (UP.Threshold != NoThreshold) 162 UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold); 163 if (UP.PartialThreshold != NoThreshold) 164 UP.PartialThreshold = 165 std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold); 166 } 167 168 return UP; 169 } 170 171 namespace { 172 class LoopUnroll : public LoopPass { 173 public: 174 static char ID; // Pass ID, replacement for typeid 175 LoopUnroll(Optional<unsigned> Threshold = None, 176 Optional<unsigned> Count = None, 177 Optional<bool> AllowPartial = None, 178 Optional<bool> Runtime = None) 179 : LoopPass(ID), ProvidedCount(Count), ProvidedThreshold(Threshold), 180 ProvidedAllowPartial(AllowPartial), ProvidedRuntime(Runtime) { 181 initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); 182 } 183 184 Optional<unsigned> ProvidedCount; 185 Optional<unsigned> ProvidedThreshold; 186 Optional<bool> ProvidedAllowPartial; 187 Optional<bool> ProvidedRuntime; 188 189 bool runOnLoop(Loop *L, LPPassManager &) override; 190 191 /// This transformation requires natural loop information & requires that 192 /// loop preheaders be inserted into the CFG... 193 /// 194 void getAnalysisUsage(AnalysisUsage &AU) const override { 195 AU.addRequired<AssumptionCacheTracker>(); 196 AU.addRequired<DominatorTreeWrapperPass>(); 197 AU.addRequired<LoopInfoWrapperPass>(); 198 AU.addPreserved<LoopInfoWrapperPass>(); 199 AU.addRequiredID(LoopSimplifyID); 200 AU.addPreservedID(LoopSimplifyID); 201 AU.addRequiredID(LCSSAID); 202 AU.addPreservedID(LCSSAID); 203 AU.addRequired<ScalarEvolutionWrapperPass>(); 204 AU.addPreserved<ScalarEvolutionWrapperPass>(); 205 AU.addRequired<TargetTransformInfoWrapperPass>(); 206 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. 207 // If loop unroll does not preserve dom info then LCSSA pass on next 208 // loop will receive invalid dom info. 209 // For now, recreate dom info, if loop is unrolled. 210 AU.addPreserved<DominatorTreeWrapperPass>(); 211 AU.addPreserved<GlobalsAAWrapperPass>(); 212 } 213 }; 214 } 215 216 char LoopUnroll::ID = 0; 217 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 218 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 219 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 220 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 221 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 222 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 223 INITIALIZE_PASS_DEPENDENCY(LCSSA) 224 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 225 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 226 227 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial, 228 int Runtime) { 229 // TODO: It would make more sense for this function to take the optionals 230 // directly, but that's dangerous since it would silently break out of tree 231 // callers. 232 return new LoopUnroll(Threshold == -1 ? None : Optional<unsigned>(Threshold), 233 Count == -1 ? None : Optional<unsigned>(Count), 234 AllowPartial == -1 ? None 235 : Optional<bool>(AllowPartial), 236 Runtime == -1 ? None : Optional<bool>(Runtime)); 237 } 238 239 Pass *llvm::createSimpleLoopUnrollPass() { 240 return llvm::createLoopUnrollPass(-1, -1, 0, 0); 241 } 242 243 namespace { 244 // This class is used to get an estimate of the optimization effects that we 245 // could get from complete loop unrolling. It comes from the fact that some 246 // loads might be replaced with concrete constant values and that could trigger 247 // a chain of instruction simplifications. 248 // 249 // E.g. we might have: 250 // int a[] = {0, 1, 0}; 251 // v = 0; 252 // for (i = 0; i < 3; i ++) 253 // v += b[i]*a[i]; 254 // If we completely unroll the loop, we would get: 255 // v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2] 256 // Which then will be simplified to: 257 // v = b[0]* 0 + b[1]* 1 + b[2]* 0 258 // And finally: 259 // v = b[1] 260 class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> { 261 typedef InstVisitor<UnrolledInstAnalyzer, bool> Base; 262 friend class InstVisitor<UnrolledInstAnalyzer, bool>; 263 struct SimplifiedAddress { 264 Value *Base = nullptr; 265 ConstantInt *Offset = nullptr; 266 }; 267 268 public: 269 UnrolledInstAnalyzer(unsigned Iteration, 270 DenseMap<Value *, Constant *> &SimplifiedValues, 271 ScalarEvolution &SE) 272 : SimplifiedValues(SimplifiedValues), SE(SE) { 273 IterationNumber = SE.getConstant(APInt(64, Iteration)); 274 } 275 276 // Allow access to the initial visit method. 277 using Base::visit; 278 279 private: 280 /// \brief A cache of pointer bases and constant-folded offsets corresponding 281 /// to GEP (or derived from GEP) instructions. 282 /// 283 /// In order to find the base pointer one needs to perform non-trivial 284 /// traversal of the corresponding SCEV expression, so it's good to have the 285 /// results saved. 286 DenseMap<Value *, SimplifiedAddress> SimplifiedAddresses; 287 288 /// \brief SCEV expression corresponding to number of currently simulated 289 /// iteration. 290 const SCEV *IterationNumber; 291 292 /// \brief A Value->Constant map for keeping values that we managed to 293 /// constant-fold on the given iteration. 294 /// 295 /// While we walk the loop instructions, we build up and maintain a mapping 296 /// of simplified values specific to this iteration. The idea is to propagate 297 /// any special information we have about loads that can be replaced with 298 /// constants after complete unrolling, and account for likely simplifications 299 /// post-unrolling. 300 DenseMap<Value *, Constant *> &SimplifiedValues; 301 302 ScalarEvolution &SE; 303 304 /// \brief Try to simplify instruction \param I using its SCEV expression. 305 /// 306 /// The idea is that some AddRec expressions become constants, which then 307 /// could trigger folding of other instructions. However, that only happens 308 /// for expressions whose start value is also constant, which isn't always the 309 /// case. In another common and important case the start value is just some 310 /// address (i.e. SCEVUnknown) - in this case we compute the offset and save 311 /// it along with the base address instead. 312 bool simplifyInstWithSCEV(Instruction *I) { 313 if (!SE.isSCEVable(I->getType())) 314 return false; 315 316 const SCEV *S = SE.getSCEV(I); 317 if (auto *SC = dyn_cast<SCEVConstant>(S)) { 318 SimplifiedValues[I] = SC->getValue(); 319 return true; 320 } 321 322 auto *AR = dyn_cast<SCEVAddRecExpr>(S); 323 if (!AR) 324 return false; 325 326 const SCEV *ValueAtIteration = AR->evaluateAtIteration(IterationNumber, SE); 327 // Check if the AddRec expression becomes a constant. 328 if (auto *SC = dyn_cast<SCEVConstant>(ValueAtIteration)) { 329 SimplifiedValues[I] = SC->getValue(); 330 return true; 331 } 332 333 // Check if the offset from the base address becomes a constant. 334 auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(S)); 335 if (!Base) 336 return false; 337 auto *Offset = 338 dyn_cast<SCEVConstant>(SE.getMinusSCEV(ValueAtIteration, Base)); 339 if (!Offset) 340 return false; 341 SimplifiedAddress Address; 342 Address.Base = Base->getValue(); 343 Address.Offset = Offset->getValue(); 344 SimplifiedAddresses[I] = Address; 345 return true; 346 } 347 348 /// Base case for the instruction visitor. 349 bool visitInstruction(Instruction &I) { 350 return simplifyInstWithSCEV(&I); 351 } 352 353 /// Try to simplify binary operator I. 354 /// 355 /// TODO: Probably it's worth to hoist the code for estimating the 356 /// simplifications effects to a separate class, since we have a very similar 357 /// code in InlineCost already. 358 bool visitBinaryOperator(BinaryOperator &I) { 359 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 360 if (!isa<Constant>(LHS)) 361 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS)) 362 LHS = SimpleLHS; 363 if (!isa<Constant>(RHS)) 364 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS)) 365 RHS = SimpleRHS; 366 367 Value *SimpleV = nullptr; 368 const DataLayout &DL = I.getModule()->getDataLayout(); 369 if (auto FI = dyn_cast<FPMathOperator>(&I)) 370 SimpleV = 371 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL); 372 else 373 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL); 374 375 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) 376 SimplifiedValues[&I] = C; 377 378 if (SimpleV) 379 return true; 380 return Base::visitBinaryOperator(I); 381 } 382 383 /// Try to fold load I. 384 bool visitLoad(LoadInst &I) { 385 Value *AddrOp = I.getPointerOperand(); 386 387 auto AddressIt = SimplifiedAddresses.find(AddrOp); 388 if (AddressIt == SimplifiedAddresses.end()) 389 return false; 390 ConstantInt *SimplifiedAddrOp = AddressIt->second.Offset; 391 392 auto *GV = dyn_cast<GlobalVariable>(AddressIt->second.Base); 393 // We're only interested in loads that can be completely folded to a 394 // constant. 395 if (!GV || !GV->hasDefinitiveInitializer() || !GV->isConstant()) 396 return false; 397 398 ConstantDataSequential *CDS = 399 dyn_cast<ConstantDataSequential>(GV->getInitializer()); 400 if (!CDS) 401 return false; 402 403 // We might have a vector load from an array. FIXME: for now we just bail 404 // out in this case, but we should be able to resolve and simplify such 405 // loads. 406 if(!CDS->isElementTypeCompatible(I.getType())) 407 return false; 408 409 int ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U; 410 assert(SimplifiedAddrOp->getValue().getActiveBits() < 64 && 411 "Unexpectedly large index value."); 412 int64_t Index = SimplifiedAddrOp->getSExtValue() / ElemSize; 413 if (Index >= CDS->getNumElements()) { 414 // FIXME: For now we conservatively ignore out of bound accesses, but 415 // we're allowed to perform the optimization in this case. 416 return false; 417 } 418 419 Constant *CV = CDS->getElementAsConstant(Index); 420 assert(CV && "Constant expected."); 421 SimplifiedValues[&I] = CV; 422 423 return true; 424 } 425 426 bool visitCastInst(CastInst &I) { 427 // Propagate constants through casts. 428 Constant *COp = dyn_cast<Constant>(I.getOperand(0)); 429 if (!COp) 430 COp = SimplifiedValues.lookup(I.getOperand(0)); 431 if (COp) 432 if (Constant *C = 433 ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) { 434 SimplifiedValues[&I] = C; 435 return true; 436 } 437 438 return Base::visitCastInst(I); 439 } 440 441 bool visitCmpInst(CmpInst &I) { 442 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 443 444 // First try to handle simplified comparisons. 445 if (!isa<Constant>(LHS)) 446 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS)) 447 LHS = SimpleLHS; 448 if (!isa<Constant>(RHS)) 449 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS)) 450 RHS = SimpleRHS; 451 452 if (!isa<Constant>(LHS) && !isa<Constant>(RHS)) { 453 auto SimplifiedLHS = SimplifiedAddresses.find(LHS); 454 if (SimplifiedLHS != SimplifiedAddresses.end()) { 455 auto SimplifiedRHS = SimplifiedAddresses.find(RHS); 456 if (SimplifiedRHS != SimplifiedAddresses.end()) { 457 SimplifiedAddress &LHSAddr = SimplifiedLHS->second; 458 SimplifiedAddress &RHSAddr = SimplifiedRHS->second; 459 if (LHSAddr.Base == RHSAddr.Base) { 460 LHS = LHSAddr.Offset; 461 RHS = RHSAddr.Offset; 462 } 463 } 464 } 465 } 466 467 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 468 if (Constant *CRHS = dyn_cast<Constant>(RHS)) { 469 if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) { 470 SimplifiedValues[&I] = C; 471 return true; 472 } 473 } 474 } 475 476 return Base::visitCmpInst(I); 477 } 478 }; 479 } // namespace 480 481 482 namespace { 483 struct EstimatedUnrollCost { 484 /// \brief The estimated cost after unrolling. 485 int UnrolledCost; 486 487 /// \brief The estimated dynamic cost of executing the instructions in the 488 /// rolled form. 489 int RolledDynamicCost; 490 }; 491 } 492 493 /// \brief Figure out if the loop is worth full unrolling. 494 /// 495 /// Complete loop unrolling can make some loads constant, and we need to know 496 /// if that would expose any further optimization opportunities. This routine 497 /// estimates this optimization. It computes cost of unrolled loop 498 /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By 499 /// dynamic cost we mean that we won't count costs of blocks that are known not 500 /// to be executed (i.e. if we have a branch in the loop and we know that at the 501 /// given iteration its condition would be resolved to true, we won't add up the 502 /// cost of the 'false'-block). 503 /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If 504 /// the analysis failed (no benefits expected from the unrolling, or the loop is 505 /// too big to analyze), the returned value is None. 506 static Optional<EstimatedUnrollCost> 507 analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT, 508 ScalarEvolution &SE, const TargetTransformInfo &TTI, 509 int MaxUnrolledLoopSize) { 510 // We want to be able to scale offsets by the trip count and add more offsets 511 // to them without checking for overflows, and we already don't want to 512 // analyze *massive* trip counts, so we force the max to be reasonably small. 513 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) && 514 "The unroll iterations max is too large!"); 515 516 // Don't simulate loops with a big or unknown tripcount 517 if (!UnrollMaxIterationsCountToAnalyze || !TripCount || 518 TripCount > UnrollMaxIterationsCountToAnalyze) 519 return None; 520 521 SmallSetVector<BasicBlock *, 16> BBWorklist; 522 DenseMap<Value *, Constant *> SimplifiedValues; 523 SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues; 524 525 // The estimated cost of the unrolled form of the loop. We try to estimate 526 // this by simplifying as much as we can while computing the estimate. 527 int UnrolledCost = 0; 528 // We also track the estimated dynamic (that is, actually executed) cost in 529 // the rolled form. This helps identify cases when the savings from unrolling 530 // aren't just exposing dead control flows, but actual reduced dynamic 531 // instructions due to the simplifications which we expect to occur after 532 // unrolling. 533 int RolledDynamicCost = 0; 534 535 // Ensure that we don't violate the loop structure invariants relied on by 536 // this analysis. 537 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first."); 538 assert(L->isLCSSAForm(DT) && 539 "Must have loops in LCSSA form to track live-out values."); 540 541 DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n"); 542 543 // Simulate execution of each iteration of the loop counting instructions, 544 // which would be simplified. 545 // Since the same load will take different values on different iterations, 546 // we literally have to go through all loop's iterations. 547 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) { 548 DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n"); 549 550 // Prepare for the iteration by collecting any simplified entry or backedge 551 // inputs. 552 for (Instruction &I : *L->getHeader()) { 553 auto *PHI = dyn_cast<PHINode>(&I); 554 if (!PHI) 555 break; 556 557 // The loop header PHI nodes must have exactly two input: one from the 558 // loop preheader and one from the loop latch. 559 assert( 560 PHI->getNumIncomingValues() == 2 && 561 "Must have an incoming value only for the preheader and the latch."); 562 563 Value *V = PHI->getIncomingValueForBlock( 564 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch()); 565 Constant *C = dyn_cast<Constant>(V); 566 if (Iteration != 0 && !C) 567 C = SimplifiedValues.lookup(V); 568 if (C) 569 SimplifiedInputValues.push_back({PHI, C}); 570 } 571 572 // Now clear and re-populate the map for the next iteration. 573 SimplifiedValues.clear(); 574 while (!SimplifiedInputValues.empty()) 575 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val()); 576 577 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE); 578 579 BBWorklist.clear(); 580 BBWorklist.insert(L->getHeader()); 581 // Note that we *must not* cache the size, this loop grows the worklist. 582 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 583 BasicBlock *BB = BBWorklist[Idx]; 584 585 // Visit all instructions in the given basic block and try to simplify 586 // it. We don't change the actual IR, just count optimization 587 // opportunities. 588 for (Instruction &I : *BB) { 589 int InstCost = TTI.getUserCost(&I); 590 591 // Visit the instruction to analyze its loop cost after unrolling, 592 // and if the visitor returns false, include this instruction in the 593 // unrolled cost. 594 if (!Analyzer.visit(I)) 595 UnrolledCost += InstCost; 596 else { 597 DEBUG(dbgs() << " " << I 598 << " would be simplified if loop is unrolled.\n"); 599 (void)0; 600 } 601 602 // Also track this instructions expected cost when executing the rolled 603 // loop form. 604 RolledDynamicCost += InstCost; 605 606 // If unrolled body turns out to be too big, bail out. 607 if (UnrolledCost > MaxUnrolledLoopSize) { 608 DEBUG(dbgs() << " Exceeded threshold.. exiting.\n" 609 << " UnrolledCost: " << UnrolledCost 610 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize 611 << "\n"); 612 return None; 613 } 614 } 615 616 TerminatorInst *TI = BB->getTerminator(); 617 618 // Add in the live successors by first checking whether we have terminator 619 // that may be simplified based on the values simplified by this call. 620 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 621 if (BI->isConditional()) { 622 if (Constant *SimpleCond = 623 SimplifiedValues.lookup(BI->getCondition())) { 624 BasicBlock *Succ = nullptr; 625 // Just take the first successor if condition is undef 626 if (isa<UndefValue>(SimpleCond)) 627 Succ = BI->getSuccessor(0); 628 else 629 Succ = BI->getSuccessor( 630 cast<ConstantInt>(SimpleCond)->isZero() ? 1 : 0); 631 if (L->contains(Succ)) 632 BBWorklist.insert(Succ); 633 continue; 634 } 635 } 636 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 637 if (Constant *SimpleCond = 638 SimplifiedValues.lookup(SI->getCondition())) { 639 BasicBlock *Succ = nullptr; 640 // Just take the first successor if condition is undef 641 if (isa<UndefValue>(SimpleCond)) 642 Succ = SI->getSuccessor(0); 643 else 644 Succ = SI->findCaseValue(cast<ConstantInt>(SimpleCond)) 645 .getCaseSuccessor(); 646 if (L->contains(Succ)) 647 BBWorklist.insert(Succ); 648 continue; 649 } 650 } 651 652 // Add BB's successors to the worklist. 653 for (BasicBlock *Succ : successors(BB)) 654 if (L->contains(Succ)) 655 BBWorklist.insert(Succ); 656 } 657 658 // If we found no optimization opportunities on the first iteration, we 659 // won't find them on later ones too. 660 if (UnrolledCost == RolledDynamicCost) { 661 DEBUG(dbgs() << " No opportunities found.. exiting.\n" 662 << " UnrolledCost: " << UnrolledCost << "\n"); 663 return None; 664 } 665 } 666 DEBUG(dbgs() << "Analysis finished:\n" 667 << "UnrolledCost: " << UnrolledCost << ", " 668 << "RolledDynamicCost: " << RolledDynamicCost << "\n"); 669 return {{UnrolledCost, RolledDynamicCost}}; 670 } 671 672 /// ApproximateLoopSize - Approximate the size of the loop. 673 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, 674 bool &NotDuplicatable, 675 const TargetTransformInfo &TTI, 676 AssumptionCache *AC) { 677 SmallPtrSet<const Value *, 32> EphValues; 678 CodeMetrics::collectEphemeralValues(L, AC, EphValues); 679 680 CodeMetrics Metrics; 681 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 682 I != E; ++I) 683 Metrics.analyzeBasicBlock(*I, TTI, EphValues); 684 NumCalls = Metrics.NumInlineCandidates; 685 NotDuplicatable = Metrics.notDuplicatable; 686 687 unsigned LoopSize = Metrics.NumInsts; 688 689 // Don't allow an estimate of size zero. This would allows unrolling of loops 690 // with huge iteration counts, which is a compile time problem even if it's 691 // not a problem for code quality. Also, the code using this size may assume 692 // that each loop has at least three instructions (likely a conditional 693 // branch, a comparison feeding that branch, and some kind of loop increment 694 // feeding that comparison instruction). 695 LoopSize = std::max(LoopSize, 3u); 696 697 return LoopSize; 698 } 699 700 // Returns the loop hint metadata node with the given name (for example, 701 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is 702 // returned. 703 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) { 704 if (MDNode *LoopID = L->getLoopID()) 705 return GetUnrollMetadata(LoopID, Name); 706 return nullptr; 707 } 708 709 // Returns true if the loop has an unroll(full) pragma. 710 static bool HasUnrollFullPragma(const Loop *L) { 711 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full"); 712 } 713 714 // Returns true if the loop has an unroll(enable) pragma. This metadata is used 715 // for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives. 716 static bool HasUnrollEnablePragma(const Loop *L) { 717 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable"); 718 } 719 720 // Returns true if the loop has an unroll(disable) pragma. 721 static bool HasUnrollDisablePragma(const Loop *L) { 722 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable"); 723 } 724 725 // Returns true if the loop has an runtime unroll(disable) pragma. 726 static bool HasRuntimeUnrollDisablePragma(const Loop *L) { 727 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable"); 728 } 729 730 // If loop has an unroll_count pragma return the (necessarily 731 // positive) value from the pragma. Otherwise return 0. 732 static unsigned UnrollCountPragmaValue(const Loop *L) { 733 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); 734 if (MD) { 735 assert(MD->getNumOperands() == 2 && 736 "Unroll count hint metadata should have two operands."); 737 unsigned Count = 738 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 739 assert(Count >= 1 && "Unroll count must be positive."); 740 return Count; 741 } 742 return 0; 743 } 744 745 // Remove existing unroll metadata and add unroll disable metadata to 746 // indicate the loop has already been unrolled. This prevents a loop 747 // from being unrolled more than is directed by a pragma if the loop 748 // unrolling pass is run more than once (which it generally is). 749 static void SetLoopAlreadyUnrolled(Loop *L) { 750 MDNode *LoopID = L->getLoopID(); 751 if (!LoopID) return; 752 753 // First remove any existing loop unrolling metadata. 754 SmallVector<Metadata *, 4> MDs; 755 // Reserve first location for self reference to the LoopID metadata node. 756 MDs.push_back(nullptr); 757 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 758 bool IsUnrollMetadata = false; 759 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 760 if (MD) { 761 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 762 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 763 } 764 if (!IsUnrollMetadata) 765 MDs.push_back(LoopID->getOperand(i)); 766 } 767 768 // Add unroll(disable) metadata to disable future unrolling. 769 LLVMContext &Context = L->getHeader()->getContext(); 770 SmallVector<Metadata *, 1> DisableOperands; 771 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 772 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 773 MDs.push_back(DisableNode); 774 775 MDNode *NewLoopID = MDNode::get(Context, MDs); 776 // Set operand 0 to refer to the loop id itself. 777 NewLoopID->replaceOperandWith(0, NewLoopID); 778 L->setLoopID(NewLoopID); 779 } 780 781 static bool canUnrollCompletely(Loop *L, unsigned Threshold, 782 unsigned PercentDynamicCostSavedThreshold, 783 unsigned DynamicCostSavingsDiscount, 784 uint64_t UnrolledCost, 785 uint64_t RolledDynamicCost) { 786 if (Threshold == NoThreshold) { 787 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n"); 788 return true; 789 } 790 791 if (UnrolledCost <= Threshold) { 792 DEBUG(dbgs() << " Can fully unroll, because unrolled cost: " 793 << UnrolledCost << "<" << Threshold << "\n"); 794 return true; 795 } 796 797 assert(UnrolledCost && "UnrolledCost can't be 0 at this point."); 798 assert(RolledDynamicCost >= UnrolledCost && 799 "Cannot have a higher unrolled cost than a rolled cost!"); 800 801 // Compute the percentage of the dynamic cost in the rolled form that is 802 // saved when unrolled. If unrolling dramatically reduces the estimated 803 // dynamic cost of the loop, we use a higher threshold to allow more 804 // unrolling. 805 unsigned PercentDynamicCostSaved = 806 (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost; 807 808 if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold && 809 (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <= 810 (int64_t)Threshold) { 811 DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the " 812 "expected dynamic cost by " << PercentDynamicCostSaved 813 << "% (threshold: " << PercentDynamicCostSavedThreshold 814 << "%)\n" 815 << " and the unrolled cost (" << UnrolledCost 816 << ") is less than the max threshold (" 817 << DynamicCostSavingsDiscount << ").\n"); 818 return true; 819 } 820 821 DEBUG(dbgs() << " Too large to fully unroll:\n"); 822 DEBUG(dbgs() << " Threshold: " << Threshold << "\n"); 823 DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n"); 824 DEBUG(dbgs() << " Percent cost saved threshold: " 825 << PercentDynamicCostSavedThreshold << "%\n"); 826 DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n"); 827 DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n"); 828 DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved 829 << "\n"); 830 return false; 831 } 832 833 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &) { 834 if (skipOptnoneFunction(L)) 835 return false; 836 837 Function &F = *L->getHeader()->getParent(); 838 839 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 840 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 841 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 842 const TargetTransformInfo &TTI = 843 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 844 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 845 bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 846 847 BasicBlock *Header = L->getHeader(); 848 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName() 849 << "] Loop %" << Header->getName() << "\n"); 850 851 if (HasUnrollDisablePragma(L)) { 852 return false; 853 } 854 bool PragmaFullUnroll = HasUnrollFullPragma(L); 855 bool PragmaEnableUnroll = HasUnrollEnablePragma(L); 856 unsigned PragmaCount = UnrollCountPragmaValue(L); 857 bool HasPragma = PragmaFullUnroll || PragmaEnableUnroll || PragmaCount > 0; 858 859 // Find trip count and trip multiple if count is not available 860 unsigned TripCount = 0; 861 unsigned TripMultiple = 1; 862 // If there are multiple exiting blocks but one of them is the latch, use the 863 // latch for the trip count estimation. Otherwise insist on a single exiting 864 // block for the trip count estimation. 865 BasicBlock *ExitingBlock = L->getLoopLatch(); 866 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) 867 ExitingBlock = L->getExitingBlock(); 868 if (ExitingBlock) { 869 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); 870 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); 871 } 872 873 TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences( 874 L, TTI, ProvidedThreshold, ProvidedCount, ProvidedAllowPartial, 875 ProvidedRuntime, PragmaCount, PragmaFullUnroll, PragmaEnableUnroll, 876 TripCount); 877 878 unsigned Count = UP.Count; 879 bool CountSetExplicitly = Count != 0; 880 // Use a heuristic count if we didn't set anything explicitly. 881 if (!CountSetExplicitly) 882 Count = TripCount == 0 ? DefaultUnrollRuntimeCount : TripCount; 883 if (TripCount && Count > TripCount) 884 Count = TripCount; 885 886 unsigned NumInlineCandidates; 887 bool notDuplicatable; 888 unsigned LoopSize = 889 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC); 890 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); 891 892 // When computing the unrolled size, note that the conditional branch on the 893 // backedge and the comparison feeding it are not replicated like the rest of 894 // the loop body (which is why 2 is subtracted). 895 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2; 896 if (notDuplicatable) { 897 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" 898 << " instructions.\n"); 899 return false; 900 } 901 if (NumInlineCandidates != 0) { 902 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); 903 return false; 904 } 905 906 // Given Count, TripCount and thresholds determine the type of 907 // unrolling which is to be performed. 908 enum { Full = 0, Partial = 1, Runtime = 2 }; 909 int Unrolling; 910 if (TripCount && Count == TripCount) { 911 Unrolling = Partial; 912 // If the loop is really small, we don't need to run an expensive analysis. 913 if (canUnrollCompletely(L, UP.Threshold, 100, UP.DynamicCostSavingsDiscount, 914 UnrolledSize, UnrolledSize)) { 915 Unrolling = Full; 916 } else { 917 // The loop isn't that small, but we still can fully unroll it if that 918 // helps to remove a significant number of instructions. 919 // To check that, run additional analysis on the loop. 920 if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost( 921 L, TripCount, DT, *SE, TTI, 922 UP.Threshold + UP.DynamicCostSavingsDiscount)) 923 if (canUnrollCompletely(L, UP.Threshold, 924 UP.PercentDynamicCostSavedThreshold, 925 UP.DynamicCostSavingsDiscount, 926 Cost->UnrolledCost, Cost->RolledDynamicCost)) { 927 Unrolling = Full; 928 } 929 } 930 } else if (TripCount && Count < TripCount) { 931 Unrolling = Partial; 932 } else { 933 Unrolling = Runtime; 934 } 935 936 // Reduce count based on the type of unrolling and the threshold values. 937 unsigned OriginalCount = Count; 938 bool AllowRuntime = PragmaEnableUnroll || (PragmaCount > 0) || UP.Runtime; 939 // Don't unroll a runtime trip count loop with unroll full pragma. 940 if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) { 941 AllowRuntime = false; 942 } 943 if (Unrolling == Partial) { 944 bool AllowPartial = PragmaEnableUnroll || UP.Partial; 945 if (!AllowPartial && !CountSetExplicitly) { 946 DEBUG(dbgs() << " will not try to unroll partially because " 947 << "-unroll-allow-partial not given\n"); 948 return false; 949 } 950 if (UP.PartialThreshold != NoThreshold && 951 UnrolledSize > UP.PartialThreshold) { 952 // Reduce unroll count to be modulo of TripCount for partial unrolling. 953 Count = (std::max(UP.PartialThreshold, 3u) - 2) / (LoopSize - 2); 954 while (Count != 0 && TripCount % Count != 0) 955 Count--; 956 } 957 } else if (Unrolling == Runtime) { 958 if (!AllowRuntime && !CountSetExplicitly) { 959 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " 960 << "-unroll-runtime not given\n"); 961 return false; 962 } 963 // Reduce unroll count to be the largest power-of-two factor of 964 // the original count which satisfies the threshold limit. 965 while (Count != 0 && UnrolledSize > UP.PartialThreshold) { 966 Count >>= 1; 967 UnrolledSize = (LoopSize-2) * Count + 2; 968 } 969 if (Count > UP.MaxCount) 970 Count = UP.MaxCount; 971 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n"); 972 } 973 974 if (HasPragma) { 975 if (PragmaCount != 0) 976 // If loop has an unroll count pragma mark loop as unrolled to prevent 977 // unrolling beyond that requested by the pragma. 978 SetLoopAlreadyUnrolled(L); 979 980 // Emit optimization remarks if we are unable to unroll the loop 981 // as directed by a pragma. 982 DebugLoc LoopLoc = L->getStartLoc(); 983 Function *F = Header->getParent(); 984 LLVMContext &Ctx = F->getContext(); 985 if ((PragmaCount > 0) && Count != OriginalCount) { 986 emitOptimizationRemarkMissed( 987 Ctx, DEBUG_TYPE, *F, LoopLoc, 988 "Unable to unroll loop the number of times directed by " 989 "unroll_count pragma because unrolled size is too large."); 990 } else if (PragmaFullUnroll && !TripCount) { 991 emitOptimizationRemarkMissed( 992 Ctx, DEBUG_TYPE, *F, LoopLoc, 993 "Unable to fully unroll loop as directed by unroll(full) pragma " 994 "because loop has a runtime trip count."); 995 } else if (PragmaEnableUnroll && Count != TripCount && Count < 2) { 996 emitOptimizationRemarkMissed( 997 Ctx, DEBUG_TYPE, *F, LoopLoc, 998 "Unable to unroll loop as directed by unroll(enable) pragma because " 999 "unrolled size is too large."); 1000 } else if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount && 1001 Count != TripCount) { 1002 emitOptimizationRemarkMissed( 1003 Ctx, DEBUG_TYPE, *F, LoopLoc, 1004 "Unable to fully unroll loop as directed by unroll pragma because " 1005 "unrolled size is too large."); 1006 } 1007 } 1008 1009 if (Unrolling != Full && Count < 2) { 1010 // Partial unrolling by 1 is a nop. For full unrolling, a factor 1011 // of 1 makes sense because loop control can be eliminated. 1012 return false; 1013 } 1014 1015 // Unroll the loop. 1016 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount, 1017 TripMultiple, LI, SE, &DT, &AC, PreserveLCSSA)) 1018 return false; 1019 1020 return true; 1021 } 1022