Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1 | //===- LoopInterchange.cpp - Loop interchange pass------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This Pass handles loop interchange transform. |
| 11 | // This pass interchanges loops to provide a more cache-friendly memory access |
| 12 | // patterns. |
| 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
| 16 | #include "llvm/ADT/SmallVector.h" |
| 17 | #include "llvm/Analysis/AliasAnalysis.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/AssumptionCache.h" |
| 19 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 20 | #include "llvm/Analysis/CodeMetrics.h" |
| 21 | #include "llvm/Analysis/DependenceAnalysis.h" |
| 22 | #include "llvm/Analysis/LoopInfo.h" |
| 23 | #include "llvm/Analysis/LoopIterator.h" |
| 24 | #include "llvm/Analysis/LoopPass.h" |
| 25 | #include "llvm/Analysis/ScalarEvolution.h" |
| 26 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
| 27 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
| 28 | #include "llvm/Analysis/TargetTransformInfo.h" |
| 29 | #include "llvm/Analysis/ValueTracking.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 30 | #include "llvm/IR/Dominators.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 31 | #include "llvm/IR/Function.h" |
| 32 | #include "llvm/IR/IRBuilder.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 33 | #include "llvm/IR/InstIterator.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 34 | #include "llvm/IR/IntrinsicInst.h" |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 35 | #include "llvm/IR/Module.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 36 | #include "llvm/Pass.h" |
| 37 | #include "llvm/Support/Debug.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 38 | #include "llvm/Support/raw_ostream.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 39 | #include "llvm/Transforms/Scalar.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 40 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 41 | #include "llvm/Transforms/Utils/LoopUtils.h" |
| 42 | #include "llvm/Transforms/Utils/SSAUpdater.h" |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 43 | using namespace llvm; |
| 44 | |
| 45 | #define DEBUG_TYPE "loop-interchange" |
| 46 | |
Chad Rosier | 7243189 | 2016-09-14 17:07:13 +0000 | [diff] [blame^] | 47 | static cl::opt<int> LoopInterchangeCostThreshold( |
| 48 | "loop-interchange-threshold", cl::init(0), cl::Hidden, |
| 49 | cl::desc("Interchange if you gain more than this number")); |
| 50 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 51 | namespace { |
| 52 | |
| 53 | typedef SmallVector<Loop *, 8> LoopVector; |
| 54 | |
| 55 | // TODO: Check if we can use a sparse matrix here. |
| 56 | typedef std::vector<std::vector<char>> CharMatrix; |
| 57 | |
| 58 | // Maximum number of dependencies that can be handled in the dependency matrix. |
| 59 | static const unsigned MaxMemInstrCount = 100; |
| 60 | |
| 61 | // Maximum loop depth supported. |
| 62 | static const unsigned MaxLoopNestDepth = 10; |
| 63 | |
| 64 | struct LoopInterchange; |
| 65 | |
| 66 | #ifdef DUMP_DEP_MATRICIES |
| 67 | void printDepMatrix(CharMatrix &DepMatrix) { |
| 68 | for (auto I = DepMatrix.begin(), E = DepMatrix.end(); I != E; ++I) { |
| 69 | std::vector<char> Vec = *I; |
| 70 | for (auto II = Vec.begin(), EE = Vec.end(); II != EE; ++II) |
| 71 | DEBUG(dbgs() << *II << " "); |
| 72 | DEBUG(dbgs() << "\n"); |
| 73 | } |
| 74 | } |
| 75 | #endif |
| 76 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 77 | static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 78 | Loop *L, DependenceInfo *DI) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 79 | typedef SmallVector<Value *, 16> ValueVector; |
| 80 | ValueVector MemInstr; |
| 81 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 82 | // For each block. |
| 83 | for (Loop::block_iterator BB = L->block_begin(), BE = L->block_end(); |
| 84 | BB != BE; ++BB) { |
| 85 | // Scan the BB and collect legal loads and stores. |
| 86 | for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; |
| 87 | ++I) { |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 88 | if (!isa<Instruction>(I)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 89 | return false; |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 90 | if (LoadInst *Ld = dyn_cast<LoadInst>(I)) { |
| 91 | if (!Ld->isSimple()) |
| 92 | return false; |
| 93 | MemInstr.push_back(&*I); |
| 94 | } else if (StoreInst *St = dyn_cast<StoreInst>(I)) { |
| 95 | if (!St->isSimple()) |
| 96 | return false; |
| 97 | MemInstr.push_back(&*I); |
| 98 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 99 | } |
| 100 | } |
| 101 | |
| 102 | DEBUG(dbgs() << "Found " << MemInstr.size() |
| 103 | << " Loads and Stores to analyze\n"); |
| 104 | |
| 105 | ValueVector::iterator I, IE, J, JE; |
| 106 | |
| 107 | for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) { |
| 108 | for (J = I, JE = MemInstr.end(); J != JE; ++J) { |
| 109 | std::vector<char> Dep; |
Chad Rosier | 09c1109 | 2016-09-13 12:56:04 +0000 | [diff] [blame] | 110 | Instruction *Src = cast<Instruction>(*I); |
| 111 | Instruction *Dst = cast<Instruction>(*J); |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 112 | if (Src == Dst) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 113 | continue; |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 114 | if (isa<LoadInst>(Src) && isa<LoadInst>(Dst)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 115 | continue; |
Chad Rosier | 90bcb91 | 2016-09-07 16:07:17 +0000 | [diff] [blame] | 116 | if (auto D = DI->depends(Src, Dst, true)) { |
| 117 | DEBUG(dbgs() << "Found Dependency between Src and Dst\n" |
| 118 | << " Src:" << *Src << "\n Dst:" << *Dst << '\n'); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 119 | if (D->isFlow()) { |
| 120 | // TODO: Handle Flow dependence.Check if it is sufficient to populate |
| 121 | // the Dependence Matrix with the direction reversed. |
Chad Rosier | f5814f5 | 2016-09-07 15:56:59 +0000 | [diff] [blame] | 122 | DEBUG(dbgs() << "Flow dependence not handled\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 123 | return false; |
| 124 | } |
| 125 | if (D->isAnti()) { |
Chad Rosier | f5814f5 | 2016-09-07 15:56:59 +0000 | [diff] [blame] | 126 | DEBUG(dbgs() << "Found Anti dependence\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 127 | unsigned Levels = D->getLevels(); |
| 128 | char Direction; |
| 129 | for (unsigned II = 1; II <= Levels; ++II) { |
| 130 | const SCEV *Distance = D->getDistance(II); |
| 131 | const SCEVConstant *SCEVConst = |
| 132 | dyn_cast_or_null<SCEVConstant>(Distance); |
| 133 | if (SCEVConst) { |
| 134 | const ConstantInt *CI = SCEVConst->getValue(); |
| 135 | if (CI->isNegative()) |
| 136 | Direction = '<'; |
| 137 | else if (CI->isZero()) |
| 138 | Direction = '='; |
| 139 | else |
| 140 | Direction = '>'; |
| 141 | Dep.push_back(Direction); |
| 142 | } else if (D->isScalar(II)) { |
| 143 | Direction = 'S'; |
| 144 | Dep.push_back(Direction); |
| 145 | } else { |
| 146 | unsigned Dir = D->getDirection(II); |
| 147 | if (Dir == Dependence::DVEntry::LT || |
| 148 | Dir == Dependence::DVEntry::LE) |
| 149 | Direction = '<'; |
| 150 | else if (Dir == Dependence::DVEntry::GT || |
| 151 | Dir == Dependence::DVEntry::GE) |
| 152 | Direction = '>'; |
| 153 | else if (Dir == Dependence::DVEntry::EQ) |
| 154 | Direction = '='; |
| 155 | else |
| 156 | Direction = '*'; |
| 157 | Dep.push_back(Direction); |
| 158 | } |
| 159 | } |
| 160 | while (Dep.size() != Level) { |
| 161 | Dep.push_back('I'); |
| 162 | } |
| 163 | |
| 164 | DepMatrix.push_back(Dep); |
| 165 | if (DepMatrix.size() > MaxMemInstrCount) { |
| 166 | DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount |
| 167 | << " dependencies inside loop\n"); |
| 168 | return false; |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 175 | // We don't have a DepMatrix to check legality return false. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 176 | if (DepMatrix.size() == 0) |
| 177 | return false; |
| 178 | return true; |
| 179 | } |
| 180 | |
| 181 | // A loop is moved from index 'from' to an index 'to'. Update the Dependence |
| 182 | // matrix by exchanging the two columns. |
Chad Rosier | d18ea06 | 2016-09-13 13:00:29 +0000 | [diff] [blame] | 183 | static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, |
| 184 | unsigned ToIndx) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 185 | unsigned numRows = DepMatrix.size(); |
| 186 | for (unsigned i = 0; i < numRows; ++i) { |
| 187 | char TmpVal = DepMatrix[i][ToIndx]; |
| 188 | DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx]; |
| 189 | DepMatrix[i][FromIndx] = TmpVal; |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is |
| 194 | // '>' |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 195 | static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row, |
| 196 | unsigned Column) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 197 | for (unsigned i = 0; i <= Column; ++i) { |
| 198 | if (DepMatrix[Row][i] == '<') |
| 199 | return false; |
| 200 | if (DepMatrix[Row][i] == '>') |
| 201 | return true; |
| 202 | } |
| 203 | // All dependencies were '=','S' or 'I' |
| 204 | return false; |
| 205 | } |
| 206 | |
| 207 | // 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] | 208 | static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row, |
| 209 | unsigned Column) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 210 | for (unsigned i = 0; i < Column; ++i) { |
| 211 | if (DepMatrix[Row][i] != '=' || DepMatrix[Row][i] != 'S' || |
| 212 | DepMatrix[Row][i] != 'I') |
| 213 | return false; |
| 214 | } |
| 215 | return true; |
| 216 | } |
| 217 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 218 | static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row, |
| 219 | unsigned OuterLoopId, char InnerDep, |
| 220 | char OuterDep) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 221 | |
| 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 | |
| 261 | unsigned NumRows = DepMatrix.size(); |
| 262 | // For each row check if it is valid to interchange. |
| 263 | for (unsigned Row = 0; Row < NumRows; ++Row) { |
| 264 | char InnerDep = DepMatrix[Row][InnerLoopId]; |
| 265 | char OuterDep = DepMatrix[Row][OuterLoopId]; |
| 266 | if (InnerDep == '*' || OuterDep == '*') |
| 267 | return false; |
Chad Rosier | 61683a2 | 2016-09-13 13:08:53 +0000 | [diff] [blame] | 268 | if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 269 | return false; |
| 270 | } |
| 271 | return true; |
| 272 | } |
| 273 | |
| 274 | static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) { |
| 275 | |
Chad Rosier | f5814f5 | 2016-09-07 15:56:59 +0000 | [diff] [blame] | 276 | DEBUG(dbgs() << "Calling populateWorklist on Func: " |
| 277 | << L.getHeader()->getParent()->getName() << " Loop: %" |
| 278 | << L.getHeader()->getName() << '\n'); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 279 | LoopVector LoopList; |
| 280 | Loop *CurrentLoop = &L; |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 281 | const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops(); |
| 282 | while (!Vec->empty()) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 283 | // The current loop has multiple subloops in it hence it is not tightly |
| 284 | // nested. |
| 285 | // Discard all loops above it added into Worklist. |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 286 | if (Vec->size() != 1) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 287 | LoopList.clear(); |
| 288 | return; |
| 289 | } |
| 290 | LoopList.push_back(CurrentLoop); |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 291 | CurrentLoop = Vec->front(); |
| 292 | Vec = &CurrentLoop->getSubLoops(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 293 | } |
| 294 | LoopList.push_back(CurrentLoop); |
Benjamin Kramer | e448b5b | 2015-07-13 17:21:14 +0000 | [diff] [blame] | 295 | V.push_back(std::move(LoopList)); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 296 | } |
| 297 | |
| 298 | static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) { |
| 299 | PHINode *InnerIndexVar = L->getCanonicalInductionVariable(); |
| 300 | if (InnerIndexVar) |
| 301 | return InnerIndexVar; |
| 302 | if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) |
| 303 | return nullptr; |
| 304 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
| 305 | PHINode *PhiVar = cast<PHINode>(I); |
| 306 | Type *PhiTy = PhiVar->getType(); |
| 307 | if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && |
| 308 | !PhiTy->isPointerTy()) |
| 309 | return nullptr; |
| 310 | const SCEVAddRecExpr *AddRec = |
| 311 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar)); |
| 312 | if (!AddRec || !AddRec->isAffine()) |
| 313 | continue; |
| 314 | const SCEV *Step = AddRec->getStepRecurrence(*SE); |
| 315 | const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); |
| 316 | if (!C) |
| 317 | continue; |
| 318 | // Found the induction variable. |
| 319 | // FIXME: Handle loops with more than one induction variable. Note that, |
| 320 | // currently, legality makes sure we have only one induction variable. |
| 321 | return PhiVar; |
| 322 | } |
| 323 | return nullptr; |
| 324 | } |
| 325 | |
| 326 | /// LoopInterchangeLegality checks if it is legal to interchange the loop. |
| 327 | class LoopInterchangeLegality { |
| 328 | public: |
| 329 | LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE, |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 330 | LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA) |
| 331 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), |
| 332 | PreserveLCSSA(PreserveLCSSA), InnerLoopHasReduction(false) {} |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 333 | |
| 334 | /// Check if the loops can be interchanged. |
| 335 | bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId, |
| 336 | CharMatrix &DepMatrix); |
| 337 | /// Check if the loop structure is understood. We do not handle triangular |
| 338 | /// loops for now. |
| 339 | bool isLoopStructureUnderstood(PHINode *InnerInductionVar); |
| 340 | |
| 341 | bool currentLimitations(); |
| 342 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 343 | bool hasInnerLoopReduction() { return InnerLoopHasReduction; } |
| 344 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 345 | private: |
| 346 | bool tightlyNested(Loop *Outer, Loop *Inner); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 347 | bool containsUnsafeInstructionsInHeader(BasicBlock *BB); |
| 348 | bool areAllUsesReductions(Instruction *Ins, Loop *L); |
| 349 | bool containsUnsafeInstructionsInLatch(BasicBlock *BB); |
| 350 | bool findInductionAndReductions(Loop *L, |
| 351 | SmallVector<PHINode *, 8> &Inductions, |
| 352 | SmallVector<PHINode *, 8> &Reductions); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 353 | Loop *OuterLoop; |
| 354 | Loop *InnerLoop; |
| 355 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 356 | ScalarEvolution *SE; |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 357 | LoopInfo *LI; |
| 358 | DominatorTree *DT; |
| 359 | bool PreserveLCSSA; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 360 | |
| 361 | bool InnerLoopHasReduction; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 362 | }; |
| 363 | |
| 364 | /// LoopInterchangeProfitability checks if it is profitable to interchange the |
| 365 | /// loop. |
| 366 | class LoopInterchangeProfitability { |
| 367 | public: |
| 368 | LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE) |
| 369 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE) {} |
| 370 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 371 | /// Check if the loop interchange is profitable. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 372 | bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId, |
| 373 | CharMatrix &DepMatrix); |
| 374 | |
| 375 | private: |
| 376 | int getInstrOrderCost(); |
| 377 | |
| 378 | Loop *OuterLoop; |
| 379 | Loop *InnerLoop; |
| 380 | |
| 381 | /// Scev analysis. |
| 382 | ScalarEvolution *SE; |
| 383 | }; |
| 384 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 385 | /// LoopInterchangeTransform interchanges the loop. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 386 | class LoopInterchangeTransform { |
| 387 | public: |
| 388 | LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE, |
| 389 | LoopInfo *LI, DominatorTree *DT, |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 390 | BasicBlock *LoopNestExit, |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 391 | bool InnerLoopContainsReductions) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 392 | : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 393 | LoopExit(LoopNestExit), |
| 394 | InnerLoopHasReduction(InnerLoopContainsReductions) {} |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 395 | |
| 396 | /// Interchange OuterLoop and InnerLoop. |
| 397 | bool transform(); |
| 398 | void restructureLoops(Loop *InnerLoop, Loop *OuterLoop); |
| 399 | void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 400 | |
| 401 | private: |
| 402 | void splitInnerLoopLatch(Instruction *); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 403 | void splitInnerLoopHeader(); |
| 404 | bool adjustLoopLinks(); |
| 405 | void adjustLoopPreheaders(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 406 | bool adjustLoopBranches(); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 407 | void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred, |
| 408 | BasicBlock *NewPred); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 409 | |
| 410 | Loop *OuterLoop; |
| 411 | Loop *InnerLoop; |
| 412 | |
| 413 | /// Scev analysis. |
| 414 | ScalarEvolution *SE; |
| 415 | LoopInfo *LI; |
| 416 | DominatorTree *DT; |
| 417 | BasicBlock *LoopExit; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 418 | bool InnerLoopHasReduction; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 419 | }; |
| 420 | |
Vikram TV | 74b4111 | 2015-12-09 05:16:24 +0000 | [diff] [blame] | 421 | // Main LoopInterchange Pass. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 422 | struct LoopInterchange : public FunctionPass { |
| 423 | static char ID; |
| 424 | ScalarEvolution *SE; |
| 425 | LoopInfo *LI; |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 426 | DependenceInfo *DI; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 427 | DominatorTree *DT; |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 428 | bool PreserveLCSSA; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 429 | LoopInterchange() |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 430 | : FunctionPass(ID), SE(nullptr), LI(nullptr), DI(nullptr), DT(nullptr) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 431 | initializeLoopInterchangePass(*PassRegistry::getPassRegistry()); |
| 432 | } |
| 433 | |
| 434 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 435 | AU.addRequired<ScalarEvolutionWrapperPass>(); |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 436 | AU.addRequired<AAResultsWrapperPass>(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 437 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 438 | AU.addRequired<LoopInfoWrapperPass>(); |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 439 | AU.addRequired<DependenceAnalysisWrapperPass>(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 440 | AU.addRequiredID(LoopSimplifyID); |
| 441 | AU.addRequiredID(LCSSAID); |
| 442 | } |
| 443 | |
| 444 | bool runOnFunction(Function &F) override { |
Andrew Kaylor | 50271f7 | 2016-05-03 22:32:30 +0000 | [diff] [blame] | 445 | if (skipFunction(F)) |
| 446 | return false; |
| 447 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 448 | SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 449 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 450 | DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 451 | auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); |
| 452 | DT = DTWP ? &DTWP->getDomTree() : nullptr; |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 453 | PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); |
| 454 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 455 | // Build up a worklist of loop pairs to analyze. |
| 456 | SmallVector<LoopVector, 8> Worklist; |
| 457 | |
| 458 | for (Loop *L : *LI) |
| 459 | populateWorklist(*L, Worklist); |
| 460 | |
Chad Rosier | a4c4246 | 2016-09-12 13:24:47 +0000 | [diff] [blame] | 461 | DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 462 | bool Changed = true; |
| 463 | while (!Worklist.empty()) { |
| 464 | LoopVector LoopList = Worklist.pop_back_val(); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 465 | Changed = processLoopList(LoopList, F); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 466 | } |
| 467 | return Changed; |
| 468 | } |
| 469 | |
| 470 | bool isComputableLoopNest(LoopVector LoopList) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 471 | for (Loop *L : LoopList) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 472 | const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L); |
| 473 | if (ExitCountOuter == SE->getCouldNotCompute()) { |
| 474 | DEBUG(dbgs() << "Couldn't compute Backedge count\n"); |
| 475 | return false; |
| 476 | } |
| 477 | if (L->getNumBackEdges() != 1) { |
| 478 | DEBUG(dbgs() << "NumBackEdges is not equal to 1\n"); |
| 479 | return false; |
| 480 | } |
| 481 | if (!L->getExitingBlock()) { |
| 482 | DEBUG(dbgs() << "Loop Doesn't have unique exit block\n"); |
| 483 | return false; |
| 484 | } |
| 485 | } |
| 486 | return true; |
| 487 | } |
| 488 | |
Benjamin Kramer | c321e53 | 2016-06-08 19:09:22 +0000 | [diff] [blame] | 489 | unsigned selectLoopForInterchange(const LoopVector &LoopList) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 490 | // 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] | 491 | // on the dependence matrix. Currently we select the innermost loop. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 492 | return LoopList.size() - 1; |
| 493 | } |
| 494 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 495 | bool processLoopList(LoopVector LoopList, Function &F) { |
| 496 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 497 | bool Changed = false; |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 498 | unsigned LoopNestDepth = LoopList.size(); |
| 499 | if (LoopNestDepth < 2) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 500 | DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n"); |
| 501 | return false; |
| 502 | } |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 503 | if (LoopNestDepth > MaxLoopNestDepth) { |
| 504 | DEBUG(dbgs() << "Cannot handle loops of depth greater than " |
| 505 | << MaxLoopNestDepth << "\n"); |
| 506 | return false; |
| 507 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 508 | if (!isComputableLoopNest(LoopList)) { |
Chad Rosier | a4c4246 | 2016-09-12 13:24:47 +0000 | [diff] [blame] | 509 | DEBUG(dbgs() << "Not valid loop candidate for interchange\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 510 | return false; |
| 511 | } |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 512 | |
| 513 | DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth << "\n"); |
| 514 | |
| 515 | CharMatrix DependencyMatrix; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 516 | Loop *OuterMostLoop = *(LoopList.begin()); |
Chad Rosier | 7ea0d39 | 2016-09-13 13:30:30 +0000 | [diff] [blame] | 517 | if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth, |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 518 | OuterMostLoop, DI)) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 519 | DEBUG(dbgs() << "Populating Dependency matrix failed\n"); |
| 520 | return false; |
| 521 | } |
| 522 | #ifdef DUMP_DEP_MATRICIES |
Chad Rosier | 58ede27 | 2016-09-14 16:43:19 +0000 | [diff] [blame] | 523 | DEBUG(dbgs() << "Dependence before interchange\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 524 | printDepMatrix(DependencyMatrix); |
| 525 | #endif |
| 526 | |
| 527 | BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch(); |
| 528 | BranchInst *OuterMostLoopLatchBI = |
| 529 | dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator()); |
| 530 | if (!OuterMostLoopLatchBI) |
| 531 | return false; |
| 532 | |
| 533 | // Since we currently do not handle LCSSA PHI's any failure in loop |
| 534 | // condition will now branch to LoopNestExit. |
| 535 | // TODO: This should be removed once we handle LCSSA PHI nodes. |
| 536 | |
| 537 | // Get the Outermost loop exit. |
| 538 | BasicBlock *LoopNestExit; |
| 539 | if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader()) |
| 540 | LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1); |
| 541 | else |
| 542 | LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0); |
| 543 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 544 | if (isa<PHINode>(LoopNestExit->begin())) { |
| 545 | DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now " |
| 546 | "since on failure all loops branch to loop nest exit.\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 547 | return false; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 548 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 549 | |
| 550 | unsigned SelecLoopId = selectLoopForInterchange(LoopList); |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 551 | // Move the selected loop outwards to the best possible position. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 552 | for (unsigned i = SelecLoopId; i > 0; i--) { |
| 553 | bool Interchanged = |
| 554 | processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix); |
| 555 | if (!Interchanged) |
| 556 | return Changed; |
| 557 | // Loops interchanged reflect the same in LoopList |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 558 | std::swap(LoopList[i - 1], LoopList[i]); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 559 | |
| 560 | // Update the DependencyMatrix |
Chad Rosier | d18ea06 | 2016-09-13 13:00:29 +0000 | [diff] [blame] | 561 | interChangeDependencies(DependencyMatrix, i, i - 1); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 562 | DT->recalculate(F); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 563 | #ifdef DUMP_DEP_MATRICIES |
Chad Rosier | 58ede27 | 2016-09-14 16:43:19 +0000 | [diff] [blame] | 564 | DEBUG(dbgs() << "Dependence after interchange\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 565 | printDepMatrix(DependencyMatrix); |
| 566 | #endif |
| 567 | Changed |= Interchanged; |
| 568 | } |
| 569 | return Changed; |
| 570 | } |
| 571 | |
| 572 | bool processLoop(LoopVector LoopList, unsigned InnerLoopId, |
| 573 | unsigned OuterLoopId, BasicBlock *LoopNestExit, |
| 574 | std::vector<std::vector<char>> &DependencyMatrix) { |
| 575 | |
Chad Rosier | 13bc0d19 | 2016-09-07 18:15:12 +0000 | [diff] [blame] | 576 | DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 577 | << " and OuterLoopId = " << OuterLoopId << "\n"); |
| 578 | Loop *InnerLoop = LoopList[InnerLoopId]; |
| 579 | Loop *OuterLoop = LoopList[OuterLoopId]; |
| 580 | |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 581 | LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT, |
| 582 | PreserveLCSSA); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 583 | if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) { |
| 584 | DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n"); |
| 585 | return false; |
| 586 | } |
| 587 | DEBUG(dbgs() << "Loops are legal to interchange\n"); |
| 588 | LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE); |
| 589 | if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) { |
| 590 | DEBUG(dbgs() << "Interchanging Loops not profitable\n"); |
| 591 | return false; |
| 592 | } |
| 593 | |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 594 | LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 595 | LoopNestExit, LIL.hasInnerLoopReduction()); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 596 | LIT.transform(); |
| 597 | DEBUG(dbgs() << "Loops interchanged\n"); |
| 598 | return true; |
| 599 | } |
| 600 | }; |
| 601 | |
| 602 | } // end of namespace |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 603 | bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) { |
David Majnemer | 0a16c22 | 2016-08-11 21:15:00 +0000 | [diff] [blame] | 604 | return none_of(Ins->users(), [=](User *U) -> bool { |
| 605 | auto *UserIns = dyn_cast<PHINode>(U); |
Tyler Nowicki | 0a91310 | 2015-06-16 18:07:34 +0000 | [diff] [blame] | 606 | RecurrenceDescriptor RD; |
| 607 | return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 608 | }); |
| 609 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 610 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 611 | bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader( |
| 612 | BasicBlock *BB) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 613 | for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 614 | // Load corresponding to reduction PHI's are safe while concluding if |
| 615 | // tightly nested. |
| 616 | if (LoadInst *L = dyn_cast<LoadInst>(I)) { |
| 617 | if (!areAllUsesReductions(L, InnerLoop)) |
| 618 | return true; |
| 619 | } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) |
| 620 | return true; |
| 621 | } |
| 622 | return false; |
| 623 | } |
| 624 | |
| 625 | bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch( |
| 626 | BasicBlock *BB) { |
| 627 | for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 628 | // Stores corresponding to reductions are safe while concluding if tightly |
| 629 | // nested. |
| 630 | if (StoreInst *L = dyn_cast<StoreInst>(I)) { |
| 631 | PHINode *PHI = dyn_cast<PHINode>(L->getOperand(0)); |
| 632 | if (!PHI) |
| 633 | return true; |
| 634 | } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 635 | return true; |
| 636 | } |
| 637 | return false; |
| 638 | } |
| 639 | |
| 640 | bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) { |
| 641 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 642 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 643 | BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); |
| 644 | |
| 645 | DEBUG(dbgs() << "Checking if Loops are Tightly Nested\n"); |
| 646 | |
| 647 | // A perfectly nested loop will not have any branch in between the outer and |
| 648 | // inner block i.e. outer header will branch to either inner preheader and |
| 649 | // outerloop latch. |
| 650 | BranchInst *outerLoopHeaderBI = |
| 651 | dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); |
| 652 | if (!outerLoopHeaderBI) |
| 653 | return false; |
| 654 | unsigned num = outerLoopHeaderBI->getNumSuccessors(); |
| 655 | for (unsigned i = 0; i < num; i++) { |
| 656 | if (outerLoopHeaderBI->getSuccessor(i) != InnerLoopPreHeader && |
| 657 | outerLoopHeaderBI->getSuccessor(i) != OuterLoopLatch) |
| 658 | return false; |
| 659 | } |
| 660 | |
| 661 | DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch \n"); |
| 662 | // 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] | 663 | // and outer loop latch doesn't contain any unsafe instructions. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 664 | if (containsUnsafeInstructionsInHeader(OuterLoopHeader) || |
| 665 | containsUnsafeInstructionsInLatch(OuterLoopLatch)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 666 | return false; |
| 667 | |
| 668 | DEBUG(dbgs() << "Loops are perfectly nested \n"); |
| 669 | // We have a perfect loop nest. |
| 670 | return true; |
| 671 | } |
| 672 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 673 | |
| 674 | bool LoopInterchangeLegality::isLoopStructureUnderstood( |
| 675 | PHINode *InnerInduction) { |
| 676 | |
| 677 | unsigned Num = InnerInduction->getNumOperands(); |
| 678 | BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader(); |
| 679 | for (unsigned i = 0; i < Num; ++i) { |
| 680 | Value *Val = InnerInduction->getOperand(i); |
| 681 | if (isa<Constant>(Val)) |
| 682 | continue; |
| 683 | Instruction *I = dyn_cast<Instruction>(Val); |
| 684 | if (!I) |
| 685 | return false; |
| 686 | // TODO: Handle triangular loops. |
| 687 | // e.g. for(int i=0;i<N;i++) |
| 688 | // for(int j=i;j<N;j++) |
| 689 | unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i); |
| 690 | if (InnerInduction->getIncomingBlock(IncomBlockIndx) == |
| 691 | InnerLoopPreheader && |
| 692 | !OuterLoop->isLoopInvariant(I)) { |
| 693 | return false; |
| 694 | } |
| 695 | } |
| 696 | return true; |
| 697 | } |
| 698 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 699 | bool LoopInterchangeLegality::findInductionAndReductions( |
| 700 | Loop *L, SmallVector<PHINode *, 8> &Inductions, |
| 701 | SmallVector<PHINode *, 8> &Reductions) { |
| 702 | if (!L->getLoopLatch() || !L->getLoopPredecessor()) |
| 703 | return false; |
| 704 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
Tyler Nowicki | 0a91310 | 2015-06-16 18:07:34 +0000 | [diff] [blame] | 705 | RecurrenceDescriptor RD; |
James Molloy | 1bbf15c | 2015-08-27 09:53:00 +0000 | [diff] [blame] | 706 | InductionDescriptor ID; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 707 | PHINode *PHI = cast<PHINode>(I); |
Elena Demikhovsky | 376a18b | 2016-07-24 07:24:54 +0000 | [diff] [blame] | 708 | if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID)) |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 709 | Inductions.push_back(PHI); |
Tyler Nowicki | 0a91310 | 2015-06-16 18:07:34 +0000 | [diff] [blame] | 710 | else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD)) |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 711 | Reductions.push_back(PHI); |
| 712 | else { |
| 713 | DEBUG( |
| 714 | dbgs() << "Failed to recognize PHI as an induction or reduction.\n"); |
| 715 | return false; |
| 716 | } |
| 717 | } |
| 718 | return true; |
| 719 | } |
| 720 | |
| 721 | static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) { |
| 722 | for (auto I = Block->begin(); isa<PHINode>(I); ++I) { |
| 723 | PHINode *PHI = cast<PHINode>(I); |
| 724 | // Reduction lcssa phi will have only 1 incoming block that from loop latch. |
| 725 | if (PHI->getNumIncomingValues() > 1) |
| 726 | return false; |
| 727 | Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0)); |
| 728 | if (!Ins) |
| 729 | return false; |
| 730 | // Incoming value for lcssa phi's in outer loop exit can only be inner loop |
| 731 | // exits lcssa phi else it would not be tightly nested. |
| 732 | if (!isa<PHINode>(Ins) && isOuterLoopExitBlock) |
| 733 | return false; |
| 734 | } |
| 735 | return true; |
| 736 | } |
| 737 | |
| 738 | static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock, |
| 739 | BasicBlock *LoopHeader) { |
| 740 | if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) { |
| 741 | unsigned Num = BI->getNumSuccessors(); |
| 742 | assert(Num == 2); |
| 743 | for (unsigned i = 0; i < Num; ++i) { |
| 744 | if (BI->getSuccessor(i) == LoopHeader) |
| 745 | continue; |
| 746 | return BI->getSuccessor(i); |
| 747 | } |
| 748 | } |
| 749 | return nullptr; |
| 750 | } |
| 751 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 752 | // This function indicates the current limitations in the transform as a result |
| 753 | // of which we do not proceed. |
| 754 | bool LoopInterchangeLegality::currentLimitations() { |
| 755 | |
| 756 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 757 | BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 758 | BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); |
| 759 | BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 760 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 761 | |
| 762 | PHINode *InnerInductionVar; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 763 | SmallVector<PHINode *, 8> Inductions; |
| 764 | SmallVector<PHINode *, 8> Reductions; |
| 765 | if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 766 | return true; |
| 767 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 768 | // TODO: Currently we handle only loops with 1 induction variable. |
| 769 | if (Inductions.size() != 1) { |
| 770 | DEBUG(dbgs() << "We currently only support loops with 1 induction variable." |
| 771 | << "Failed to interchange due to current limitation\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 772 | return true; |
| 773 | } |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 774 | if (Reductions.size() > 0) |
| 775 | InnerLoopHasReduction = true; |
| 776 | |
| 777 | InnerInductionVar = Inductions.pop_back_val(); |
| 778 | Reductions.clear(); |
| 779 | if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) |
| 780 | return true; |
| 781 | |
| 782 | // Outer loop cannot have reduction because then loops will not be tightly |
| 783 | // nested. |
| 784 | if (!Reductions.empty()) |
| 785 | return true; |
| 786 | // TODO: Currently we handle only loops with 1 induction variable. |
| 787 | if (Inductions.size() != 1) |
| 788 | return true; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 789 | |
| 790 | // TODO: Triangular loops are not handled for now. |
| 791 | if (!isLoopStructureUnderstood(InnerInductionVar)) { |
| 792 | DEBUG(dbgs() << "Loop structure not understood by pass\n"); |
| 793 | return true; |
| 794 | } |
| 795 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 796 | // TODO: We only handle LCSSA PHI's corresponding to reduction for now. |
| 797 | BasicBlock *LoopExitBlock = |
| 798 | getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader); |
| 799 | if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 800 | return true; |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 801 | |
| 802 | LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader); |
| 803 | if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 804 | return true; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 805 | |
| 806 | // TODO: Current limitation: Since we split the inner loop latch at the point |
| 807 | // were induction variable is incremented (induction.next); We cannot have |
| 808 | // more than 1 user of induction.next since it would result in broken code |
| 809 | // after split. |
| 810 | // e.g. |
| 811 | // for(i=0;i<N;i++) { |
| 812 | // for(j = 0;j<M;j++) { |
| 813 | // A[j+1][i+2] = A[j][i]+k; |
| 814 | // } |
| 815 | // } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 816 | Instruction *InnerIndexVarInc = nullptr; |
| 817 | if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader) |
| 818 | InnerIndexVarInc = |
| 819 | dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1)); |
| 820 | else |
| 821 | InnerIndexVarInc = |
| 822 | dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0)); |
| 823 | |
Pete Cooper | 11bd958 | 2015-07-27 18:37:58 +0000 | [diff] [blame] | 824 | if (!InnerIndexVarInc) |
| 825 | return true; |
| 826 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 827 | // Since we split the inner loop latch on this induction variable. Make sure |
| 828 | // we do not have any instruction between the induction variable and branch |
| 829 | // instruction. |
| 830 | |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 831 | bool FoundInduction = false; |
| 832 | for (const Instruction &I : reverse(*InnerLoopLatch)) { |
| 833 | if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 834 | continue; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 835 | // We found an instruction. If this is not induction variable then it is not |
| 836 | // safe to split this loop latch. |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 837 | if (!I.isIdenticalTo(InnerIndexVarInc)) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 838 | return true; |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 839 | |
| 840 | FoundInduction = true; |
| 841 | break; |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 842 | } |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 843 | // 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] | 844 | // current limitation. |
| 845 | if (!FoundInduction) |
| 846 | return true; |
| 847 | |
| 848 | return false; |
| 849 | } |
| 850 | |
| 851 | bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId, |
| 852 | unsigned OuterLoopId, |
| 853 | CharMatrix &DepMatrix) { |
| 854 | |
| 855 | if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) { |
| 856 | DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId |
Chad Rosier | 58ede27 | 2016-09-14 16:43:19 +0000 | [diff] [blame] | 857 | << " and OuterLoopId = " << OuterLoopId |
| 858 | << " due to dependence\n"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 859 | return false; |
| 860 | } |
| 861 | |
| 862 | // Create unique Preheaders if we already do not have one. |
| 863 | BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); |
| 864 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 865 | |
| 866 | // Create a unique outer preheader - |
| 867 | // 1) If OuterLoop preheader is not present. |
| 868 | // 2) If OuterLoop Preheader is same as OuterLoop Header |
| 869 | // 3) If OuterLoop Preheader is same as Header of the previous loop. |
| 870 | // 4) If OuterLoop Preheader is Entry node. |
| 871 | if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() || |
| 872 | isa<PHINode>(OuterLoopPreHeader->begin()) || |
| 873 | !OuterLoopPreHeader->getUniquePredecessor()) { |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 874 | OuterLoopPreHeader = |
| 875 | InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 876 | } |
| 877 | |
| 878 | if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() || |
| 879 | InnerLoopPreHeader == OuterLoop->getHeader()) { |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 880 | InnerLoopPreHeader = |
| 881 | InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 882 | } |
| 883 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 884 | // TODO: The loops could not be interchanged due to current limitations in the |
| 885 | // transform module. |
| 886 | if (currentLimitations()) { |
| 887 | DEBUG(dbgs() << "Not legal because of current transform limitation\n"); |
| 888 | return false; |
| 889 | } |
| 890 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 891 | // Check if the loops are tightly nested. |
| 892 | if (!tightlyNested(OuterLoop, InnerLoop)) { |
| 893 | DEBUG(dbgs() << "Loops not tightly nested\n"); |
| 894 | return false; |
| 895 | } |
| 896 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 897 | return true; |
| 898 | } |
| 899 | |
| 900 | int LoopInterchangeProfitability::getInstrOrderCost() { |
| 901 | unsigned GoodOrder, BadOrder; |
| 902 | BadOrder = GoodOrder = 0; |
| 903 | for (auto BI = InnerLoop->block_begin(), BE = InnerLoop->block_end(); |
| 904 | BI != BE; ++BI) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 905 | for (Instruction &Ins : **BI) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 906 | if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) { |
| 907 | unsigned NumOp = GEP->getNumOperands(); |
| 908 | bool FoundInnerInduction = false; |
| 909 | bool FoundOuterInduction = false; |
| 910 | for (unsigned i = 0; i < NumOp; ++i) { |
| 911 | const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i)); |
| 912 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal); |
| 913 | if (!AR) |
| 914 | continue; |
| 915 | |
| 916 | // If we find the inner induction after an outer induction e.g. |
| 917 | // for(int i=0;i<N;i++) |
| 918 | // for(int j=0;j<N;j++) |
| 919 | // A[i][j] = A[i-1][j-1]+k; |
| 920 | // then it is a good order. |
| 921 | if (AR->getLoop() == InnerLoop) { |
| 922 | // We found an InnerLoop induction after OuterLoop induction. It is |
| 923 | // a good order. |
| 924 | FoundInnerInduction = true; |
| 925 | if (FoundOuterInduction) { |
| 926 | GoodOrder++; |
| 927 | break; |
| 928 | } |
| 929 | } |
| 930 | // If we find the outer induction after an inner induction e.g. |
| 931 | // for(int i=0;i<N;i++) |
| 932 | // for(int j=0;j<N;j++) |
| 933 | // A[j][i] = A[j-1][i-1]+k; |
| 934 | // then it is a bad order. |
| 935 | if (AR->getLoop() == OuterLoop) { |
| 936 | // We found an OuterLoop induction after InnerLoop induction. It is |
| 937 | // a bad order. |
| 938 | FoundOuterInduction = true; |
| 939 | if (FoundInnerInduction) { |
| 940 | BadOrder++; |
| 941 | break; |
| 942 | } |
| 943 | } |
| 944 | } |
| 945 | } |
| 946 | } |
| 947 | } |
| 948 | return GoodOrder - BadOrder; |
| 949 | } |
| 950 | |
Benjamin Kramer | f044d3f | 2015-03-09 16:23:46 +0000 | [diff] [blame] | 951 | static bool isProfitabileForVectorization(unsigned InnerLoopId, |
| 952 | unsigned OuterLoopId, |
| 953 | CharMatrix &DepMatrix) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 954 | // TODO: Improve this heuristic to catch more cases. |
| 955 | // If the inner loop is loop independent or doesn't carry any dependency it is |
| 956 | // profitable to move this to outer position. |
| 957 | unsigned Row = DepMatrix.size(); |
| 958 | for (unsigned i = 0; i < Row; ++i) { |
| 959 | if (DepMatrix[i][InnerLoopId] != 'S' && DepMatrix[i][InnerLoopId] != 'I') |
| 960 | return false; |
| 961 | // TODO: We need to improve this heuristic. |
| 962 | if (DepMatrix[i][OuterLoopId] != '=') |
| 963 | return false; |
| 964 | } |
| 965 | // If outer loop has dependence and inner loop is loop independent then it is |
| 966 | // profitable to interchange to enable parallelism. |
| 967 | return true; |
| 968 | } |
| 969 | |
| 970 | bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId, |
| 971 | unsigned OuterLoopId, |
| 972 | CharMatrix &DepMatrix) { |
| 973 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 974 | // TODO: Add better profitability checks. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 975 | // e.g |
| 976 | // 1) Construct dependency matrix and move the one with no loop carried dep |
| 977 | // inside to enable vectorization. |
| 978 | |
| 979 | // This is rough cost estimation algorithm. It counts the good and bad order |
| 980 | // of induction variables in the instruction and allows reordering if number |
| 981 | // of bad orders is more than good. |
Chad Rosier | 7243189 | 2016-09-14 17:07:13 +0000 | [diff] [blame^] | 982 | int Cost = getInstrOrderCost(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 983 | DEBUG(dbgs() << "Cost = " << Cost << "\n"); |
Chad Rosier | 7243189 | 2016-09-14 17:07:13 +0000 | [diff] [blame^] | 984 | if (Cost < -LoopInterchangeCostThreshold) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 985 | return true; |
| 986 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 987 | // 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] | 988 | // we can move this loop outside to improve parallelism. |
| 989 | bool ImprovesPar = |
| 990 | isProfitabileForVectorization(InnerLoopId, OuterLoopId, DepMatrix); |
| 991 | return ImprovesPar; |
| 992 | } |
| 993 | |
| 994 | void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop, |
| 995 | Loop *InnerLoop) { |
Daniel Jasper | 6adbd7a | 2015-03-06 10:39:14 +0000 | [diff] [blame] | 996 | for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E; |
| 997 | ++I) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 998 | if (*I == InnerLoop) { |
| 999 | OuterLoop->removeChildLoop(I); |
| 1000 | return; |
| 1001 | } |
| 1002 | } |
Benjamin Kramer | 8ceb323 | 2015-10-25 22:28:27 +0000 | [diff] [blame] | 1003 | llvm_unreachable("Couldn't find loop"); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1004 | } |
Daniel Jasper | 6adbd7a | 2015-03-06 10:39:14 +0000 | [diff] [blame] | 1005 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1006 | void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop, |
| 1007 | Loop *OuterLoop) { |
| 1008 | Loop *OuterLoopParent = OuterLoop->getParentLoop(); |
| 1009 | if (OuterLoopParent) { |
| 1010 | // Remove the loop from its parent loop. |
| 1011 | removeChildLoop(OuterLoopParent, OuterLoop); |
| 1012 | removeChildLoop(OuterLoop, InnerLoop); |
| 1013 | OuterLoopParent->addChildLoop(InnerLoop); |
| 1014 | } else { |
| 1015 | removeChildLoop(OuterLoop, InnerLoop); |
| 1016 | LI->changeTopLevelLoop(OuterLoop, InnerLoop); |
| 1017 | } |
| 1018 | |
Andrew Kaylor | 08c5f1e | 2015-04-24 17:39:16 +0000 | [diff] [blame] | 1019 | while (!InnerLoop->empty()) |
| 1020 | OuterLoop->addChildLoop(InnerLoop->removeChildLoop(InnerLoop->begin())); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1021 | |
| 1022 | InnerLoop->addChildLoop(OuterLoop); |
| 1023 | } |
| 1024 | |
| 1025 | bool LoopInterchangeTransform::transform() { |
| 1026 | |
| 1027 | DEBUG(dbgs() << "transform\n"); |
| 1028 | bool Transformed = false; |
| 1029 | Instruction *InnerIndexVar; |
| 1030 | |
| 1031 | if (InnerLoop->getSubLoops().size() == 0) { |
| 1032 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1033 | DEBUG(dbgs() << "Calling Split Inner Loop\n"); |
| 1034 | PHINode *InductionPHI = getInductionVariable(InnerLoop, SE); |
| 1035 | if (!InductionPHI) { |
| 1036 | DEBUG(dbgs() << "Failed to find the point to split loop latch \n"); |
| 1037 | return false; |
| 1038 | } |
| 1039 | |
| 1040 | if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader) |
| 1041 | InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1)); |
| 1042 | else |
| 1043 | InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0)); |
| 1044 | |
| 1045 | // |
| 1046 | // Split at the place were the induction variable is |
| 1047 | // incremented/decremented. |
| 1048 | // TODO: This splitting logic may not work always. Fix this. |
| 1049 | splitInnerLoopLatch(InnerIndexVar); |
| 1050 | DEBUG(dbgs() << "splitInnerLoopLatch Done\n"); |
| 1051 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1052 | // Splits the inner loops phi nodes out into a separate basic block. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1053 | splitInnerLoopHeader(); |
| 1054 | DEBUG(dbgs() << "splitInnerLoopHeader Done\n"); |
| 1055 | } |
| 1056 | |
| 1057 | Transformed |= adjustLoopLinks(); |
| 1058 | if (!Transformed) { |
| 1059 | DEBUG(dbgs() << "adjustLoopLinks Failed\n"); |
| 1060 | return false; |
| 1061 | } |
| 1062 | |
| 1063 | restructureLoops(InnerLoop, OuterLoop); |
| 1064 | return true; |
| 1065 | } |
| 1066 | |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1067 | void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) { |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1068 | BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1069 | BasicBlock *InnerLoopLatchPred = InnerLoopLatch; |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1070 | InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1071 | } |
| 1072 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1073 | void LoopInterchangeTransform::splitInnerLoopHeader() { |
| 1074 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1075 | // Split the inner loop header out. Here make sure that the reduction PHI's |
| 1076 | // stay in the innerloop body. |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1077 | BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1078 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1079 | if (InnerLoopHasReduction) { |
| 1080 | // FIXME: Check if the induction PHI will always be the first PHI. |
| 1081 | BasicBlock *New = InnerLoopHeader->splitBasicBlock( |
| 1082 | ++(InnerLoopHeader->begin()), InnerLoopHeader->getName() + ".split"); |
| 1083 | if (LI) |
| 1084 | if (Loop *L = LI->getLoopFor(InnerLoopHeader)) |
| 1085 | L->addBasicBlockToLoop(New, *LI); |
| 1086 | |
| 1087 | // Adjust Reduction PHI's in the block. |
| 1088 | SmallVector<PHINode *, 8> PHIVec; |
| 1089 | for (auto I = New->begin(); isa<PHINode>(I); ++I) { |
| 1090 | PHINode *PHI = dyn_cast<PHINode>(I); |
| 1091 | Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader); |
| 1092 | PHI->replaceAllUsesWith(V); |
| 1093 | PHIVec.push_back((PHI)); |
| 1094 | } |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1095 | for (PHINode *P : PHIVec) { |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1096 | P->eraseFromParent(); |
| 1097 | } |
| 1098 | } else { |
| 1099 | SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI); |
| 1100 | } |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1101 | |
| 1102 | DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & " |
| 1103 | "InnerLoopHeader \n"); |
| 1104 | } |
| 1105 | |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1106 | /// \brief Move all instructions except the terminator from FromBB right before |
| 1107 | /// InsertBefore |
| 1108 | static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) { |
| 1109 | auto &ToList = InsertBefore->getParent()->getInstList(); |
| 1110 | auto &FromList = FromBB->getInstList(); |
| 1111 | |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1112 | ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(), |
| 1113 | FromBB->getTerminator()->getIterator()); |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1114 | } |
| 1115 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1116 | void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock, |
| 1117 | BasicBlock *OldPred, |
| 1118 | BasicBlock *NewPred) { |
| 1119 | for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) { |
| 1120 | PHINode *PHI = cast<PHINode>(I); |
| 1121 | unsigned Num = PHI->getNumIncomingValues(); |
| 1122 | for (unsigned i = 0; i < Num; ++i) { |
| 1123 | if (PHI->getIncomingBlock(i) == OldPred) |
| 1124 | PHI->setIncomingBlock(i, NewPred); |
| 1125 | } |
| 1126 | } |
| 1127 | } |
| 1128 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1129 | bool LoopInterchangeTransform::adjustLoopBranches() { |
| 1130 | |
| 1131 | DEBUG(dbgs() << "adjustLoopBranches called\n"); |
| 1132 | // Adjust the loop preheader |
| 1133 | BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); |
| 1134 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 1135 | BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); |
| 1136 | BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); |
| 1137 | BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); |
| 1138 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1139 | BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor(); |
| 1140 | BasicBlock *InnerLoopLatchPredecessor = |
| 1141 | InnerLoopLatch->getUniquePredecessor(); |
| 1142 | BasicBlock *InnerLoopLatchSuccessor; |
| 1143 | BasicBlock *OuterLoopLatchSuccessor; |
| 1144 | |
| 1145 | BranchInst *OuterLoopLatchBI = |
| 1146 | dyn_cast<BranchInst>(OuterLoopLatch->getTerminator()); |
| 1147 | BranchInst *InnerLoopLatchBI = |
| 1148 | dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); |
| 1149 | BranchInst *OuterLoopHeaderBI = |
| 1150 | dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); |
| 1151 | BranchInst *InnerLoopHeaderBI = |
| 1152 | dyn_cast<BranchInst>(InnerLoopHeader->getTerminator()); |
| 1153 | |
| 1154 | if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor || |
| 1155 | !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI || |
| 1156 | !InnerLoopHeaderBI) |
| 1157 | return false; |
| 1158 | |
| 1159 | BranchInst *InnerLoopLatchPredecessorBI = |
| 1160 | dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator()); |
| 1161 | BranchInst *OuterLoopPredecessorBI = |
| 1162 | dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator()); |
| 1163 | |
| 1164 | if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI) |
| 1165 | return false; |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1166 | BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor(); |
| 1167 | if (!InnerLoopHeaderSuccessor) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1168 | return false; |
| 1169 | |
| 1170 | // Adjust Loop Preheader and headers |
| 1171 | |
| 1172 | unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors(); |
| 1173 | for (unsigned i = 0; i < NumSucc; ++i) { |
| 1174 | if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader) |
| 1175 | OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader); |
| 1176 | } |
| 1177 | |
| 1178 | NumSucc = OuterLoopHeaderBI->getNumSuccessors(); |
| 1179 | for (unsigned i = 0; i < NumSucc; ++i) { |
| 1180 | if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch) |
| 1181 | OuterLoopHeaderBI->setSuccessor(i, LoopExit); |
| 1182 | else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader) |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1183 | OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1184 | } |
| 1185 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1186 | // Adjust reduction PHI's now that the incoming block has changed. |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1187 | updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader, |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1188 | OuterLoopHeader); |
| 1189 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1190 | BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI); |
| 1191 | InnerLoopHeaderBI->eraseFromParent(); |
| 1192 | |
| 1193 | // -------------Adjust loop latches----------- |
| 1194 | if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader) |
| 1195 | InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1); |
| 1196 | else |
| 1197 | InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0); |
| 1198 | |
| 1199 | NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors(); |
| 1200 | for (unsigned i = 0; i < NumSucc; ++i) { |
| 1201 | if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch) |
| 1202 | InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor); |
| 1203 | } |
| 1204 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1205 | // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with |
| 1206 | // the value and remove this PHI node from inner loop. |
| 1207 | SmallVector<PHINode *, 8> LcssaVec; |
| 1208 | for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) { |
| 1209 | PHINode *LcssaPhi = cast<PHINode>(I); |
| 1210 | LcssaVec.push_back(LcssaPhi); |
| 1211 | } |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1212 | for (PHINode *P : LcssaVec) { |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1213 | Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch); |
| 1214 | P->replaceAllUsesWith(Incoming); |
| 1215 | P->eraseFromParent(); |
| 1216 | } |
| 1217 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1218 | if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader) |
| 1219 | OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1); |
| 1220 | else |
| 1221 | OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0); |
| 1222 | |
| 1223 | if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor) |
| 1224 | InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor); |
| 1225 | else |
| 1226 | InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor); |
| 1227 | |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1228 | updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch); |
| 1229 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1230 | if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) { |
| 1231 | OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch); |
| 1232 | } else { |
| 1233 | OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch); |
| 1234 | } |
| 1235 | |
| 1236 | return true; |
| 1237 | } |
| 1238 | void LoopInterchangeTransform::adjustLoopPreheaders() { |
| 1239 | |
| 1240 | // We have interchanged the preheaders so we need to interchange the data in |
| 1241 | // the preheader as well. |
| 1242 | // This is because the content of inner preheader was previously executed |
| 1243 | // inside the outer loop. |
| 1244 | BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); |
| 1245 | BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); |
| 1246 | BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); |
| 1247 | BranchInst *InnerTermBI = |
| 1248 | cast<BranchInst>(InnerLoopPreHeader->getTerminator()); |
| 1249 | |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1250 | // These instructions should now be executed inside the loop. |
| 1251 | // Move instruction into a new block after outer header. |
Karthik Bhat | 8210fdf | 2015-04-23 04:51:44 +0000 | [diff] [blame] | 1252 | moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator()); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1253 | // These instructions were not executed previously in the loop so move them to |
| 1254 | // the older inner loop preheader. |
Benjamin Kramer | 7944292 | 2015-03-06 18:59:14 +0000 | [diff] [blame] | 1255 | moveBBContents(OuterLoopPreHeader, InnerTermBI); |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1256 | } |
| 1257 | |
| 1258 | bool LoopInterchangeTransform::adjustLoopLinks() { |
| 1259 | |
| 1260 | // Adjust all branches in the inner and outer loop. |
| 1261 | bool Changed = adjustLoopBranches(); |
| 1262 | if (Changed) |
| 1263 | adjustLoopPreheaders(); |
| 1264 | return Changed; |
| 1265 | } |
| 1266 | |
| 1267 | char LoopInterchange::ID = 0; |
| 1268 | INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange", |
| 1269 | "Interchanges loops for cache reuse", false, false) |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 1270 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 1271 | INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1272 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1273 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1274 | INITIALIZE_PASS_DEPENDENCY(LoopSimplify) |
Easwaran Raman | e12c487 | 2016-06-09 19:44:46 +0000 | [diff] [blame] | 1275 | INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) |
Karthik Bhat | 88db86d | 2015-03-06 10:11:25 +0000 | [diff] [blame] | 1276 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 1277 | |
| 1278 | INITIALIZE_PASS_END(LoopInterchange, "loop-interchange", |
| 1279 | "Interchanges loops for cache reuse", false, false) |
| 1280 | |
| 1281 | Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); } |