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