Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 1 | //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===// |
| 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 file implements some loop unrolling utilities for loops with run-time |
| 11 | // trip counts. See LoopUnroll.cpp for unrolling loops with compile-time |
| 12 | // trip counts. |
| 13 | // |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 14 | // The functions in this file are used to generate extra code when the |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 15 | // run-time trip count modulo the unroll factor is not 0. When this is the |
| 16 | // case, we need to generate code to execute these 'left over' iterations. |
| 17 | // |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 18 | // The current strategy generates an if-then-else sequence prior to the |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 19 | // unrolled loop to execute the 'left over' iterations before or after the |
| 20 | // unrolled loop. |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 21 | // |
| 22 | //===----------------------------------------------------------------------===// |
| 23 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 24 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | b5797b6 | 2015-01-18 09:21:15 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/AliasAnalysis.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/LoopIterator.h" |
| 27 | #include "llvm/Analysis/LoopPass.h" |
| 28 | #include "llvm/Analysis/ScalarEvolution.h" |
| 29 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 30 | #include "llvm/IR/BasicBlock.h" |
Chandler Carruth | 32c52c7 | 2015-01-18 02:39:37 +0000 | [diff] [blame] | 31 | #include "llvm/IR/Dominators.h" |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 32 | #include "llvm/IR/Metadata.h" |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 33 | #include "llvm/IR/Module.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 34 | #include "llvm/Support/Debug.h" |
| 35 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | b5797b6 | 2015-01-18 09:21:15 +0000 | [diff] [blame] | 36 | #include "llvm/Transforms/Scalar.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 37 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 38 | #include "llvm/Transforms/Utils/Cloning.h" |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 39 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 40 | #include "llvm/Transforms/Utils/UnrollLoop.h" |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 41 | #include <algorithm> |
| 42 | |
| 43 | using namespace llvm; |
| 44 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 45 | #define DEBUG_TYPE "loop-unroll" |
| 46 | |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 47 | STATISTIC(NumRuntimeUnrolled, |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 48 | "Number of loops unrolled with run-time trip counts"); |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 49 | static cl::opt<bool> UnrollRuntimeMultiExit( |
| 50 | "unroll-runtime-multi-exit", cl::init(false), cl::Hidden, |
| 51 | cl::desc("Allow runtime unrolling for loops with multiple exits, when " |
| 52 | "epilog is generated")); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 53 | |
| 54 | /// Connect the unrolling prolog code to the original loop. |
| 55 | /// The unrolling prolog code contains code to execute the |
| 56 | /// 'extra' iterations if the run-time trip count modulo the |
| 57 | /// unroll count is non-zero. |
| 58 | /// |
| 59 | /// This function performs the following: |
| 60 | /// - Create PHI nodes at prolog end block to combine values |
| 61 | /// that exit the prolog code and jump around the prolog. |
| 62 | /// - Add a PHI operand to a PHI node at the loop exit block |
| 63 | /// for values that exit the prolog and go around the loop. |
| 64 | /// - Branch around the original loop if the trip count is less |
| 65 | /// than the unroll factor. |
| 66 | /// |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 67 | static void ConnectProlog(Loop *L, Value *BECount, unsigned Count, |
Anna Thomas | 734ab3f | 2017-07-07 18:05:28 +0000 | [diff] [blame] | 68 | BasicBlock *PrologExit, |
| 69 | BasicBlock *OriginalLoopLatchExit, |
| 70 | BasicBlock *PreHeader, BasicBlock *NewPreHeader, |
| 71 | ValueToValueMapTy &VMap, DominatorTree *DT, |
| 72 | LoopInfo *LI, bool PreserveLCSSA) { |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 73 | BasicBlock *Latch = L->getLoopLatch(); |
Craig Topper | e73658d | 2014-04-28 04:05:08 +0000 | [diff] [blame] | 74 | assert(Latch && "Loop must have a latch"); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 75 | BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 76 | |
| 77 | // Create a PHI node for each outgoing value from the original loop |
| 78 | // (which means it is an outgoing value from the prolog code too). |
| 79 | // The new PHI node is inserted in the prolog end basic block. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 80 | // The new PHI node value is added as an operand of a PHI node in either |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 81 | // the loop header or the loop exit block. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 82 | for (BasicBlock *Succ : successors(Latch)) { |
| 83 | for (Instruction &BBI : *Succ) { |
| 84 | PHINode *PN = dyn_cast<PHINode>(&BBI); |
| 85 | // Exit when we passed all PHI nodes. |
| 86 | if (!PN) |
| 87 | break; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 88 | // Add a new PHI node to the prolog end block and add the |
| 89 | // appropriate incoming values. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 90 | PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr", |
| 91 | PrologExit->getFirstNonPHI()); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 92 | // Adding a value to the new PHI node from the original loop preheader. |
| 93 | // This is the value that skips all the prolog code. |
| 94 | if (L->contains(PN)) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 95 | NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), |
| 96 | PreHeader); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 97 | } else { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 98 | NewPN->addIncoming(UndefValue::get(PN->getType()), PreHeader); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 99 | } |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 100 | |
| 101 | Value *V = PN->getIncomingValueForBlock(Latch); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 102 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 103 | if (L->contains(I)) { |
Duncan P. N. Exon Smith | a71301b | 2016-04-17 19:26:49 +0000 | [diff] [blame] | 104 | V = VMap.lookup(I); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 105 | } |
| 106 | } |
| 107 | // Adding a value to the new PHI node from the last prolog block |
| 108 | // that was created. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 109 | NewPN->addIncoming(V, PrologLatch); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 110 | |
| 111 | // Update the existing PHI node operand with the value from the |
| 112 | // new PHI node. How this is done depends on if the existing |
| 113 | // PHI node is in the original loop block, or the exit block. |
| 114 | if (L->contains(PN)) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 115 | PN->setIncomingValue(PN->getBasicBlockIndex(NewPreHeader), NewPN); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 116 | } else { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 117 | PN->addIncoming(NewPN, PrologExit); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
Michael Zolotukhin | d9b6ad3 | 2016-08-02 19:19:31 +0000 | [diff] [blame] | 122 | // Make sure that created prolog loop is in simplified form |
| 123 | SmallVector<BasicBlock *, 4> PrologExitPreds; |
| 124 | Loop *PrologLoop = LI->getLoopFor(PrologLatch); |
| 125 | if (PrologLoop) { |
| 126 | for (BasicBlock *PredBB : predecessors(PrologExit)) |
| 127 | if (PrologLoop->contains(PredBB)) |
| 128 | PrologExitPreds.push_back(PredBB); |
| 129 | |
| 130 | SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI, |
| 131 | PreserveLCSSA); |
| 132 | } |
| 133 | |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 134 | // Create a branch around the original loop, which is taken if there are no |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 135 | // iterations remaining to be executed after running the prologue. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 136 | Instruction *InsertPt = PrologExit->getTerminator(); |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 137 | IRBuilder<> B(InsertPt); |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 138 | |
| 139 | assert(Count != 0 && "nonsensical Count!"); |
| 140 | |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 141 | // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1) |
| 142 | // This means %xtraiter is (BECount + 1) and all of the iterations of this |
| 143 | // loop were executed by the prologue. Note that if BECount <u (Count - 1) |
| 144 | // then (BECount + 1) cannot unsigned-overflow. |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 145 | Value *BrLoopExit = |
| 146 | B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1)); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 147 | // Split the exit to maintain loop canonicalization guarantees |
Anna Thomas | 734ab3f | 2017-07-07 18:05:28 +0000 | [diff] [blame] | 148 | SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit)); |
| 149 | SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI, |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 150 | PreserveLCSSA); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 151 | // Add the branch to the exit block (around the unrolled loop) |
Anna Thomas | 734ab3f | 2017-07-07 18:05:28 +0000 | [diff] [blame] | 152 | B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 153 | InsertPt->eraseFromParent(); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 154 | if (DT) |
Anna Thomas | 734ab3f | 2017-07-07 18:05:28 +0000 | [diff] [blame] | 155 | DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 156 | } |
| 157 | |
| 158 | /// Connect the unrolling epilog code to the original loop. |
| 159 | /// The unrolling epilog code contains code to execute the |
| 160 | /// 'extra' iterations if the run-time trip count modulo the |
| 161 | /// unroll count is non-zero. |
| 162 | /// |
| 163 | /// This function performs the following: |
| 164 | /// - Update PHI nodes at the unrolling loop exit and epilog loop exit |
| 165 | /// - Create PHI nodes at the unrolling loop exit to combine |
| 166 | /// values that exit the unrolling loop code and jump around it. |
| 167 | /// - Update PHI operands in the epilog loop by the new PHI nodes |
| 168 | /// - Branch around the epilog loop if extra iters (ModVal) is zero. |
| 169 | /// |
| 170 | static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit, |
| 171 | BasicBlock *Exit, BasicBlock *PreHeader, |
| 172 | BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader, |
| 173 | ValueToValueMapTy &VMap, DominatorTree *DT, |
| 174 | LoopInfo *LI, bool PreserveLCSSA) { |
| 175 | BasicBlock *Latch = L->getLoopLatch(); |
| 176 | assert(Latch && "Loop must have a latch"); |
| 177 | BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]); |
| 178 | |
| 179 | // Loop structure should be the following: |
| 180 | // |
| 181 | // PreHeader |
| 182 | // NewPreHeader |
| 183 | // Header |
| 184 | // ... |
| 185 | // Latch |
| 186 | // NewExit (PN) |
| 187 | // EpilogPreHeader |
| 188 | // EpilogHeader |
| 189 | // ... |
| 190 | // EpilogLatch |
| 191 | // Exit (EpilogPN) |
| 192 | |
| 193 | // Update PHI nodes at NewExit and Exit. |
| 194 | for (Instruction &BBI : *NewExit) { |
| 195 | PHINode *PN = dyn_cast<PHINode>(&BBI); |
| 196 | // Exit when we passed all PHI nodes. |
| 197 | if (!PN) |
| 198 | break; |
| 199 | // PN should be used in another PHI located in Exit block as |
| 200 | // Exit was split by SplitBlockPredecessors into Exit and NewExit |
| 201 | // Basicaly it should look like: |
| 202 | // NewExit: |
| 203 | // PN = PHI [I, Latch] |
| 204 | // ... |
| 205 | // Exit: |
| 206 | // EpilogPN = PHI [PN, EpilogPreHeader] |
| 207 | // |
| 208 | // There is EpilogPreHeader incoming block instead of NewExit as |
| 209 | // NewExit was spilt 1 more time to get EpilogPreHeader. |
| 210 | assert(PN->hasOneUse() && "The phi should have 1 use"); |
| 211 | PHINode *EpilogPN = cast<PHINode> (PN->use_begin()->getUser()); |
| 212 | assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block"); |
| 213 | |
| 214 | // Add incoming PreHeader from branch around the Loop |
| 215 | PN->addIncoming(UndefValue::get(PN->getType()), PreHeader); |
| 216 | |
| 217 | Value *V = PN->getIncomingValueForBlock(Latch); |
| 218 | Instruction *I = dyn_cast<Instruction>(V); |
| 219 | if (I && L->contains(I)) |
| 220 | // If value comes from an instruction in the loop add VMap value. |
Duncan P. N. Exon Smith | a71301b | 2016-04-17 19:26:49 +0000 | [diff] [blame] | 221 | V = VMap.lookup(I); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 222 | // For the instruction out of the loop, constant or undefined value |
| 223 | // insert value itself. |
| 224 | EpilogPN->addIncoming(V, EpilogLatch); |
| 225 | |
| 226 | assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 && |
| 227 | "EpilogPN should have EpilogPreHeader incoming block"); |
| 228 | // Change EpilogPreHeader incoming block to NewExit. |
| 229 | EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader), |
| 230 | NewExit); |
| 231 | // Now PHIs should look like: |
| 232 | // NewExit: |
| 233 | // PN = PHI [I, Latch], [undef, PreHeader] |
| 234 | // ... |
| 235 | // Exit: |
| 236 | // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch] |
| 237 | } |
| 238 | |
| 239 | // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader). |
| 240 | // Update corresponding PHI nodes in epilog loop. |
| 241 | for (BasicBlock *Succ : successors(Latch)) { |
| 242 | // Skip this as we already updated phis in exit blocks. |
| 243 | if (!L->contains(Succ)) |
| 244 | continue; |
| 245 | for (Instruction &BBI : *Succ) { |
| 246 | PHINode *PN = dyn_cast<PHINode>(&BBI); |
| 247 | // Exit when we passed all PHI nodes. |
| 248 | if (!PN) |
| 249 | break; |
| 250 | // Add new PHI nodes to the loop exit block and update epilog |
| 251 | // PHIs with the new PHI values. |
| 252 | PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr", |
| 253 | NewExit->getFirstNonPHI()); |
| 254 | // Adding a value to the new PHI node from the unrolling loop preheader. |
| 255 | NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), PreHeader); |
| 256 | // Adding a value to the new PHI node from the unrolling loop latch. |
| 257 | NewPN->addIncoming(PN->getIncomingValueForBlock(Latch), Latch); |
| 258 | |
| 259 | // Update the existing PHI node operand with the value from the new PHI |
| 260 | // node. Corresponding instruction in epilog loop should be PHI. |
| 261 | PHINode *VPN = cast<PHINode>(VMap[&BBI]); |
| 262 | VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN); |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | Instruction *InsertPt = NewExit->getTerminator(); |
| 267 | IRBuilder<> B(InsertPt); |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 268 | Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod"); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 269 | assert(Exit && "Loop must have a single exit block only"); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 270 | // Split the epilogue exit to maintain loop canonicalization guarantees |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 271 | SmallVector<BasicBlock*, 4> Preds(predecessors(Exit)); |
| 272 | SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, |
| 273 | PreserveLCSSA); |
| 274 | // Add the branch to the exit block (around the unrolling loop) |
| 275 | B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 276 | InsertPt->eraseFromParent(); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 277 | if (DT) |
| 278 | DT->changeImmediateDominator(Exit, NewExit); |
| 279 | |
| 280 | // Split the main loop exit to maintain canonicalization guarantees. |
| 281 | SmallVector<BasicBlock*, 4> NewExitPreds{Latch}; |
| 282 | SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, |
| 283 | PreserveLCSSA); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 284 | } |
| 285 | |
| 286 | /// Create a clone of the blocks in a loop and connect them together. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 287 | /// If CreateRemainderLoop is false, loop structure will not be cloned, |
| 288 | /// otherwise a new loop will be created including all cloned blocks, and the |
| 289 | /// iterator of it switches to count NewIter down to 0. |
| 290 | /// The cloned blocks should be inserted between InsertTop and InsertBot. |
| 291 | /// If loop structure is cloned InsertTop should be new preheader, InsertBot |
| 292 | /// new loop exit. |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 293 | /// Return the new cloned loop that is created when CreateRemainderLoop is true. |
| 294 | static Loop * |
| 295 | CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop, |
| 296 | const bool UseEpilogRemainder, BasicBlock *InsertTop, |
| 297 | BasicBlock *InsertBot, BasicBlock *Preheader, |
| 298 | std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, |
| 299 | ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 300 | StringRef suffix = UseEpilogRemainder ? "epil" : "prol"; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 301 | BasicBlock *Header = L->getHeader(); |
| 302 | BasicBlock *Latch = L->getLoopLatch(); |
| 303 | Function *F = Header->getParent(); |
| 304 | LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); |
| 305 | LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 306 | Loop *ParentLoop = L->getParentLoop(); |
Florian Hahn | 4f9d6d5 | 2017-01-10 23:43:35 +0000 | [diff] [blame] | 307 | NewLoopsMap NewLoops; |
Florian Hahn | 5364cf3 | 2017-01-31 11:13:44 +0000 | [diff] [blame] | 308 | NewLoops[ParentLoop] = ParentLoop; |
| 309 | if (!CreateRemainderLoop) |
Michael Kuperstein | 5dd55e8 | 2017-01-26 01:04:11 +0000 | [diff] [blame] | 310 | NewLoops[L] = ParentLoop; |
| 311 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 312 | // For each block in the original loop, create a new copy, |
| 313 | // and update the value map with the newly created values. |
| 314 | for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 315 | BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 316 | NewBlocks.push_back(NewBB); |
Florian Hahn | 5364cf3 | 2017-01-31 11:13:44 +0000 | [diff] [blame] | 317 | |
Michael Kuperstein | 5dd55e8 | 2017-01-26 01:04:11 +0000 | [diff] [blame] | 318 | // If we're unrolling the outermost loop, there's no remainder loop, |
| 319 | // and this block isn't in a nested loop, then the new block is not |
| 320 | // in any loop. Otherwise, add it to loopinfo. |
| 321 | if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop) |
Florian Hahn | 4f9d6d5 | 2017-01-10 23:43:35 +0000 | [diff] [blame] | 322 | addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 323 | |
| 324 | VMap[*BB] = NewBB; |
| 325 | if (Header == *BB) { |
| 326 | // For the first block, add a CFG connection to this newly |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 327 | // created block. |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 328 | InsertTop->getTerminator()->setSuccessor(0, NewBB); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 329 | } |
Junmo Park | 502ff66 | 2016-01-28 01:23:18 +0000 | [diff] [blame] | 330 | |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 331 | if (DT) { |
| 332 | if (Header == *BB) { |
| 333 | // The header is dominated by the preheader. |
| 334 | DT->addNewBlock(NewBB, InsertTop); |
| 335 | } else { |
| 336 | // Copy information from original loop to unrolled loop. |
| 337 | BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock(); |
| 338 | DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB])); |
| 339 | } |
| 340 | } |
| 341 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 342 | if (Latch == *BB) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 343 | // For the last block, if CreateRemainderLoop is false, create a direct |
| 344 | // jump to InsertBot. If not, create a loop back to cloned head. |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 345 | VMap.erase((*BB)->getTerminator()); |
| 346 | BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]); |
| 347 | BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator()); |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 348 | IRBuilder<> Builder(LatchBR); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 349 | if (!CreateRemainderLoop) { |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 350 | Builder.CreateBr(InsertBot); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 351 | } else { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 352 | PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, |
| 353 | suffix + ".iter", |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 354 | FirstLoopBB->getFirstNonPHI()); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 355 | Value *IdxSub = |
| 356 | Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), |
| 357 | NewIdx->getName() + ".sub"); |
| 358 | Value *IdxCmp = |
| 359 | Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp"); |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 360 | Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 361 | NewIdx->addIncoming(NewIter, InsertTop); |
| 362 | NewIdx->addIncoming(IdxSub, NewBB); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 363 | } |
Alexey Samsonov | ea20199 | 2015-06-11 18:25:44 +0000 | [diff] [blame] | 364 | LatchBR->eraseFromParent(); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 365 | } |
| 366 | } |
| 367 | |
| 368 | // Change the incoming values to the ones defined in the preheader or |
| 369 | // cloned loop. |
| 370 | for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 371 | PHINode *NewPHI = cast<PHINode>(VMap[&*I]); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 372 | if (!CreateRemainderLoop) { |
| 373 | if (UseEpilogRemainder) { |
| 374 | unsigned idx = NewPHI->getBasicBlockIndex(Preheader); |
| 375 | NewPHI->setIncomingBlock(idx, InsertTop); |
| 376 | NewPHI->removeIncomingValue(Latch, false); |
| 377 | } else { |
| 378 | VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader); |
| 379 | cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); |
| 380 | } |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 381 | } else { |
| 382 | unsigned idx = NewPHI->getBasicBlockIndex(Preheader); |
| 383 | NewPHI->setIncomingBlock(idx, InsertTop); |
| 384 | BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); |
| 385 | idx = NewPHI->getBasicBlockIndex(Latch); |
| 386 | Value *InVal = NewPHI->getIncomingValue(idx); |
| 387 | NewPHI->setIncomingBlock(idx, NewLatch); |
Duncan P. N. Exon Smith | a71301b | 2016-04-17 19:26:49 +0000 | [diff] [blame] | 388 | if (Value *V = VMap.lookup(InVal)) |
| 389 | NewPHI->setIncomingValue(idx, V); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 390 | } |
| 391 | } |
Florian Hahn | 5364cf3 | 2017-01-31 11:13:44 +0000 | [diff] [blame] | 392 | if (CreateRemainderLoop) { |
| 393 | Loop *NewLoop = NewLoops[L]; |
| 394 | assert(NewLoop && "L should have been cloned"); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 395 | // Add unroll disable metadata to disable future unrolling for this loop. |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 396 | SmallVector<Metadata *, 4> MDs; |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 397 | // Reserve first location for self reference to the LoopID metadata node. |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 398 | MDs.push_back(nullptr); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 399 | MDNode *LoopID = NewLoop->getLoopID(); |
| 400 | if (LoopID) { |
| 401 | // First remove any existing loop unrolling metadata. |
| 402 | for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { |
| 403 | bool IsUnrollMetadata = false; |
| 404 | MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); |
| 405 | if (MD) { |
| 406 | const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); |
| 407 | IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 408 | } |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 409 | if (!IsUnrollMetadata) |
| 410 | MDs.push_back(LoopID->getOperand(i)); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 411 | } |
| 412 | } |
| 413 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 414 | LLVMContext &Context = NewLoop->getHeader()->getContext(); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 415 | SmallVector<Metadata *, 1> DisableOperands; |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 416 | DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); |
| 417 | MDNode *DisableNode = MDNode::get(Context, DisableOperands); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 418 | MDs.push_back(DisableNode); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 419 | |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 420 | MDNode *NewLoopID = MDNode::get(Context, MDs); |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 421 | // Set operand 0 to refer to the loop id itself. |
| 422 | NewLoopID->replaceOperandWith(0, NewLoopID); |
| 423 | NewLoop->setLoopID(NewLoopID); |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 424 | return NewLoop; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 425 | } |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 426 | else |
| 427 | return nullptr; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 428 | } |
| 429 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 430 | /// Insert code in the prolog/epilog code when unrolling a loop with a |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 431 | /// run-time trip-count. |
| 432 | /// |
| 433 | /// This method assumes that the loop unroll factor is total number |
Justin Lebar | 6086c6a | 2016-02-12 21:01:37 +0000 | [diff] [blame] | 434 | /// of loop bodies in the loop after unrolling. (Some folks refer |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 435 | /// to the unroll factor as the number of *extra* copies added). |
| 436 | /// We assume also that the loop unroll factor is a power-of-two. So, after |
| 437 | /// unrolling the loop, the number of loop bodies executed is 2, |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 438 | /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 439 | /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for |
| 440 | /// the switch instruction is generated. |
| 441 | /// |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 442 | /// ***Prolog case*** |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 443 | /// extraiters = tripcount % loopfactor |
| 444 | /// if (extraiters == 0) jump Loop: |
Evgeny Stupachenko | 8788048 | 2016-04-08 20:20:38 +0000 | [diff] [blame] | 445 | /// else jump Prol: |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 446 | /// Prol: LoopBody; |
| 447 | /// extraiters -= 1 // Omitted if unroll factor is 2. |
| 448 | /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2. |
Evgeny Stupachenko | 8788048 | 2016-04-08 20:20:38 +0000 | [diff] [blame] | 449 | /// if (tripcount < loopfactor) jump End: |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 450 | /// Loop: |
| 451 | /// ... |
| 452 | /// End: |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 453 | /// |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 454 | /// ***Epilog case*** |
| 455 | /// extraiters = tripcount % loopfactor |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 456 | /// if (tripcount < loopfactor) jump LoopExit: |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 457 | /// unroll_iters = tripcount - extraiters |
| 458 | /// Loop: LoopBody; (executes unroll_iter times); |
| 459 | /// unroll_iter -= 1 |
| 460 | /// if (unroll_iter != 0) jump Loop: |
| 461 | /// LoopExit: |
| 462 | /// if (extraiters == 0) jump EpilExit: |
| 463 | /// Epil: LoopBody; (executes extraiters times) |
| 464 | /// extraiters -= 1 // Omitted if unroll factor is 2. |
| 465 | /// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2. |
| 466 | /// EpilExit: |
| 467 | |
| 468 | bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, |
| 469 | bool AllowExpensiveTripCount, |
| 470 | bool UseEpilogRemainder, |
| 471 | LoopInfo *LI, ScalarEvolution *SE, |
| 472 | DominatorTree *DT, bool PreserveLCSSA) { |
Anna Thomas | 5526a33 | 2017-07-11 17:16:33 +0000 | [diff] [blame] | 473 | bool hasMultipleExitingBlocks = !L->getExitingBlock(); |
| 474 | // Support only single exiting block unless UnrollRuntimeMultiExit is true. |
| 475 | if (!UnrollRuntimeMultiExit && hasMultipleExitingBlocks) |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 476 | return false; |
| 477 | |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 478 | // Make sure the loop is in canonical form. |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 479 | if (!L->isLoopSimplifyForm()) |
| 480 | return false; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 481 | |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 482 | // Guaranteed by LoopSimplifyForm. |
| 483 | BasicBlock *Latch = L->getLoopLatch(); |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 484 | BasicBlock *Header = L->getHeader(); |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 485 | |
| 486 | BasicBlock *LatchExit = L->getUniqueExitBlock(); // successor out of loop |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 487 | if (!LatchExit && !UnrollRuntimeMultiExit) |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 488 | return false; |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 489 | // These are exit blocks other than the target of the latch exiting block. |
| 490 | SmallVector<BasicBlock *, 4> OtherExits; |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 491 | BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator()); |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 492 | unsigned int ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0; |
| 493 | // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the |
| 494 | // targets of the Latch be an exit block out of the loop. This needs |
| 495 | // to be guaranteed by the callers of UnrollRuntimeLoopRemainder. |
| 496 | assert(!L->contains(LatchBR->getSuccessor(ExitIndex)) && |
| 497 | "one of the loop latch successors should be the exit block!"); |
| 498 | // Support runtime unrolling for multiple exit blocks and multiple exiting |
| 499 | // blocks. |
| 500 | if (!LatchExit) { |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 501 | LatchExit = LatchBR->getSuccessor(ExitIndex); |
| 502 | // We rely on LCSSA form being preserved when the exit blocks are |
| 503 | // transformed. |
| 504 | if (!PreserveLCSSA) |
| 505 | return false; |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 506 | SmallVector<BasicBlock *, 4> Exits; |
| 507 | L->getUniqueExitBlocks(Exits); |
| 508 | for (auto *BB : Exits) |
| 509 | if (BB != LatchExit) |
| 510 | OtherExits.push_back(BB); |
| 511 | } |
| 512 | |
| 513 | assert(LatchExit && "Latch Exit should exist!"); |
| 514 | |
Anna Thomas | eb6d5d1 | 2017-07-06 18:39:26 +0000 | [diff] [blame] | 515 | // TODO: Support multiple exiting blocks jumping to the `LatchExit` when |
| 516 | // UnrollRuntimeMultiExit is true. This will need updating the logic in |
| 517 | // connectEpilog. |
| 518 | if (!LatchExit->getSinglePredecessor()) |
| 519 | return false; |
Anna Thomas | 5526a33 | 2017-07-11 17:16:33 +0000 | [diff] [blame] | 520 | // FIXME: We bail out of multi-exit unrolling when epilog loop is generated |
| 521 | // and L is an inner loop. This is because in presence of multiple exits, the |
| 522 | // outer loop is incorrect: we do not add the EpilogPreheader and exit to the |
| 523 | // outer loop. This is automatically handled in the prolog case, so we do not |
| 524 | // have that bug in prolog generation. |
| 525 | if (hasMultipleExitingBlocks && UseEpilogRemainder && L->getParentLoop()) |
| 526 | return false; |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 527 | // Use Scalar Evolution to compute the trip count. This allows more loops to |
| 528 | // be unrolled than relying on induction var simplification. |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 529 | if (!SE) |
Andrew Trick | d29cd73 | 2012-05-08 02:52:09 +0000 | [diff] [blame] | 530 | return false; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 531 | |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 532 | // Only unroll loops with a computable trip count, and the trip count needs |
| 533 | // to be an int value (allowing a pointer type is a TODO item). |
Anna Thomas | dc935a6 | 2017-06-27 14:14:35 +0000 | [diff] [blame] | 534 | // We calculate the backedge count by using getExitCount on the Latch block, |
| 535 | // which is proven to be the only exiting block in this loop. This is same as |
| 536 | // calculating getBackedgeTakenCount on the loop (which computes SCEV for all |
| 537 | // exiting blocks). |
| 538 | const SCEV *BECountSC = SE->getExitCount(L, Latch); |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 539 | if (isa<SCEVCouldNotCompute>(BECountSC) || |
| 540 | !BECountSC->getType()->isIntegerTy()) |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 541 | return false; |
| 542 | |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 543 | unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth(); |
Michael Zolotukhin | 0dcae71 | 2014-11-20 20:19:55 +0000 | [diff] [blame] | 544 | |
Sanjay Patel | e08381a | 2016-02-08 19:27:33 +0000 | [diff] [blame] | 545 | // Add 1 since the backedge count doesn't include the first loop iteration. |
Jakub Staszak | 1b1d523 | 2011-12-18 21:52:30 +0000 | [diff] [blame] | 546 | const SCEV *TripCountSC = |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 547 | SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1)); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 548 | if (isa<SCEVCouldNotCompute>(TripCountSC)) |
| 549 | return false; |
| 550 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 551 | BasicBlock *PreHeader = L->getLoopPreheader(); |
| 552 | BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); |
Sanjoy Das | e178f46 | 2015-04-14 03:20:38 +0000 | [diff] [blame] | 553 | const DataLayout &DL = Header->getModule()->getDataLayout(); |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 554 | SCEVExpander Expander(*SE, DL, "loop-unroll"); |
Junmo Park | 6ebdc14 | 2016-02-16 06:46:58 +0000 | [diff] [blame] | 555 | if (!AllowExpensiveTripCount && |
| 556 | Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) |
Sanjoy Das | e178f46 | 2015-04-14 03:20:38 +0000 | [diff] [blame] | 557 | return false; |
| 558 | |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 559 | // This constraint lets us deal with an overflowing trip count easily; see the |
Sanjoy Das | 71190fe | 2015-04-12 01:24:01 +0000 | [diff] [blame] | 560 | // comment on ModVal below. |
| 561 | if (Log2_32(Count) > BEWidth) |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 562 | return false; |
| 563 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 564 | // Loop structure is the following: |
| 565 | // |
| 566 | // PreHeader |
| 567 | // Header |
| 568 | // ... |
| 569 | // Latch |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 570 | // LatchExit |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 571 | |
| 572 | BasicBlock *NewPreHeader; |
| 573 | BasicBlock *NewExit = nullptr; |
| 574 | BasicBlock *PrologExit = nullptr; |
| 575 | BasicBlock *EpilogPreHeader = nullptr; |
| 576 | BasicBlock *PrologPreHeader = nullptr; |
| 577 | |
| 578 | if (UseEpilogRemainder) { |
| 579 | // If epilog remainder |
| 580 | // Split PreHeader to insert a branch around loop for unrolling. |
| 581 | NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI); |
| 582 | NewPreHeader->setName(PreHeader->getName() + ".new"); |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 583 | // Split LatchExit to create phi nodes from branch above. |
| 584 | SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit)); |
| 585 | NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa", |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 586 | DT, LI, PreserveLCSSA); |
| 587 | // Split NewExit to insert epilog remainder loop. |
| 588 | EpilogPreHeader = SplitBlock(NewExit, NewExit->getTerminator(), DT, LI); |
| 589 | EpilogPreHeader->setName(Header->getName() + ".epil.preheader"); |
| 590 | } else { |
| 591 | // If prolog remainder |
| 592 | // Split the original preheader twice to insert prolog remainder loop |
| 593 | PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI); |
| 594 | PrologPreHeader->setName(Header->getName() + ".prol.preheader"); |
| 595 | PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(), |
| 596 | DT, LI); |
| 597 | PrologExit->setName(Header->getName() + ".prol.loopexit"); |
| 598 | // Split PrologExit to get NewPreHeader. |
| 599 | NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI); |
| 600 | NewPreHeader->setName(PreHeader->getName() + ".new"); |
| 601 | } |
| 602 | // Loop structure should be the following: |
| 603 | // Epilog Prolog |
| 604 | // |
| 605 | // PreHeader PreHeader |
| 606 | // *NewPreHeader *PrologPreHeader |
| 607 | // Header *PrologExit |
| 608 | // ... *NewPreHeader |
| 609 | // Latch Header |
| 610 | // *NewExit ... |
| 611 | // *EpilogPreHeader Latch |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 612 | // LatchExit LatchExit |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 613 | |
| 614 | // Calculate conditions for branch around loop for unrolling |
| 615 | // in epilog case and around prolog remainder loop in prolog case. |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 616 | // Compute the number of extra iterations required, which is: |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 617 | // extra iterations = run-time trip count % loop unroll factor |
| 618 | PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 619 | Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(), |
| 620 | PreHeaderBR); |
Sanjoy Das | 11b279a | 2015-02-18 19:32:25 +0000 | [diff] [blame] | 621 | Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(), |
| 622 | PreHeaderBR); |
Benjamin Kramer | 0bf086f | 2014-06-21 13:46:25 +0000 | [diff] [blame] | 623 | IRBuilder<> B(PreHeaderBR); |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 624 | Value *ModVal; |
| 625 | // Calculate ModVal = (BECount + 1) % Count. |
| 626 | // Note that TripCount is BECount + 1. |
| 627 | if (isPowerOf2_32(Count)) { |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 628 | // When Count is power of 2 we don't BECount for epilog case, however we'll |
| 629 | // need it for a branch around unrolling loop for prolog case. |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 630 | ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter"); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 631 | // 1. There are no iterations to be run in the prolog/epilog loop. |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 632 | // OR |
| 633 | // 2. The addition computing TripCount overflowed. |
| 634 | // |
| 635 | // If (2) is true, we know that TripCount really is (1 << BEWidth) and so |
| 636 | // the number of iterations that remain to be run in the original loop is a |
| 637 | // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we |
| 638 | // explicitly check this above). |
| 639 | } else { |
| 640 | // As (BECount + 1) can potentially unsigned overflow we count |
| 641 | // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count. |
| 642 | Value *ModValTmp = B.CreateURem(BECount, |
| 643 | ConstantInt::get(BECount->getType(), |
| 644 | Count)); |
| 645 | Value *ModValAdd = B.CreateAdd(ModValTmp, |
| 646 | ConstantInt::get(ModValTmp->getType(), 1)); |
| 647 | // At that point (BECount % Count) + 1 could be equal to Count. |
| 648 | // To handle this case we need to take mod by Count one more time. |
| 649 | ModVal = B.CreateURem(ModValAdd, |
| 650 | ConstantInt::get(BECount->getType(), Count), |
| 651 | "xtraiter"); |
| 652 | } |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 653 | Value *BranchVal = |
| 654 | UseEpilogRemainder ? B.CreateICmpULT(BECount, |
| 655 | ConstantInt::get(BECount->getType(), |
| 656 | Count - 1)) : |
| 657 | B.CreateIsNotNull(ModVal, "lcmp.mod"); |
| 658 | BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader; |
| 659 | BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit; |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 660 | // Branch to either remainder (extra iterations) loop or unrolling loop. |
Evgeny Stupachenko | 23ce61b | 2016-04-27 03:04:54 +0000 | [diff] [blame] | 661 | B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 662 | PreHeaderBR->eraseFromParent(); |
Eli Friedman | 0a21745 | 2017-01-18 23:26:37 +0000 | [diff] [blame] | 663 | if (DT) { |
| 664 | if (UseEpilogRemainder) |
| 665 | DT->changeImmediateDominator(NewExit, PreHeader); |
| 666 | else |
| 667 | DT->changeImmediateDominator(PrologExit, PreHeader); |
| 668 | } |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 669 | Function *F = Header->getParent(); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 670 | // Get an ordered list of blocks in the loop to help with the ordering of the |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 671 | // cloned blocks in the prolog/epilog code |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 672 | LoopBlocksDFS LoopBlocks(L); |
| 673 | LoopBlocks.perform(LI); |
| 674 | |
| 675 | // |
| 676 | // For each extra loop iteration, create a copy of the loop's basic blocks |
| 677 | // and generate a condition that branches to the copy depending on the |
| 678 | // number of 'left over' iterations. |
| 679 | // |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 680 | std::vector<BasicBlock *> NewBlocks; |
| 681 | ValueToValueMapTy VMap; |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 682 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 683 | // For unroll factor 2 remainder loop will have 1 iterations. |
| 684 | // Do not create 1 iteration loop. |
| 685 | bool CreateRemainderLoop = (Count != 2); |
Michael Zolotukhin | 0dcae71 | 2014-11-20 20:19:55 +0000 | [diff] [blame] | 686 | |
Kevin Qin | fc02e3c | 2014-09-29 11:15:00 +0000 | [diff] [blame] | 687 | // Clone all the basic blocks in the loop. If Count is 2, we don't clone |
| 688 | // the loop, otherwise we create a cloned loop to execute the extra |
| 689 | // iterations. This function adds the appropriate CFG connections. |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 690 | BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit; |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 691 | BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader; |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 692 | Loop *remainderLoop = CloneLoopBlocks( |
| 693 | L, ModVal, CreateRemainderLoop, UseEpilogRemainder, InsertTop, InsertBot, |
| 694 | NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 695 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 696 | // Insert the cloned blocks into the function. |
| 697 | F->getBasicBlockList().splice(InsertBot->getIterator(), |
| 698 | F->getBasicBlockList(), |
| 699 | NewBlocks[0]->getIterator(), |
| 700 | F->end()); |
| 701 | |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 702 | // Now the loop blocks are cloned and the other exiting blocks from the |
| 703 | // remainder are connected to the original Loop's exit blocks. The remaining |
| 704 | // work is to update the phi nodes in the original loop, and take in the |
| 705 | // values from the cloned region. Also update the dominator info for |
| 706 | // OtherExits, since we have new edges into OtherExits. |
| 707 | for (auto *BB : OtherExits) { |
| 708 | for (auto &II : *BB) { |
| 709 | |
| 710 | // Given we preserve LCSSA form, we know that the values used outside the |
| 711 | // loop will be used through these phi nodes at the exit blocks that are |
| 712 | // transformed below. |
| 713 | if (!isa<PHINode>(II)) |
| 714 | break; |
| 715 | PHINode *Phi = cast<PHINode>(&II); |
| 716 | unsigned oldNumOperands = Phi->getNumIncomingValues(); |
| 717 | // Add the incoming values from the remainder code to the end of the phi |
| 718 | // node. |
| 719 | for (unsigned i =0; i < oldNumOperands; i++){ |
| 720 | Value *newVal = VMap[Phi->getIncomingValue(i)]; |
Anna Thomas | 70ffd65 | 2017-07-10 15:29:38 +0000 | [diff] [blame] | 721 | // newVal can be a constant or derived from values outside the loop, and |
| 722 | // hence need not have a VMap value. |
| 723 | if (!newVal) |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 724 | newVal = Phi->getIncomingValue(i); |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 725 | Phi->addIncoming(newVal, |
| 726 | cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)])); |
| 727 | } |
| 728 | } |
| 729 | // Update the dominator info because the immediate dominator is no longer the |
| 730 | // header of the original Loop. BB has edges both from L and remainder code. |
| 731 | // Since the preheader determines which loop is run (L or directly jump to |
| 732 | // the remainder code), we set the immediate dominator as the preheader. |
| 733 | if (DT) |
| 734 | DT->changeImmediateDominator(BB, PreHeader); |
| 735 | } |
| 736 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 737 | // Loop structure should be the following: |
| 738 | // Epilog Prolog |
| 739 | // |
| 740 | // PreHeader PreHeader |
| 741 | // NewPreHeader PrologPreHeader |
| 742 | // Header PrologHeader |
| 743 | // ... ... |
| 744 | // Latch PrologLatch |
| 745 | // NewExit PrologExit |
| 746 | // EpilogPreHeader NewPreHeader |
| 747 | // EpilogHeader Header |
| 748 | // ... ... |
| 749 | // EpilogLatch Latch |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 750 | // LatchExit LatchExit |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 751 | |
Sanjay Patel | 4d36bba | 2016-02-08 21:32:43 +0000 | [diff] [blame] | 752 | // Rewrite the cloned instruction operands to use the values created when the |
| 753 | // clone is created. |
| 754 | for (BasicBlock *BB : NewBlocks) { |
| 755 | for (Instruction &I : *BB) { |
| 756 | RemapInstruction(&I, VMap, |
Duncan P. N. Exon Smith | da68cbc | 2016-04-07 00:26:43 +0000 | [diff] [blame] | 757 | RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 758 | } |
| 759 | } |
| 760 | |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 761 | if (UseEpilogRemainder) { |
| 762 | // Connect the epilog code to the original loop and update the |
| 763 | // PHI functions. |
Anna Thomas | 91eed9a | 2017-06-23 14:28:01 +0000 | [diff] [blame] | 764 | ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader, |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 765 | EpilogPreHeader, NewPreHeader, VMap, DT, LI, |
| 766 | PreserveLCSSA); |
| 767 | |
| 768 | // Update counter in loop for unrolling. |
| 769 | // I should be multiply of Count. |
| 770 | IRBuilder<> B2(NewPreHeader->getTerminator()); |
| 771 | Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter"); |
| 772 | BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator()); |
| 773 | B2.SetInsertPoint(LatchBR); |
| 774 | PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter", |
| 775 | Header->getFirstNonPHI()); |
| 776 | Value *IdxSub = |
| 777 | B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), |
| 778 | NewIdx->getName() + ".nsub"); |
| 779 | Value *IdxCmp; |
| 780 | if (LatchBR->getSuccessor(0) == Header) |
| 781 | IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp"); |
| 782 | else |
| 783 | IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp"); |
| 784 | NewIdx->addIncoming(TestVal, NewPreHeader); |
| 785 | NewIdx->addIncoming(IdxSub, Latch); |
| 786 | LatchBR->setCondition(IdxCmp); |
| 787 | } else { |
| 788 | // Connect the prolog code to the original loop and update the |
| 789 | // PHI functions. |
Anna Thomas | 734ab3f | 2017-07-07 18:05:28 +0000 | [diff] [blame] | 790 | ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader, |
| 791 | NewPreHeader, VMap, DT, LI, PreserveLCSSA); |
David L Kreitzer | 188de5a | 2016-04-05 12:19:35 +0000 | [diff] [blame] | 792 | } |
Wei Mi | 59ca966 | 2016-08-25 16:17:18 +0000 | [diff] [blame] | 793 | |
| 794 | // If this loop is nested, then the loop unroller changes the code in the |
| 795 | // parent loop, so the Scalar Evolution pass needs to be run again. |
| 796 | if (Loop *ParentLoop = L->getParentLoop()) |
| 797 | SE->forgetLoop(ParentLoop); |
| 798 | |
Anna Thomas | e5e5e59 | 2017-06-30 17:57:07 +0000 | [diff] [blame] | 799 | // Canonicalize to LoopSimplifyForm both original and remainder loops. We |
| 800 | // cannot rely on the LoopUnrollPass to do this because it only does |
| 801 | // canonicalization for parent/subloops and not the sibling loops. |
| 802 | if (OtherExits.size() > 0) { |
| 803 | // Generate dedicated exit blocks for the original loop, to preserve |
| 804 | // LoopSimplifyForm. |
| 805 | formDedicatedExitBlocks(L, DT, LI, PreserveLCSSA); |
| 806 | // Generate dedicated exit blocks for the remainder loop if one exists, to |
| 807 | // preserve LoopSimplifyForm. |
| 808 | if (remainderLoop) |
| 809 | formDedicatedExitBlocks(remainderLoop, DT, LI, PreserveLCSSA); |
| 810 | } |
| 811 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 812 | NumRuntimeUnrolled++; |
| 813 | return true; |
| 814 | } |