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