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/Analysis/AssumptionTracker.h" 17 #include "llvm/Analysis/CodeMetrics.h" 18 #include "llvm/Analysis/LoopPass.h" 19 #include "llvm/Analysis/ScalarEvolution.h" 20 #include "llvm/Analysis/TargetTransformInfo.h" 21 #include "llvm/IR/DataLayout.h" 22 #include "llvm/IR/DiagnosticInfo.h" 23 #include "llvm/IR/Dominators.h" 24 #include "llvm/IR/IntrinsicInst.h" 25 #include "llvm/IR/Metadata.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/Debug.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include "llvm/Transforms/Utils/UnrollLoop.h" 30 #include <climits> 31 32 using namespace llvm; 33 34 #define DEBUG_TYPE "loop-unroll" 35 36 static cl::opt<unsigned> 37 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden, 38 cl::desc("The cut-off point for automatic loop unrolling")); 39 40 static cl::opt<unsigned> 41 UnrollCount("unroll-count", cl::init(0), cl::Hidden, 42 cl::desc("Use this unroll count for all loops including those with " 43 "unroll_count pragma values, for testing purposes")); 44 45 static cl::opt<bool> 46 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden, 47 cl::desc("Allows loops to be partially unrolled until " 48 "-unroll-threshold loop size is reached.")); 49 50 static cl::opt<bool> 51 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden, 52 cl::desc("Unroll loops with run-time trip counts")); 53 54 static cl::opt<unsigned> 55 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden, 56 cl::desc("Unrolled size limit for loops with an unroll(full) or " 57 "unroll_count pragma.")); 58 59 namespace { 60 class LoopUnroll : public LoopPass { 61 public: 62 static char ID; // Pass ID, replacement for typeid 63 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) { 64 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T); 65 CurrentCount = (C == -1) ? UnrollCount : unsigned(C); 66 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P; 67 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R; 68 69 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0); 70 UserAllowPartial = (P != -1) || 71 (UnrollAllowPartial.getNumOccurrences() > 0); 72 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0); 73 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0); 74 75 initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); 76 } 77 78 /// A magic value for use with the Threshold parameter to indicate 79 /// that the loop unroll should be performed regardless of how much 80 /// code expansion would result. 81 static const unsigned NoThreshold = UINT_MAX; 82 83 // Threshold to use when optsize is specified (and there is no 84 // explicit -unroll-threshold). 85 static const unsigned OptSizeUnrollThreshold = 50; 86 87 // Default unroll count for loops with run-time trip count if 88 // -unroll-count is not set 89 static const unsigned UnrollRuntimeCount = 8; 90 91 unsigned CurrentCount; 92 unsigned CurrentThreshold; 93 bool CurrentAllowPartial; 94 bool CurrentRuntime; 95 bool UserCount; // CurrentCount is user-specified. 96 bool UserThreshold; // CurrentThreshold is user-specified. 97 bool UserAllowPartial; // CurrentAllowPartial is user-specified. 98 bool UserRuntime; // CurrentRuntime is user-specified. 99 100 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 101 102 /// This transformation requires natural loop information & requires that 103 /// loop preheaders be inserted into the CFG... 104 /// 105 void getAnalysisUsage(AnalysisUsage &AU) const override { 106 AU.addRequired<AssumptionTracker>(); 107 AU.addRequired<LoopInfo>(); 108 AU.addPreserved<LoopInfo>(); 109 AU.addRequiredID(LoopSimplifyID); 110 AU.addPreservedID(LoopSimplifyID); 111 AU.addRequiredID(LCSSAID); 112 AU.addPreservedID(LCSSAID); 113 AU.addRequired<ScalarEvolution>(); 114 AU.addPreserved<ScalarEvolution>(); 115 AU.addRequired<TargetTransformInfo>(); 116 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. 117 // If loop unroll does not preserve dom info then LCSSA pass on next 118 // loop will receive invalid dom info. 119 // For now, recreate dom info, if loop is unrolled. 120 AU.addPreserved<DominatorTreeWrapperPass>(); 121 } 122 123 // Fill in the UnrollingPreferences parameter with values from the 124 // TargetTransformationInfo. 125 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI, 126 TargetTransformInfo::UnrollingPreferences &UP) { 127 UP.Threshold = CurrentThreshold; 128 UP.OptSizeThreshold = OptSizeUnrollThreshold; 129 UP.PartialThreshold = CurrentThreshold; 130 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold; 131 UP.Count = CurrentCount; 132 UP.MaxCount = UINT_MAX; 133 UP.Partial = CurrentAllowPartial; 134 UP.Runtime = CurrentRuntime; 135 TTI.getUnrollingPreferences(L, UP); 136 } 137 138 // Select and return an unroll count based on parameters from 139 // user, unroll preferences, unroll pragmas, or a heuristic. 140 // SetExplicitly is set to true if the unroll count is is set by 141 // the user or a pragma rather than selected heuristically. 142 unsigned 143 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 144 unsigned PragmaCount, 145 const TargetTransformInfo::UnrollingPreferences &UP, 146 bool &SetExplicitly); 147 148 // Select threshold values used to limit unrolling based on a 149 // total unrolled size. Parameters Threshold and PartialThreshold 150 // are set to the maximum unrolled size for fully and partially 151 // unrolled loops respectively. 152 void selectThresholds(const Loop *L, bool HasPragma, 153 const TargetTransformInfo::UnrollingPreferences &UP, 154 unsigned &Threshold, unsigned &PartialThreshold) { 155 // Determine the current unrolling threshold. While this is 156 // normally set from UnrollThreshold, it is overridden to a 157 // smaller value if the current function is marked as 158 // optimize-for-size, and the unroll threshold was not user 159 // specified. 160 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold; 161 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold; 162 if (!UserThreshold && 163 L->getHeader()->getParent()->getAttributes(). 164 hasAttribute(AttributeSet::FunctionIndex, 165 Attribute::OptimizeForSize)) { 166 Threshold = UP.OptSizeThreshold; 167 PartialThreshold = UP.PartialOptSizeThreshold; 168 } 169 if (HasPragma) { 170 // If the loop has an unrolling pragma, we want to be more 171 // aggressive with unrolling limits. Set thresholds to at 172 // least the PragmaTheshold value which is larger than the 173 // default limits. 174 if (Threshold != NoThreshold) 175 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold); 176 if (PartialThreshold != NoThreshold) 177 PartialThreshold = 178 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold); 179 } 180 } 181 }; 182 } 183 184 char LoopUnroll::ID = 0; 185 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 186 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 187 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker) 188 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 189 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 190 INITIALIZE_PASS_DEPENDENCY(LCSSA) 191 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 192 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 193 194 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial, 195 int Runtime) { 196 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime); 197 } 198 199 Pass *llvm::createSimpleLoopUnrollPass() { 200 return llvm::createLoopUnrollPass(-1, -1, 0, 0); 201 } 202 203 /// ApproximateLoopSize - Approximate the size of the loop. 204 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, 205 bool &NotDuplicatable, 206 const TargetTransformInfo &TTI, 207 AssumptionTracker *AT) { 208 SmallPtrSet<const Value *, 32> EphValues; 209 CodeMetrics::collectEphemeralValues(L, AT, EphValues); 210 211 CodeMetrics Metrics; 212 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 213 I != E; ++I) 214 Metrics.analyzeBasicBlock(*I, TTI, EphValues); 215 NumCalls = Metrics.NumInlineCandidates; 216 NotDuplicatable = Metrics.notDuplicatable; 217 218 unsigned LoopSize = Metrics.NumInsts; 219 220 // Don't allow an estimate of size zero. This would allows unrolling of loops 221 // with huge iteration counts, which is a compile time problem even if it's 222 // not a problem for code quality. 223 if (LoopSize == 0) LoopSize = 1; 224 225 return LoopSize; 226 } 227 228 // Returns the loop hint metadata node with the given name (for example, 229 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is 230 // returned. 231 static const MDNode *GetUnrollMetadata(const Loop *L, StringRef Name) { 232 MDNode *LoopID = L->getLoopID(); 233 if (!LoopID) 234 return nullptr; 235 236 // First operand should refer to the loop id itself. 237 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 238 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 239 240 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { 241 const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 242 if (!MD) 243 continue; 244 245 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 246 if (!S) 247 continue; 248 249 if (Name.equals(S->getString())) 250 return MD; 251 } 252 return nullptr; 253 } 254 255 // Returns true if the loop has an unroll(full) pragma. 256 static bool HasUnrollFullPragma(const Loop *L) { 257 return GetUnrollMetadata(L, "llvm.loop.unroll.full"); 258 } 259 260 // Returns true if the loop has an unroll(disable) pragma. 261 static bool HasUnrollDisablePragma(const Loop *L) { 262 return GetUnrollMetadata(L, "llvm.loop.unroll.disable"); 263 } 264 265 // If loop has an unroll_count pragma return the (necessarily 266 // positive) value from the pragma. Otherwise return 0. 267 static unsigned UnrollCountPragmaValue(const Loop *L) { 268 const MDNode *MD = GetUnrollMetadata(L, "llvm.loop.unroll.count"); 269 if (MD) { 270 assert(MD->getNumOperands() == 2 && 271 "Unroll count hint metadata should have two operands."); 272 unsigned Count = cast<ConstantInt>(MD->getOperand(1))->getZExtValue(); 273 assert(Count >= 1 && "Unroll count must be positive."); 274 return Count; 275 } 276 return 0; 277 } 278 279 // Remove existing unroll metadata and add unroll disable metadata to 280 // indicate the loop has already been unrolled. This prevents a loop 281 // from being unrolled more than is directed by a pragma if the loop 282 // unrolling pass is run more than once (which it generally is). 283 static void SetLoopAlreadyUnrolled(Loop *L) { 284 MDNode *LoopID = L->getLoopID(); 285 if (!LoopID) return; 286 287 // First remove any existing loop unrolling metadata. 288 SmallVector<Value *, 4> Vals; 289 // Reserve first location for self reference to the LoopID metadata node. 290 Vals.push_back(nullptr); 291 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 292 bool IsUnrollMetadata = false; 293 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 294 if (MD) { 295 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 296 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 297 } 298 if (!IsUnrollMetadata) Vals.push_back(LoopID->getOperand(i)); 299 } 300 301 // Add unroll(disable) metadata to disable future unrolling. 302 LLVMContext &Context = L->getHeader()->getContext(); 303 SmallVector<Value *, 1> DisableOperands; 304 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 305 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 306 Vals.push_back(DisableNode); 307 308 MDNode *NewLoopID = MDNode::get(Context, Vals); 309 // Set operand 0 to refer to the loop id itself. 310 NewLoopID->replaceOperandWith(0, NewLoopID); 311 L->setLoopID(NewLoopID); 312 } 313 314 unsigned LoopUnroll::selectUnrollCount( 315 const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 316 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP, 317 bool &SetExplicitly) { 318 SetExplicitly = true; 319 320 // User-specified count (either as a command-line option or 321 // constructor parameter) has highest precedence. 322 unsigned Count = UserCount ? CurrentCount : 0; 323 324 // If there is no user-specified count, unroll pragmas have the next 325 // highest precendence. 326 if (Count == 0) { 327 if (PragmaCount) { 328 Count = PragmaCount; 329 } else if (PragmaFullUnroll) { 330 Count = TripCount; 331 } 332 } 333 334 if (Count == 0) 335 Count = UP.Count; 336 337 if (Count == 0) { 338 SetExplicitly = false; 339 if (TripCount == 0) 340 // Runtime trip count. 341 Count = UnrollRuntimeCount; 342 else 343 // Conservative heuristic: if we know the trip count, see if we can 344 // completely unroll (subject to the threshold, checked below); otherwise 345 // try to find greatest modulo of the trip count which is still under 346 // threshold value. 347 Count = TripCount; 348 } 349 if (TripCount && Count > TripCount) 350 return TripCount; 351 return Count; 352 } 353 354 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) { 355 if (skipOptnoneFunction(L)) 356 return false; 357 358 LoopInfo *LI = &getAnalysis<LoopInfo>(); 359 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>(); 360 const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>(); 361 AssumptionTracker *AT = &getAnalysis<AssumptionTracker>(); 362 363 BasicBlock *Header = L->getHeader(); 364 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName() 365 << "] Loop %" << Header->getName() << "\n"); 366 367 if (HasUnrollDisablePragma(L)) { 368 return false; 369 } 370 bool PragmaFullUnroll = HasUnrollFullPragma(L); 371 unsigned PragmaCount = UnrollCountPragmaValue(L); 372 bool HasPragma = PragmaFullUnroll || PragmaCount > 0; 373 374 TargetTransformInfo::UnrollingPreferences UP; 375 getUnrollingPreferences(L, TTI, UP); 376 377 // Find trip count and trip multiple if count is not available 378 unsigned TripCount = 0; 379 unsigned TripMultiple = 1; 380 // Find "latch trip count". UnrollLoop assumes that control cannot exit 381 // via the loop latch on any iteration prior to TripCount. The loop may exit 382 // early via an earlier branch. 383 BasicBlock *LatchBlock = L->getLoopLatch(); 384 if (LatchBlock) { 385 TripCount = SE->getSmallConstantTripCount(L, LatchBlock); 386 TripMultiple = SE->getSmallConstantTripMultiple(L, LatchBlock); 387 } 388 389 // Select an initial unroll count. This may be reduced later based 390 // on size thresholds. 391 bool CountSetExplicitly; 392 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll, 393 PragmaCount, UP, CountSetExplicitly); 394 395 unsigned NumInlineCandidates; 396 bool notDuplicatable; 397 unsigned LoopSize = 398 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, AT); 399 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); 400 uint64_t UnrolledSize = (uint64_t)LoopSize * Count; 401 if (notDuplicatable) { 402 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" 403 << " instructions.\n"); 404 return false; 405 } 406 if (NumInlineCandidates != 0) { 407 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); 408 return false; 409 } 410 411 unsigned Threshold, PartialThreshold; 412 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold); 413 414 // Given Count, TripCount and thresholds determine the type of 415 // unrolling which is to be performed. 416 enum { Full = 0, Partial = 1, Runtime = 2 }; 417 int Unrolling; 418 if (TripCount && Count == TripCount) { 419 if (Threshold != NoThreshold && UnrolledSize > Threshold) { 420 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count 421 << " because size: " << UnrolledSize << ">" << Threshold 422 << "\n"); 423 Unrolling = Partial; 424 } else { 425 Unrolling = Full; 426 } 427 } else if (TripCount && Count < TripCount) { 428 Unrolling = Partial; 429 } else { 430 Unrolling = Runtime; 431 } 432 433 // Reduce count based on the type of unrolling and the threshold values. 434 unsigned OriginalCount = Count; 435 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime; 436 if (Unrolling == Partial) { 437 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial; 438 if (!AllowPartial && !CountSetExplicitly) { 439 DEBUG(dbgs() << " will not try to unroll partially because " 440 << "-unroll-allow-partial not given\n"); 441 return false; 442 } 443 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) { 444 // Reduce unroll count to be modulo of TripCount for partial unrolling. 445 Count = PartialThreshold / LoopSize; 446 while (Count != 0 && TripCount % Count != 0) 447 Count--; 448 } 449 } else if (Unrolling == Runtime) { 450 if (!AllowRuntime && !CountSetExplicitly) { 451 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " 452 << "-unroll-runtime not given\n"); 453 return false; 454 } 455 // Reduce unroll count to be the largest power-of-two factor of 456 // the original count which satisfies the threshold limit. 457 while (Count != 0 && UnrolledSize > PartialThreshold) { 458 Count >>= 1; 459 UnrolledSize = LoopSize * Count; 460 } 461 if (Count > UP.MaxCount) 462 Count = UP.MaxCount; 463 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n"); 464 } 465 466 if (HasPragma) { 467 if (PragmaCount != 0) 468 // If loop has an unroll count pragma mark loop as unrolled to prevent 469 // unrolling beyond that requested by the pragma. 470 SetLoopAlreadyUnrolled(L); 471 472 // Emit optimization remarks if we are unable to unroll the loop 473 // as directed by a pragma. 474 DebugLoc LoopLoc = L->getStartLoc(); 475 Function *F = Header->getParent(); 476 LLVMContext &Ctx = F->getContext(); 477 if (PragmaFullUnroll && PragmaCount == 0) { 478 if (TripCount && Count != TripCount) { 479 emitOptimizationRemarkMissed( 480 Ctx, DEBUG_TYPE, *F, LoopLoc, 481 "Unable to fully unroll loop as directed by unroll(full) pragma " 482 "because unrolled size is too large."); 483 } else if (!TripCount) { 484 emitOptimizationRemarkMissed( 485 Ctx, DEBUG_TYPE, *F, LoopLoc, 486 "Unable to fully unroll loop as directed by unroll(full) pragma " 487 "because loop has a runtime trip count."); 488 } 489 } else if (PragmaCount > 0 && Count != OriginalCount) { 490 emitOptimizationRemarkMissed( 491 Ctx, DEBUG_TYPE, *F, LoopLoc, 492 "Unable to unroll loop the number of times directed by " 493 "unroll_count pragma because unrolled size is too large."); 494 } 495 } 496 497 if (Unrolling != Full && Count < 2) { 498 // Partial unrolling by 1 is a nop. For full unrolling, a factor 499 // of 1 makes sense because loop control can be eliminated. 500 return false; 501 } 502 503 // Unroll the loop. 504 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this, 505 &LPM, AT)) 506 return false; 507 508 return true; 509 } 510