Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 1 | //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements Loop Rotation Pass. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
Justin Bogner | d0d2341 | 2016-05-03 22:02:31 +0000 | [diff] [blame] | 14 | #include "llvm/Transforms/Scalar/LoopRotation.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | 08eebe2 | 2015-07-23 09:34:01 +0000 | [diff] [blame] | 16 | #include "llvm/Analysis/AliasAnalysis.h" |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 17 | #include "llvm/Analysis/BasicAliasAnalysis.h" |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/AssumptionCache.h" |
Chris Lattner | 679572e | 2011-01-02 07:35:53 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/CodeMetrics.h" |
Chris Lattner | 8c5defd | 2011-01-08 08:24:46 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/InstructionSimplify.h" |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/GlobalsModRef.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/LoopPass.h" |
Justin Bogner | d0d2341 | 2016-05-03 22:02:31 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/LoopPassManager.h" |
Devang Patel | fac4d1f | 2007-07-11 23:47:28 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/ScalarEvolution.h" |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" |
Chandler Carruth | bb9caa9 | 2013-01-21 13:04:33 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/TargetTransformInfo.h" |
Andrew Trick | 10cc453 | 2012-02-14 00:00:23 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 1305dc3 | 2014-03-04 11:45:46 +0000 | [diff] [blame] | 28 | #include "llvm/IR/CFG.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 29 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 30 | #include "llvm/IR/Function.h" |
| 31 | #include "llvm/IR/IntrinsicInst.h" |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 32 | #include "llvm/IR/Module.h" |
Owen Anderson | 115aa16 | 2014-05-26 08:58:51 +0000 | [diff] [blame] | 33 | #include "llvm/Support/CommandLine.h" |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 34 | #include "llvm/Support/Debug.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 35 | #include "llvm/Support/raw_ostream.h" |
Justin Bogner | d0d2341 | 2016-05-03 22:02:31 +0000 | [diff] [blame] | 36 | #include "llvm/Transforms/Scalar.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 37 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 38 | #include "llvm/Transforms/Utils/Local.h" |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 39 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 40 | #include "llvm/Transforms/Utils/SSAUpdater.h" |
| 41 | #include "llvm/Transforms/Utils/ValueMapper.h" |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 42 | using namespace llvm; |
| 43 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 44 | #define DEBUG_TYPE "loop-rotate" |
| 45 | |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 46 | static cl::opt<unsigned> DefaultRotationThreshold( |
| 47 | "rotation-max-header-size", cl::init(16), cl::Hidden, |
| 48 | cl::desc("The default maximum header size for automatic loop rotation")); |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 49 | |
| 50 | STATISTIC(NumRotated, "Number of loops rotated"); |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 51 | |
Benjamin Kramer | 4d09892 | 2016-07-10 11:28:51 +0000 | [diff] [blame] | 52 | namespace { |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 53 | /// A simple loop rotation transformation. |
| 54 | class LoopRotate { |
| 55 | const unsigned MaxHeaderSize; |
| 56 | LoopInfo *LI; |
| 57 | const TargetTransformInfo *TTI; |
| 58 | AssumptionCache *AC; |
| 59 | DominatorTree *DT; |
| 60 | ScalarEvolution *SE; |
| 61 | |
| 62 | public: |
| 63 | LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI, |
| 64 | const TargetTransformInfo *TTI, AssumptionCache *AC, |
| 65 | DominatorTree *DT, ScalarEvolution *SE) |
| 66 | : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE) { |
| 67 | } |
| 68 | bool processLoop(Loop *L); |
| 69 | |
| 70 | private: |
| 71 | bool rotateLoop(Loop *L, bool SimplifiedLatch); |
| 72 | bool simplifyLoopLatch(Loop *L); |
| 73 | }; |
Benjamin Kramer | 4d09892 | 2016-07-10 11:28:51 +0000 | [diff] [blame] | 74 | } // end anonymous namespace |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 75 | |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 76 | /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the |
| 77 | /// old header into the preheader. If there were uses of the values produced by |
| 78 | /// these instruction that were outside of the loop, we have to insert PHI nodes |
| 79 | /// to merge the two values. Do this now. |
| 80 | static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, |
| 81 | BasicBlock *OrigPreheader, |
| 82 | ValueToValueMapTy &ValueMap) { |
| 83 | // Remove PHI node entries that are no longer live. |
| 84 | BasicBlock::iterator I, E = OrigHeader->end(); |
| 85 | for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I) |
| 86 | PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader)); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 87 | |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 88 | // Now fix up users of the instructions in OrigHeader, inserting PHI nodes |
| 89 | // as necessary. |
| 90 | SSAUpdater SSA; |
| 91 | for (I = OrigHeader->begin(); I != E; ++I) { |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 92 | Value *OrigHeaderVal = &*I; |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 93 | |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 94 | // If there are no uses of the value (e.g. because it returns void), there |
| 95 | // is nothing to rewrite. |
| 96 | if (OrigHeaderVal->use_empty()) |
| 97 | continue; |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 98 | |
Duncan P. N. Exon Smith | a71301b | 2016-04-17 19:26:49 +0000 | [diff] [blame] | 99 | Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal); |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 100 | |
| 101 | // The value now exits in two versions: the initial value in the preheader |
| 102 | // and the loop "next" value in the original header. |
| 103 | SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName()); |
| 104 | SSA.AddAvailableValue(OrigHeader, OrigHeaderVal); |
| 105 | SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 106 | |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 107 | // Visit each use of the OrigHeader instruction. |
| 108 | for (Value::use_iterator UI = OrigHeaderVal->use_begin(), |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 109 | UE = OrigHeaderVal->use_end(); |
| 110 | UI != UE;) { |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 111 | // Grab the use before incrementing the iterator. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 112 | Use &U = *UI; |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 113 | |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 114 | // Increment the iterator before removing the use from the list. |
| 115 | ++UI; |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 116 | |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 117 | // SSAUpdater can't handle a non-PHI use in the same block as an |
| 118 | // earlier def. We can easily handle those cases manually. |
| 119 | Instruction *UserInst = cast<Instruction>(U.getUser()); |
| 120 | if (!isa<PHINode>(UserInst)) { |
| 121 | BasicBlock *UserBB = UserInst->getParent(); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 122 | |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 123 | // The original users in the OrigHeader are already using the |
| 124 | // original definitions. |
| 125 | if (UserBB == OrigHeader) |
| 126 | continue; |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 127 | |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 128 | // Users in the OrigPreHeader need to use the value to which the |
| 129 | // original definitions are mapped. |
| 130 | if (UserBB == OrigPreheader) { |
| 131 | U = OrigPreHeaderVal; |
| 132 | continue; |
| 133 | } |
| 134 | } |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 135 | |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 136 | // Anything else can be handled by SSAUpdater. |
| 137 | SSA.RewriteUse(U); |
| 138 | } |
Chuang-Yu Cheng | 175741d | 2016-05-10 09:45:44 +0000 | [diff] [blame] | 139 | |
| 140 | // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug |
| 141 | // intrinsics. |
| 142 | LLVMContext &C = OrigHeader->getContext(); |
| 143 | if (auto *VAM = ValueAsMetadata::getIfExists(OrigHeaderVal)) { |
| 144 | if (auto *MAV = MetadataAsValue::getIfExists(C, VAM)) { |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 145 | for (auto UI = MAV->use_begin(), E = MAV->use_end(); UI != E;) { |
Chuang-Yu Cheng | 175741d | 2016-05-10 09:45:44 +0000 | [diff] [blame] | 146 | // Grab the use before incrementing the iterator. Otherwise, altering |
| 147 | // the Use will invalidate the iterator. |
| 148 | Use &U = *UI++; |
| 149 | DbgInfoIntrinsic *UserInst = dyn_cast<DbgInfoIntrinsic>(U.getUser()); |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 150 | if (!UserInst) |
| 151 | continue; |
Chuang-Yu Cheng | 175741d | 2016-05-10 09:45:44 +0000 | [diff] [blame] | 152 | |
| 153 | // The original users in the OrigHeader are already using the original |
| 154 | // definitions. |
| 155 | BasicBlock *UserBB = UserInst->getParent(); |
| 156 | if (UserBB == OrigHeader) |
| 157 | continue; |
| 158 | |
| 159 | // Users in the OrigPreHeader need to use the value to which the |
| 160 | // original definitions are mapped and anything else can be handled by |
| 161 | // the SSAUpdater. To avoid adding PHINodes, check if the value is |
| 162 | // available in UserBB, if not substitute undef. |
| 163 | Value *NewVal; |
| 164 | if (UserBB == OrigPreheader) |
| 165 | NewVal = OrigPreHeaderVal; |
| 166 | else if (SSA.HasValueForBlock(UserBB)) |
| 167 | NewVal = SSA.GetValueInMiddleOfBlock(UserBB); |
| 168 | else |
| 169 | NewVal = UndefValue::get(OrigHeaderVal->getType()); |
| 170 | U = MetadataAsValue::get(C, ValueAsMetadata::get(NewVal)); |
| 171 | } |
| 172 | } |
| 173 | } |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 174 | } |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 175 | } |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 176 | |
Dan Gohman | b5650eb | 2007-05-11 21:10:54 +0000 | [diff] [blame] | 177 | /// Rotate loop LP. Return true if the loop is rotated. |
Andrew Trick | 9c72b07 | 2013-05-06 17:58:18 +0000 | [diff] [blame] | 178 | /// |
| 179 | /// \param SimplifiedLatch is true if the latch was just folded into the final |
| 180 | /// loop exit. In this case we may want to rotate even though the new latch is |
| 181 | /// now an exiting branch. This rotation would have happened had the latch not |
| 182 | /// been simplified. However, if SimplifiedLatch is false, then we avoid |
| 183 | /// rotating loops in which the latch exits to avoid excessive or endless |
| 184 | /// rotation. LoopRotate should be repeatable and converge to a canonical |
| 185 | /// form. This property is satisfied because simplifying the loop latch can only |
| 186 | /// happen once across multiple invocations of the LoopRotate pass. |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 187 | bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) { |
Dan Gohman | 091e440 | 2009-06-25 00:22:44 +0000 | [diff] [blame] | 188 | // If the loop has only one block then there is not much to rotate. |
Devang Patel | 88bc2c6 | 2007-04-09 16:11:48 +0000 | [diff] [blame] | 189 | if (L->getBlocks().size() == 1) |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 190 | return false; |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 191 | |
Chris Lattner | 7fab23b | 2011-01-08 18:06:22 +0000 | [diff] [blame] | 192 | BasicBlock *OrigHeader = L->getHeader(); |
Benjamin Kramer | afdfdb5 | 2012-08-30 15:39:42 +0000 | [diff] [blame] | 193 | BasicBlock *OrigLatch = L->getLoopLatch(); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 194 | |
Chris Lattner | 7fab23b | 2011-01-08 18:06:22 +0000 | [diff] [blame] | 195 | BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 196 | if (!BI || BI->isUnconditional()) |
Chris Lattner | 7fab23b | 2011-01-08 18:06:22 +0000 | [diff] [blame] | 197 | return false; |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 198 | |
Dan Gohman | 091e440 | 2009-06-25 00:22:44 +0000 | [diff] [blame] | 199 | // If the loop header is not one of the loop exiting blocks then |
| 200 | // either this loop is already rotated or it is not |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 201 | // suitable for loop rotation transformations. |
Dan Gohman | 8f4078b | 2009-10-24 23:34:26 +0000 | [diff] [blame] | 202 | if (!L->isLoopExiting(OrigHeader)) |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 203 | return false; |
| 204 | |
Benjamin Kramer | afdfdb5 | 2012-08-30 15:39:42 +0000 | [diff] [blame] | 205 | // If the loop latch already contains a branch that leaves the loop then the |
| 206 | // loop is already rotated. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 207 | if (!OrigLatch) |
Andrew Trick | 9c72b07 | 2013-05-06 17:58:18 +0000 | [diff] [blame] | 208 | return false; |
| 209 | |
| 210 | // Rotate if either the loop latch does *not* exit the loop, or if the loop |
| 211 | // latch was just simplified. |
| 212 | if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch) |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 213 | return false; |
| 214 | |
James Molloy | 4f6fb95 | 2012-12-20 16:04:27 +0000 | [diff] [blame] | 215 | // Check size of original header and reject loop if it is very big or we can't |
| 216 | // duplicate blocks inside it. |
Chris Lattner | 679572e | 2011-01-02 07:35:53 +0000 | [diff] [blame] | 217 | { |
Hal Finkel | 57f03dd | 2014-09-07 13:49:57 +0000 | [diff] [blame] | 218 | SmallPtrSet<const Value *, 32> EphValues; |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 219 | CodeMetrics::collectEphemeralValues(L, AC, EphValues); |
Hal Finkel | 57f03dd | 2014-09-07 13:49:57 +0000 | [diff] [blame] | 220 | |
Chris Lattner | 679572e | 2011-01-02 07:35:53 +0000 | [diff] [blame] | 221 | CodeMetrics Metrics; |
Hal Finkel | 57f03dd | 2014-09-07 13:49:57 +0000 | [diff] [blame] | 222 | Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues); |
James Molloy | 4f6fb95 | 2012-12-20 16:04:27 +0000 | [diff] [blame] | 223 | if (Metrics.notDuplicatable) { |
Alp Toker | f907b89 | 2013-12-05 05:44:44 +0000 | [diff] [blame] | 224 | DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable" |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 225 | << " instructions: "; |
| 226 | L->dump()); |
James Molloy | 4f6fb95 | 2012-12-20 16:04:27 +0000 | [diff] [blame] | 227 | return false; |
| 228 | } |
Justin Lebar | df04d2a | 2016-02-12 21:01:33 +0000 | [diff] [blame] | 229 | if (Metrics.convergent) { |
| 230 | DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent " |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 231 | "instructions: "; |
| 232 | L->dump()); |
Justin Lebar | df04d2a | 2016-02-12 21:01:33 +0000 | [diff] [blame] | 233 | return false; |
| 234 | } |
Owen Anderson | 115aa16 | 2014-05-26 08:58:51 +0000 | [diff] [blame] | 235 | if (Metrics.NumInsts > MaxHeaderSize) |
Chris Lattner | 679572e | 2011-01-02 07:35:53 +0000 | [diff] [blame] | 236 | return false; |
Devang Patel | bab43b4 | 2009-03-06 03:51:30 +0000 | [diff] [blame] | 237 | } |
| 238 | |
Devang Patel | fac4d1f | 2007-07-11 23:47:28 +0000 | [diff] [blame] | 239 | // Now, this loop is suitable for rotation. |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 240 | BasicBlock *OrigPreheader = L->getLoopPreheader(); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 241 | |
Chris Lattner | 88974f4 | 2011-04-09 07:25:58 +0000 | [diff] [blame] | 242 | // If the loop could not be converted to canonical form, it must have an |
| 243 | // indirectbr in it, just give up. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 244 | if (!OrigPreheader) |
Chris Lattner | 88974f4 | 2011-04-09 07:25:58 +0000 | [diff] [blame] | 245 | return false; |
Devang Patel | fac4d1f | 2007-07-11 23:47:28 +0000 | [diff] [blame] | 246 | |
Dan Gohman | fc20b67 | 2009-09-27 15:37:03 +0000 | [diff] [blame] | 247 | // Anything ScalarEvolution may know about this loop or the PHI nodes |
| 248 | // in its header will soon be invalidated. |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 249 | if (SE) |
| 250 | SE->forgetLoop(L); |
Dan Gohman | fc20b67 | 2009-09-27 15:37:03 +0000 | [diff] [blame] | 251 | |
Benjamin Kramer | afdfdb5 | 2012-08-30 15:39:42 +0000 | [diff] [blame] | 252 | DEBUG(dbgs() << "LoopRotation: rotating "; L->dump()); |
| 253 | |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 254 | // Find new Loop header. NewHeader is a Header's one and only successor |
Chris Lattner | 57cb472 | 2009-01-26 01:57:01 +0000 | [diff] [blame] | 255 | // that is inside loop. Header's other successor is outside the |
| 256 | // loop. Otherwise loop is not suitable for rotation. |
Chris Lattner | 385f2ec | 2011-01-08 17:48:33 +0000 | [diff] [blame] | 257 | BasicBlock *Exit = BI->getSuccessor(0); |
| 258 | BasicBlock *NewHeader = BI->getSuccessor(1); |
Devang Patel | 88bc2c6 | 2007-04-09 16:11:48 +0000 | [diff] [blame] | 259 | if (L->contains(Exit)) |
| 260 | std::swap(Exit, NewHeader); |
Chris Lattner | d67aaa6 | 2009-01-26 01:38:24 +0000 | [diff] [blame] | 261 | assert(NewHeader && "Unable to determine new loop header"); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 262 | assert(L->contains(NewHeader) && !L->contains(Exit) && |
Devang Patel | 88bc2c6 | 2007-04-09 16:11:48 +0000 | [diff] [blame] | 263 | "Unable to determine loop header and exit blocks"); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 264 | |
Dan Gohman | 091e440 | 2009-06-25 00:22:44 +0000 | [diff] [blame] | 265 | // This code assumes that the new header has exactly one predecessor. |
| 266 | // Remove any single-entry PHI nodes in it. |
Chris Lattner | 7b6647c | 2009-01-26 02:11:30 +0000 | [diff] [blame] | 267 | assert(NewHeader->getSinglePredecessor() && |
| 268 | "New header doesn't have one pred!"); |
| 269 | FoldSingleEntryPHINodes(NewHeader); |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 270 | |
Dan Gohman | b979794 | 2009-10-24 23:19:52 +0000 | [diff] [blame] | 271 | // Begin by walking OrigHeader and populating ValueMap with an entry for |
| 272 | // each Instruction. |
Devang Patel | 88bc2c6 | 2007-04-09 16:11:48 +0000 | [diff] [blame] | 273 | BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end(); |
Chris Lattner | 2b3f20e | 2011-01-08 07:21:31 +0000 | [diff] [blame] | 274 | ValueToValueMapTy ValueMap; |
Devang Patel | b9af574 | 2007-04-09 19:04:21 +0000 | [diff] [blame] | 275 | |
Dan Gohman | b979794 | 2009-10-24 23:19:52 +0000 | [diff] [blame] | 276 | // For PHI nodes, the value available in OldPreHeader is just the |
| 277 | // incoming value from OldPreHeader. |
| 278 | for (; PHINode *PN = dyn_cast<PHINode>(I); ++I) |
Jay Foad | 372ad64 | 2011-06-20 14:18:48 +0000 | [diff] [blame] | 279 | ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader); |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 280 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 281 | const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); |
| 282 | |
Chris Lattner | b01c24a | 2010-09-06 01:10:22 +0000 | [diff] [blame] | 283 | // For the rest of the instructions, either hoist to the OrigPreheader if |
| 284 | // possible or create a clone in the OldPreHeader if not. |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 285 | TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator(); |
Chris Lattner | b01c24a | 2010-09-06 01:10:22 +0000 | [diff] [blame] | 286 | while (I != E) { |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 287 | Instruction *Inst = &*I++; |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 288 | |
Chris Lattner | b01c24a | 2010-09-06 01:10:22 +0000 | [diff] [blame] | 289 | // If the instruction's operands are invariant and it doesn't read or write |
| 290 | // memory, then it is safe to hoist. Doing this doesn't change the order of |
| 291 | // execution in the preheader, but does prevent the instruction from |
| 292 | // executing in each iteration of the loop. This means it is safe to hoist |
| 293 | // something that might trap, but isn't safe to hoist something that reads |
| 294 | // memory (without proving that the loop doesn't write). |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 295 | if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() && |
| 296 | !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) && |
| 297 | !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) { |
Chris Lattner | b01c24a | 2010-09-06 01:10:22 +0000 | [diff] [blame] | 298 | Inst->moveBefore(LoopEntryBranch); |
| 299 | continue; |
| 300 | } |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 301 | |
Chris Lattner | b01c24a | 2010-09-06 01:10:22 +0000 | [diff] [blame] | 302 | // Otherwise, create a duplicate of the instruction. |
| 303 | Instruction *C = Inst->clone(); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 304 | |
Chris Lattner | 8c5defd | 2011-01-08 08:24:46 +0000 | [diff] [blame] | 305 | // Eagerly remap the operands of the instruction. |
| 306 | RemapInstruction(C, ValueMap, |
Duncan P. N. Exon Smith | da68cbc | 2016-04-07 00:26:43 +0000 | [diff] [blame] | 307 | RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 308 | |
Chris Lattner | 8c5defd | 2011-01-08 08:24:46 +0000 | [diff] [blame] | 309 | // With the operands remapped, see if the instruction constant folds or is |
| 310 | // otherwise simplifyable. This commonly occurs because the entry from PHI |
| 311 | // nodes allows icmps and other instructions to fold. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 312 | // FIXME: Provide TLI, DT, AC to SimplifyInstruction. |
| 313 | Value *V = SimplifyInstruction(C, DL); |
Chris Lattner | 25ba40a | 2011-01-08 17:38:45 +0000 | [diff] [blame] | 314 | if (V && LI->replacementPreservesLCSSAForm(C, V)) { |
Chris Lattner | 8c5defd | 2011-01-08 08:24:46 +0000 | [diff] [blame] | 315 | // If so, then delete the temporary instruction and stick the folded value |
| 316 | // in the map. |
Chris Lattner | 8c5defd | 2011-01-08 08:24:46 +0000 | [diff] [blame] | 317 | ValueMap[Inst] = V; |
David Majnemer | b8da3a2 | 2016-06-25 00:04:10 +0000 | [diff] [blame] | 318 | if (!C->mayHaveSideEffects()) { |
| 319 | delete C; |
| 320 | C = nullptr; |
| 321 | } |
Chris Lattner | 8c5defd | 2011-01-08 08:24:46 +0000 | [diff] [blame] | 322 | } else { |
David Majnemer | b8da3a2 | 2016-06-25 00:04:10 +0000 | [diff] [blame] | 323 | ValueMap[Inst] = C; |
| 324 | } |
| 325 | if (C) { |
Chris Lattner | 8c5defd | 2011-01-08 08:24:46 +0000 | [diff] [blame] | 326 | // Otherwise, stick the new instruction into the new block! |
| 327 | C->setName(Inst->getName()); |
| 328 | C->insertBefore(LoopEntryBranch); |
Chris Lattner | 8c5defd | 2011-01-08 08:24:46 +0000 | [diff] [blame] | 329 | } |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 330 | } |
| 331 | |
Dan Gohman | b979794 | 2009-10-24 23:19:52 +0000 | [diff] [blame] | 332 | // Along with all the other instructions, we just cloned OrigHeader's |
| 333 | // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's |
| 334 | // successors by duplicating their incoming values for OrigHeader. |
| 335 | TerminatorInst *TI = OrigHeader->getTerminator(); |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 336 | for (BasicBlock *SuccBB : TI->successors()) |
| 337 | for (BasicBlock::iterator BI = SuccBB->begin(); |
Dan Gohman | b979794 | 2009-10-24 23:19:52 +0000 | [diff] [blame] | 338 | PHINode *PN = dyn_cast<PHINode>(BI); ++BI) |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 339 | PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader); |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 340 | |
Dan Gohman | b979794 | 2009-10-24 23:19:52 +0000 | [diff] [blame] | 341 | // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove |
| 342 | // OrigPreHeader's old terminator (the original branch into the loop), and |
| 343 | // remove the corresponding incoming values from the PHI nodes in OrigHeader. |
| 344 | LoopEntryBranch->eraseFromParent(); |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 345 | |
Chris Lattner | 30f318e | 2011-01-08 19:26:33 +0000 | [diff] [blame] | 346 | // If there were any uses of instructions in the duplicated block outside the |
| 347 | // loop, update them, inserting PHI nodes as required |
| 348 | RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap); |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 349 | |
Dan Gohman | b979794 | 2009-10-24 23:19:52 +0000 | [diff] [blame] | 350 | // NewHeader is now the header of the loop. |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 351 | L->moveToHeader(NewHeader); |
Chris Lattner | 2615130 | 2011-01-08 19:10:28 +0000 | [diff] [blame] | 352 | assert(L->getHeader() == NewHeader && "Latch block is our new header"); |
Devang Patel | f42389f | 2007-04-07 01:25:15 +0000 | [diff] [blame] | 353 | |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 354 | // At this point, we've finished our major CFG changes. As part of cloning |
| 355 | // the loop into the preheader we've simplified instructions and the |
| 356 | // duplicated conditional branch may now be branching on a constant. If it is |
| 357 | // branching on a constant and if that constant means that we enter the loop, |
| 358 | // then we fold away the cond branch to an uncond branch. This simplifies the |
| 359 | // loop in cases important for nested loops, and it also means we don't have |
| 360 | // to split as many edges. |
| 361 | BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator()); |
| 362 | assert(PHBI->isConditional() && "Should be clone of BI condbr!"); |
| 363 | if (!isa<ConstantInt>(PHBI->getCondition()) || |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 364 | PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) != |
| 365 | NewHeader) { |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 366 | // The conditional branch can't be folded, handle the general case. |
| 367 | // Update DominatorTree to reflect the CFG change we just made. Then split |
| 368 | // edges as necessary to preserve LoopSimplify form. |
Chandler Carruth | 9420909 | 2015-01-18 02:08:05 +0000 | [diff] [blame] | 369 | if (DT) { |
Benjamin Kramer | afdfdb5 | 2012-08-30 15:39:42 +0000 | [diff] [blame] | 370 | // Everything that was dominated by the old loop header is now dominated |
| 371 | // by the original loop preheader. Conceptually the header was merged |
| 372 | // into the preheader, even though we reuse the actual block as a new |
| 373 | // loop latch. |
Chandler Carruth | 9420909 | 2015-01-18 02:08:05 +0000 | [diff] [blame] | 374 | DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader); |
Benjamin Kramer | afdfdb5 | 2012-08-30 15:39:42 +0000 | [diff] [blame] | 375 | SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(), |
| 376 | OrigHeaderNode->end()); |
Chandler Carruth | 9420909 | 2015-01-18 02:08:05 +0000 | [diff] [blame] | 377 | DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader); |
Benjamin Kramer | afdfdb5 | 2012-08-30 15:39:42 +0000 | [diff] [blame] | 378 | for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) |
Chandler Carruth | 9420909 | 2015-01-18 02:08:05 +0000 | [diff] [blame] | 379 | DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 380 | |
Chandler Carruth | 9420909 | 2015-01-18 02:08:05 +0000 | [diff] [blame] | 381 | assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode); |
| 382 | assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode); |
Benjamin Kramer | 3be6a48 | 2012-09-01 12:04:51 +0000 | [diff] [blame] | 383 | |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 384 | // Update OrigHeader to be dominated by the new header block. |
Chandler Carruth | 9420909 | 2015-01-18 02:08:05 +0000 | [diff] [blame] | 385 | DT->changeImmediateDominator(OrigHeader, OrigLatch); |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 386 | } |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 387 | |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 388 | // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 389 | // thus is not a preheader anymore. |
| 390 | // Split the edge to form a real preheader. |
Chandler Carruth | 37df2cf | 2015-01-19 12:09:11 +0000 | [diff] [blame] | 391 | BasicBlock *NewPH = SplitCriticalEdge( |
| 392 | OrigPreheader, NewHeader, |
| 393 | CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA()); |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 394 | NewPH->setName(NewHeader->getName() + ".lr.ph"); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 395 | |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 396 | // Preserve canonical loop form, which means that 'Exit' should have only |
Chandler Carruth | d4be9dc | 2014-01-29 13:16:53 +0000 | [diff] [blame] | 397 | // one predecessor. Note that Exit could be an exit block for multiple |
| 398 | // nested loops, causing both of the edges to now be critical and need to |
| 399 | // be split. |
| 400 | SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit)); |
| 401 | bool SplitLatchEdge = false; |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 402 | for (BasicBlock *ExitPred : ExitPreds) { |
Chandler Carruth | d4be9dc | 2014-01-29 13:16:53 +0000 | [diff] [blame] | 403 | // We only need to split loop exit edges. |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 404 | Loop *PredLoop = LI->getLoopFor(ExitPred); |
Chandler Carruth | d4be9dc | 2014-01-29 13:16:53 +0000 | [diff] [blame] | 405 | if (!PredLoop || PredLoop->contains(Exit)) |
| 406 | continue; |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 407 | if (isa<IndirectBrInst>(ExitPred->getTerminator())) |
Benjamin Kramer | 911d5b3 | 2015-02-20 20:49:25 +0000 | [diff] [blame] | 408 | continue; |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 409 | SplitLatchEdge |= L->getLoopLatch() == ExitPred; |
Chandler Carruth | 37df2cf | 2015-01-19 12:09:11 +0000 | [diff] [blame] | 410 | BasicBlock *ExitSplit = SplitCriticalEdge( |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 411 | ExitPred, Exit, |
| 412 | CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA()); |
Chandler Carruth | d4be9dc | 2014-01-29 13:16:53 +0000 | [diff] [blame] | 413 | ExitSplit->moveBefore(Exit); |
| 414 | } |
| 415 | assert(SplitLatchEdge && |
| 416 | "Despite splitting all preds, failed to split latch exit?"); |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 417 | } else { |
| 418 | // We can fold the conditional branch in the preheader, this makes things |
| 419 | // simpler. The first step is to remove the extra edge to the Exit block. |
| 420 | Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/); |
Devang Patel | c1f7c1d | 2011-04-29 20:38:55 +0000 | [diff] [blame] | 421 | BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI); |
| 422 | NewBI->setDebugLoc(PHBI->getDebugLoc()); |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 423 | PHBI->eraseFromParent(); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 424 | |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 425 | // With our CFG finalized, update DomTree if it is available. |
Chandler Carruth | 9420909 | 2015-01-18 02:08:05 +0000 | [diff] [blame] | 426 | if (DT) { |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 427 | // Update OrigHeader to be dominated by the new header block. |
Chandler Carruth | 9420909 | 2015-01-18 02:08:05 +0000 | [diff] [blame] | 428 | DT->changeImmediateDominator(NewHeader, OrigPreheader); |
| 429 | DT->changeImmediateDominator(OrigHeader, OrigLatch); |
Benjamin Kramer | afdfdb5 | 2012-08-30 15:39:42 +0000 | [diff] [blame] | 430 | |
| 431 | // Brute force incremental dominator tree update. Call |
| 432 | // findNearestCommonDominator on all CFG predecessors of each child of the |
| 433 | // original header. |
Chandler Carruth | 9420909 | 2015-01-18 02:08:05 +0000 | [diff] [blame] | 434 | DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader); |
Benjamin Kramer | 599a4bb | 2012-09-02 11:57:22 +0000 | [diff] [blame] | 435 | SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(), |
| 436 | OrigHeaderNode->end()); |
| 437 | bool Changed; |
| 438 | do { |
| 439 | Changed = false; |
| 440 | for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) { |
| 441 | DomTreeNode *Node = HeaderChildren[I]; |
| 442 | BasicBlock *BB = Node->getBlock(); |
Benjamin Kramer | afdfdb5 | 2012-08-30 15:39:42 +0000 | [diff] [blame] | 443 | |
Benjamin Kramer | 599a4bb | 2012-09-02 11:57:22 +0000 | [diff] [blame] | 444 | pred_iterator PI = pred_begin(BB); |
| 445 | BasicBlock *NearestDom = *PI; |
| 446 | for (pred_iterator PE = pred_end(BB); PI != PE; ++PI) |
Chandler Carruth | 9420909 | 2015-01-18 02:08:05 +0000 | [diff] [blame] | 447 | NearestDom = DT->findNearestCommonDominator(NearestDom, *PI); |
Benjamin Kramer | 599a4bb | 2012-09-02 11:57:22 +0000 | [diff] [blame] | 448 | |
| 449 | // Remember if this changes the DomTree. |
| 450 | if (Node->getIDom()->getBlock() != NearestDom) { |
Chandler Carruth | 9420909 | 2015-01-18 02:08:05 +0000 | [diff] [blame] | 451 | DT->changeImmediateDominator(BB, NearestDom); |
Benjamin Kramer | 599a4bb | 2012-09-02 11:57:22 +0000 | [diff] [blame] | 452 | Changed = true; |
Benjamin Kramer | afdfdb5 | 2012-08-30 15:39:42 +0000 | [diff] [blame] | 453 | } |
Benjamin Kramer | afdfdb5 | 2012-08-30 15:39:42 +0000 | [diff] [blame] | 454 | } |
| 455 | |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 456 | // If the dominator changed, this may have an effect on other |
| 457 | // predecessors, continue until we reach a fixpoint. |
Benjamin Kramer | 599a4bb | 2012-09-02 11:57:22 +0000 | [diff] [blame] | 458 | } while (Changed); |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 459 | } |
Devang Patel | fac4d1f | 2007-07-11 23:47:28 +0000 | [diff] [blame] | 460 | } |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 461 | |
Chris Lattner | 59c82f8 | 2011-01-08 19:59:06 +0000 | [diff] [blame] | 462 | assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation"); |
Chris Lattner | 063dca0 | 2011-01-08 18:52:51 +0000 | [diff] [blame] | 463 | assert(L->getLoopLatch() && "Invalid loop latch after loop rotation"); |
Chris Lattner | fee37c5 | 2011-01-08 18:55:50 +0000 | [diff] [blame] | 464 | |
Chris Lattner | 63fe78d | 2011-01-11 07:47:59 +0000 | [diff] [blame] | 465 | // Now that the CFG and DomTree are in a consistent state again, try to merge |
| 466 | // the OrigHeader block into OrigLatch. This will succeed if they are |
| 467 | // connected by an unconditional branch. This is just a cleanup so the |
| 468 | // emitted code isn't too gross in this common case. |
Chandler Carruth | b5c1153 | 2015-01-18 02:11:23 +0000 | [diff] [blame] | 469 | MergeBlockIntoPredecessor(OrigHeader, DT, LI); |
Andrew Trick | a20f198 | 2012-02-14 00:00:19 +0000 | [diff] [blame] | 470 | |
Benjamin Kramer | afdfdb5 | 2012-08-30 15:39:42 +0000 | [diff] [blame] | 471 | DEBUG(dbgs() << "LoopRotation: into "; L->dump()); |
| 472 | |
Chris Lattner | fee37c5 | 2011-01-08 18:55:50 +0000 | [diff] [blame] | 473 | ++NumRotated; |
| 474 | return true; |
Devang Patel | 8541978 | 2007-04-09 20:19:46 +0000 | [diff] [blame] | 475 | } |
Justin Bogner | a730045 | 2015-12-14 23:22:44 +0000 | [diff] [blame] | 476 | |
| 477 | /// Determine whether the instructions in this range may be safely and cheaply |
| 478 | /// speculated. This is not an important enough situation to develop complex |
| 479 | /// heuristics. We handle a single arithmetic instruction along with any type |
| 480 | /// conversions. |
| 481 | static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, |
| 482 | BasicBlock::iterator End, Loop *L) { |
| 483 | bool seenIncrement = false; |
| 484 | bool MultiExitLoop = false; |
| 485 | |
| 486 | if (!L->getExitingBlock()) |
| 487 | MultiExitLoop = true; |
| 488 | |
| 489 | for (BasicBlock::iterator I = Begin; I != End; ++I) { |
| 490 | |
| 491 | if (!isSafeToSpeculativelyExecute(&*I)) |
| 492 | return false; |
| 493 | |
| 494 | if (isa<DbgInfoIntrinsic>(I)) |
| 495 | continue; |
| 496 | |
| 497 | switch (I->getOpcode()) { |
| 498 | default: |
| 499 | return false; |
| 500 | case Instruction::GetElementPtr: |
| 501 | // GEPs are cheap if all indices are constant. |
| 502 | if (!cast<GEPOperator>(I)->hasAllConstantIndices()) |
| 503 | return false; |
Justin Bogner | b03fd12 | 2016-08-17 05:10:15 +0000 | [diff] [blame^] | 504 | // fall-thru to increment case |
| 505 | LLVM_FALLTHROUGH; |
Justin Bogner | a730045 | 2015-12-14 23:22:44 +0000 | [diff] [blame] | 506 | case Instruction::Add: |
| 507 | case Instruction::Sub: |
| 508 | case Instruction::And: |
| 509 | case Instruction::Or: |
| 510 | case Instruction::Xor: |
| 511 | case Instruction::Shl: |
| 512 | case Instruction::LShr: |
| 513 | case Instruction::AShr: { |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 514 | Value *IVOpnd = |
| 515 | !isa<Constant>(I->getOperand(0)) |
| 516 | ? I->getOperand(0) |
| 517 | : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr; |
Justin Bogner | a730045 | 2015-12-14 23:22:44 +0000 | [diff] [blame] | 518 | if (!IVOpnd) |
| 519 | return false; |
| 520 | |
| 521 | // If increment operand is used outside of the loop, this speculation |
| 522 | // could cause extra live range interference. |
| 523 | if (MultiExitLoop) { |
| 524 | for (User *UseI : IVOpnd->users()) { |
| 525 | auto *UserInst = cast<Instruction>(UseI); |
| 526 | if (!L->contains(UserInst)) |
| 527 | return false; |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | if (seenIncrement) |
| 532 | return false; |
| 533 | seenIncrement = true; |
| 534 | break; |
| 535 | } |
| 536 | case Instruction::Trunc: |
| 537 | case Instruction::ZExt: |
| 538 | case Instruction::SExt: |
| 539 | // ignore type conversions |
| 540 | break; |
| 541 | } |
| 542 | } |
| 543 | return true; |
| 544 | } |
| 545 | |
| 546 | /// Fold the loop tail into the loop exit by speculating the loop tail |
| 547 | /// instructions. Typically, this is a single post-increment. In the case of a |
| 548 | /// simple 2-block loop, hoisting the increment can be much better than |
| 549 | /// duplicating the entire loop header. In the case of loops with early exits, |
| 550 | /// rotation will not work anyway, but simplifyLoopLatch will put the loop in |
| 551 | /// canonical form so downstream passes can handle it. |
| 552 | /// |
| 553 | /// I don't believe this invalidates SCEV. |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 554 | bool LoopRotate::simplifyLoopLatch(Loop *L) { |
Justin Bogner | a730045 | 2015-12-14 23:22:44 +0000 | [diff] [blame] | 555 | BasicBlock *Latch = L->getLoopLatch(); |
| 556 | if (!Latch || Latch->hasAddressTaken()) |
| 557 | return false; |
| 558 | |
| 559 | BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator()); |
| 560 | if (!Jmp || !Jmp->isUnconditional()) |
| 561 | return false; |
| 562 | |
| 563 | BasicBlock *LastExit = Latch->getSinglePredecessor(); |
| 564 | if (!LastExit || !L->isLoopExiting(LastExit)) |
| 565 | return false; |
| 566 | |
| 567 | BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator()); |
| 568 | if (!BI) |
| 569 | return false; |
| 570 | |
| 571 | if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L)) |
| 572 | return false; |
| 573 | |
| 574 | DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into " |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 575 | << LastExit->getName() << "\n"); |
Justin Bogner | a730045 | 2015-12-14 23:22:44 +0000 | [diff] [blame] | 576 | |
| 577 | // Hoist the instructions from Latch into LastExit. |
| 578 | LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(), |
| 579 | Latch->begin(), Jmp->getIterator()); |
| 580 | |
| 581 | unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1; |
| 582 | BasicBlock *Header = Jmp->getSuccessor(0); |
| 583 | assert(Header == L->getHeader() && "expected a backward branch"); |
| 584 | |
| 585 | // Remove Latch from the CFG so that LastExit becomes the new Latch. |
| 586 | BI->setSuccessor(FallThruPath, Header); |
| 587 | Latch->replaceSuccessorsPhiUsesWith(LastExit); |
| 588 | Jmp->eraseFromParent(); |
| 589 | |
| 590 | // Nuke the Latch block. |
| 591 | assert(Latch->empty() && "unable to evacuate Latch"); |
| 592 | LI->removeBlock(Latch); |
| 593 | if (DT) |
| 594 | DT->eraseNode(Latch); |
| 595 | Latch->eraseFromParent(); |
| 596 | return true; |
| 597 | } |
| 598 | |
Michael Zolotukhin | b98294d | 2016-06-10 22:03:56 +0000 | [diff] [blame] | 599 | /// Rotate \c L, and return true if any modification was made. |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 600 | bool LoopRotate::processLoop(Loop *L) { |
Justin Bogner | a730045 | 2015-12-14 23:22:44 +0000 | [diff] [blame] | 601 | // Save the loop metadata. |
| 602 | MDNode *LoopMD = L->getLoopID(); |
| 603 | |
Justin Bogner | a730045 | 2015-12-14 23:22:44 +0000 | [diff] [blame] | 604 | // Simplify the loop latch before attempting to rotate the header |
| 605 | // upward. Rotation may not be needed if the loop tail can be folded into the |
| 606 | // loop exit. |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 607 | bool SimplifiedLatch = simplifyLoopLatch(L); |
Justin Bogner | a730045 | 2015-12-14 23:22:44 +0000 | [diff] [blame] | 608 | |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 609 | bool MadeChange = rotateLoop(L, SimplifiedLatch); |
Michael Zolotukhin | b98294d | 2016-06-10 22:03:56 +0000 | [diff] [blame] | 610 | assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) && |
| 611 | "Loop latch should be exiting after loop-rotate."); |
Justin Bogner | a730045 | 2015-12-14 23:22:44 +0000 | [diff] [blame] | 612 | |
| 613 | // Restore the loop metadata. |
| 614 | // NB! We presume LoopRotation DOESN'T ADD its own metadata. |
| 615 | if ((MadeChange || SimplifiedLatch) && LoopMD) |
| 616 | L->setLoopID(LoopMD); |
| 617 | |
| 618 | return MadeChange; |
| 619 | } |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 620 | |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 621 | LoopRotatePass::LoopRotatePass() {} |
Justin Bogner | d0d2341 | 2016-05-03 22:02:31 +0000 | [diff] [blame] | 622 | |
Sean Silva | 0746f3b | 2016-08-09 00:28:52 +0000 | [diff] [blame] | 623 | PreservedAnalyses LoopRotatePass::run(Loop &L, LoopAnalysisManager &AM) { |
Justin Bogner | d0d2341 | 2016-05-03 22:02:31 +0000 | [diff] [blame] | 624 | auto &FAM = AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager(); |
| 625 | Function *F = L.getHeader()->getParent(); |
| 626 | |
| 627 | auto *LI = FAM.getCachedResult<LoopAnalysis>(*F); |
| 628 | const auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F); |
| 629 | auto *AC = FAM.getCachedResult<AssumptionAnalysis>(*F); |
| 630 | assert((LI && TTI && AC) && "Analyses for loop rotation not available"); |
| 631 | |
| 632 | // Optional analyses. |
| 633 | auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F); |
| 634 | auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F); |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 635 | LoopRotate LR(DefaultRotationThreshold, LI, TTI, AC, DT, SE); |
Justin Bogner | d0d2341 | 2016-05-03 22:02:31 +0000 | [diff] [blame] | 636 | |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 637 | bool Changed = LR.processLoop(&L); |
Justin Bogner | d0d2341 | 2016-05-03 22:02:31 +0000 | [diff] [blame] | 638 | if (!Changed) |
| 639 | return PreservedAnalyses::all(); |
| 640 | return getLoopPassPreservedAnalyses(); |
| 641 | } |
| 642 | |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 643 | namespace { |
| 644 | |
Justin Bogner | d0d2341 | 2016-05-03 22:02:31 +0000 | [diff] [blame] | 645 | class LoopRotateLegacyPass : public LoopPass { |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 646 | unsigned MaxHeaderSize; |
| 647 | |
| 648 | public: |
| 649 | static char ID; // Pass ID, replacement for typeid |
Justin Bogner | d0d2341 | 2016-05-03 22:02:31 +0000 | [diff] [blame] | 650 | LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) { |
| 651 | initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry()); |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 652 | if (SpecifiedMaxHeaderSize == -1) |
| 653 | MaxHeaderSize = DefaultRotationThreshold; |
| 654 | else |
| 655 | MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize); |
| 656 | } |
| 657 | |
| 658 | // LCSSA form makes instruction renaming easier. |
| 659 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 660 | AU.addRequired<AssumptionCacheTracker>(); |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 661 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 662 | getLoopAnalysisUsage(AU); |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 663 | } |
| 664 | |
| 665 | bool runOnLoop(Loop *L, LPPassManager &LPM) override { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 666 | if (skipLoop(L)) |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 667 | return false; |
| 668 | Function &F = *L->getHeader()->getParent(); |
| 669 | |
| 670 | auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
| 671 | const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
| 672 | auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); |
| 673 | auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); |
| 674 | auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; |
| 675 | auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); |
| 676 | auto *SE = SEWP ? &SEWP->getSE() : nullptr; |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 677 | LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE); |
| 678 | return LR.processLoop(L); |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 679 | } |
| 680 | }; |
| 681 | } |
| 682 | |
Justin Bogner | d0d2341 | 2016-05-03 22:02:31 +0000 | [diff] [blame] | 683 | char LoopRotateLegacyPass::ID = 0; |
| 684 | INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", |
| 685 | false, false) |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 686 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 687 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
| 688 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Sebastian Pop | dfb66a1 | 2016-06-14 14:44:05 +0000 | [diff] [blame] | 689 | INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false, |
| 690 | false) |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 691 | |
| 692 | Pass *llvm::createLoopRotatePass(int MaxHeaderSize) { |
Justin Bogner | d0d2341 | 2016-05-03 22:02:31 +0000 | [diff] [blame] | 693 | return new LoopRotateLegacyPass(MaxHeaderSize); |
Justin Bogner | 6291b58 | 2015-12-14 23:22:48 +0000 | [diff] [blame] | 694 | } |