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