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