Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 1 | //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 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. |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 13 | //===----------------------------------------------------------------------===// |
| 14 | |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 15 | #include "llvm/Transforms/Scalar.h" |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 16 | #include "llvm/Analysis/AssumptionCache.h" |
Chris Lattner | 679572e | 2011-01-02 07:35:53 +0000 | [diff] [blame] | 17 | #include "llvm/Analysis/CodeMetrics.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/LoopPass.h" |
Dan Gohman | 0141c13 | 2010-07-26 18:11:16 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/ScalarEvolution.h" |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chandler Carruth | bb9caa9 | 2013-01-21 13:04:33 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 22 | #include "llvm/IR/DataLayout.h" |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 23 | #include "llvm/IR/DiagnosticInfo.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 24 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 25 | #include "llvm/IR/IntrinsicInst.h" |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 26 | #include "llvm/IR/Metadata.h" |
Reid Spencer | 7c16caa | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 27 | #include "llvm/Support/CommandLine.h" |
| 28 | #include "llvm/Support/Debug.h" |
Daniel Dunbar | 0dd5e1e | 2009-07-25 00:23:56 +0000 | [diff] [blame] | 29 | #include "llvm/Support/raw_ostream.h" |
Dan Gohman | 3dc2d92 | 2008-05-14 00:24:14 +0000 | [diff] [blame] | 30 | #include "llvm/Transforms/Utils/UnrollLoop.h" |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 31 | #include "llvm/IR/InstVisitor.h" |
| 32 | #include "llvm/Analysis/InstructionSimplify.h" |
Duncan Sands | 67933e6 | 2008-05-16 09:30:00 +0000 | [diff] [blame] | 33 | #include <climits> |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 34 | |
Dan Gohman | 3dc2d92 | 2008-05-14 00:24:14 +0000 | [diff] [blame] | 35 | using namespace llvm; |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 36 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 37 | #define DEBUG_TYPE "loop-unroll" |
| 38 | |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 39 | static cl::opt<unsigned> |
Owen Anderson | d85c9cc | 2010-09-10 17:57:00 +0000 | [diff] [blame] | 40 | UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden, |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 41 | cl::desc("The cut-off point for automatic loop unrolling")); |
| 42 | |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 43 | static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze( |
| 44 | "unroll-max-iteration-count-to-analyze", cl::init(1000), cl::Hidden, |
| 45 | cl::desc("Don't allow loop unrolling to simulate more than this number of" |
| 46 | "iterations when checking full unroll profitability")); |
| 47 | |
Michael Zolotukhin | 7af83c1 | 2015-02-06 20:20:40 +0000 | [diff] [blame^] | 48 | static cl::opt<unsigned> UnrollMinPercentOfOptimized( |
| 49 | "unroll-percent-of-optimized-for-complete-unroll", cl::init(20), cl::Hidden, |
| 50 | cl::desc("If complete unrolling could trigger further optimizations, and, " |
| 51 | "by that, remove the given percent of instructions, perform the " |
| 52 | "complete unroll even if it's beyond the threshold")); |
| 53 | |
| 54 | static cl::opt<unsigned> UnrollAbsoluteThreshold( |
| 55 | "unroll-absolute-threshold", cl::init(2000), cl::Hidden, |
| 56 | cl::desc("Don't unroll if the unrolled size is bigger than this threshold," |
| 57 | " even if we can remove big portion of instructions later.")); |
| 58 | |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 59 | static cl::opt<unsigned> |
| 60 | UnrollCount("unroll-count", cl::init(0), cl::Hidden, |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 61 | cl::desc("Use this unroll count for all loops including those with " |
| 62 | "unroll_count pragma values, for testing purposes")); |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 63 | |
Matthijs Kooijman | 98b5c16 | 2008-07-29 13:21:23 +0000 | [diff] [blame] | 64 | static cl::opt<bool> |
| 65 | UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden, |
| 66 | cl::desc("Allows loops to be partially unrolled until " |
| 67 | "-unroll-threshold loop size is reached.")); |
| 68 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 69 | static cl::opt<bool> |
| 70 | UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden, |
| 71 | cl::desc("Unroll loops with run-time trip counts")); |
| 72 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 73 | static cl::opt<unsigned> |
| 74 | PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden, |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 75 | cl::desc("Unrolled size limit for loops with an unroll(full) or " |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 76 | "unroll_count pragma.")); |
| 77 | |
Chris Lattner | 79a42ac | 2006-12-19 21:40:18 +0000 | [diff] [blame] | 78 | namespace { |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 79 | class LoopUnroll : public LoopPass { |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 80 | public: |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 81 | static char ID; // Pass ID, replacement for typeid |
Hal Finkel | 081eaef | 2013-11-05 00:08:03 +0000 | [diff] [blame] | 82 | LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) { |
Chris Lattner | 35a65b2 | 2011-04-14 02:27:25 +0000 | [diff] [blame] | 83 | CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T); |
Michael Zolotukhin | 7af83c1 | 2015-02-06 20:20:40 +0000 | [diff] [blame^] | 84 | CurrentAbsoluteThreshold = UnrollAbsoluteThreshold; |
| 85 | CurrentMinPercentOfOptimized = UnrollMinPercentOfOptimized; |
Chris Lattner | 35a65b2 | 2011-04-14 02:27:25 +0000 | [diff] [blame] | 86 | CurrentCount = (C == -1) ? UnrollCount : unsigned(C); |
Junjie Gu | 7c3b459 | 2011-04-13 16:15:29 +0000 | [diff] [blame] | 87 | CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P; |
Hal Finkel | 081eaef | 2013-11-05 00:08:03 +0000 | [diff] [blame] | 88 | CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R; |
Junjie Gu | 7c3b459 | 2011-04-13 16:15:29 +0000 | [diff] [blame] | 89 | |
| 90 | UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0); |
Michael Zolotukhin | 7af83c1 | 2015-02-06 20:20:40 +0000 | [diff] [blame^] | 91 | UserAbsoluteThreshold = (UnrollAbsoluteThreshold.getNumOccurrences() > 0); |
| 92 | UserPercentOfOptimized = |
| 93 | (UnrollMinPercentOfOptimized.getNumOccurrences() > 0); |
Hal Finkel | 8f2e700 | 2013-09-11 19:25:43 +0000 | [diff] [blame] | 94 | UserAllowPartial = (P != -1) || |
| 95 | (UnrollAllowPartial.getNumOccurrences() > 0); |
Hal Finkel | 081eaef | 2013-11-05 00:08:03 +0000 | [diff] [blame] | 96 | UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0); |
Hal Finkel | 8f2e700 | 2013-09-11 19:25:43 +0000 | [diff] [blame] | 97 | UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0); |
Andrew Trick | 279e7a6 | 2011-07-23 00:29:16 +0000 | [diff] [blame] | 98 | |
Owen Anderson | 6c18d1a | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 99 | initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); |
| 100 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 101 | |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 102 | /// A magic value for use with the Threshold parameter to indicate |
| 103 | /// that the loop unroll should be performed regardless of how much |
| 104 | /// code expansion would result. |
| 105 | static const unsigned NoThreshold = UINT_MAX; |
Andrew Trick | 279e7a6 | 2011-07-23 00:29:16 +0000 | [diff] [blame] | 106 | |
Owen Anderson | a4d9c78 | 2010-09-07 23:15:30 +0000 | [diff] [blame] | 107 | // Threshold to use when optsize is specified (and there is no |
| 108 | // explicit -unroll-threshold). |
| 109 | static const unsigned OptSizeUnrollThreshold = 50; |
Andrew Trick | 279e7a6 | 2011-07-23 00:29:16 +0000 | [diff] [blame] | 110 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 111 | // Default unroll count for loops with run-time trip count if |
| 112 | // -unroll-count is not set |
| 113 | static const unsigned UnrollRuntimeCount = 8; |
| 114 | |
Junjie Gu | 7c3b459 | 2011-04-13 16:15:29 +0000 | [diff] [blame] | 115 | unsigned CurrentCount; |
Owen Anderson | a4d9c78 | 2010-09-07 23:15:30 +0000 | [diff] [blame] | 116 | unsigned CurrentThreshold; |
Michael Zolotukhin | 7af83c1 | 2015-02-06 20:20:40 +0000 | [diff] [blame^] | 117 | unsigned CurrentAbsoluteThreshold; |
| 118 | unsigned CurrentMinPercentOfOptimized; |
Junjie Gu | 7c3b459 | 2011-04-13 16:15:29 +0000 | [diff] [blame] | 119 | bool CurrentAllowPartial; |
Hal Finkel | 081eaef | 2013-11-05 00:08:03 +0000 | [diff] [blame] | 120 | bool CurrentRuntime; |
Hal Finkel | 8f2e700 | 2013-09-11 19:25:43 +0000 | [diff] [blame] | 121 | bool UserCount; // CurrentCount is user-specified. |
Junjie Gu | 7c3b459 | 2011-04-13 16:15:29 +0000 | [diff] [blame] | 122 | bool UserThreshold; // CurrentThreshold is user-specified. |
Michael Zolotukhin | 7af83c1 | 2015-02-06 20:20:40 +0000 | [diff] [blame^] | 123 | bool UserAbsoluteThreshold; // CurrentAbsoluteThreshold is |
| 124 | // user-specified. |
| 125 | bool UserPercentOfOptimized; // CurrentMinPercentOfOptimized is |
| 126 | // user-specified. |
Hal Finkel | 8f2e700 | 2013-09-11 19:25:43 +0000 | [diff] [blame] | 127 | bool UserAllowPartial; // CurrentAllowPartial is user-specified. |
Hal Finkel | 081eaef | 2013-11-05 00:08:03 +0000 | [diff] [blame] | 128 | bool UserRuntime; // CurrentRuntime is user-specified. |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 129 | |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 130 | bool runOnLoop(Loop *L, LPPassManager &LPM) override; |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 131 | |
| 132 | /// This transformation requires natural loop information & requires that |
| 133 | /// loop preheaders be inserted into the CFG... |
| 134 | /// |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 135 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 136 | AU.addRequired<AssumptionCacheTracker>(); |
Chandler Carruth | 4f8f307 | 2015-01-17 14:16:18 +0000 | [diff] [blame] | 137 | AU.addRequired<LoopInfoWrapperPass>(); |
| 138 | AU.addPreserved<LoopInfoWrapperPass>(); |
Dan Gohman | 0141c13 | 2010-07-26 18:11:16 +0000 | [diff] [blame] | 139 | AU.addRequiredID(LoopSimplifyID); |
| 140 | AU.addPreservedID(LoopSimplifyID); |
| 141 | AU.addRequiredID(LCSSAID); |
| 142 | AU.addPreservedID(LCSSAID); |
Andrew Trick | 4d0040b | 2011-08-10 04:29:49 +0000 | [diff] [blame] | 143 | AU.addRequired<ScalarEvolution>(); |
Chris Lattner | d6f46b8 | 2010-08-29 17:21:35 +0000 | [diff] [blame] | 144 | AU.addPreserved<ScalarEvolution>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 145 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Devang Patel | f94b982 | 2008-07-03 07:04:22 +0000 | [diff] [blame] | 146 | // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. |
| 147 | // If loop unroll does not preserve dom info then LCSSA pass on next |
| 148 | // loop will receive invalid dom info. |
| 149 | // For now, recreate dom info, if loop is unrolled. |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 150 | AU.addPreserved<DominatorTreeWrapperPass>(); |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 151 | } |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 152 | |
| 153 | // Fill in the UnrollingPreferences parameter with values from the |
| 154 | // TargetTransformationInfo. |
Chandler Carruth | 21fc195 | 2015-02-01 14:37:03 +0000 | [diff] [blame] | 155 | void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI, |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 156 | TargetTransformInfo::UnrollingPreferences &UP) { |
| 157 | UP.Threshold = CurrentThreshold; |
Michael Zolotukhin | 7af83c1 | 2015-02-06 20:20:40 +0000 | [diff] [blame^] | 158 | UP.AbsoluteThreshold = CurrentAbsoluteThreshold; |
| 159 | UP.MinPercentOfOptimized = CurrentMinPercentOfOptimized; |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 160 | UP.OptSizeThreshold = OptSizeUnrollThreshold; |
| 161 | UP.PartialThreshold = CurrentThreshold; |
| 162 | UP.PartialOptSizeThreshold = OptSizeUnrollThreshold; |
| 163 | UP.Count = CurrentCount; |
| 164 | UP.MaxCount = UINT_MAX; |
| 165 | UP.Partial = CurrentAllowPartial; |
| 166 | UP.Runtime = CurrentRuntime; |
Chandler Carruth | 21fc195 | 2015-02-01 14:37:03 +0000 | [diff] [blame] | 167 | TTI.getUnrollingPreferences(L, UP); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 168 | } |
| 169 | |
| 170 | // Select and return an unroll count based on parameters from |
| 171 | // user, unroll preferences, unroll pragmas, or a heuristic. |
| 172 | // SetExplicitly is set to true if the unroll count is is set by |
| 173 | // the user or a pragma rather than selected heuristically. |
| 174 | unsigned |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 175 | selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll, |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 176 | unsigned PragmaCount, |
| 177 | const TargetTransformInfo::UnrollingPreferences &UP, |
| 178 | bool &SetExplicitly); |
| 179 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 180 | // Select threshold values used to limit unrolling based on a |
| 181 | // total unrolled size. Parameters Threshold and PartialThreshold |
| 182 | // are set to the maximum unrolled size for fully and partially |
| 183 | // unrolled loops respectively. |
| 184 | void selectThresholds(const Loop *L, bool HasPragma, |
| 185 | const TargetTransformInfo::UnrollingPreferences &UP, |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 186 | unsigned &Threshold, unsigned &PartialThreshold, |
Michael Zolotukhin | 7af83c1 | 2015-02-06 20:20:40 +0000 | [diff] [blame^] | 187 | unsigned NumberOfOptimizedInstructions) { |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 188 | // Determine the current unrolling threshold. While this is |
| 189 | // normally set from UnrollThreshold, it is overridden to a |
| 190 | // smaller value if the current function is marked as |
| 191 | // optimize-for-size, and the unroll threshold was not user |
| 192 | // specified. |
| 193 | Threshold = UserThreshold ? CurrentThreshold : UP.Threshold; |
Michael Zolotukhin | 7af83c1 | 2015-02-06 20:20:40 +0000 | [diff] [blame^] | 194 | |
| 195 | // If we are allowed to completely unroll if we can remove M% of |
| 196 | // instructions, and we know that with complete unrolling we'll be able |
| 197 | // to kill N instructions, then we can afford to completely unroll loops |
| 198 | // with unrolled size up to N*100/M. |
| 199 | // Adjust the threshold according to that: |
| 200 | unsigned PercentOfOptimizedForCompleteUnroll = |
| 201 | UserPercentOfOptimized ? CurrentMinPercentOfOptimized |
| 202 | : UP.MinPercentOfOptimized; |
| 203 | unsigned AbsoluteThreshold = UserAbsoluteThreshold |
| 204 | ? CurrentAbsoluteThreshold |
| 205 | : UP.AbsoluteThreshold; |
| 206 | if (PercentOfOptimizedForCompleteUnroll) |
| 207 | Threshold = std::max<unsigned>(Threshold, |
| 208 | NumberOfOptimizedInstructions * 100 / |
| 209 | PercentOfOptimizedForCompleteUnroll); |
| 210 | // But don't allow unrolling loops bigger than absolute threshold. |
| 211 | Threshold = std::min<unsigned>(Threshold, AbsoluteThreshold); |
| 212 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 213 | PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold; |
| 214 | if (!UserThreshold && |
| 215 | L->getHeader()->getParent()->getAttributes(). |
| 216 | hasAttribute(AttributeSet::FunctionIndex, |
| 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 | } |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 233 | }; |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 234 | } |
| 235 | |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 236 | char LoopUnroll::ID = 0; |
Owen Anderson | 8ac477f | 2010-10-12 19:48:12 +0000 | [diff] [blame] | 237 | INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 238 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 239 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
Chandler Carruth | 4f8f307 | 2015-01-17 14:16:18 +0000 | [diff] [blame] | 240 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
Owen Anderson | 8ac477f | 2010-10-12 19:48:12 +0000 | [diff] [blame] | 241 | INITIALIZE_PASS_DEPENDENCY(LoopSimplify) |
| 242 | INITIALIZE_PASS_DEPENDENCY(LCSSA) |
Devang Patel | 88b4fa2 | 2011-10-19 23:56:07 +0000 | [diff] [blame] | 243 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) |
Owen Anderson | 8ac477f | 2010-10-12 19:48:12 +0000 | [diff] [blame] | 244 | INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 245 | |
Hal Finkel | 081eaef | 2013-11-05 00:08:03 +0000 | [diff] [blame] | 246 | Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial, |
| 247 | int Runtime) { |
| 248 | return new LoopUnroll(Threshold, Count, AllowPartial, Runtime); |
Junjie Gu | 7c3b459 | 2011-04-13 16:15:29 +0000 | [diff] [blame] | 249 | } |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 250 | |
Hal Finkel | 86b3064 | 2014-03-31 23:23:51 +0000 | [diff] [blame] | 251 | Pass *llvm::createSimpleLoopUnrollPass() { |
| 252 | return llvm::createLoopUnrollPass(-1, -1, 0, 0); |
| 253 | } |
| 254 | |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 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 | unsigned NumberOfOptimizedInstructions; |
| 334 | |
| 335 | DenseMap<Value *, Constant *> SimplifiedValues; |
| 336 | DenseMap<LoadInst *, Value *> LoadBaseAddresses; |
| 337 | SmallPtrSet<Instruction *, 32> CountedInsns; |
| 338 | |
| 339 | // Provide base case for our instruction visit. |
| 340 | bool visitInstruction(Instruction &I) { return false; }; |
| 341 | // TODO: We should also visit ICmp, FCmp, GetElementPtr, Trunc, ZExt, SExt, |
| 342 | // FPTrunc, FPExt, FPToUI, FPToSI, UIToFP, SIToFP, BitCast, Select, |
| 343 | // ExtractElement, InsertElement, ShuffleVector, ExtractValue, InsertValue. |
| 344 | // |
| 345 | // Probaly it's worth to hoist the code for estimating the simplifications |
| 346 | // effects to a separate class, since we have a very similar code in |
| 347 | // InlineCost already. |
| 348 | bool visitBinaryOperator(BinaryOperator &I) { |
| 349 | Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); |
| 350 | if (!isa<Constant>(LHS)) |
| 351 | if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS)) |
| 352 | LHS = SimpleLHS; |
| 353 | if (!isa<Constant>(RHS)) |
| 354 | if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS)) |
| 355 | RHS = SimpleRHS; |
Michael Zolotukhin | 4e8598e | 2015-02-06 20:02:51 +0000 | [diff] [blame] | 356 | Value *SimpleV = nullptr; |
| 357 | if (auto FI = dyn_cast<FPMathOperator>(&I)) |
| 358 | SimpleV = |
| 359 | SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags()); |
| 360 | else |
| 361 | SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS); |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 362 | |
| 363 | if (SimpleV && CountedInsns.insert(&I).second) |
| 364 | NumberOfOptimizedInstructions += TTI.getUserCost(&I); |
| 365 | |
| 366 | if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) { |
| 367 | SimplifiedValues[&I] = C; |
| 368 | return true; |
| 369 | } |
| 370 | return false; |
| 371 | } |
| 372 | |
| 373 | Constant *computeLoadValue(LoadInst *LI, unsigned Iteration) { |
| 374 | if (!LI) |
| 375 | return nullptr; |
| 376 | Value *BaseAddr = LoadBaseAddresses[LI]; |
| 377 | if (!BaseAddr) |
| 378 | return nullptr; |
| 379 | |
| 380 | auto GV = dyn_cast<GlobalVariable>(BaseAddr); |
| 381 | if (!GV) |
| 382 | return nullptr; |
| 383 | |
| 384 | ConstantDataSequential *CDS = |
| 385 | dyn_cast<ConstantDataSequential>(GV->getInitializer()); |
| 386 | if (!CDS) |
| 387 | return nullptr; |
| 388 | |
| 389 | const SCEV *BaseAddrSE = SE.getSCEV(BaseAddr); |
| 390 | const SCEV *S = SE.getSCEV(LI->getPointerOperand()); |
| 391 | const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE); |
| 392 | |
| 393 | APInt StepC, StartC; |
| 394 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE); |
| 395 | if (!AR) |
| 396 | return nullptr; |
| 397 | |
| 398 | if (const SCEVConstant *StepSE = |
| 399 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) |
| 400 | StepC = StepSE->getValue()->getValue(); |
| 401 | else |
| 402 | return nullptr; |
| 403 | |
| 404 | if (const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart())) |
| 405 | StartC = StartSE->getValue()->getValue(); |
| 406 | else |
| 407 | return nullptr; |
| 408 | |
| 409 | unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U; |
| 410 | unsigned Start = StartC.getLimitedValue(); |
| 411 | unsigned Step = StepC.getLimitedValue(); |
| 412 | |
| 413 | unsigned Index = (Start + Step * Iteration) / ElemSize; |
| 414 | if (Index >= CDS->getNumElements()) |
| 415 | return nullptr; |
| 416 | |
| 417 | Constant *CV = CDS->getElementAsConstant(Index); |
| 418 | |
| 419 | return CV; |
| 420 | } |
| 421 | |
| 422 | public: |
| 423 | UnrollAnalyzer(const Loop *L, unsigned TripCount, ScalarEvolution &SE, |
| 424 | const TargetTransformInfo &TTI) |
| 425 | : L(L), TripCount(TripCount), SE(SE), TTI(TTI), |
| 426 | NumberOfOptimizedInstructions(0) {} |
| 427 | |
| 428 | // Visit all loads the loop L, and for those that, after complete loop |
| 429 | // unrolling, would have a constant address and it will point to a known |
| 430 | // constant initializer, record its base address for future use. It is used |
| 431 | // when we estimate number of potentially simplified instructions. |
| 432 | void FindConstFoldableLoads() { |
| 433 | for (auto BB : L->getBlocks()) { |
| 434 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 435 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 436 | if (!LI->isSimple()) |
| 437 | continue; |
| 438 | Value *AddrOp = LI->getPointerOperand(); |
| 439 | const SCEV *S = SE.getSCEV(AddrOp); |
| 440 | FindConstantPointers Visitor(L, SE); |
| 441 | SCEVTraversal<FindConstantPointers> T(Visitor); |
| 442 | T.visitAll(S); |
| 443 | if (Visitor.IndexIsConstant && Visitor.LoadCanBeConstantFolded) { |
| 444 | LoadBaseAddresses[LI] = Visitor.BaseAddress; |
| 445 | } |
| 446 | } |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | // Given a list of loads that could be constant-folded (LoadBaseAddresses), |
| 452 | // estimate number of optimized instructions after substituting the concrete |
| 453 | // values for the given Iteration. |
| 454 | // Fill in SimplifiedInsns map for future use in DCE-estimation. |
| 455 | unsigned EstimateNumberOfSimplifiedInsns(unsigned Iteration) { |
| 456 | SmallVector<Instruction *, 8> Worklist; |
| 457 | SimplifiedValues.clear(); |
| 458 | CountedInsns.clear(); |
| 459 | |
| 460 | NumberOfOptimizedInstructions = 0; |
| 461 | // We start by adding all loads to the worklist. |
| 462 | for (auto LoadDescr : LoadBaseAddresses) { |
| 463 | LoadInst *LI = LoadDescr.first; |
| 464 | SimplifiedValues[LI] = computeLoadValue(LI, Iteration); |
| 465 | if (CountedInsns.insert(LI).second) |
| 466 | NumberOfOptimizedInstructions += TTI.getUserCost(LI); |
| 467 | |
| 468 | for (auto U : LI->users()) { |
| 469 | Instruction *UI = dyn_cast<Instruction>(U); |
| 470 | if (!UI) |
| 471 | continue; |
| 472 | if (!L->contains(UI)) |
| 473 | continue; |
| 474 | Worklist.push_back(UI); |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | // And then we try to simplify every user of every instruction from the |
| 479 | // worklist. If we do simplify a user, add it to the worklist to process |
| 480 | // its users as well. |
| 481 | while (!Worklist.empty()) { |
| 482 | Instruction *I = Worklist.pop_back_val(); |
| 483 | if (!visit(I)) |
| 484 | continue; |
| 485 | for (auto U : I->users()) { |
| 486 | Instruction *UI = dyn_cast<Instruction>(U); |
| 487 | if (!UI) |
| 488 | continue; |
| 489 | if (!L->contains(UI)) |
| 490 | continue; |
| 491 | Worklist.push_back(UI); |
| 492 | } |
| 493 | } |
| 494 | return NumberOfOptimizedInstructions; |
| 495 | } |
| 496 | |
| 497 | // Given a list of potentially simplifed instructions, estimate number of |
| 498 | // instructions that would become dead if we do perform the simplification. |
| 499 | unsigned EstimateNumberOfDeadInsns() { |
| 500 | NumberOfOptimizedInstructions = 0; |
| 501 | SmallVector<Instruction *, 8> Worklist; |
| 502 | DenseMap<Instruction *, bool> DeadInstructions; |
| 503 | // Start by initializing worklist with simplified instructions. |
| 504 | for (auto Folded : SimplifiedValues) { |
| 505 | if (auto FoldedInsn = dyn_cast<Instruction>(Folded.first)) { |
| 506 | Worklist.push_back(FoldedInsn); |
| 507 | DeadInstructions[FoldedInsn] = true; |
| 508 | } |
| 509 | } |
| 510 | // If a definition of an insn is only used by simplified or dead |
| 511 | // instructions, it's also dead. Check defs of all instructions from the |
| 512 | // worklist. |
| 513 | while (!Worklist.empty()) { |
| 514 | Instruction *FoldedInsn = Worklist.pop_back_val(); |
| 515 | for (Value *Op : FoldedInsn->operands()) { |
| 516 | if (auto I = dyn_cast<Instruction>(Op)) { |
| 517 | if (!L->contains(I)) |
| 518 | continue; |
| 519 | if (SimplifiedValues[I]) |
| 520 | continue; // This insn has been counted already. |
| 521 | if (I->getNumUses() == 0) |
| 522 | continue; |
| 523 | bool AllUsersFolded = true; |
| 524 | for (auto U : I->users()) { |
| 525 | Instruction *UI = dyn_cast<Instruction>(U); |
| 526 | if (!SimplifiedValues[UI] && !DeadInstructions[UI]) { |
| 527 | AllUsersFolded = false; |
| 528 | break; |
| 529 | } |
| 530 | } |
| 531 | if (AllUsersFolded) { |
| 532 | NumberOfOptimizedInstructions += TTI.getUserCost(I); |
| 533 | Worklist.push_back(I); |
| 534 | DeadInstructions[I] = true; |
| 535 | } |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | return NumberOfOptimizedInstructions; |
| 540 | } |
| 541 | }; |
| 542 | |
| 543 | // Complete loop unrolling can make some loads constant, and we need to know if |
| 544 | // that would expose any further optimization opportunities. |
| 545 | // This routine estimates this optimization effect and returns the number of |
| 546 | // instructions, that potentially might be optimized away. |
| 547 | static unsigned |
| 548 | ApproximateNumberOfOptimizedInstructions(const Loop *L, ScalarEvolution &SE, |
| 549 | unsigned TripCount, |
| 550 | const TargetTransformInfo &TTI) { |
| 551 | if (!TripCount) |
| 552 | return 0; |
| 553 | |
| 554 | UnrollAnalyzer UA(L, TripCount, SE, TTI); |
| 555 | UA.FindConstFoldableLoads(); |
| 556 | |
| 557 | // Estimate number of instructions, that could be simplified if we replace a |
| 558 | // load with the corresponding constant. Since the same load will take |
| 559 | // different values on different iterations, we have to go through all loop's |
| 560 | // iterations here. To limit ourselves here, we check only first N |
| 561 | // iterations, and then scale the found number, if necessary. |
| 562 | unsigned IterationsNumberForEstimate = |
| 563 | std::min<unsigned>(UnrollMaxIterationsCountToAnalyze, TripCount); |
| 564 | unsigned NumberOfOptimizedInstructions = 0; |
| 565 | for (unsigned i = 0; i < IterationsNumberForEstimate; ++i) { |
| 566 | NumberOfOptimizedInstructions += UA.EstimateNumberOfSimplifiedInsns(i); |
| 567 | NumberOfOptimizedInstructions += UA.EstimateNumberOfDeadInsns(); |
| 568 | } |
| 569 | NumberOfOptimizedInstructions *= TripCount / IterationsNumberForEstimate; |
| 570 | |
| 571 | return NumberOfOptimizedInstructions; |
| 572 | } |
| 573 | |
Dan Gohman | 49d08a5 | 2007-05-08 15:14:19 +0000 | [diff] [blame] | 574 | /// ApproximateLoopSize - Approximate the size of the loop. |
Andrew Trick | f765601 | 2011-10-01 01:39:05 +0000 | [diff] [blame] | 575 | static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, |
Chandler Carruth | bb9caa9 | 2013-01-21 13:04:33 +0000 | [diff] [blame] | 576 | bool &NotDuplicatable, |
Hal Finkel | 57f03dd | 2014-09-07 13:49:57 +0000 | [diff] [blame] | 577 | const TargetTransformInfo &TTI, |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 578 | AssumptionCache *AC) { |
Hal Finkel | 57f03dd | 2014-09-07 13:49:57 +0000 | [diff] [blame] | 579 | SmallPtrSet<const Value *, 32> EphValues; |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 580 | CodeMetrics::collectEphemeralValues(L, AC, EphValues); |
Hal Finkel | 57f03dd | 2014-09-07 13:49:57 +0000 | [diff] [blame] | 581 | |
Dan Gohman | 969e83a | 2009-10-31 14:54:17 +0000 | [diff] [blame] | 582 | CodeMetrics Metrics; |
Dan Gohman | 9007107 | 2008-06-22 20:18:58 +0000 | [diff] [blame] | 583 | for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); |
Dan Gohman | 969e83a | 2009-10-31 14:54:17 +0000 | [diff] [blame] | 584 | I != E; ++I) |
Hal Finkel | 57f03dd | 2014-09-07 13:49:57 +0000 | [diff] [blame] | 585 | Metrics.analyzeBasicBlock(*I, TTI, EphValues); |
Owen Anderson | 04cf3fd | 2010-09-09 20:32:23 +0000 | [diff] [blame] | 586 | NumCalls = Metrics.NumInlineCandidates; |
James Molloy | 4f6fb95 | 2012-12-20 16:04:27 +0000 | [diff] [blame] | 587 | NotDuplicatable = Metrics.notDuplicatable; |
Andrew Trick | 279e7a6 | 2011-07-23 00:29:16 +0000 | [diff] [blame] | 588 | |
Owen Anderson | 62ea1b7 | 2010-09-09 19:07:31 +0000 | [diff] [blame] | 589 | unsigned LoopSize = Metrics.NumInsts; |
Andrew Trick | 279e7a6 | 2011-07-23 00:29:16 +0000 | [diff] [blame] | 590 | |
Owen Anderson | 62ea1b7 | 2010-09-09 19:07:31 +0000 | [diff] [blame] | 591 | // Don't allow an estimate of size zero. This would allows unrolling of loops |
| 592 | // with huge iteration counts, which is a compile time problem even if it's |
Hal Finkel | 38dd590 | 2015-01-10 00:30:55 +0000 | [diff] [blame] | 593 | // not a problem for code quality. Also, the code using this size may assume |
| 594 | // that each loop has at least three instructions (likely a conditional |
| 595 | // branch, a comparison feeding that branch, and some kind of loop increment |
| 596 | // feeding that comparison instruction). |
| 597 | LoopSize = std::max(LoopSize, 3u); |
Andrew Trick | 279e7a6 | 2011-07-23 00:29:16 +0000 | [diff] [blame] | 598 | |
Owen Anderson | 62ea1b7 | 2010-09-09 19:07:31 +0000 | [diff] [blame] | 599 | return LoopSize; |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 600 | } |
| 601 | |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 602 | // Returns the loop hint metadata node with the given name (for example, |
| 603 | // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is |
| 604 | // returned. |
Jingyue Wu | 49a766e | 2015-02-02 20:41:11 +0000 | [diff] [blame] | 605 | static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) { |
| 606 | if (MDNode *LoopID = L->getLoopID()) |
| 607 | return GetUnrollMetadata(LoopID, Name); |
| 608 | return nullptr; |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 609 | } |
| 610 | |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 611 | // Returns true if the loop has an unroll(full) pragma. |
| 612 | static bool HasUnrollFullPragma(const Loop *L) { |
Jingyue Wu | 0220df0 | 2015-02-01 02:27:45 +0000 | [diff] [blame] | 613 | return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full"); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 614 | } |
| 615 | |
| 616 | // Returns true if the loop has an unroll(disable) pragma. |
| 617 | static bool HasUnrollDisablePragma(const Loop *L) { |
Jingyue Wu | 0220df0 | 2015-02-01 02:27:45 +0000 | [diff] [blame] | 618 | return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable"); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 619 | } |
| 620 | |
| 621 | // If loop has an unroll_count pragma return the (necessarily |
| 622 | // positive) value from the pragma. Otherwise return 0. |
| 623 | static unsigned UnrollCountPragmaValue(const Loop *L) { |
Jingyue Wu | 49a766e | 2015-02-02 20:41:11 +0000 | [diff] [blame] | 624 | MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 625 | if (MD) { |
| 626 | assert(MD->getNumOperands() == 2 && |
| 627 | "Unroll count hint metadata should have two operands."); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 628 | unsigned Count = |
| 629 | mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 630 | assert(Count >= 1 && "Unroll count must be positive."); |
| 631 | return Count; |
| 632 | } |
| 633 | return 0; |
| 634 | } |
| 635 | |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 636 | // Remove existing unroll metadata and add unroll disable metadata to |
| 637 | // indicate the loop has already been unrolled. This prevents a loop |
| 638 | // from being unrolled more than is directed by a pragma if the loop |
| 639 | // unrolling pass is run more than once (which it generally is). |
| 640 | static void SetLoopAlreadyUnrolled(Loop *L) { |
| 641 | MDNode *LoopID = L->getLoopID(); |
| 642 | if (!LoopID) return; |
| 643 | |
| 644 | // First remove any existing loop unrolling metadata. |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 645 | SmallVector<Metadata *, 4> MDs; |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 646 | // Reserve first location for self reference to the LoopID metadata node. |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 647 | MDs.push_back(nullptr); |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 648 | for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { |
| 649 | bool IsUnrollMetadata = false; |
| 650 | MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); |
| 651 | if (MD) { |
| 652 | const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); |
| 653 | IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); |
| 654 | } |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 655 | if (!IsUnrollMetadata) |
| 656 | MDs.push_back(LoopID->getOperand(i)); |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 657 | } |
| 658 | |
| 659 | // Add unroll(disable) metadata to disable future unrolling. |
| 660 | LLVMContext &Context = L->getHeader()->getContext(); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 661 | SmallVector<Metadata *, 1> DisableOperands; |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 662 | DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); |
Mark Heffernan | f3764da | 2014-07-18 21:29:41 +0000 | [diff] [blame] | 663 | MDNode *DisableNode = MDNode::get(Context, DisableOperands); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 664 | MDs.push_back(DisableNode); |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 665 | |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 666 | MDNode *NewLoopID = MDNode::get(Context, MDs); |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 667 | // Set operand 0 to refer to the loop id itself. |
| 668 | NewLoopID->replaceOperandWith(0, NewLoopID); |
| 669 | L->setLoopID(NewLoopID); |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 670 | } |
| 671 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 672 | unsigned LoopUnroll::selectUnrollCount( |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 673 | const Loop *L, unsigned TripCount, bool PragmaFullUnroll, |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 674 | unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP, |
| 675 | bool &SetExplicitly) { |
| 676 | SetExplicitly = true; |
| 677 | |
| 678 | // User-specified count (either as a command-line option or |
| 679 | // constructor parameter) has highest precedence. |
| 680 | unsigned Count = UserCount ? CurrentCount : 0; |
| 681 | |
| 682 | // If there is no user-specified count, unroll pragmas have the next |
| 683 | // highest precendence. |
| 684 | if (Count == 0) { |
| 685 | if (PragmaCount) { |
| 686 | Count = PragmaCount; |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 687 | } else if (PragmaFullUnroll) { |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 688 | Count = TripCount; |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | if (Count == 0) |
| 693 | Count = UP.Count; |
| 694 | |
| 695 | if (Count == 0) { |
| 696 | SetExplicitly = false; |
| 697 | if (TripCount == 0) |
| 698 | // Runtime trip count. |
| 699 | Count = UnrollRuntimeCount; |
| 700 | else |
| 701 | // Conservative heuristic: if we know the trip count, see if we can |
| 702 | // completely unroll (subject to the threshold, checked below); otherwise |
| 703 | // try to find greatest modulo of the trip count which is still under |
| 704 | // threshold value. |
| 705 | Count = TripCount; |
| 706 | } |
| 707 | if (TripCount && Count > TripCount) |
| 708 | return TripCount; |
| 709 | return Count; |
| 710 | } |
| 711 | |
Devang Patel | 9779e56 | 2007-03-07 01:38:05 +0000 | [diff] [blame] | 712 | bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) { |
Paul Robinson | af4e64d | 2014-02-06 00:07:05 +0000 | [diff] [blame] | 713 | if (skipOptnoneFunction(L)) |
| 714 | return false; |
| 715 | |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 716 | Function &F = *L->getHeader()->getParent(); |
| 717 | |
Chandler Carruth | 4f8f307 | 2015-01-17 14:16:18 +0000 | [diff] [blame] | 718 | LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 719 | ScalarEvolution *SE = &getAnalysis<ScalarEvolution>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 720 | const TargetTransformInfo &TTI = |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 721 | getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 722 | auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 723 | |
Dan Gohman | 2e1f804 | 2007-05-08 15:19:19 +0000 | [diff] [blame] | 724 | BasicBlock *Header = L->getHeader(); |
David Greene | e0b9789 | 2010-01-05 01:27:44 +0000 | [diff] [blame] | 725 | DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName() |
Daniel Dunbar | 0dd5e1e | 2009-07-25 00:23:56 +0000 | [diff] [blame] | 726 | << "] Loop %" << Header->getName() << "\n"); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 727 | |
| 728 | if (HasUnrollDisablePragma(L)) { |
| 729 | return false; |
| 730 | } |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 731 | bool PragmaFullUnroll = HasUnrollFullPragma(L); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 732 | unsigned PragmaCount = UnrollCountPragmaValue(L); |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 733 | bool HasPragma = PragmaFullUnroll || PragmaCount > 0; |
Andrew Trick | 279e7a6 | 2011-07-23 00:29:16 +0000 | [diff] [blame] | 734 | |
Hal Finkel | 8f2e700 | 2013-09-11 19:25:43 +0000 | [diff] [blame] | 735 | TargetTransformInfo::UnrollingPreferences UP; |
Chandler Carruth | 21fc195 | 2015-02-01 14:37:03 +0000 | [diff] [blame] | 736 | getUnrollingPreferences(L, TTI, UP); |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 737 | |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 738 | // Find trip count and trip multiple if count is not available |
| 739 | unsigned TripCount = 0; |
Andrew Trick | 1cabe54 | 2011-07-23 00:33:05 +0000 | [diff] [blame] | 740 | unsigned TripMultiple = 1; |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 741 | // If there are multiple exiting blocks but one of them is the latch, use the |
| 742 | // latch for the trip count estimation. Otherwise insist on a single exiting |
| 743 | // block for the trip count estimation. |
| 744 | BasicBlock *ExitingBlock = L->getLoopLatch(); |
| 745 | if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) |
| 746 | ExitingBlock = L->getExitingBlock(); |
| 747 | if (ExitingBlock) { |
| 748 | TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); |
| 749 | TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 750 | } |
Hal Finkel | 8f2e700 | 2013-09-11 19:25:43 +0000 | [diff] [blame] | 751 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 752 | // Select an initial unroll count. This may be reduced later based |
| 753 | // on size thresholds. |
| 754 | bool CountSetExplicitly; |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 755 | unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll, |
| 756 | PragmaCount, UP, CountSetExplicitly); |
Eli Bendersky | dc6de2c | 2014-06-12 18:05:39 +0000 | [diff] [blame] | 757 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 758 | unsigned NumInlineCandidates; |
| 759 | bool notDuplicatable; |
| 760 | unsigned LoopSize = |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 761 | ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 762 | DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); |
Hal Finkel | 38dd590 | 2015-01-10 00:30:55 +0000 | [diff] [blame] | 763 | |
| 764 | // When computing the unrolled size, note that the conditional branch on the |
| 765 | // backedge and the comparison feeding it are not replicated like the rest of |
| 766 | // the loop body (which is why 2 is subtracted). |
| 767 | uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2; |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 768 | if (notDuplicatable) { |
| 769 | DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" |
| 770 | << " instructions.\n"); |
| 771 | return false; |
| 772 | } |
| 773 | if (NumInlineCandidates != 0) { |
| 774 | DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); |
| 775 | return false; |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 776 | } |
| 777 | |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 778 | unsigned NumberOfOptimizedInstructions = |
| 779 | ApproximateNumberOfOptimizedInstructions(L, *SE, TripCount, TTI); |
| 780 | DEBUG(dbgs() << " Complete unrolling could save: " |
| 781 | << NumberOfOptimizedInstructions << "\n"); |
| 782 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 783 | unsigned Threshold, PartialThreshold; |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 784 | selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold, |
| 785 | NumberOfOptimizedInstructions); |
Benjamin Kramer | 9130cb8 | 2014-05-04 19:12:38 +0000 | [diff] [blame] | 786 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 787 | // Given Count, TripCount and thresholds determine the type of |
| 788 | // unrolling which is to be performed. |
| 789 | enum { Full = 0, Partial = 1, Runtime = 2 }; |
| 790 | int Unrolling; |
| 791 | if (TripCount && Count == TripCount) { |
| 792 | if (Threshold != NoThreshold && UnrolledSize > Threshold) { |
| 793 | DEBUG(dbgs() << " Too large to fully unroll with count: " << Count |
| 794 | << " because size: " << UnrolledSize << ">" << Threshold |
| 795 | << "\n"); |
| 796 | Unrolling = Partial; |
| 797 | } else { |
| 798 | Unrolling = Full; |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 799 | } |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 800 | } else if (TripCount && Count < TripCount) { |
| 801 | Unrolling = Partial; |
| 802 | } else { |
| 803 | Unrolling = Runtime; |
| 804 | } |
| 805 | |
| 806 | // Reduce count based on the type of unrolling and the threshold values. |
| 807 | unsigned OriginalCount = Count; |
| 808 | bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime; |
| 809 | if (Unrolling == Partial) { |
| 810 | bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial; |
| 811 | if (!AllowPartial && !CountSetExplicitly) { |
| 812 | DEBUG(dbgs() << " will not try to unroll partially because " |
| 813 | << "-unroll-allow-partial not given\n"); |
| 814 | return false; |
| 815 | } |
| 816 | if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) { |
| 817 | // Reduce unroll count to be modulo of TripCount for partial unrolling. |
Hal Finkel | 38dd590 | 2015-01-10 00:30:55 +0000 | [diff] [blame] | 818 | Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 819 | while (Count != 0 && TripCount % Count != 0) |
| 820 | Count--; |
| 821 | } |
| 822 | } else if (Unrolling == Runtime) { |
| 823 | if (!AllowRuntime && !CountSetExplicitly) { |
| 824 | DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " |
| 825 | << "-unroll-runtime not given\n"); |
| 826 | return false; |
| 827 | } |
| 828 | // Reduce unroll count to be the largest power-of-two factor of |
| 829 | // the original count which satisfies the threshold limit. |
| 830 | while (Count != 0 && UnrolledSize > PartialThreshold) { |
| 831 | Count >>= 1; |
Hal Finkel | 38dd590 | 2015-01-10 00:30:55 +0000 | [diff] [blame] | 832 | UnrolledSize = (LoopSize-2) * Count + 2; |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 833 | } |
| 834 | if (Count > UP.MaxCount) |
| 835 | Count = UP.MaxCount; |
| 836 | DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n"); |
| 837 | } |
| 838 | |
| 839 | if (HasPragma) { |
Mark Heffernan | 9e11244 | 2014-07-23 20:05:44 +0000 | [diff] [blame] | 840 | if (PragmaCount != 0) |
| 841 | // If loop has an unroll count pragma mark loop as unrolled to prevent |
| 842 | // unrolling beyond that requested by the pragma. |
| 843 | SetLoopAlreadyUnrolled(L); |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 844 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 845 | // Emit optimization remarks if we are unable to unroll the loop |
| 846 | // as directed by a pragma. |
| 847 | DebugLoc LoopLoc = L->getStartLoc(); |
| 848 | Function *F = Header->getParent(); |
| 849 | LLVMContext &Ctx = F->getContext(); |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 850 | if (PragmaFullUnroll && PragmaCount == 0) { |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 851 | if (TripCount && Count != TripCount) { |
| 852 | emitOptimizationRemarkMissed( |
| 853 | Ctx, DEBUG_TYPE, *F, LoopLoc, |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 854 | "Unable to fully unroll loop as directed by unroll(full) pragma " |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 855 | "because unrolled size is too large."); |
| 856 | } else if (!TripCount) { |
| 857 | emitOptimizationRemarkMissed( |
| 858 | Ctx, DEBUG_TYPE, *F, LoopLoc, |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 859 | "Unable to fully unroll loop as directed by unroll(full) pragma " |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 860 | "because loop has a runtime trip count."); |
| 861 | } |
| 862 | } else if (PragmaCount > 0 && Count != OriginalCount) { |
| 863 | emitOptimizationRemarkMissed( |
| 864 | Ctx, DEBUG_TYPE, *F, LoopLoc, |
| 865 | "Unable to unroll loop the number of times directed by " |
| 866 | "unroll_count pragma because unrolled size is too large."); |
| 867 | } |
| 868 | } |
| 869 | |
| 870 | if (Unrolling != Full && Count < 2) { |
| 871 | // Partial unrolling by 1 is a nop. For full unrolling, a factor |
| 872 | // of 1 makes sense because loop control can be eliminated. |
| 873 | return false; |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 874 | } |
| 875 | |
Dan Gohman | 3dc2d92 | 2008-05-14 00:24:14 +0000 | [diff] [blame] | 876 | // Unroll the loop. |
Hal Finkel | 74c2f35 | 2014-09-07 12:44:26 +0000 | [diff] [blame] | 877 | if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this, |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 878 | &LPM, &AC)) |
Dan Gohman | 3dc2d92 | 2008-05-14 00:24:14 +0000 | [diff] [blame] | 879 | return false; |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 880 | |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 881 | return true; |
| 882 | } |