Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 1 | //===- LoopInterchange.cpp - Loop interchange pass-------------------------===// |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This Pass handles loop interchange transform. |
| 10 | // This pass interchanges loops to provide a more cache-friendly memory access |
| 11 | // patterns. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/STLExtras.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/SmallVector.h" |
Florian Hahn | 6e00433 | 2018-04-05 10:39:23 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/Statistic.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/StringRef.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/DependenceAnalysis.h" |
| 20 | #include "llvm/Analysis/LoopInfo.h" |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/LoopPass.h" |
Adam Nemet | 0965da2 | 2017-10-09 23:19:02 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/ScalarEvolution.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 25 | #include "llvm/IR/BasicBlock.h" |
| 26 | #include "llvm/IR/Constants.h" |
| 27 | #include "llvm/IR/DiagnosticInfo.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Dominators.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 29 | #include "llvm/IR/Function.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 30 | #include "llvm/IR/InstrTypes.h" |
| 31 | #include "llvm/IR/Instruction.h" |
| 32 | #include "llvm/IR/Instructions.h" |
| 33 | #include "llvm/IR/Type.h" |
| 34 | #include "llvm/IR/User.h" |
| 35 | #include "llvm/IR/Value.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 36 | #include "llvm/Pass.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 37 | #include "llvm/Support/Casting.h" |
| 38 | #include "llvm/Support/CommandLine.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 39 | #include "llvm/Support/Debug.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 40 | #include "llvm/Support/ErrorHandling.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 41 | #include "llvm/Support/raw_ostream.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 42 | #include "llvm/Transforms/Scalar.h" |
David Blaikie | a373d18 | 2018-03-28 17:44:36 +0000 | [diff] [blame] | 43 | #include "llvm/Transforms/Utils.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 44 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 45 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 46 | #include <cassert> |
| 47 | #include <utility> |
| 48 | #include <vector> |
Davide Italiano | 9d8f6f8 | 2017-01-29 01:55:24 +0000 | [diff] [blame] | 49 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 50 | using namespace llvm; |
| 51 | |
| 52 | #define DEBUG_TYPE "loop-interchange" |
| 53 | |
Florian Hahn | 6e00433 | 2018-04-05 10:39:23 +0000 | [diff] [blame] | 54 | STATISTIC(LoopsInterchanged, "Number of loops interchanged"); |
| 55 | |
Chad Rosier | 7243189 | 2016-09-14 17:07:13 +0000 | [diff] [blame] | 56 | static cl::opt<int> LoopInterchangeCostThreshold( |
| 57 | "loop-interchange-threshold", cl::init(0), cl::Hidden, |
| 58 | cl::desc("Interchange if you gain more than this number")); |
| 59 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 60 | namespace { |
| 61 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 62 | using LoopVector = SmallVector<Loop *, 8>; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 63 | |
| 64 | // TODO: Check if we can use a sparse matrix here. |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 65 | using CharMatrix = std::vector<std::vector<char>>; |
| 66 | |
| 67 | } // end anonymous namespace |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 68 | |
| 69 | // Maximum number of dependencies that can be handled in the dependency matrix. |
| 70 | static const unsigned MaxMemInstrCount = 100; |
| 71 | |
| 72 | // Maximum loop depth supported. |
| 73 | static const unsigned MaxLoopNestDepth = 10; |
| 74 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 75 | #ifdef DUMP_DEP_MATRICIES |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 76 | static void printDepMatrix(CharMatrix &DepMatrix) { |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 77 | for (auto &Row : DepMatrix) { |
| 78 | for (auto D : Row) |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 79 | LLVM_DEBUG(dbgs() << D << " "); |
| 80 | LLVM_DEBUG(dbgs() << "\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 81 | } |
| 82 | } |
| 83 | #endif |
| 84 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 85 | static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 86 | Loop *L, DependenceInfo *DI) { |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 87 | using ValueVector = SmallVector<Value *, 16>; |
| 88 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 89 | ValueVector MemInstr; |
| 90 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 91 | // For each block. |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 92 | for (BasicBlock *BB : L->blocks()) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 93 | // Scan the BB and collect legal loads and stores. |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 94 | for (Instruction &I : *BB) { |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 95 | if (!isa<Instruction>(I)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 96 | return false; |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 97 | if (auto *Ld = dyn_cast<LoadInst>(&I)) { |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 98 | if (!Ld->isSimple()) |
| 99 | return false; |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 100 | MemInstr.push_back(&I); |
| 101 | } else if (auto *St = dyn_cast<StoreInst>(&I)) { |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 102 | if (!St->isSimple()) |
| 103 | return false; |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 104 | MemInstr.push_back(&I); |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 105 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 106 | } |
| 107 | } |
| 108 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 109 | LLVM_DEBUG(dbgs() << "Found " << MemInstr.size() |
| 110 | << " Loads and Stores to analyze\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 111 | |
| 112 | ValueVector::iterator I, IE, J, JE; |
| 113 | |
| 114 | for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) { |
| 115 | for (J = I, JE = MemInstr.end(); J != JE; ++J) { |
| 116 | std::vector<char> Dep; |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 117 | Instruction *Src = cast<Instruction>(*I); |
| 118 | Instruction *Dst = cast<Instruction>(*J); |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 119 | if (Src == Dst) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 120 | continue; |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 121 | // Ignore Input dependencies. |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 122 | if (isa<LoadInst>(Src) && isa<LoadInst>(Dst)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 123 | continue; |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 124 | // Track Output, Flow, and Anti dependencies. |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 125 | if (auto D = DI->depends(Src, Dst, true)) { |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 126 | assert(D->isOrdered() && "Expected an output, flow or anti dep."); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 127 | LLVM_DEBUG(StringRef DepType = |
| 128 | D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output"; |
| 129 | dbgs() << "Found " << DepType |
| 130 | << " dependency between Src and Dst\n" |
| 131 | << " Src:" << *Src << "\n Dst:" << *Dst << '\n'); |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 132 | unsigned Levels = D->getLevels(); |
| 133 | char Direction; |
| 134 | for (unsigned II = 1; II <= Levels; ++II) { |
| 135 | const SCEV *Distance = D->getDistance(II); |
| 136 | const SCEVConstant *SCEVConst = |
| 137 | dyn_cast_or_null<SCEVConstant>(Distance); |
| 138 | if (SCEVConst) { |
| 139 | const ConstantInt *CI = SCEVConst->getValue(); |
| 140 | if (CI->isNegative()) |
| 141 | Direction = '<'; |
| 142 | else if (CI->isZero()) |
| 143 | Direction = '='; |
| 144 | else |
| 145 | Direction = '>'; |
| 146 | Dep.push_back(Direction); |
| 147 | } else if (D->isScalar(II)) { |
| 148 | Direction = 'S'; |
| 149 | Dep.push_back(Direction); |
| 150 | } else { |
| 151 | unsigned Dir = D->getDirection(II); |
| 152 | if (Dir == Dependence::DVEntry::LT || |
| 153 | Dir == Dependence::DVEntry::LE) |
| 154 | Direction = '<'; |
| 155 | else if (Dir == Dependence::DVEntry::GT || |
| 156 | Dir == Dependence::DVEntry::GE) |
| 157 | Direction = '>'; |
| 158 | else if (Dir == Dependence::DVEntry::EQ) |
| 159 | Direction = '='; |
| 160 | else |
| 161 | Direction = '*'; |
| 162 | Dep.push_back(Direction); |
| 163 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 164 | } |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 165 | while (Dep.size() != Level) { |
| 166 | Dep.push_back('I'); |
| 167 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 168 | |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 169 | DepMatrix.push_back(Dep); |
| 170 | if (DepMatrix.size() > MaxMemInstrCount) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 171 | LLVM_DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount |
| 172 | << " dependencies inside loop\n"); |
Chad Rosier | 00eb8db | 2016-09-21 19:16:47 +0000 | [diff] [blame] | 173 | return false; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 174 | } |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 179 | return true; |
| 180 | } |
| 181 | |
| 182 | // A loop is moved from index 'from' to an index 'to'. Update the Dependence |
| 183 | // matrix by exchanging the two columns. |
Chad Rosier | d18ea06 | 2016-09-13 13:00:29 +0000 | [diff] [blame] | 184 | static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, |
| 185 | unsigned ToIndx) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 186 | unsigned numRows = DepMatrix.size(); |
| 187 | for (unsigned i = 0; i < numRows; ++i) { |
| 188 | char TmpVal = DepMatrix[i][ToIndx]; |
| 189 | DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx]; |
| 190 | DepMatrix[i][FromIndx] = TmpVal; |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is |
| 195 | // '>' |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 196 | static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row, |
| 197 | unsigned Column) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 198 | for (unsigned i = 0; i <= Column; ++i) { |
| 199 | if (DepMatrix[Row][i] == '<') |
| 200 | return false; |
| 201 | if (DepMatrix[Row][i] == '>') |
| 202 | return true; |
| 203 | } |
| 204 | // All dependencies were '=','S' or 'I' |
| 205 | return false; |
| 206 | } |
| 207 | |
| 208 | // Checks if no dependence exist in the dependency matrix in Row before Column. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 209 | static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row, |
| 210 | unsigned Column) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 211 | for (unsigned i = 0; i < Column; ++i) { |
Chandler Carruth | fca1ff0 | 2016-11-03 16:39:25 +0000 | [diff] [blame] | 212 | if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' && |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 213 | DepMatrix[Row][i] != 'I') |
| 214 | return false; |
| 215 | } |
| 216 | return true; |
| 217 | } |
| 218 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 219 | static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row, |
| 220 | unsigned OuterLoopId, char InnerDep, |
| 221 | char OuterDep) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 222 | if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId)) |
| 223 | return false; |
| 224 | |
| 225 | if (InnerDep == OuterDep) |
| 226 | return true; |
| 227 | |
| 228 | // It is legal to interchange if and only if after interchange no row has a |
| 229 | // '>' direction as the leftmost non-'='. |
| 230 | |
| 231 | if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I') |
| 232 | return true; |
| 233 | |
| 234 | if (InnerDep == '<') |
| 235 | return true; |
| 236 | |
| 237 | if (InnerDep == '>') { |
| 238 | // If OuterLoopId represents outermost loop then interchanging will make the |
| 239 | // 1st dependency as '>' |
| 240 | if (OuterLoopId == 0) |
| 241 | return false; |
| 242 | |
| 243 | // If all dependencies before OuterloopId are '=','S'or 'I'. Then |
| 244 | // interchanging will result in this row having an outermost non '=' |
| 245 | // dependency of '>' |
| 246 | if (!containsNoDependence(DepMatrix, Row, OuterLoopId)) |
| 247 | return true; |
| 248 | } |
| 249 | |
| 250 | return false; |
| 251 | } |
| 252 | |
| 253 | // Checks if it is legal to interchange 2 loops. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 254 | // [Theorem] A permutation of the loops in a perfect nest is legal if and only |
Chad Rosier | 61683a2 | 2016-09-13 13:08:53 +0000 | [diff] [blame] | 255 | // if the direction matrix, after the same permutation is applied to its |
| 256 | // columns, has no ">" direction as the leftmost non-"=" direction in any row. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 257 | static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, |
| 258 | unsigned InnerLoopId, |
| 259 | unsigned OuterLoopId) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 260 | unsigned NumRows = DepMatrix.size(); |
| 261 | // For each row check if it is valid to interchange. |
| 262 | for (unsigned Row = 0; Row < NumRows; ++Row) { |
| 263 | char InnerDep = DepMatrix[Row][InnerLoopId]; |
| 264 | char OuterDep = DepMatrix[Row][OuterLoopId]; |
| 265 | if (InnerDep == '*' || OuterDep == '*') |
| 266 | return false; |
Chad Rosier | 61683a2 | 2016-09-13 13:08:53 +0000 | [diff] [blame] | 267 | if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 268 | return false; |
| 269 | } |
| 270 | return true; |
| 271 | } |
| 272 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 273 | static LoopVector populateWorklist(Loop &L) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 274 | LLVM_DEBUG(dbgs() << "Calling populateWorklist on Func: " |
| 275 | << L.getHeader()->getParent()->getName() << " Loop: %" |
| 276 | << L.getHeader()->getName() << '\n'); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 277 | LoopVector LoopList; |
| 278 | Loop *CurrentLoop = &L; |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 279 | const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops(); |
| 280 | while (!Vec->empty()) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 281 | // The current loop has multiple subloops in it hence it is not tightly |
| 282 | // nested. |
| 283 | // Discard all loops above it added into Worklist. |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 284 | if (Vec->size() != 1) |
| 285 | return {}; |
| 286 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 287 | LoopList.push_back(CurrentLoop); |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 288 | CurrentLoop = Vec->front(); |
| 289 | Vec = &CurrentLoop->getSubLoops(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 290 | } |
| 291 | LoopList.push_back(CurrentLoop); |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 292 | return LoopList; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 293 | } |
| 294 | |
Kit Barton | 987fdfd | 2019-05-23 20:53:05 +0000 | [diff] [blame] | 295 | static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) { |
| 296 | PHINode *InnerIndexVar = L->getCanonicalInductionVariable(); |
| 297 | if (InnerIndexVar) |
| 298 | return InnerIndexVar; |
| 299 | if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) |
| 300 | return nullptr; |
| 301 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
| 302 | PHINode *PhiVar = cast<PHINode>(I); |
| 303 | Type *PhiTy = PhiVar->getType(); |
| 304 | if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && |
| 305 | !PhiTy->isPointerTy()) |
| 306 | return nullptr; |
| 307 | const SCEVAddRecExpr *AddRec = |
| 308 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar)); |
| 309 | if (!AddRec || !AddRec->isAffine()) |
| 310 | continue; |
| 311 | const SCEV *Step = AddRec->getStepRecurrence(*SE); |
| 312 | if (!isa<SCEVConstant>(Step)) |
| 313 | continue; |
| 314 | // Found the induction variable. |
| 315 | // FIXME: Handle loops with more than one induction variable. Note that, |
| 316 | // currently, legality makes sure we have only one induction variable. |
| 317 | return PhiVar; |
| 318 | } |
| 319 | return nullptr; |
| 320 | } |
| 321 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 322 | namespace { |
| 323 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 324 | /// LoopInterchangeLegality checks if it is legal to interchange the loop. |
| 325 | class LoopInterchangeLegality { |
| 326 | public: |
| 327 | LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE, |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 328 | OptimizationRemarkEmitter *ORE) |
Florian Hahn | c51d088 | 2018-09-06 10:41:01 +0000 | [diff] [blame] | 329 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {} |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 330 | |
| 331 | /// Check if the loops can be interchanged. |
| 332 | bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId, |
| 333 | CharMatrix &DepMatrix); |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 334 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 335 | /// Check if the loop structure is understood. We do not handle triangular |
| 336 | /// loops for now. |
| 337 | bool isLoopStructureUnderstood(PHINode *InnerInductionVar); |
| 338 | |
| 339 | bool currentLimitations(); |
| 340 | |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 341 | const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions() const { |
| 342 | return OuterInnerReductions; |
| 343 | } |
| 344 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 345 | private: |
| 346 | bool tightlyNested(Loop *Outer, Loop *Inner); |
Florian Hahn | c8bd6ea | 2018-11-01 19:25:00 +0000 | [diff] [blame] | 347 | bool containsUnsafeInstructions(BasicBlock *BB); |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 348 | |
| 349 | /// Discover induction and reduction PHIs in the header of \p L. Induction |
| 350 | /// PHIs are added to \p Inductions, reductions are added to |
| 351 | /// OuterInnerReductions. When the outer loop is passed, the inner loop needs |
| 352 | /// to be passed as \p InnerLoop. |
| 353 | bool findInductionAndReductions(Loop *L, |
| 354 | SmallVector<PHINode *, 8> &Inductions, |
| 355 | Loop *InnerLoop); |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 356 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 357 | Loop *OuterLoop; |
| 358 | Loop *InnerLoop; |
| 359 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 360 | ScalarEvolution *SE; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 361 | |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 362 | /// Interface to emit optimization remarks. |
| 363 | OptimizationRemarkEmitter *ORE; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 364 | |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 365 | /// Set of reduction PHIs taking part of a reduction across the inner and |
| 366 | /// outer loop. |
| 367 | SmallPtrSet<PHINode *, 4> OuterInnerReductions; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 368 | }; |
| 369 | |
| 370 | /// LoopInterchangeProfitability checks if it is profitable to interchange the |
| 371 | /// loop. |
| 372 | class LoopInterchangeProfitability { |
| 373 | public: |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 374 | LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE, |
| 375 | OptimizationRemarkEmitter *ORE) |
| 376 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {} |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 377 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 378 | /// Check if the loop interchange is profitable. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 379 | bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId, |
| 380 | CharMatrix &DepMatrix); |
| 381 | |
| 382 | private: |
| 383 | int getInstrOrderCost(); |
| 384 | |
| 385 | Loop *OuterLoop; |
| 386 | Loop *InnerLoop; |
| 387 | |
| 388 | /// Scev analysis. |
| 389 | ScalarEvolution *SE; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 390 | |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 391 | /// Interface to emit optimization remarks. |
| 392 | OptimizationRemarkEmitter *ORE; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 393 | }; |
| 394 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 395 | /// LoopInterchangeTransform interchanges the loop. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 396 | class LoopInterchangeTransform { |
| 397 | public: |
| 398 | LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE, |
| 399 | LoopInfo *LI, DominatorTree *DT, |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 400 | BasicBlock *LoopNestExit, |
| 401 | const LoopInterchangeLegality &LIL) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 402 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 403 | LoopExit(LoopNestExit), LIL(LIL) {} |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 404 | |
| 405 | /// Interchange OuterLoop and InnerLoop. |
| 406 | bool transform(); |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 407 | void restructureLoops(Loop *NewInner, Loop *NewOuter, |
| 408 | BasicBlock *OrigInnerPreHeader, |
| 409 | BasicBlock *OrigOuterPreHeader); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 410 | void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 411 | |
| 412 | private: |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 413 | bool adjustLoopLinks(); |
| 414 | void adjustLoopPreheaders(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 415 | bool adjustLoopBranches(); |
| 416 | |
| 417 | Loop *OuterLoop; |
| 418 | Loop *InnerLoop; |
| 419 | |
| 420 | /// Scev analysis. |
| 421 | ScalarEvolution *SE; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 422 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 423 | LoopInfo *LI; |
| 424 | DominatorTree *DT; |
| 425 | BasicBlock *LoopExit; |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 426 | |
| 427 | const LoopInterchangeLegality &LIL; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 428 | }; |
| 429 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 430 | // Main LoopInterchange Pass. |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 431 | struct LoopInterchange : public LoopPass { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 432 | static char ID; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 433 | ScalarEvolution *SE = nullptr; |
| 434 | LoopInfo *LI = nullptr; |
| 435 | DependenceInfo *DI = nullptr; |
| 436 | DominatorTree *DT = nullptr; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 437 | |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 438 | /// Interface to emit optimization remarks. |
| 439 | OptimizationRemarkEmitter *ORE; |
| 440 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 441 | LoopInterchange() : LoopPass(ID) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 442 | initializeLoopInterchangePass(*PassRegistry::getPassRegistry()); |
| 443 | } |
| 444 | |
| 445 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 446 | AU.addRequired<DependenceAnalysisWrapperPass>(); |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 447 | AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 448 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 449 | getLoopAnalysisUsage(AU); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 450 | } |
| 451 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 452 | bool runOnLoop(Loop *L, LPPassManager &LPM) override { |
| 453 | if (skipLoop(L) || L->getParentLoop()) |
Florian Hahn | 8d72ecc | 2018-09-28 10:20:07 +0000 | [diff] [blame] | 454 | return false; |
Andrew Kaylor | 50271f7 | 2016-05-03 22:32:30 +0000 | [diff] [blame] | 455 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 456 | SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 457 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 458 | DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI(); |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 459 | DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 460 | ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 461 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 462 | return processLoopList(populateWorklist(*L)); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 463 | } |
| 464 | |
| 465 | bool isComputableLoopNest(LoopVector LoopList) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 466 | for (Loop *L : LoopList) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 467 | const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L); |
| 468 | if (ExitCountOuter == SE->getCouldNotCompute()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 469 | LLVM_DEBUG(dbgs() << "Couldn't compute backedge count\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 470 | return false; |
| 471 | } |
| 472 | if (L->getNumBackEdges() != 1) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 473 | LLVM_DEBUG(dbgs() << "NumBackEdges is not equal to 1\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 474 | return false; |
| 475 | } |
| 476 | if (!L->getExitingBlock()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 477 | LLVM_DEBUG(dbgs() << "Loop doesn't have unique exit block\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 478 | return false; |
| 479 | } |
| 480 | } |
| 481 | return true; |
| 482 | } |
| 483 | |
Benjamin Kramer | c321e53 | 2016-06-08 19:09:22 +0000 | [diff] [blame] | 484 | unsigned selectLoopForInterchange(const LoopVector &LoopList) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 485 | // TODO: Add a better heuristic to select the loop to be interchanged based |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 486 | // on the dependence matrix. Currently we select the innermost loop. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 487 | return LoopList.size() - 1; |
| 488 | } |
| 489 | |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 490 | bool processLoopList(LoopVector LoopList) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 491 | bool Changed = false; |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 492 | unsigned LoopNestDepth = LoopList.size(); |
| 493 | if (LoopNestDepth < 2) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 494 | LLVM_DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 495 | return false; |
| 496 | } |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 497 | if (LoopNestDepth > MaxLoopNestDepth) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 498 | LLVM_DEBUG(dbgs() << "Cannot handle loops of depth greater than " |
| 499 | << MaxLoopNestDepth << "\n"); |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 500 | return false; |
| 501 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 502 | if (!isComputableLoopNest(LoopList)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 503 | LLVM_DEBUG(dbgs() << "Not valid loop candidate for interchange\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 504 | return false; |
| 505 | } |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 506 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 507 | LLVM_DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth |
| 508 | << "\n"); |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 509 | |
| 510 | CharMatrix DependencyMatrix; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 511 | Loop *OuterMostLoop = *(LoopList.begin()); |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 512 | if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth, |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 513 | OuterMostLoop, DI)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 514 | LLVM_DEBUG(dbgs() << "Populating dependency matrix failed\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 515 | return false; |
| 516 | } |
| 517 | #ifdef DUMP_DEP_MATRICIES |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 518 | LLVM_DEBUG(dbgs() << "Dependence before interchange\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 519 | printDepMatrix(DependencyMatrix); |
| 520 | #endif |
| 521 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 522 | // Get the Outermost loop exit. |
Florian Hahn | 1da30c6 | 2018-04-25 09:35:54 +0000 | [diff] [blame] | 523 | BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock(); |
| 524 | if (!LoopNestExit) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 525 | LLVM_DEBUG(dbgs() << "OuterMostLoop needs an unique exit block"); |
Florian Hahn | 1da30c6 | 2018-04-25 09:35:54 +0000 | [diff] [blame] | 526 | return false; |
| 527 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 528 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 529 | unsigned SelecLoopId = selectLoopForInterchange(LoopList); |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 530 | // Move the selected loop outwards to the best possible position. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 531 | for (unsigned i = SelecLoopId; i > 0; i--) { |
| 532 | bool Interchanged = |
| 533 | processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix); |
| 534 | if (!Interchanged) |
| 535 | return Changed; |
| 536 | // Loops interchanged reflect the same in LoopList |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 537 | std::swap(LoopList[i - 1], LoopList[i]); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 538 | |
| 539 | // Update the DependencyMatrix |
Chad Rosier | d18ea06 | 2016-09-13 13:00:29 +0000 | [diff] [blame] | 540 | interChangeDependencies(DependencyMatrix, i, i - 1); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 541 | #ifdef DUMP_DEP_MATRICIES |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 542 | LLVM_DEBUG(dbgs() << "Dependence after interchange\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 543 | printDepMatrix(DependencyMatrix); |
| 544 | #endif |
| 545 | Changed |= Interchanged; |
| 546 | } |
| 547 | return Changed; |
| 548 | } |
| 549 | |
| 550 | bool processLoop(LoopVector LoopList, unsigned InnerLoopId, |
| 551 | unsigned OuterLoopId, BasicBlock *LoopNestExit, |
| 552 | std::vector<std::vector<char>> &DependencyMatrix) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 553 | LLVM_DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId |
| 554 | << " and OuterLoopId = " << OuterLoopId << "\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 555 | Loop *InnerLoop = LoopList[InnerLoopId]; |
| 556 | Loop *OuterLoop = LoopList[OuterLoopId]; |
| 557 | |
Florian Hahn | c51d088 | 2018-09-06 10:41:01 +0000 | [diff] [blame] | 558 | LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 559 | if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 560 | LLVM_DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 561 | return false; |
| 562 | } |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 563 | LLVM_DEBUG(dbgs() << "Loops are legal to interchange\n"); |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 564 | LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 565 | if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 566 | LLVM_DEBUG(dbgs() << "Interchanging loops not profitable.\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 567 | return false; |
| 568 | } |
| 569 | |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 570 | ORE->emit([&]() { |
| 571 | return OptimizationRemark(DEBUG_TYPE, "Interchanged", |
| 572 | InnerLoop->getStartLoc(), |
| 573 | InnerLoop->getHeader()) |
| 574 | << "Loop interchanged with enclosing loop."; |
| 575 | }); |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 576 | |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 577 | LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LoopNestExit, |
| 578 | LIL); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 579 | LIT.transform(); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 580 | LLVM_DEBUG(dbgs() << "Loops interchanged.\n"); |
Florian Hahn | 6e00433 | 2018-04-05 10:39:23 +0000 | [diff] [blame] | 581 | LoopsInterchanged++; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 582 | return true; |
| 583 | } |
| 584 | }; |
| 585 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 586 | } // end anonymous namespace |
| 587 | |
Florian Hahn | c8bd6ea | 2018-11-01 19:25:00 +0000 | [diff] [blame] | 588 | bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB) { |
| 589 | return any_of(*BB, [](const Instruction &I) { |
| 590 | return I.mayHaveSideEffects() || I.mayReadFromMemory(); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 591 | }); |
| 592 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 593 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 594 | bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) { |
| 595 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 596 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 597 | BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); |
| 598 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 599 | LLVM_DEBUG(dbgs() << "Checking if loops are tightly nested\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 600 | |
| 601 | // A perfectly nested loop will not have any branch in between the outer and |
| 602 | // inner block i.e. outer header will branch to either inner preheader and |
| 603 | // outerloop latch. |
Chad Rosier | f7c76f9 | 2016-09-21 13:28:41 +0000 | [diff] [blame] | 604 | BranchInst *OuterLoopHeaderBI = |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 605 | dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); |
Chad Rosier | f7c76f9 | 2016-09-21 13:28:41 +0000 | [diff] [blame] | 606 | if (!OuterLoopHeaderBI) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 607 | return false; |
Chad Rosier | f7c76f9 | 2016-09-21 13:28:41 +0000 | [diff] [blame] | 608 | |
Chandler Carruth | 96fc1de | 2018-08-26 08:41:15 +0000 | [diff] [blame] | 609 | for (BasicBlock *Succ : successors(OuterLoopHeaderBI)) |
Florian Hahn | 236f6fe | 2018-09-06 09:57:27 +0000 | [diff] [blame] | 610 | if (Succ != InnerLoopPreHeader && Succ != InnerLoop->getHeader() && |
| 611 | Succ != OuterLoopLatch) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 612 | return false; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 613 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 614 | LLVM_DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 615 | // We do not have any basic block in between now make sure the outer header |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 616 | // and outer loop latch doesn't contain any unsafe instructions. |
Florian Hahn | c8bd6ea | 2018-11-01 19:25:00 +0000 | [diff] [blame] | 617 | if (containsUnsafeInstructions(OuterLoopHeader) || |
| 618 | containsUnsafeInstructions(OuterLoopLatch)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 619 | return false; |
| 620 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 621 | LLVM_DEBUG(dbgs() << "Loops are perfectly nested\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 622 | // We have a perfect loop nest. |
| 623 | return true; |
| 624 | } |
| 625 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 626 | bool LoopInterchangeLegality::isLoopStructureUnderstood( |
| 627 | PHINode *InnerInduction) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 628 | unsigned Num = InnerInduction->getNumOperands(); |
| 629 | BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader(); |
| 630 | for (unsigned i = 0; i < Num; ++i) { |
| 631 | Value *Val = InnerInduction->getOperand(i); |
| 632 | if (isa<Constant>(Val)) |
| 633 | continue; |
| 634 | Instruction *I = dyn_cast<Instruction>(Val); |
| 635 | if (!I) |
| 636 | return false; |
| 637 | // TODO: Handle triangular loops. |
| 638 | // e.g. for(int i=0;i<N;i++) |
| 639 | // for(int j=i;j<N;j++) |
| 640 | unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i); |
| 641 | if (InnerInduction->getIncomingBlock(IncomBlockIndx) == |
| 642 | InnerLoopPreheader && |
| 643 | !OuterLoop->isLoopInvariant(I)) { |
| 644 | return false; |
| 645 | } |
| 646 | } |
| 647 | return true; |
| 648 | } |
| 649 | |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 650 | // If SV is a LCSSA PHI node with a single incoming value, return the incoming |
| 651 | // value. |
| 652 | static Value *followLCSSA(Value *SV) { |
| 653 | PHINode *PHI = dyn_cast<PHINode>(SV); |
| 654 | if (!PHI) |
| 655 | return SV; |
| 656 | |
| 657 | if (PHI->getNumIncomingValues() != 1) |
| 658 | return SV; |
| 659 | return followLCSSA(PHI->getIncomingValue(0)); |
| 660 | } |
| 661 | |
| 662 | // Check V's users to see if it is involved in a reduction in L. |
| 663 | static PHINode *findInnerReductionPhi(Loop *L, Value *V) { |
| 664 | for (Value *User : V->users()) { |
| 665 | if (PHINode *PHI = dyn_cast<PHINode>(User)) { |
| 666 | if (PHI->getNumIncomingValues() == 1) |
| 667 | continue; |
| 668 | RecurrenceDescriptor RD; |
| 669 | if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD)) |
| 670 | return PHI; |
| 671 | return nullptr; |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | return nullptr; |
| 676 | } |
| 677 | |
| 678 | bool LoopInterchangeLegality::findInductionAndReductions( |
| 679 | Loop *L, SmallVector<PHINode *, 8> &Inductions, Loop *InnerLoop) { |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 680 | if (!L->getLoopLatch() || !L->getLoopPredecessor()) |
| 681 | return false; |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 682 | for (PHINode &PHI : L->getHeader()->phis()) { |
Tyler Nowicki | 0a91310 | 2015-06-16 18:07:34 +0000 | [diff] [blame] | 683 | RecurrenceDescriptor RD; |
James Molloy | 1bbf15c | 2015-08-27 09:53:00 +0000 | [diff] [blame] | 684 | InductionDescriptor ID; |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 685 | if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID)) |
| 686 | Inductions.push_back(&PHI); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 687 | else { |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 688 | // PHIs in inner loops need to be part of a reduction in the outer loop, |
| 689 | // discovered when checking the PHIs of the outer loop earlier. |
| 690 | if (!InnerLoop) { |
| 691 | if (OuterInnerReductions.find(&PHI) == OuterInnerReductions.end()) { |
| 692 | LLVM_DEBUG(dbgs() << "Inner loop PHI is not part of reductions " |
| 693 | "across the outer loop.\n"); |
| 694 | return false; |
| 695 | } |
| 696 | } else { |
| 697 | assert(PHI.getNumIncomingValues() == 2 && |
| 698 | "Phis in loop header should have exactly 2 incoming values"); |
| 699 | // Check if we have a PHI node in the outer loop that has a reduction |
| 700 | // result from the inner loop as an incoming value. |
| 701 | Value *V = followLCSSA(PHI.getIncomingValueForBlock(L->getLoopLatch())); |
| 702 | PHINode *InnerRedPhi = findInnerReductionPhi(InnerLoop, V); |
| 703 | if (!InnerRedPhi || |
| 704 | !llvm::any_of(InnerRedPhi->incoming_values(), |
| 705 | [&PHI](Value *V) { return V == &PHI; })) { |
| 706 | LLVM_DEBUG( |
| 707 | dbgs() |
| 708 | << "Failed to recognize PHI as an induction or reduction.\n"); |
| 709 | return false; |
| 710 | } |
| 711 | OuterInnerReductions.insert(&PHI); |
| 712 | OuterInnerReductions.insert(InnerRedPhi); |
| 713 | } |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 714 | } |
| 715 | } |
| 716 | return true; |
| 717 | } |
| 718 | |
| 719 | static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) { |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 720 | for (PHINode &PHI : Block->phis()) { |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 721 | // Reduction lcssa phi will have only 1 incoming block that from loop latch. |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 722 | if (PHI.getNumIncomingValues() > 1) |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 723 | return false; |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 724 | Instruction *Ins = dyn_cast<Instruction>(PHI.getIncomingValue(0)); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 725 | if (!Ins) |
| 726 | return false; |
| 727 | // Incoming value for lcssa phi's in outer loop exit can only be inner loop |
| 728 | // exits lcssa phi else it would not be tightly nested. |
| 729 | if (!isa<PHINode>(Ins) && isOuterLoopExitBlock) |
| 730 | return false; |
| 731 | } |
| 732 | return true; |
| 733 | } |
| 734 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 735 | // This function indicates the current limitations in the transform as a result |
| 736 | // of which we do not proceed. |
| 737 | bool LoopInterchangeLegality::currentLimitations() { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 738 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 739 | BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); |
Florian Hahn | 1da30c6 | 2018-04-25 09:35:54 +0000 | [diff] [blame] | 740 | |
| 741 | // transform currently expects the loop latches to also be the exiting |
| 742 | // blocks. |
| 743 | if (InnerLoop->getExitingBlock() != InnerLoopLatch || |
| 744 | OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() || |
| 745 | !isa<BranchInst>(InnerLoopLatch->getTerminator()) || |
| 746 | !isa<BranchInst>(OuterLoop->getLoopLatch()->getTerminator())) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 747 | LLVM_DEBUG( |
| 748 | dbgs() << "Loops where the latch is not the exiting block are not" |
| 749 | << " supported currently.\n"); |
Florian Hahn | 1da30c6 | 2018-04-25 09:35:54 +0000 | [diff] [blame] | 750 | ORE->emit([&]() { |
| 751 | return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch", |
| 752 | OuterLoop->getStartLoc(), |
| 753 | OuterLoop->getHeader()) |
| 754 | << "Loops where the latch is not the exiting block cannot be" |
| 755 | " interchange currently."; |
| 756 | }); |
| 757 | return true; |
| 758 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 759 | |
| 760 | PHINode *InnerInductionVar; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 761 | SmallVector<PHINode *, 8> Inductions; |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 762 | if (!findInductionAndReductions(OuterLoop, Inductions, InnerLoop)) { |
| 763 | LLVM_DEBUG( |
| 764 | dbgs() << "Only outer loops with induction or reduction PHI nodes " |
| 765 | << "are supported currently.\n"); |
| 766 | ORE->emit([&]() { |
| 767 | return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter", |
| 768 | OuterLoop->getStartLoc(), |
| 769 | OuterLoop->getHeader()) |
| 770 | << "Only outer loops with induction or reduction PHI nodes can be" |
| 771 | " interchanged currently."; |
| 772 | }); |
| 773 | return true; |
| 774 | } |
| 775 | |
| 776 | // TODO: Currently we handle only loops with 1 induction variable. |
| 777 | if (Inductions.size() != 1) { |
| 778 | LLVM_DEBUG(dbgs() << "Loops with more than 1 induction variables are not " |
| 779 | << "supported currently.\n"); |
| 780 | ORE->emit([&]() { |
| 781 | return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter", |
| 782 | OuterLoop->getStartLoc(), |
| 783 | OuterLoop->getHeader()) |
| 784 | << "Only outer loops with 1 induction variable can be " |
| 785 | "interchanged currently."; |
| 786 | }); |
| 787 | return true; |
| 788 | } |
| 789 | |
| 790 | Inductions.clear(); |
| 791 | if (!findInductionAndReductions(InnerLoop, Inductions, nullptr)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 792 | LLVM_DEBUG( |
| 793 | dbgs() << "Only inner loops with induction or reduction PHI nodes " |
| 794 | << "are supported currently.\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 795 | ORE->emit([&]() { |
| 796 | return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner", |
| 797 | InnerLoop->getStartLoc(), |
| 798 | InnerLoop->getHeader()) |
| 799 | << "Only inner loops with induction or reduction PHI nodes can be" |
| 800 | " interchange currently."; |
| 801 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 802 | return true; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 803 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 804 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 805 | // TODO: Currently we handle only loops with 1 induction variable. |
| 806 | if (Inductions.size() != 1) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 807 | LLVM_DEBUG( |
| 808 | dbgs() << "We currently only support loops with 1 induction variable." |
| 809 | << "Failed to interchange due to current limitation\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 810 | ORE->emit([&]() { |
| 811 | return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner", |
| 812 | InnerLoop->getStartLoc(), |
| 813 | InnerLoop->getHeader()) |
| 814 | << "Only inner loops with 1 induction variable can be " |
| 815 | "interchanged currently."; |
| 816 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 817 | return true; |
| 818 | } |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 819 | InnerInductionVar = Inductions.pop_back_val(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 820 | |
| 821 | // TODO: Triangular loops are not handled for now. |
| 822 | if (!isLoopStructureUnderstood(InnerInductionVar)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 823 | LLVM_DEBUG(dbgs() << "Loop structure not understood by pass\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 824 | ORE->emit([&]() { |
| 825 | return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner", |
| 826 | InnerLoop->getStartLoc(), |
| 827 | InnerLoop->getHeader()) |
| 828 | << "Inner loop structure not understood currently."; |
| 829 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 830 | return true; |
| 831 | } |
| 832 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 833 | // TODO: We only handle LCSSA PHI's corresponding to reduction for now. |
Florian Hahn | 1da30c6 | 2018-04-25 09:35:54 +0000 | [diff] [blame] | 834 | BasicBlock *InnerExit = InnerLoop->getExitBlock(); |
| 835 | if (!containsSafePHI(InnerExit, false)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 836 | LLVM_DEBUG( |
| 837 | dbgs() << "Can only handle LCSSA PHIs in inner loops currently.\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 838 | ORE->emit([&]() { |
| 839 | return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuterInner", |
| 840 | InnerLoop->getStartLoc(), |
| 841 | InnerLoop->getHeader()) |
| 842 | << "Only inner loops with LCSSA PHIs can be interchange " |
| 843 | "currently."; |
| 844 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 845 | return true; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 846 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 847 | |
| 848 | // TODO: Current limitation: Since we split the inner loop latch at the point |
| 849 | // were induction variable is incremented (induction.next); We cannot have |
| 850 | // more than 1 user of induction.next since it would result in broken code |
| 851 | // after split. |
| 852 | // e.g. |
| 853 | // for(i=0;i<N;i++) { |
| 854 | // for(j = 0;j<M;j++) { |
| 855 | // A[j+1][i+2] = A[j][i]+k; |
| 856 | // } |
| 857 | // } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 858 | Instruction *InnerIndexVarInc = nullptr; |
| 859 | if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader) |
| 860 | InnerIndexVarInc = |
| 861 | dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1)); |
| 862 | else |
| 863 | InnerIndexVarInc = |
| 864 | dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0)); |
| 865 | |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 866 | if (!InnerIndexVarInc) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 867 | LLVM_DEBUG( |
| 868 | dbgs() << "Did not find an instruction to increment the induction " |
| 869 | << "variable.\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 870 | ORE->emit([&]() { |
| 871 | return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner", |
| 872 | InnerLoop->getStartLoc(), |
| 873 | InnerLoop->getHeader()) |
| 874 | << "The inner loop does not increment the induction variable."; |
| 875 | }); |
Pete Cooper | 11bd958 | 2015-07-27 18:37:58 +0000 | [diff] [blame] | 876 | return true; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 877 | } |
Pete Cooper | 11bd958 | 2015-07-27 18:37:58 +0000 | [diff] [blame] | 878 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 879 | // Since we split the inner loop latch on this induction variable. Make sure |
| 880 | // we do not have any instruction between the induction variable and branch |
| 881 | // instruction. |
| 882 | |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 883 | bool FoundInduction = false; |
Florian Hahn | fd2bc11 | 2018-04-26 10:26:17 +0000 | [diff] [blame] | 884 | for (const Instruction &I : |
| 885 | llvm::reverse(InnerLoopLatch->instructionsWithoutDebug())) { |
Florian Hahn | cd78345 | 2017-08-25 16:52:29 +0000 | [diff] [blame] | 886 | if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) || |
| 887 | isa<ZExtInst>(I)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 888 | continue; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 889 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 890 | // We found an instruction. If this is not induction variable then it is not |
| 891 | // safe to split this loop latch. |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 892 | if (!I.isIdenticalTo(InnerIndexVarInc)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 893 | LLVM_DEBUG(dbgs() << "Found unsupported instructions between induction " |
| 894 | << "variable increment and branch.\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 895 | ORE->emit([&]() { |
| 896 | return OptimizationRemarkMissed( |
| 897 | DEBUG_TYPE, "UnsupportedInsBetweenInduction", |
| 898 | InnerLoop->getStartLoc(), InnerLoop->getHeader()) |
| 899 | << "Found unsupported instruction between induction variable " |
| 900 | "increment and branch."; |
| 901 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 902 | return true; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 903 | } |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 904 | |
| 905 | FoundInduction = true; |
| 906 | break; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 907 | } |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 908 | // The loop latch ended and we didn't find the induction variable return as |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 909 | // current limitation. |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 910 | if (!FoundInduction) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 911 | LLVM_DEBUG(dbgs() << "Did not find the induction variable.\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 912 | ORE->emit([&]() { |
| 913 | return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable", |
| 914 | InnerLoop->getStartLoc(), |
| 915 | InnerLoop->getHeader()) |
| 916 | << "Did not find the induction variable."; |
| 917 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 918 | return true; |
Florian Hahn | 4eeff39 | 2017-07-03 15:32:00 +0000 | [diff] [blame] | 919 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 920 | return false; |
| 921 | } |
| 922 | |
Florian Hahn | f3fea0f | 2018-04-27 13:52:51 +0000 | [diff] [blame] | 923 | // We currently support LCSSA PHI nodes in the outer loop exit, if their |
| 924 | // incoming values do not come from the outer loop latch or if the |
| 925 | // outer loop latch has a single predecessor. In that case, the value will |
| 926 | // be available if both the inner and outer loop conditions are true, which |
| 927 | // will still be true after interchanging. If we have multiple predecessor, |
| 928 | // that may not be the case, e.g. because the outer loop latch may be executed |
| 929 | // if the inner loop is not executed. |
| 930 | static bool areLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) { |
| 931 | BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock(); |
| 932 | for (PHINode &PHI : LoopNestExit->phis()) { |
| 933 | // FIXME: We currently are not able to detect floating point reductions |
| 934 | // and have to use floating point PHIs as a proxy to prevent |
| 935 | // interchanging in the presence of floating point reductions. |
| 936 | if (PHI.getType()->isFloatingPointTy()) |
| 937 | return false; |
| 938 | for (unsigned i = 0; i < PHI.getNumIncomingValues(); i++) { |
| 939 | Instruction *IncomingI = dyn_cast<Instruction>(PHI.getIncomingValue(i)); |
| 940 | if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch()) |
| 941 | continue; |
| 942 | |
| 943 | // The incoming value is defined in the outer loop latch. Currently we |
| 944 | // only support that in case the outer loop latch has a single predecessor. |
| 945 | // This guarantees that the outer loop latch is executed if and only if |
| 946 | // the inner loop is executed (because tightlyNested() guarantees that the |
| 947 | // outer loop header only branches to the inner loop or the outer loop |
| 948 | // latch). |
| 949 | // FIXME: We could weaken this logic and allow multiple predecessors, |
| 950 | // if the values are produced outside the loop latch. We would need |
| 951 | // additional logic to update the PHI nodes in the exit block as |
| 952 | // well. |
| 953 | if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr) |
| 954 | return false; |
| 955 | } |
| 956 | } |
| 957 | return true; |
| 958 | } |
| 959 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 960 | bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId, |
| 961 | unsigned OuterLoopId, |
| 962 | CharMatrix &DepMatrix) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 963 | if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 964 | LLVM_DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId |
| 965 | << " and OuterLoopId = " << OuterLoopId |
| 966 | << " due to dependence\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 967 | ORE->emit([&]() { |
| 968 | return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence", |
| 969 | InnerLoop->getStartLoc(), |
| 970 | InnerLoop->getHeader()) |
| 971 | << "Cannot interchange loops due to dependences."; |
| 972 | }); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 973 | return false; |
| 974 | } |
Florian Hahn | 4284049 | 2017-07-31 09:00:52 +0000 | [diff] [blame] | 975 | // Check if outer and inner loop contain legal instructions only. |
| 976 | for (auto *BB : OuterLoop->blocks()) |
Florian Hahn | fd2bc11 | 2018-04-26 10:26:17 +0000 | [diff] [blame] | 977 | for (Instruction &I : BB->instructionsWithoutDebug()) |
Florian Hahn | 4284049 | 2017-07-31 09:00:52 +0000 | [diff] [blame] | 978 | if (CallInst *CI = dyn_cast<CallInst>(&I)) { |
| 979 | // readnone functions do not prevent interchanging. |
| 980 | if (CI->doesNotReadMemory()) |
| 981 | continue; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 982 | LLVM_DEBUG( |
| 983 | dbgs() << "Loops with call instructions cannot be interchanged " |
| 984 | << "safely."); |
Florian Hahn | 9467ccf | 2018-04-03 20:54:04 +0000 | [diff] [blame] | 985 | ORE->emit([&]() { |
| 986 | return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst", |
| 987 | CI->getDebugLoc(), |
| 988 | CI->getParent()) |
| 989 | << "Cannot interchange loops due to call instruction."; |
| 990 | }); |
| 991 | |
Florian Hahn | 4284049 | 2017-07-31 09:00:52 +0000 | [diff] [blame] | 992 | return false; |
| 993 | } |
| 994 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 995 | // TODO: The loops could not be interchanged due to current limitations in the |
| 996 | // transform module. |
| 997 | if (currentLimitations()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 998 | LLVM_DEBUG(dbgs() << "Not legal because of current transform limitation\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 999 | return false; |
| 1000 | } |
| 1001 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1002 | // Check if the loops are tightly nested. |
| 1003 | if (!tightlyNested(OuterLoop, InnerLoop)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1004 | LLVM_DEBUG(dbgs() << "Loops not tightly nested\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 1005 | ORE->emit([&]() { |
| 1006 | return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested", |
| 1007 | InnerLoop->getStartLoc(), |
| 1008 | InnerLoop->getHeader()) |
| 1009 | << "Cannot interchange loops because they are not tightly " |
| 1010 | "nested."; |
| 1011 | }); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1012 | return false; |
| 1013 | } |
| 1014 | |
Florian Hahn | f3fea0f | 2018-04-27 13:52:51 +0000 | [diff] [blame] | 1015 | if (!areLoopExitPHIsSupported(OuterLoop, InnerLoop)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1016 | LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n"); |
Florian Hahn | f3fea0f | 2018-04-27 13:52:51 +0000 | [diff] [blame] | 1017 | ORE->emit([&]() { |
| 1018 | return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI", |
| 1019 | OuterLoop->getStartLoc(), |
| 1020 | OuterLoop->getHeader()) |
| 1021 | << "Found unsupported PHI node in loop exit."; |
| 1022 | }); |
| 1023 | return false; |
| 1024 | } |
| 1025 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1026 | return true; |
| 1027 | } |
| 1028 | |
| 1029 | int LoopInterchangeProfitability::getInstrOrderCost() { |
| 1030 | unsigned GoodOrder, BadOrder; |
| 1031 | BadOrder = GoodOrder = 0; |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 1032 | for (BasicBlock *BB : InnerLoop->blocks()) { |
| 1033 | for (Instruction &Ins : *BB) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1034 | if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) { |
| 1035 | unsigned NumOp = GEP->getNumOperands(); |
| 1036 | bool FoundInnerInduction = false; |
| 1037 | bool FoundOuterInduction = false; |
| 1038 | for (unsigned i = 0; i < NumOp; ++i) { |
| 1039 | const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i)); |
| 1040 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal); |
| 1041 | if (!AR) |
| 1042 | continue; |
| 1043 | |
| 1044 | // If we find the inner induction after an outer induction e.g. |
| 1045 | // for(int i=0;i<N;i++) |
| 1046 | // for(int j=0;j<N;j++) |
| 1047 | // A[i][j] = A[i-1][j-1]+k; |
| 1048 | // then it is a good order. |
| 1049 | if (AR->getLoop() == InnerLoop) { |
| 1050 | // We found an InnerLoop induction after OuterLoop induction. It is |
| 1051 | // a good order. |
| 1052 | FoundInnerInduction = true; |
| 1053 | if (FoundOuterInduction) { |
| 1054 | GoodOrder++; |
| 1055 | break; |
| 1056 | } |
| 1057 | } |
| 1058 | // If we find the outer induction after an inner induction e.g. |
| 1059 | // for(int i=0;i<N;i++) |
| 1060 | // for(int j=0;j<N;j++) |
| 1061 | // A[j][i] = A[j-1][i-1]+k; |
| 1062 | // then it is a bad order. |
| 1063 | if (AR->getLoop() == OuterLoop) { |
| 1064 | // We found an OuterLoop induction after InnerLoop induction. It is |
| 1065 | // a bad order. |
| 1066 | FoundOuterInduction = true; |
| 1067 | if (FoundInnerInduction) { |
| 1068 | BadOrder++; |
| 1069 | break; |
| 1070 | } |
| 1071 | } |
| 1072 | } |
| 1073 | } |
| 1074 | } |
| 1075 | } |
| 1076 | return GoodOrder - BadOrder; |
| 1077 | } |
| 1078 | |
Chad Rosier | e6b3a63 | 2016-09-14 17:12:30 +0000 | [diff] [blame] | 1079 | static bool isProfitableForVectorization(unsigned InnerLoopId, |
| 1080 | unsigned OuterLoopId, |
| 1081 | CharMatrix &DepMatrix) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1082 | // TODO: Improve this heuristic to catch more cases. |
| 1083 | // If the inner loop is loop independent or doesn't carry any dependency it is |
| 1084 | // profitable to move this to outer position. |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 1085 | for (auto &Row : DepMatrix) { |
| 1086 | if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I') |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1087 | return false; |
| 1088 | // TODO: We need to improve this heuristic. |
Florian Hahn | f66efd6 | 2017-07-24 11:41:30 +0000 | [diff] [blame] | 1089 | if (Row[OuterLoopId] != '=') |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1090 | return false; |
| 1091 | } |
| 1092 | // If outer loop has dependence and inner loop is loop independent then it is |
| 1093 | // profitable to interchange to enable parallelism. |
Florian Hahn | ceee788 | 2018-04-24 16:55:32 +0000 | [diff] [blame] | 1094 | // If there are no dependences, interchanging will not improve anything. |
| 1095 | return !DepMatrix.empty(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1096 | } |
| 1097 | |
| 1098 | bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId, |
| 1099 | unsigned OuterLoopId, |
| 1100 | CharMatrix &DepMatrix) { |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1101 | // TODO: Add better profitability checks. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1102 | // e.g |
| 1103 | // 1) Construct dependency matrix and move the one with no loop carried dep |
| 1104 | // inside to enable vectorization. |
| 1105 | |
| 1106 | // This is rough cost estimation algorithm. It counts the good and bad order |
| 1107 | // of induction variables in the instruction and allows reordering if number |
| 1108 | // of bad orders is more than good. |
Chad Rosier | 7243189 | 2016-09-14 17:07:13 +0000 | [diff] [blame] | 1109 | int Cost = getInstrOrderCost(); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1110 | LLVM_DEBUG(dbgs() << "Cost = " << Cost << "\n"); |
Chad Rosier | 7243189 | 2016-09-14 17:07:13 +0000 | [diff] [blame] | 1111 | if (Cost < -LoopInterchangeCostThreshold) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1112 | return true; |
| 1113 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1114 | // It is not profitable as per current cache profitability model. But check if |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1115 | // we can move this loop outside to improve parallelism. |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 1116 | if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix)) |
| 1117 | return true; |
| 1118 | |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 1119 | ORE->emit([&]() { |
| 1120 | return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable", |
| 1121 | InnerLoop->getStartLoc(), |
| 1122 | InnerLoop->getHeader()) |
| 1123 | << "Interchanging loops is too costly (cost=" |
| 1124 | << ore::NV("Cost", Cost) << ", threshold=" |
| 1125 | << ore::NV("Threshold", LoopInterchangeCostThreshold) |
| 1126 | << ") and it does not improve parallelism."; |
| 1127 | }); |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 1128 | return false; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1129 | } |
| 1130 | |
| 1131 | void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop, |
| 1132 | Loop *InnerLoop) { |
Florian Hahn | 5912c66 | 2018-05-02 10:53:04 +0000 | [diff] [blame] | 1133 | for (Loop *L : *OuterLoop) |
| 1134 | if (L == InnerLoop) { |
| 1135 | OuterLoop->removeChildLoop(L); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1136 | return; |
| 1137 | } |
Benjamin Kramer | 8ceb323 | 2015-10-25 22:28:27 +0000 | [diff] [blame] | 1138 | llvm_unreachable("Couldn't find loop"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1139 | } |
Daniel Jasper | 6adbd7a | 2015-03-06 10:39:14 +0000 | [diff] [blame] | 1140 | |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1141 | /// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the |
| 1142 | /// new inner and outer loop after interchanging: NewInner is the original |
| 1143 | /// outer loop and NewOuter is the original inner loop. |
| 1144 | /// |
| 1145 | /// Before interchanging, we have the following structure |
| 1146 | /// Outer preheader |
| 1147 | // Outer header |
| 1148 | // Inner preheader |
| 1149 | // Inner header |
| 1150 | // Inner body |
| 1151 | // Inner latch |
| 1152 | // outer bbs |
| 1153 | // Outer latch |
| 1154 | // |
| 1155 | // After interchanging: |
| 1156 | // Inner preheader |
| 1157 | // Inner header |
| 1158 | // Outer preheader |
| 1159 | // Outer header |
| 1160 | // Inner body |
| 1161 | // outer bbs |
| 1162 | // Outer latch |
| 1163 | // Inner latch |
| 1164 | void LoopInterchangeTransform::restructureLoops( |
| 1165 | Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader, |
| 1166 | BasicBlock *OrigOuterPreHeader) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1167 | Loop *OuterLoopParent = OuterLoop->getParentLoop(); |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1168 | // The original inner loop preheader moves from the new inner loop to |
| 1169 | // the parent loop, if there is one. |
| 1170 | NewInner->removeBlockFromLoop(OrigInnerPreHeader); |
| 1171 | LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent); |
| 1172 | |
| 1173 | // Switch the loop levels. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1174 | if (OuterLoopParent) { |
| 1175 | // Remove the loop from its parent loop. |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1176 | removeChildLoop(OuterLoopParent, NewInner); |
| 1177 | removeChildLoop(NewInner, NewOuter); |
| 1178 | OuterLoopParent->addChildLoop(NewOuter); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1179 | } else { |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1180 | removeChildLoop(NewInner, NewOuter); |
| 1181 | LI->changeTopLevelLoop(NewInner, NewOuter); |
| 1182 | } |
| 1183 | while (!NewOuter->empty()) |
| 1184 | NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin())); |
| 1185 | NewOuter->addChildLoop(NewInner); |
| 1186 | |
| 1187 | // BBs from the original inner loop. |
| 1188 | SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks()); |
| 1189 | |
| 1190 | // Add BBs from the original outer loop to the original inner loop (excluding |
| 1191 | // BBs already in inner loop) |
| 1192 | for (BasicBlock *BB : NewInner->blocks()) |
| 1193 | if (LI->getLoopFor(BB) == NewInner) |
| 1194 | NewOuter->addBlockEntry(BB); |
| 1195 | |
| 1196 | // Now remove inner loop header and latch from the new inner loop and move |
| 1197 | // other BBs (the loop body) to the new inner loop. |
| 1198 | BasicBlock *OuterHeader = NewOuter->getHeader(); |
| 1199 | BasicBlock *OuterLatch = NewOuter->getLoopLatch(); |
| 1200 | for (BasicBlock *BB : OrigInnerBBs) { |
Florian Hahn | 74418185 | 2018-04-23 21:38:19 +0000 | [diff] [blame] | 1201 | // Nothing will change for BBs in child loops. |
| 1202 | if (LI->getLoopFor(BB) != NewOuter) |
| 1203 | continue; |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1204 | // Remove the new outer loop header and latch from the new inner loop. |
| 1205 | if (BB == OuterHeader || BB == OuterLatch) |
| 1206 | NewInner->removeBlockFromLoop(BB); |
| 1207 | else |
| 1208 | LI->changeLoopFor(BB, NewInner); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1209 | } |
| 1210 | |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1211 | // The preheader of the original outer loop becomes part of the new |
| 1212 | // outer loop. |
| 1213 | NewOuter->addBlockEntry(OrigOuterPreHeader); |
| 1214 | LI->changeLoopFor(OrigOuterPreHeader, NewOuter); |
Florian Hahn | 3afb974 | 2018-09-14 07:50:20 +0000 | [diff] [blame] | 1215 | |
| 1216 | // Tell SE that we move the loops around. |
| 1217 | SE->forgetLoop(NewOuter); |
| 1218 | SE->forgetLoop(NewInner); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1219 | } |
| 1220 | |
| 1221 | bool LoopInterchangeTransform::transform() { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1222 | bool Transformed = false; |
| 1223 | Instruction *InnerIndexVar; |
| 1224 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 1225 | if (InnerLoop->getSubLoops().empty()) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1226 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
Florian Hahn | e496121 | 2019-09-11 08:23:23 +0000 | [diff] [blame] | 1227 | LLVM_DEBUG(dbgs() << "Splitting the inner loop latch\n"); |
Kit Barton | 987fdfd | 2019-05-23 20:53:05 +0000 | [diff] [blame] | 1228 | PHINode *InductionPHI = getInductionVariable(InnerLoop, SE); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1229 | if (!InductionPHI) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1230 | LLVM_DEBUG(dbgs() << "Failed to find the point to split loop latch \n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1231 | return false; |
| 1232 | } |
| 1233 | |
| 1234 | if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader) |
| 1235 | InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1)); |
| 1236 | else |
| 1237 | InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0)); |
| 1238 | |
Florian Hahn | d8fcf0d | 2018-06-19 08:03:24 +0000 | [diff] [blame] | 1239 | // Ensure that InductionPHI is the first Phi node. |
David Green | 907b60f | 2017-10-21 13:58:37 +0000 | [diff] [blame] | 1240 | if (&InductionPHI->getParent()->front() != InductionPHI) |
| 1241 | InductionPHI->moveBefore(&InductionPHI->getParent()->front()); |
| 1242 | |
Florian Hahn | e496121 | 2019-09-11 08:23:23 +0000 | [diff] [blame] | 1243 | // Create a new latch block for the inner loop. We split at the |
| 1244 | // current latch's terminator and then move the condition and all |
| 1245 | // operands that are not either loop-invariant or the induction PHI into the |
| 1246 | // new latch block. |
| 1247 | BasicBlock *NewLatch = |
| 1248 | SplitBlock(InnerLoop->getLoopLatch(), |
| 1249 | InnerLoop->getLoopLatch()->getTerminator(), DT, LI); |
| 1250 | |
| 1251 | SmallSetVector<Instruction *, 4> WorkList; |
| 1252 | unsigned i = 0; |
| 1253 | auto MoveInstructions = [&i, &WorkList, this, InductionPHI, NewLatch]() { |
| 1254 | for (; i < WorkList.size(); i++) { |
| 1255 | // Duplicate instruction and move it the new latch. Update uses that |
| 1256 | // have been moved. |
| 1257 | Instruction *NewI = WorkList[i]->clone(); |
| 1258 | NewI->insertBefore(NewLatch->getFirstNonPHI()); |
| 1259 | assert(!NewI->mayHaveSideEffects() && |
| 1260 | "Moving instructions with side-effects may change behavior of " |
| 1261 | "the loop nest!"); |
| 1262 | for (auto UI = WorkList[i]->use_begin(), UE = WorkList[i]->use_end(); |
| 1263 | UI != UE;) { |
| 1264 | Use &U = *UI++; |
| 1265 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 1266 | if (!InnerLoop->contains(UserI->getParent()) || |
| 1267 | UserI->getParent() == NewLatch || UserI == InductionPHI) |
| 1268 | U.set(NewI); |
| 1269 | } |
| 1270 | // Add operands of moved instruction to the worklist, except if they are |
| 1271 | // outside the inner loop or are the induction PHI. |
| 1272 | for (Value *Op : WorkList[i]->operands()) { |
| 1273 | Instruction *OpI = dyn_cast<Instruction>(Op); |
| 1274 | if (!OpI || |
| 1275 | this->LI->getLoopFor(OpI->getParent()) != this->InnerLoop || |
| 1276 | OpI == InductionPHI) |
| 1277 | continue; |
| 1278 | WorkList.insert(OpI); |
| 1279 | } |
| 1280 | } |
| 1281 | }; |
| 1282 | |
| 1283 | // FIXME: Should we interchange when we have a constant condition? |
| 1284 | Instruction *CondI = dyn_cast<Instruction>( |
| 1285 | cast<BranchInst>(InnerLoop->getLoopLatch()->getTerminator()) |
| 1286 | ->getCondition()); |
| 1287 | if (CondI) |
| 1288 | WorkList.insert(CondI); |
| 1289 | MoveInstructions(); |
| 1290 | WorkList.insert(cast<Instruction>(InnerIndexVar)); |
| 1291 | MoveInstructions(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1292 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1293 | // Splits the inner loops phi nodes out into a separate basic block. |
Florian Hahn | d8fcf0d | 2018-06-19 08:03:24 +0000 | [diff] [blame] | 1294 | BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); |
| 1295 | SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI); |
| 1296 | LLVM_DEBUG(dbgs() << "splitting InnerLoopHeader done\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1297 | } |
| 1298 | |
| 1299 | Transformed |= adjustLoopLinks(); |
| 1300 | if (!Transformed) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1301 | LLVM_DEBUG(dbgs() << "adjustLoopLinks failed\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1302 | return false; |
| 1303 | } |
| 1304 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1305 | return true; |
| 1306 | } |
| 1307 | |
Florian Hahn | d8fcf0d | 2018-06-19 08:03:24 +0000 | [diff] [blame] | 1308 | /// \brief Move all instructions except the terminator from FromBB right before |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1309 | /// InsertBefore |
| 1310 | static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) { |
| 1311 | auto &ToList = InsertBefore->getParent()->getInstList(); |
| 1312 | auto &FromList = FromBB->getInstList(); |
| 1313 | |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1314 | ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(), |
| 1315 | FromBB->getTerminator()->getIterator()); |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1316 | } |
| 1317 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 1318 | /// Update BI to jump to NewBB instead of OldBB. Records updates to |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1319 | /// the dominator tree in DTUpdates, if DT should be preserved. |
| 1320 | static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB, |
| 1321 | BasicBlock *NewBB, |
| 1322 | std::vector<DominatorTree::UpdateType> &DTUpdates) { |
Chandler Carruth | 96fc1de | 2018-08-26 08:41:15 +0000 | [diff] [blame] | 1323 | assert(llvm::count_if(successors(BI), |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1324 | [OldBB](BasicBlock *BB) { return BB == OldBB; }) < 2 && |
| 1325 | "BI must jump to OldBB at most once."); |
| 1326 | for (unsigned i = 0, e = BI->getNumSuccessors(); i < e; ++i) { |
| 1327 | if (BI->getSuccessor(i) == OldBB) { |
| 1328 | BI->setSuccessor(i, NewBB); |
| 1329 | |
| 1330 | DTUpdates.push_back( |
| 1331 | {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB}); |
| 1332 | DTUpdates.push_back( |
| 1333 | {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB}); |
| 1334 | break; |
| 1335 | } |
| 1336 | } |
| 1337 | } |
| 1338 | |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1339 | // Move Lcssa PHIs to the right place. |
Florian Hahn | 11b2f4f | 2019-05-26 23:38:25 +0000 | [diff] [blame] | 1340 | static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader, |
| 1341 | BasicBlock *InnerLatch, BasicBlock *OuterHeader, |
| 1342 | BasicBlock *OuterLatch, BasicBlock *OuterExit) { |
| 1343 | |
| 1344 | // Deal with LCSSA PHI nodes in the exit block of the inner loop, that are |
| 1345 | // defined either in the header or latch. Those blocks will become header and |
| 1346 | // latch of the new outer loop, and the only possible users can PHI nodes |
| 1347 | // in the exit block of the loop nest or the outer loop header (reduction |
| 1348 | // PHIs, in that case, the incoming value must be defined in the inner loop |
| 1349 | // header). We can just substitute the user with the incoming value and remove |
| 1350 | // the PHI. |
| 1351 | for (PHINode &P : make_early_inc_range(InnerExit->phis())) { |
| 1352 | assert(P.getNumIncomingValues() == 1 && |
| 1353 | "Only loops with a single exit are supported!"); |
| 1354 | |
| 1355 | // Incoming values are guaranteed be instructions currently. |
| 1356 | auto IncI = cast<Instruction>(P.getIncomingValueForBlock(InnerLatch)); |
| 1357 | // Skip phis with incoming values from the inner loop body, excluding the |
| 1358 | // header and latch. |
| 1359 | if (IncI->getParent() != InnerLatch && IncI->getParent() != InnerHeader) |
| 1360 | continue; |
| 1361 | |
| 1362 | assert(all_of(P.users(), |
| 1363 | [OuterHeader, OuterExit, IncI, InnerHeader](User *U) { |
| 1364 | return (cast<PHINode>(U)->getParent() == OuterHeader && |
| 1365 | IncI->getParent() == InnerHeader) || |
| 1366 | cast<PHINode>(U)->getParent() == OuterExit; |
| 1367 | }) && |
| 1368 | "Can only replace phis iff the uses are in the loop nest exit or " |
| 1369 | "the incoming value is defined in the inner header (it will " |
| 1370 | "dominate all loop blocks after interchanging)"); |
| 1371 | P.replaceAllUsesWith(IncI); |
| 1372 | P.eraseFromParent(); |
| 1373 | } |
| 1374 | |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1375 | SmallVector<PHINode *, 8> LcssaInnerExit; |
| 1376 | for (PHINode &P : InnerExit->phis()) |
| 1377 | LcssaInnerExit.push_back(&P); |
| 1378 | |
| 1379 | SmallVector<PHINode *, 8> LcssaInnerLatch; |
| 1380 | for (PHINode &P : InnerLatch->phis()) |
| 1381 | LcssaInnerLatch.push_back(&P); |
| 1382 | |
| 1383 | // Lcssa PHIs for values used outside the inner loop are in InnerExit. |
| 1384 | // If a PHI node has users outside of InnerExit, it has a use outside the |
| 1385 | // interchanged loop and we have to preserve it. We move these to |
| 1386 | // InnerLatch, which will become the new exit block for the innermost |
Florian Hahn | 11b2f4f | 2019-05-26 23:38:25 +0000 | [diff] [blame] | 1387 | // loop after interchanging. |
| 1388 | for (PHINode *P : LcssaInnerExit) |
| 1389 | P->moveBefore(InnerLatch->getFirstNonPHI()); |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1390 | |
| 1391 | // If the inner loop latch contains LCSSA PHIs, those come from a child loop |
| 1392 | // and we have to move them to the new inner latch. |
| 1393 | for (PHINode *P : LcssaInnerLatch) |
| 1394 | P->moveBefore(InnerExit->getFirstNonPHI()); |
| 1395 | |
Florian Hahn | 11b2f4f | 2019-05-26 23:38:25 +0000 | [diff] [blame] | 1396 | // Deal with LCSSA PHI nodes in the loop nest exit block. For PHIs that have |
| 1397 | // incoming values from the outer latch or header, we have to add a new PHI |
| 1398 | // in the inner loop latch, which became the exit block of the outer loop, |
| 1399 | // after interchanging. |
| 1400 | if (OuterExit) { |
| 1401 | for (PHINode &P : OuterExit->phis()) { |
| 1402 | if (P.getNumIncomingValues() != 1) |
| 1403 | continue; |
| 1404 | // Skip Phis with incoming values not defined in the outer loop's header |
| 1405 | // and latch. Also skip incoming phis defined in the latch. Those should |
| 1406 | // already have been updated. |
| 1407 | auto I = dyn_cast<Instruction>(P.getIncomingValue(0)); |
| 1408 | if (!I || ((I->getParent() != OuterLatch || isa<PHINode>(I)) && |
| 1409 | I->getParent() != OuterHeader)) |
| 1410 | continue; |
| 1411 | |
| 1412 | PHINode *NewPhi = dyn_cast<PHINode>(P.clone()); |
| 1413 | NewPhi->setIncomingValue(0, P.getIncomingValue(0)); |
| 1414 | NewPhi->setIncomingBlock(0, OuterLatch); |
| 1415 | NewPhi->insertBefore(InnerLatch->getFirstNonPHI()); |
| 1416 | P.setIncomingValue(0, NewPhi); |
| 1417 | } |
| 1418 | } |
| 1419 | |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1420 | // Now adjust the incoming blocks for the LCSSA PHIs. |
| 1421 | // For PHIs moved from Inner's exit block, we need to replace Inner's latch |
| 1422 | // with the new latch. |
Roman Lebedev | 1a1b922 | 2019-05-05 18:59:39 +0000 | [diff] [blame] | 1423 | InnerLatch->replacePhiUsesWith(InnerLatch, OuterLatch); |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1424 | } |
| 1425 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1426 | bool LoopInterchangeTransform::adjustLoopBranches() { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1427 | LLVM_DEBUG(dbgs() << "adjustLoopBranches called\n"); |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1428 | std::vector<DominatorTree::UpdateType> DTUpdates; |
| 1429 | |
Florian Hahn | 236f6fe | 2018-09-06 09:57:27 +0000 | [diff] [blame] | 1430 | BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); |
| 1431 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1432 | |
| 1433 | assert(OuterLoopPreHeader != OuterLoop->getHeader() && |
| 1434 | InnerLoopPreHeader != InnerLoop->getHeader() && OuterLoopPreHeader && |
| 1435 | InnerLoopPreHeader && "Guaranteed by loop-simplify form"); |
| 1436 | // Ensure that both preheaders do not contain PHI nodes and have single |
| 1437 | // predecessors. This allows us to move them easily. We use |
| 1438 | // InsertPreHeaderForLoop to create an 'extra' preheader, if the existing |
| 1439 | // preheaders do not satisfy those conditions. |
| 1440 | if (isa<PHINode>(OuterLoopPreHeader->begin()) || |
| 1441 | !OuterLoopPreHeader->getUniquePredecessor()) |
Alina Sbirlea | f31eba6 | 2019-05-08 17:05:36 +0000 | [diff] [blame] | 1442 | OuterLoopPreHeader = |
| 1443 | InsertPreheaderForLoop(OuterLoop, DT, LI, nullptr, true); |
Florian Hahn | 236f6fe | 2018-09-06 09:57:27 +0000 | [diff] [blame] | 1444 | if (InnerLoopPreHeader == OuterLoop->getHeader()) |
Alina Sbirlea | f31eba6 | 2019-05-08 17:05:36 +0000 | [diff] [blame] | 1445 | InnerLoopPreHeader = |
| 1446 | InsertPreheaderForLoop(InnerLoop, DT, LI, nullptr, true); |
Florian Hahn | 236f6fe | 2018-09-06 09:57:27 +0000 | [diff] [blame] | 1447 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1448 | // Adjust the loop preheader |
| 1449 | BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); |
| 1450 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 1451 | BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); |
| 1452 | BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1453 | BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor(); |
| 1454 | BasicBlock *InnerLoopLatchPredecessor = |
| 1455 | InnerLoopLatch->getUniquePredecessor(); |
| 1456 | BasicBlock *InnerLoopLatchSuccessor; |
| 1457 | BasicBlock *OuterLoopLatchSuccessor; |
| 1458 | |
| 1459 | BranchInst *OuterLoopLatchBI = |
| 1460 | dyn_cast<BranchInst>(OuterLoopLatch->getTerminator()); |
| 1461 | BranchInst *InnerLoopLatchBI = |
| 1462 | dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); |
| 1463 | BranchInst *OuterLoopHeaderBI = |
| 1464 | dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); |
| 1465 | BranchInst *InnerLoopHeaderBI = |
| 1466 | dyn_cast<BranchInst>(InnerLoopHeader->getTerminator()); |
| 1467 | |
| 1468 | if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor || |
| 1469 | !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI || |
| 1470 | !InnerLoopHeaderBI) |
| 1471 | return false; |
| 1472 | |
| 1473 | BranchInst *InnerLoopLatchPredecessorBI = |
| 1474 | dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator()); |
| 1475 | BranchInst *OuterLoopPredecessorBI = |
| 1476 | dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator()); |
| 1477 | |
| 1478 | if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI) |
| 1479 | return false; |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1480 | BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor(); |
| 1481 | if (!InnerLoopHeaderSuccessor) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1482 | return false; |
| 1483 | |
| 1484 | // Adjust Loop Preheader and headers |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1485 | updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader, |
| 1486 | InnerLoopPreHeader, DTUpdates); |
| 1487 | updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates); |
| 1488 | updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader, |
| 1489 | InnerLoopHeaderSuccessor, DTUpdates); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1490 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1491 | // Adjust reduction PHI's now that the incoming block has changed. |
Roman Lebedev | 1a1b922 | 2019-05-05 18:59:39 +0000 | [diff] [blame] | 1492 | InnerLoopHeaderSuccessor->replacePhiUsesWith(InnerLoopHeader, |
| 1493 | OuterLoopHeader); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1494 | |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1495 | updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor, |
| 1496 | OuterLoopPreHeader, DTUpdates); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1497 | |
| 1498 | // -------------Adjust loop latches----------- |
| 1499 | if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader) |
| 1500 | InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1); |
| 1501 | else |
| 1502 | InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0); |
| 1503 | |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1504 | updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch, |
| 1505 | InnerLoopLatchSuccessor, DTUpdates); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1506 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1507 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1508 | if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader) |
| 1509 | OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1); |
| 1510 | else |
| 1511 | OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0); |
| 1512 | |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1513 | updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor, |
| 1514 | OuterLoopLatchSuccessor, DTUpdates); |
| 1515 | updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch, |
| 1516 | DTUpdates); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1517 | |
Florian Hahn | c6296fe | 2018-02-14 13:13:15 +0000 | [diff] [blame] | 1518 | DT->applyUpdates(DTUpdates); |
Florian Hahn | 831a757 | 2018-04-05 09:48:45 +0000 | [diff] [blame] | 1519 | restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader, |
| 1520 | OuterLoopPreHeader); |
| 1521 | |
Florian Hahn | 11b2f4f | 2019-05-26 23:38:25 +0000 | [diff] [blame] | 1522 | moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch, |
| 1523 | OuterLoopHeader, OuterLoopLatch, InnerLoop->getExitBlock()); |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1524 | // For PHIs in the exit block of the outer loop, outer's latch has been |
| 1525 | // replaced by Inners'. |
Roman Lebedev | 1a1b922 | 2019-05-05 18:59:39 +0000 | [diff] [blame] | 1526 | OuterLoopLatchSuccessor->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch); |
Florian Hahn | 6feb637 | 2018-09-26 19:34:25 +0000 | [diff] [blame] | 1527 | |
Florian Hahn | a684a99 | 2018-11-08 20:44:19 +0000 | [diff] [blame] | 1528 | // Now update the reduction PHIs in the inner and outer loop headers. |
| 1529 | SmallVector<PHINode *, 4> InnerLoopPHIs, OuterLoopPHIs; |
| 1530 | for (PHINode &PHI : drop_begin(InnerLoopHeader->phis(), 1)) |
| 1531 | InnerLoopPHIs.push_back(cast<PHINode>(&PHI)); |
| 1532 | for (PHINode &PHI : drop_begin(OuterLoopHeader->phis(), 1)) |
| 1533 | OuterLoopPHIs.push_back(cast<PHINode>(&PHI)); |
| 1534 | |
| 1535 | auto &OuterInnerReductions = LIL.getOuterInnerReductions(); |
| 1536 | (void)OuterInnerReductions; |
| 1537 | |
| 1538 | // Now move the remaining reduction PHIs from outer to inner loop header and |
| 1539 | // vice versa. The PHI nodes must be part of a reduction across the inner and |
| 1540 | // outer loop and all the remains to do is and updating the incoming blocks. |
| 1541 | for (PHINode *PHI : OuterLoopPHIs) { |
| 1542 | PHI->moveBefore(InnerLoopHeader->getFirstNonPHI()); |
| 1543 | assert(OuterInnerReductions.find(PHI) != OuterInnerReductions.end() && |
| 1544 | "Expected a reduction PHI node"); |
| 1545 | } |
| 1546 | for (PHINode *PHI : InnerLoopPHIs) { |
| 1547 | PHI->moveBefore(OuterLoopHeader->getFirstNonPHI()); |
| 1548 | assert(OuterInnerReductions.find(PHI) != OuterInnerReductions.end() && |
| 1549 | "Expected a reduction PHI node"); |
| 1550 | } |
Florian Hahn | d8fcf0d | 2018-06-19 08:03:24 +0000 | [diff] [blame] | 1551 | |
| 1552 | // Update the incoming blocks for moved PHI nodes. |
Roman Lebedev | 1a1b922 | 2019-05-05 18:59:39 +0000 | [diff] [blame] | 1553 | OuterLoopHeader->replacePhiUsesWith(InnerLoopPreHeader, OuterLoopPreHeader); |
| 1554 | OuterLoopHeader->replacePhiUsesWith(InnerLoopLatch, OuterLoopLatch); |
| 1555 | InnerLoopHeader->replacePhiUsesWith(OuterLoopPreHeader, InnerLoopPreHeader); |
| 1556 | InnerLoopHeader->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch); |
Florian Hahn | d8fcf0d | 2018-06-19 08:03:24 +0000 | [diff] [blame] | 1557 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1558 | return true; |
| 1559 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1560 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 1561 | void LoopInterchangeTransform::adjustLoopPreheaders() { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1562 | // We have interchanged the preheaders so we need to interchange the data in |
| 1563 | // the preheader as well. |
| 1564 | // This is because the content of inner preheader was previously executed |
| 1565 | // inside the outer loop. |
| 1566 | BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); |
| 1567 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1568 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 1569 | BranchInst *InnerTermBI = |
| 1570 | cast<BranchInst>(InnerLoopPreHeader->getTerminator()); |
| 1571 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1572 | // These instructions should now be executed inside the loop. |
| 1573 | // Move instruction into a new block after outer header. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1574 | moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator()); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1575 | // These instructions were not executed previously in the loop so move them to |
| 1576 | // the older inner loop preheader. |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1577 | moveBBContents(OuterLoopPreHeader, InnerTermBI); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1578 | } |
| 1579 | |
| 1580 | bool LoopInterchangeTransform::adjustLoopLinks() { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1581 | // Adjust all branches in the inner and outer loop. |
| 1582 | bool Changed = adjustLoopBranches(); |
| 1583 | if (Changed) |
| 1584 | adjustLoopPreheaders(); |
| 1585 | return Changed; |
| 1586 | } |
| 1587 | |
| 1588 | char LoopInterchange::ID = 0; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 1589 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1590 | INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange", |
| 1591 | "Interchanges loops for cache reuse", false, false) |
Florian Hahn | 8600fee | 2018-10-01 09:59:48 +0000 | [diff] [blame] | 1592 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 1593 | INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) |
Florian Hahn | ad99352 | 2017-07-15 13:13:19 +0000 | [diff] [blame] | 1594 | INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1595 | |
| 1596 | INITIALIZE_PASS_END(LoopInterchange, "loop-interchange", |
| 1597 | "Interchanges loops for cache reuse", false, false) |
| 1598 | |
| 1599 | Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); } |