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