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/LoopPass.h" 20 #include "llvm/Analysis/ScalarEvolution.h" 21 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 22 #include "llvm/Analysis/TargetTransformInfo.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DiagnosticInfo.h" 25 #include "llvm/IR/Dominators.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/Metadata.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include "llvm/Transforms/Utils/UnrollLoop.h" 32 #include "llvm/IR/InstVisitor.h" 33 #include "llvm/Analysis/InstructionSimplify.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 cut-off point for automatic loop unrolling")); 43 44 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze( 45 "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden, 46 cl::desc("Don't allow loop unrolling to simulate more than this number of" 47 "iterations when checking full unroll profitability")); 48 49 static cl::opt<unsigned> UnrollMinPercentOfOptimized( 50 "unroll-percent-of-optimized-for-complete-unroll", cl::init(20), cl::Hidden, 51 cl::desc("If complete unrolling could trigger further optimizations, and, " 52 "by that, remove the given percent of instructions, perform the " 53 "complete unroll even if it's beyond the threshold")); 54 55 static cl::opt<unsigned> UnrollAbsoluteThreshold( 56 "unroll-absolute-threshold", cl::init(2000), cl::Hidden, 57 cl::desc("Don't unroll if the unrolled size is bigger than this threshold," 58 " even if we can remove big portion of instructions later.")); 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 CurrentAbsoluteThreshold = UnrollAbsoluteThreshold; 86 CurrentMinPercentOfOptimized = UnrollMinPercentOfOptimized; 87 CurrentCount = (C == -1) ? UnrollCount : unsigned(C); 88 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P; 89 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R; 90 91 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0); 92 UserAbsoluteThreshold = (UnrollAbsoluteThreshold.getNumOccurrences() > 0); 93 UserPercentOfOptimized = 94 (UnrollMinPercentOfOptimized.getNumOccurrences() > 0); 95 UserAllowPartial = (P != -1) || 96 (UnrollAllowPartial.getNumOccurrences() > 0); 97 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0); 98 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0); 99 100 initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); 101 } 102 103 /// A magic value for use with the Threshold parameter to indicate 104 /// that the loop unroll should be performed regardless of how much 105 /// code expansion would result. 106 static const unsigned NoThreshold = UINT_MAX; 107 108 // Threshold to use when optsize is specified (and there is no 109 // explicit -unroll-threshold). 110 static const unsigned OptSizeUnrollThreshold = 50; 111 112 // Default unroll count for loops with run-time trip count if 113 // -unroll-count is not set 114 static const unsigned UnrollRuntimeCount = 8; 115 116 unsigned CurrentCount; 117 unsigned CurrentThreshold; 118 unsigned CurrentAbsoluteThreshold; 119 unsigned CurrentMinPercentOfOptimized; 120 bool CurrentAllowPartial; 121 bool CurrentRuntime; 122 bool UserCount; // CurrentCount is user-specified. 123 bool UserThreshold; // CurrentThreshold is user-specified. 124 bool UserAbsoluteThreshold; // CurrentAbsoluteThreshold is 125 // user-specified. 126 bool UserPercentOfOptimized; // CurrentMinPercentOfOptimized is 127 // user-specified. 128 bool UserAllowPartial; // CurrentAllowPartial is user-specified. 129 bool UserRuntime; // CurrentRuntime is user-specified. 130 131 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 132 133 /// This transformation requires natural loop information & requires that 134 /// loop preheaders be inserted into the CFG... 135 /// 136 void getAnalysisUsage(AnalysisUsage &AU) const override { 137 AU.addRequired<AssumptionCacheTracker>(); 138 AU.addRequired<LoopInfoWrapperPass>(); 139 AU.addPreserved<LoopInfoWrapperPass>(); 140 AU.addRequiredID(LoopSimplifyID); 141 AU.addPreservedID(LoopSimplifyID); 142 AU.addRequiredID(LCSSAID); 143 AU.addPreservedID(LCSSAID); 144 AU.addRequired<ScalarEvolution>(); 145 AU.addPreserved<ScalarEvolution>(); 146 AU.addRequired<TargetTransformInfoWrapperPass>(); 147 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. 148 // If loop unroll does not preserve dom info then LCSSA pass on next 149 // loop will receive invalid dom info. 150 // For now, recreate dom info, if loop is unrolled. 151 AU.addPreserved<DominatorTreeWrapperPass>(); 152 } 153 154 // Fill in the UnrollingPreferences parameter with values from the 155 // TargetTransformationInfo. 156 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI, 157 TargetTransformInfo::UnrollingPreferences &UP) { 158 UP.Threshold = CurrentThreshold; 159 UP.AbsoluteThreshold = CurrentAbsoluteThreshold; 160 UP.MinPercentOfOptimized = CurrentMinPercentOfOptimized; 161 UP.OptSizeThreshold = OptSizeUnrollThreshold; 162 UP.PartialThreshold = CurrentThreshold; 163 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold; 164 UP.Count = CurrentCount; 165 UP.MaxCount = UINT_MAX; 166 UP.Partial = CurrentAllowPartial; 167 UP.Runtime = CurrentRuntime; 168 TTI.getUnrollingPreferences(L, UP); 169 } 170 171 // Select and return an unroll count based on parameters from 172 // user, unroll preferences, unroll pragmas, or a heuristic. 173 // SetExplicitly is set to true if the unroll count is is set by 174 // the user or a pragma rather than selected heuristically. 175 unsigned 176 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 177 unsigned PragmaCount, 178 const TargetTransformInfo::UnrollingPreferences &UP, 179 bool &SetExplicitly); 180 181 // Select threshold values used to limit unrolling based on a 182 // total unrolled size. Parameters Threshold and PartialThreshold 183 // are set to the maximum unrolled size for fully and partially 184 // unrolled loops respectively. 185 void selectThresholds(const Loop *L, bool HasPragma, 186 const TargetTransformInfo::UnrollingPreferences &UP, 187 unsigned &Threshold, unsigned &PartialThreshold, 188 unsigned NumberOfOptimizedInstructions) { 189 // Determine the current unrolling threshold. While this is 190 // normally set from UnrollThreshold, it is overridden to a 191 // smaller value if the current function is marked as 192 // optimize-for-size, and the unroll threshold was not user 193 // specified. 194 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold; 195 196 // If we are allowed to completely unroll if we can remove M% of 197 // instructions, and we know that with complete unrolling we'll be able 198 // to kill N instructions, then we can afford to completely unroll loops 199 // with unrolled size up to N*100/M. 200 // Adjust the threshold according to that: 201 unsigned PercentOfOptimizedForCompleteUnroll = 202 UserPercentOfOptimized ? CurrentMinPercentOfOptimized 203 : UP.MinPercentOfOptimized; 204 unsigned AbsoluteThreshold = UserAbsoluteThreshold 205 ? CurrentAbsoluteThreshold 206 : UP.AbsoluteThreshold; 207 if (PercentOfOptimizedForCompleteUnroll) 208 Threshold = std::max<unsigned>(Threshold, 209 NumberOfOptimizedInstructions * 100 / 210 PercentOfOptimizedForCompleteUnroll); 211 // But don't allow unrolling loops bigger than absolute threshold. 212 Threshold = std::min<unsigned>(Threshold, AbsoluteThreshold); 213 214 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold; 215 if (!UserThreshold && 216 L->getHeader()->getParent()->hasFnAttribute( 217 Attribute::OptimizeForSize)) { 218 Threshold = UP.OptSizeThreshold; 219 PartialThreshold = UP.PartialOptSizeThreshold; 220 } 221 if (HasPragma) { 222 // If the loop has an unrolling pragma, we want to be more 223 // aggressive with unrolling limits. Set thresholds to at 224 // least the PragmaTheshold value which is larger than the 225 // default limits. 226 if (Threshold != NoThreshold) 227 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold); 228 if (PartialThreshold != NoThreshold) 229 PartialThreshold = 230 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold); 231 } 232 } 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(LoopInfoWrapperPass) 241 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 242 INITIALIZE_PASS_DEPENDENCY(LCSSA) 243 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 244 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 245 246 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial, 247 int Runtime) { 248 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime); 249 } 250 251 Pass *llvm::createSimpleLoopUnrollPass() { 252 return llvm::createLoopUnrollPass(-1, -1, 0, 0); 253 } 254 255 static bool isLoadFromConstantInitializer(Value *V) { 256 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 257 if (GV->isConstant() && GV->hasDefinitiveInitializer()) 258 return GV->getInitializer(); 259 return false; 260 } 261 262 struct FindConstantPointers { 263 bool LoadCanBeConstantFolded; 264 bool IndexIsConstant; 265 APInt Step; 266 APInt StartValue; 267 Value *BaseAddress; 268 const Loop *L; 269 ScalarEvolution &SE; 270 FindConstantPointers(const Loop *loop, ScalarEvolution &SE) 271 : LoadCanBeConstantFolded(true), IndexIsConstant(true), L(loop), SE(SE) {} 272 273 bool follow(const SCEV *S) { 274 if (const SCEVUnknown *SC = dyn_cast<SCEVUnknown>(S)) { 275 // We've reached the leaf node of SCEV, it's most probably just a 276 // variable. Now it's time to see if it corresponds to a global constant 277 // global (in which case we can eliminate the load), or not. 278 BaseAddress = SC->getValue(); 279 LoadCanBeConstantFolded = 280 IndexIsConstant && isLoadFromConstantInitializer(BaseAddress); 281 return false; 282 } 283 if (isa<SCEVConstant>(S)) 284 return true; 285 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 286 // If the current SCEV expression is AddRec, and its loop isn't the loop 287 // we are about to unroll, then we won't get a constant address after 288 // unrolling, and thus, won't be able to eliminate the load. 289 if (AR->getLoop() != L) 290 return IndexIsConstant = false; 291 // If the step isn't constant, we won't get constant addresses in unrolled 292 // version. Bail out. 293 if (const SCEVConstant *StepSE = 294 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 295 Step = StepSE->getValue()->getValue(); 296 else 297 return IndexIsConstant = false; 298 299 return IndexIsConstant; 300 } 301 // If Result is true, continue traversal. 302 // Otherwise, we have found something that prevents us from (possible) load 303 // elimination. 304 return IndexIsConstant; 305 } 306 bool isDone() const { return !IndexIsConstant; } 307 }; 308 309 // This class is used to get an estimate of the optimization effects that we 310 // could get from complete loop unrolling. It comes from the fact that some 311 // loads might be replaced with concrete constant values and that could trigger 312 // a chain of instruction simplifications. 313 // 314 // E.g. we might have: 315 // int a[] = {0, 1, 0}; 316 // v = 0; 317 // for (i = 0; i < 3; i ++) 318 // v += b[i]*a[i]; 319 // If we completely unroll the loop, we would get: 320 // v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2] 321 // Which then will be simplified to: 322 // v = b[0]* 0 + b[1]* 1 + b[2]* 0 323 // And finally: 324 // v = b[1] 325 class UnrollAnalyzer : public InstVisitor<UnrollAnalyzer, bool> { 326 typedef InstVisitor<UnrollAnalyzer, bool> Base; 327 friend class InstVisitor<UnrollAnalyzer, bool>; 328 329 const Loop *L; 330 unsigned TripCount; 331 ScalarEvolution &SE; 332 const TargetTransformInfo &TTI; 333 334 DenseMap<Value *, Constant *> SimplifiedValues; 335 DenseMap<LoadInst *, Value *> LoadBaseAddresses; 336 SmallPtrSet<Instruction *, 32> CountedInstructions; 337 338 /// \brief Count the number of optimized instructions. 339 unsigned NumberOfOptimizedInstructions; 340 341 // Provide base case for our instruction visit. 342 bool visitInstruction(Instruction &I) { return false; }; 343 // TODO: We should also visit ICmp, FCmp, GetElementPtr, Trunc, ZExt, SExt, 344 // FPTrunc, FPExt, FPToUI, FPToSI, UIToFP, SIToFP, BitCast, Select, 345 // ExtractElement, InsertElement, ShuffleVector, ExtractValue, InsertValue. 346 // 347 // Probaly it's worth to hoist the code for estimating the simplifications 348 // effects to a separate class, since we have a very similar code in 349 // InlineCost already. 350 bool visitBinaryOperator(BinaryOperator &I) { 351 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 352 if (!isa<Constant>(LHS)) 353 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS)) 354 LHS = SimpleLHS; 355 if (!isa<Constant>(RHS)) 356 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS)) 357 RHS = SimpleRHS; 358 Value *SimpleV = nullptr; 359 if (auto FI = dyn_cast<FPMathOperator>(&I)) 360 SimpleV = 361 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags()); 362 else 363 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS); 364 365 if (SimpleV && CountedInstructions.insert(&I).second) 366 NumberOfOptimizedInstructions += TTI.getUserCost(&I); 367 368 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) { 369 SimplifiedValues[&I] = C; 370 return true; 371 } 372 return false; 373 } 374 375 Constant *computeLoadValue(LoadInst *LI, unsigned Iteration) { 376 if (!LI) 377 return nullptr; 378 Value *BaseAddr = LoadBaseAddresses[LI]; 379 if (!BaseAddr) 380 return nullptr; 381 382 auto GV = dyn_cast<GlobalVariable>(BaseAddr); 383 if (!GV) 384 return nullptr; 385 386 ConstantDataSequential *CDS = 387 dyn_cast<ConstantDataSequential>(GV->getInitializer()); 388 if (!CDS) 389 return nullptr; 390 391 const SCEV *BaseAddrSE = SE.getSCEV(BaseAddr); 392 const SCEV *S = SE.getSCEV(LI->getPointerOperand()); 393 const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE); 394 395 APInt StepC, StartC; 396 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE); 397 if (!AR) 398 return nullptr; 399 400 if (const SCEVConstant *StepSE = 401 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 402 StepC = StepSE->getValue()->getValue(); 403 else 404 return nullptr; 405 406 if (const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart())) 407 StartC = StartSE->getValue()->getValue(); 408 else 409 return nullptr; 410 411 unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U; 412 unsigned Start = StartC.getLimitedValue(); 413 unsigned Step = StepC.getLimitedValue(); 414 415 unsigned Index = (Start + Step * Iteration) / ElemSize; 416 if (Index >= CDS->getNumElements()) 417 return nullptr; 418 419 Constant *CV = CDS->getElementAsConstant(Index); 420 421 return CV; 422 } 423 424 public: 425 UnrollAnalyzer(const Loop *L, unsigned TripCount, ScalarEvolution &SE, 426 const TargetTransformInfo &TTI) 427 : L(L), TripCount(TripCount), SE(SE), TTI(TTI), 428 NumberOfOptimizedInstructions(0) {} 429 430 // Visit all loads the loop L, and for those that, after complete loop 431 // unrolling, would have a constant address and it will point to a known 432 // constant initializer, record its base address for future use. It is used 433 // when we estimate number of potentially simplified instructions. 434 void findConstFoldableLoads() { 435 for (auto BB : L->getBlocks()) { 436 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 437 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 438 if (!LI->isSimple()) 439 continue; 440 Value *AddrOp = LI->getPointerOperand(); 441 const SCEV *S = SE.getSCEV(AddrOp); 442 FindConstantPointers Visitor(L, SE); 443 SCEVTraversal<FindConstantPointers> T(Visitor); 444 T.visitAll(S); 445 if (Visitor.IndexIsConstant && Visitor.LoadCanBeConstantFolded) { 446 LoadBaseAddresses[LI] = Visitor.BaseAddress; 447 } 448 } 449 } 450 } 451 } 452 453 // Given a list of loads that could be constant-folded (LoadBaseAddresses), 454 // estimate number of optimized instructions after substituting the concrete 455 // values for the given Iteration. Also track how many instructions become 456 // dead through this process. 457 unsigned estimateNumberOfOptimizedInstructions(unsigned Iteration) { 458 // We keep a set vector for the worklist so that we don't wast space in the 459 // worklist queuing up the same instruction repeatedly. This can happen due 460 // to multiple operands being the same instruction or due to the same 461 // instruction being an operand of lots of things that end up dead or 462 // simplified. 463 SmallSetVector<Instruction *, 8> Worklist; 464 465 // Clear the simplified values and counts for this iteration. 466 SimplifiedValues.clear(); 467 CountedInstructions.clear(); 468 NumberOfOptimizedInstructions = 0; 469 470 // We start by adding all loads to the worklist. 471 for (auto &LoadDescr : LoadBaseAddresses) { 472 LoadInst *LI = LoadDescr.first; 473 SimplifiedValues[LI] = computeLoadValue(LI, Iteration); 474 if (CountedInstructions.insert(LI).second) 475 NumberOfOptimizedInstructions += TTI.getUserCost(LI); 476 477 for (User *U : LI->users()) 478 Worklist.insert(cast<Instruction>(U)); 479 } 480 481 // And then we try to simplify every user of every instruction from the 482 // worklist. If we do simplify a user, add it to the worklist to process 483 // its users as well. 484 while (!Worklist.empty()) { 485 Instruction *I = Worklist.pop_back_val(); 486 if (!L->contains(I)) 487 continue; 488 if (!visit(I)) 489 continue; 490 for (User *U : I->users()) 491 Worklist.insert(cast<Instruction>(U)); 492 } 493 494 // Now that we know the potentially simplifed instructions, estimate number 495 // of instructions that would become dead if we do perform the 496 // simplification. 497 498 // The dead instructions are held in a separate set. This is used to 499 // prevent us from re-examining instructions and make sure we only count 500 // the benifit once. The worklist's internal set handles insertion 501 // deduplication. 502 SmallPtrSet<Instruction *, 16> DeadInstructions; 503 504 // Lambda to enque operands onto the worklist. 505 auto EnqueueOperands = [&](Instruction &I) { 506 for (auto *Op : I.operand_values()) 507 if (auto *OpI = dyn_cast<Instruction>(Op)) 508 if (!OpI->use_empty()) 509 Worklist.insert(OpI); 510 }; 511 512 // Start by initializing worklist with simplified instructions. 513 for (auto &FoldedKeyValue : SimplifiedValues) 514 if (auto *FoldedInst = dyn_cast<Instruction>(FoldedKeyValue.first)) { 515 DeadInstructions.insert(FoldedInst); 516 517 // Add each instruction operand of this dead instruction to the 518 // worklist. 519 EnqueueOperands(*FoldedInst); 520 } 521 522 // If a definition of an insn is only used by simplified or dead 523 // instructions, it's also dead. Check defs of all instructions from the 524 // worklist. 525 while (!Worklist.empty()) { 526 Instruction *I = Worklist.pop_back_val(); 527 if (!L->contains(I)) 528 continue; 529 if (DeadInstructions.count(I)) 530 continue; 531 532 if (std::all_of(I->user_begin(), I->user_end(), [&](User *U) { 533 return DeadInstructions.count(cast<Instruction>(U)); 534 })) { 535 NumberOfOptimizedInstructions += TTI.getUserCost(I); 536 DeadInstructions.insert(I); 537 EnqueueOperands(*I); 538 } 539 } 540 return NumberOfOptimizedInstructions; 541 } 542 }; 543 544 // Complete loop unrolling can make some loads constant, and we need to know if 545 // that would expose any further optimization opportunities. 546 // This routine estimates this optimization effect and returns the number of 547 // instructions, that potentially might be optimized away. 548 static unsigned 549 approximateNumberOfOptimizedInstructions(const Loop *L, ScalarEvolution &SE, 550 unsigned TripCount, 551 const TargetTransformInfo &TTI) { 552 if (!TripCount || !UnrollMaxIterationsCountToAnalyze) 553 return 0; 554 555 UnrollAnalyzer UA(L, TripCount, SE, TTI); 556 UA.findConstFoldableLoads(); 557 558 // Estimate number of instructions, that could be simplified if we replace a 559 // load with the corresponding constant. Since the same load will take 560 // different values on different iterations, we have to go through all loop's 561 // iterations here. To limit ourselves here, we check only first N 562 // iterations, and then scale the found number, if necessary. 563 unsigned IterationsNumberForEstimate = 564 std::min<unsigned>(UnrollMaxIterationsCountToAnalyze, TripCount); 565 unsigned NumberOfOptimizedInstructions = 0; 566 for (unsigned i = 0; i < IterationsNumberForEstimate; ++i) 567 NumberOfOptimizedInstructions += 568 UA.estimateNumberOfOptimizedInstructions(i); 569 570 NumberOfOptimizedInstructions *= TripCount / IterationsNumberForEstimate; 571 572 return NumberOfOptimizedInstructions; 573 } 574 575 /// ApproximateLoopSize - Approximate the size of the loop. 576 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, 577 bool &NotDuplicatable, 578 const TargetTransformInfo &TTI, 579 AssumptionCache *AC) { 580 SmallPtrSet<const Value *, 32> EphValues; 581 CodeMetrics::collectEphemeralValues(L, AC, EphValues); 582 583 CodeMetrics Metrics; 584 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 585 I != E; ++I) 586 Metrics.analyzeBasicBlock(*I, TTI, EphValues); 587 NumCalls = Metrics.NumInlineCandidates; 588 NotDuplicatable = Metrics.notDuplicatable; 589 590 unsigned LoopSize = Metrics.NumInsts; 591 592 // Don't allow an estimate of size zero. This would allows unrolling of loops 593 // with huge iteration counts, which is a compile time problem even if it's 594 // not a problem for code quality. Also, the code using this size may assume 595 // that each loop has at least three instructions (likely a conditional 596 // branch, a comparison feeding that branch, and some kind of loop increment 597 // feeding that comparison instruction). 598 LoopSize = std::max(LoopSize, 3u); 599 600 return LoopSize; 601 } 602 603 // Returns the loop hint metadata node with the given name (for example, 604 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is 605 // returned. 606 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) { 607 if (MDNode *LoopID = L->getLoopID()) 608 return GetUnrollMetadata(LoopID, Name); 609 return nullptr; 610 } 611 612 // Returns true if the loop has an unroll(full) pragma. 613 static bool HasUnrollFullPragma(const Loop *L) { 614 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full"); 615 } 616 617 // Returns true if the loop has an unroll(disable) pragma. 618 static bool HasUnrollDisablePragma(const Loop *L) { 619 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable"); 620 } 621 622 // If loop has an unroll_count pragma return the (necessarily 623 // positive) value from the pragma. Otherwise return 0. 624 static unsigned UnrollCountPragmaValue(const Loop *L) { 625 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); 626 if (MD) { 627 assert(MD->getNumOperands() == 2 && 628 "Unroll count hint metadata should have two operands."); 629 unsigned Count = 630 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 631 assert(Count >= 1 && "Unroll count must be positive."); 632 return Count; 633 } 634 return 0; 635 } 636 637 // Remove existing unroll metadata and add unroll disable metadata to 638 // indicate the loop has already been unrolled. This prevents a loop 639 // from being unrolled more than is directed by a pragma if the loop 640 // unrolling pass is run more than once (which it generally is). 641 static void SetLoopAlreadyUnrolled(Loop *L) { 642 MDNode *LoopID = L->getLoopID(); 643 if (!LoopID) return; 644 645 // First remove any existing loop unrolling metadata. 646 SmallVector<Metadata *, 4> MDs; 647 // Reserve first location for self reference to the LoopID metadata node. 648 MDs.push_back(nullptr); 649 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 650 bool IsUnrollMetadata = false; 651 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 652 if (MD) { 653 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 654 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 655 } 656 if (!IsUnrollMetadata) 657 MDs.push_back(LoopID->getOperand(i)); 658 } 659 660 // Add unroll(disable) metadata to disable future unrolling. 661 LLVMContext &Context = L->getHeader()->getContext(); 662 SmallVector<Metadata *, 1> DisableOperands; 663 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 664 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 665 MDs.push_back(DisableNode); 666 667 MDNode *NewLoopID = MDNode::get(Context, MDs); 668 // Set operand 0 to refer to the loop id itself. 669 NewLoopID->replaceOperandWith(0, NewLoopID); 670 L->setLoopID(NewLoopID); 671 } 672 673 unsigned LoopUnroll::selectUnrollCount( 674 const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 675 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP, 676 bool &SetExplicitly) { 677 SetExplicitly = true; 678 679 // User-specified count (either as a command-line option or 680 // constructor parameter) has highest precedence. 681 unsigned Count = UserCount ? CurrentCount : 0; 682 683 // If there is no user-specified count, unroll pragmas have the next 684 // highest precendence. 685 if (Count == 0) { 686 if (PragmaCount) { 687 Count = PragmaCount; 688 } else if (PragmaFullUnroll) { 689 Count = TripCount; 690 } 691 } 692 693 if (Count == 0) 694 Count = UP.Count; 695 696 if (Count == 0) { 697 SetExplicitly = false; 698 if (TripCount == 0) 699 // Runtime trip count. 700 Count = UnrollRuntimeCount; 701 else 702 // Conservative heuristic: if we know the trip count, see if we can 703 // completely unroll (subject to the threshold, checked below); otherwise 704 // try to find greatest modulo of the trip count which is still under 705 // threshold value. 706 Count = TripCount; 707 } 708 if (TripCount && Count > TripCount) 709 return TripCount; 710 return Count; 711 } 712 713 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) { 714 if (skipOptnoneFunction(L)) 715 return false; 716 717 Function &F = *L->getHeader()->getParent(); 718 719 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 720 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>(); 721 const TargetTransformInfo &TTI = 722 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 723 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 724 725 BasicBlock *Header = L->getHeader(); 726 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName() 727 << "] Loop %" << Header->getName() << "\n"); 728 729 if (HasUnrollDisablePragma(L)) { 730 return false; 731 } 732 bool PragmaFullUnroll = HasUnrollFullPragma(L); 733 unsigned PragmaCount = UnrollCountPragmaValue(L); 734 bool HasPragma = PragmaFullUnroll || PragmaCount > 0; 735 736 TargetTransformInfo::UnrollingPreferences UP; 737 getUnrollingPreferences(L, TTI, UP); 738 739 // Find trip count and trip multiple if count is not available 740 unsigned TripCount = 0; 741 unsigned TripMultiple = 1; 742 // If there are multiple exiting blocks but one of them is the latch, use the 743 // latch for the trip count estimation. Otherwise insist on a single exiting 744 // block for the trip count estimation. 745 BasicBlock *ExitingBlock = L->getLoopLatch(); 746 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) 747 ExitingBlock = L->getExitingBlock(); 748 if (ExitingBlock) { 749 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); 750 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); 751 } 752 753 // Select an initial unroll count. This may be reduced later based 754 // on size thresholds. 755 bool CountSetExplicitly; 756 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll, 757 PragmaCount, UP, CountSetExplicitly); 758 759 unsigned NumInlineCandidates; 760 bool notDuplicatable; 761 unsigned LoopSize = 762 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC); 763 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); 764 765 // When computing the unrolled size, note that the conditional branch on the 766 // backedge and the comparison feeding it are not replicated like the rest of 767 // the loop body (which is why 2 is subtracted). 768 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2; 769 if (notDuplicatable) { 770 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" 771 << " instructions.\n"); 772 return false; 773 } 774 if (NumInlineCandidates != 0) { 775 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); 776 return false; 777 } 778 779 unsigned NumberOfOptimizedInstructions = 780 approximateNumberOfOptimizedInstructions(L, *SE, TripCount, TTI); 781 DEBUG(dbgs() << " Complete unrolling could save: " 782 << NumberOfOptimizedInstructions << "\n"); 783 784 unsigned Threshold, PartialThreshold; 785 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold, 786 NumberOfOptimizedInstructions); 787 788 // Given Count, TripCount and thresholds determine the type of 789 // unrolling which is to be performed. 790 enum { Full = 0, Partial = 1, Runtime = 2 }; 791 int Unrolling; 792 if (TripCount && Count == TripCount) { 793 if (Threshold != NoThreshold && UnrolledSize > Threshold) { 794 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count 795 << " because size: " << UnrolledSize << ">" << Threshold 796 << "\n"); 797 Unrolling = Partial; 798 } else { 799 Unrolling = Full; 800 } 801 } else if (TripCount && Count < TripCount) { 802 Unrolling = Partial; 803 } else { 804 Unrolling = Runtime; 805 } 806 807 // Reduce count based on the type of unrolling and the threshold values. 808 unsigned OriginalCount = Count; 809 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime; 810 if (Unrolling == Partial) { 811 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial; 812 if (!AllowPartial && !CountSetExplicitly) { 813 DEBUG(dbgs() << " will not try to unroll partially because " 814 << "-unroll-allow-partial not given\n"); 815 return false; 816 } 817 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) { 818 // Reduce unroll count to be modulo of TripCount for partial unrolling. 819 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2); 820 while (Count != 0 && TripCount % Count != 0) 821 Count--; 822 } 823 } else if (Unrolling == Runtime) { 824 if (!AllowRuntime && !CountSetExplicitly) { 825 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " 826 << "-unroll-runtime not given\n"); 827 return false; 828 } 829 // Reduce unroll count to be the largest power-of-two factor of 830 // the original count which satisfies the threshold limit. 831 while (Count != 0 && UnrolledSize > PartialThreshold) { 832 Count >>= 1; 833 UnrolledSize = (LoopSize-2) * Count + 2; 834 } 835 if (Count > UP.MaxCount) 836 Count = UP.MaxCount; 837 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n"); 838 } 839 840 if (HasPragma) { 841 if (PragmaCount != 0) 842 // If loop has an unroll count pragma mark loop as unrolled to prevent 843 // unrolling beyond that requested by the pragma. 844 SetLoopAlreadyUnrolled(L); 845 846 // Emit optimization remarks if we are unable to unroll the loop 847 // as directed by a pragma. 848 DebugLoc LoopLoc = L->getStartLoc(); 849 Function *F = Header->getParent(); 850 LLVMContext &Ctx = F->getContext(); 851 if (PragmaFullUnroll && PragmaCount == 0) { 852 if (TripCount && Count != TripCount) { 853 emitOptimizationRemarkMissed( 854 Ctx, DEBUG_TYPE, *F, LoopLoc, 855 "Unable to fully unroll loop as directed by unroll(full) pragma " 856 "because unrolled size is too large."); 857 } else if (!TripCount) { 858 emitOptimizationRemarkMissed( 859 Ctx, DEBUG_TYPE, *F, LoopLoc, 860 "Unable to fully unroll loop as directed by unroll(full) pragma " 861 "because loop has a runtime trip count."); 862 } 863 } else if (PragmaCount > 0 && Count != OriginalCount) { 864 emitOptimizationRemarkMissed( 865 Ctx, DEBUG_TYPE, *F, LoopLoc, 866 "Unable to unroll loop the number of times directed by " 867 "unroll_count pragma because unrolled size is too large."); 868 } 869 } 870 871 if (Unrolling != Full && Count < 2) { 872 // Partial unrolling by 1 is a nop. For full unrolling, a factor 873 // of 1 makes sense because loop control can be eliminated. 874 return false; 875 } 876 877 // Unroll the loop. 878 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this, 879 &LPM, &AC)) 880 return false; 881 882 return true; 883 } 884