blob: fde6bacb4921659f6aa3b3f3f2a63b63b2562700 [file] [log] [blame]
Devang Patelc4625da2007-04-07 01:25:15 +00001//===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Devang Patelc4625da2007-04-07 01:25:15 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Rotation Pass.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel32231332007-04-09 16:11:48 +000014#define DEBUG_TYPE "loop-rotate"
Devang Patelc4625da2007-04-07 01:25:15 +000015#include "llvm/Transforms/Scalar.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/ADT/Statistic.h"
Chris Lattnerd9e07972011-01-02 07:35:53 +000017#include "llvm/Analysis/CodeMetrics.h"
Chris Lattnerd9ec3572011-01-08 08:24:46 +000018#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000019#include "llvm/Analysis/LoopPass.h"
Devang Patel990e8662007-07-11 23:47:28 +000020#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carrutha5157e62013-01-21 13:04:33 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Andrew Trickf6629ab2012-02-14 00:00:23 +000022#include "llvm/Analysis/ValueTracking.h"
Stephen Hines36b56882014-04-23 16:57:46 -070023#include "llvm/IR/CFG.h"
24#include "llvm/IR/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000025#include "llvm/IR/Function.h"
26#include "llvm/IR/IntrinsicInst.h"
Devang Patelc4625da2007-04-07 01:25:15 +000027#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000028#include "llvm/Transforms/Utils/BasicBlockUtils.h"
29#include "llvm/Transforms/Utils/Local.h"
30#include "llvm/Transforms/Utils/SSAUpdater.h"
31#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelc4625da2007-04-07 01:25:15 +000032using namespace llvm;
33
34#define MAX_HEADER_SIZE 16
35
36STATISTIC(NumRotated, "Number of loops rotated");
37namespace {
38
Chris Lattner3e8b6632009-09-02 06:11:42 +000039 class LoopRotate : public LoopPass {
Devang Patelc4625da2007-04-07 01:25:15 +000040 public:
Devang Patel19974732007-05-03 01:11:54 +000041 static char ID; // Pass ID, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000042 LoopRotate() : LoopPass(ID) {
43 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
44 }
Devang Patel794fd752007-05-01 21:15:47 +000045
Devang Patel32231332007-04-09 16:11:48 +000046 // LCSSA form makes instruction renaming easier.
Stephen Hines36b56882014-04-23 16:57:46 -070047 void getAnalysisUsage(AnalysisUsage &AU) const override {
48 AU.addPreserved<DominatorTreeWrapperPass>();
Dan Gohman1e381fc2010-07-16 17:58:45 +000049 AU.addRequired<LoopInfo>();
50 AU.addPreserved<LoopInfo>();
Devang Patel9d9b2042008-02-15 01:24:49 +000051 AU.addRequiredID(LoopSimplifyID);
52 AU.addPreservedID(LoopSimplifyID);
Devang Patelc4625da2007-04-07 01:25:15 +000053 AU.addRequiredID(LCSSAID);
54 AU.addPreservedID(LCSSAID);
Devang Patel990e8662007-07-11 23:47:28 +000055 AU.addPreserved<ScalarEvolution>();
Chandler Carrutha5157e62013-01-21 13:04:33 +000056 AU.addRequired<TargetTransformInfo>();
Devang Patelc4625da2007-04-07 01:25:15 +000057 }
58
Stephen Hines36b56882014-04-23 16:57:46 -070059 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Andrew Trickfcf79522013-05-06 17:58:18 +000060 bool simplifyLoopLatch(Loop *L);
61 bool rotateLoop(Loop *L, bool SimplifiedLatch);
Andrew Trickc3a825b2012-02-14 00:00:19 +000062
Devang Patelc4625da2007-04-07 01:25:15 +000063 private:
Chris Lattner012ca942011-01-08 17:38:45 +000064 LoopInfo *LI;
Chandler Carrutha5157e62013-01-21 13:04:33 +000065 const TargetTransformInfo *TTI;
Devang Patelc4625da2007-04-07 01:25:15 +000066 };
Devang Patelc4625da2007-04-07 01:25:15 +000067}
Andrew Trickc3a825b2012-02-14 00:00:19 +000068
Dan Gohman844731a2008-05-13 00:00:25 +000069char LoopRotate::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000070INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Chandler Carrutha5157e62013-01-21 13:04:33 +000071INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +000072INITIALIZE_PASS_DEPENDENCY(LoopInfo)
73INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
74INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +000075INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelc4625da2007-04-07 01:25:15 +000076
Daniel Dunbar394f0442008-10-22 23:32:42 +000077Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +000078
Devang Patel32231332007-04-09 16:11:48 +000079/// Rotate Loop L as many times as possible. Return true if
Dan Gohmancc4e6052009-06-25 00:22:44 +000080/// the loop is rotated at least once.
Chris Lattner4aefc9b2011-01-08 17:48:33 +000081bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Stephen Hines36b56882014-04-23 16:57:46 -070082 if (skipOptnoneFunction(L))
83 return false;
84
Chris Lattner012ca942011-01-08 17:38:45 +000085 LI = &getAnalysis<LoopInfo>();
Chandler Carrutha5157e62013-01-21 13:04:33 +000086 TTI = &getAnalysis<TargetTransformInfo>();
Devang Patel990e8662007-07-11 23:47:28 +000087
Andrew Trickf6629ab2012-02-14 00:00:23 +000088 // Simplify the loop latch before attempting to rotate the header
89 // upward. Rotation may not be needed if the loop tail can be folded into the
90 // loop exit.
Andrew Trickfcf79522013-05-06 17:58:18 +000091 bool SimplifiedLatch = simplifyLoopLatch(L);
Andrew Trickf6629ab2012-02-14 00:00:23 +000092
Devang Patelc4625da2007-04-07 01:25:15 +000093 // One loop can be rotated multiple times.
Chris Lattner012ca942011-01-08 17:38:45 +000094 bool MadeChange = false;
Andrew Trickfcf79522013-05-06 17:58:18 +000095 while (rotateLoop(L, SimplifiedLatch)) {
Chris Lattner012ca942011-01-08 17:38:45 +000096 MadeChange = true;
Andrew Trickfcf79522013-05-06 17:58:18 +000097 SimplifiedLatch = false;
98 }
Chris Lattner012ca942011-01-08 17:38:45 +000099 return MadeChange;
Devang Patelc4625da2007-04-07 01:25:15 +0000100}
101
Chris Lattner64c24db2011-01-08 19:26:33 +0000102/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
103/// old header into the preheader. If there were uses of the values produced by
104/// these instruction that were outside of the loop, we have to insert PHI nodes
105/// to merge the two values. Do this now.
106static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
107 BasicBlock *OrigPreheader,
108 ValueToValueMapTy &ValueMap) {
109 // Remove PHI node entries that are no longer live.
110 BasicBlock::iterator I, E = OrigHeader->end();
111 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
112 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Trickc3a825b2012-02-14 00:00:19 +0000113
Chris Lattner64c24db2011-01-08 19:26:33 +0000114 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
115 // as necessary.
116 SSAUpdater SSA;
117 for (I = OrigHeader->begin(); I != E; ++I) {
118 Value *OrigHeaderVal = I;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000119
Chris Lattner64c24db2011-01-08 19:26:33 +0000120 // If there are no uses of the value (e.g. because it returns void), there
121 // is nothing to rewrite.
122 if (OrigHeaderVal->use_empty())
123 continue;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000124
Chris Lattner64c24db2011-01-08 19:26:33 +0000125 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
126
127 // The value now exits in two versions: the initial value in the preheader
128 // and the loop "next" value in the original header.
129 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
130 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
131 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000132
Chris Lattner64c24db2011-01-08 19:26:33 +0000133 // Visit each use of the OrigHeader instruction.
134 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
135 UE = OrigHeaderVal->use_end(); UI != UE; ) {
136 // Grab the use before incrementing the iterator.
Stephen Hines36b56882014-04-23 16:57:46 -0700137 Use &U = *UI;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000138
Chris Lattner64c24db2011-01-08 19:26:33 +0000139 // Increment the iterator before removing the use from the list.
140 ++UI;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000141
Chris Lattner64c24db2011-01-08 19:26:33 +0000142 // SSAUpdater can't handle a non-PHI use in the same block as an
143 // earlier def. We can easily handle those cases manually.
144 Instruction *UserInst = cast<Instruction>(U.getUser());
145 if (!isa<PHINode>(UserInst)) {
146 BasicBlock *UserBB = UserInst->getParent();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000147
Chris Lattner64c24db2011-01-08 19:26:33 +0000148 // The original users in the OrigHeader are already using the
149 // original definitions.
150 if (UserBB == OrigHeader)
151 continue;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000152
Chris Lattner64c24db2011-01-08 19:26:33 +0000153 // Users in the OrigPreHeader need to use the value to which the
154 // original definitions are mapped.
155 if (UserBB == OrigPreheader) {
156 U = OrigPreHeaderVal;
157 continue;
158 }
159 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000160
Chris Lattner64c24db2011-01-08 19:26:33 +0000161 // Anything else can be handled by SSAUpdater.
162 SSA.RewriteUse(U);
163 }
164 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000165}
Chris Lattner64c24db2011-01-08 19:26:33 +0000166
Andrew Trickf6629ab2012-02-14 00:00:23 +0000167/// Determine whether the instructions in this range my be safely and cheaply
168/// speculated. This is not an important enough situation to develop complex
169/// heuristics. We handle a single arithmetic instruction along with any type
170/// conversions.
171static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
172 BasicBlock::iterator End) {
173 bool seenIncrement = false;
174 for (BasicBlock::iterator I = Begin; I != End; ++I) {
175
176 if (!isSafeToSpeculativelyExecute(I))
177 return false;
178
179 if (isa<DbgInfoIntrinsic>(I))
180 continue;
181
182 switch (I->getOpcode()) {
183 default:
184 return false;
185 case Instruction::GetElementPtr:
186 // GEPs are cheap if all indices are constant.
187 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
188 return false;
189 // fall-thru to increment case
190 case Instruction::Add:
191 case Instruction::Sub:
192 case Instruction::And:
193 case Instruction::Or:
194 case Instruction::Xor:
195 case Instruction::Shl:
196 case Instruction::LShr:
197 case Instruction::AShr:
198 if (seenIncrement)
199 return false;
200 seenIncrement = true;
201 break;
202 case Instruction::Trunc:
203 case Instruction::ZExt:
204 case Instruction::SExt:
205 // ignore type conversions
206 break;
207 }
208 }
209 return true;
210}
211
212/// Fold the loop tail into the loop exit by speculating the loop tail
213/// instructions. Typically, this is a single post-increment. In the case of a
214/// simple 2-block loop, hoisting the increment can be much better than
215/// duplicating the entire loop header. In the cast of loops with early exits,
216/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
217/// canonical form so downstream passes can handle it.
218///
219/// I don't believe this invalidates SCEV.
Andrew Trickfcf79522013-05-06 17:58:18 +0000220bool LoopRotate::simplifyLoopLatch(Loop *L) {
Andrew Trickf6629ab2012-02-14 00:00:23 +0000221 BasicBlock *Latch = L->getLoopLatch();
222 if (!Latch || Latch->hasAddressTaken())
Andrew Trickfcf79522013-05-06 17:58:18 +0000223 return false;
Andrew Trickf6629ab2012-02-14 00:00:23 +0000224
225 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
226 if (!Jmp || !Jmp->isUnconditional())
Andrew Trickfcf79522013-05-06 17:58:18 +0000227 return false;
Andrew Trickf6629ab2012-02-14 00:00:23 +0000228
229 BasicBlock *LastExit = Latch->getSinglePredecessor();
230 if (!LastExit || !L->isLoopExiting(LastExit))
Andrew Trickfcf79522013-05-06 17:58:18 +0000231 return false;
Andrew Trickf6629ab2012-02-14 00:00:23 +0000232
233 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
234 if (!BI)
Andrew Trickfcf79522013-05-06 17:58:18 +0000235 return false;
Andrew Trickf6629ab2012-02-14 00:00:23 +0000236
237 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
Andrew Trickfcf79522013-05-06 17:58:18 +0000238 return false;
Andrew Trickf6629ab2012-02-14 00:00:23 +0000239
240 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
241 << LastExit->getName() << "\n");
242
243 // Hoist the instructions from Latch into LastExit.
244 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
245
246 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
247 BasicBlock *Header = Jmp->getSuccessor(0);
248 assert(Header == L->getHeader() && "expected a backward branch");
249
250 // Remove Latch from the CFG so that LastExit becomes the new Latch.
251 BI->setSuccessor(FallThruPath, Header);
252 Latch->replaceSuccessorsPhiUsesWith(LastExit);
253 Jmp->eraseFromParent();
254
255 // Nuke the Latch block.
256 assert(Latch->empty() && "unable to evacuate Latch");
257 LI->removeBlock(Latch);
Stephen Hines36b56882014-04-23 16:57:46 -0700258 if (DominatorTreeWrapperPass *DTWP =
259 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
260 DTWP->getDomTree().eraseNode(Latch);
Andrew Trickf6629ab2012-02-14 00:00:23 +0000261 Latch->eraseFromParent();
Andrew Trickfcf79522013-05-06 17:58:18 +0000262 return true;
Andrew Trickf6629ab2012-02-14 00:00:23 +0000263}
264
Dan Gohman23d9d272007-05-11 21:10:54 +0000265/// Rotate loop LP. Return true if the loop is rotated.
Andrew Trickfcf79522013-05-06 17:58:18 +0000266///
267/// \param SimplifiedLatch is true if the latch was just folded into the final
268/// loop exit. In this case we may want to rotate even though the new latch is
269/// now an exiting branch. This rotation would have happened had the latch not
270/// been simplified. However, if SimplifiedLatch is false, then we avoid
271/// rotating loops in which the latch exits to avoid excessive or endless
272/// rotation. LoopRotate should be repeatable and converge to a canonical
273/// form. This property is satisfied because simplifying the loop latch can only
274/// happen once across multiple invocations of the LoopRotate pass.
275bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
Dan Gohmancc4e6052009-06-25 00:22:44 +0000276 // If the loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000277 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000278 return false;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000279
Chris Lattner2aa69082011-01-08 18:06:22 +0000280 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000281 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000282
Chris Lattner2aa69082011-01-08 18:06:22 +0000283 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
284 if (BI == 0 || BI->isUnconditional())
285 return false;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000286
Dan Gohmancc4e6052009-06-25 00:22:44 +0000287 // If the loop header is not one of the loop exiting blocks then
288 // either this loop is already rotated or it is not
Devang Patelc4625da2007-04-07 01:25:15 +0000289 // suitable for loop rotation transformations.
Dan Gohman32663b72009-10-24 23:34:26 +0000290 if (!L->isLoopExiting(OrigHeader))
Devang Patelc4625da2007-04-07 01:25:15 +0000291 return false;
292
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000293 // If the loop latch already contains a branch that leaves the loop then the
294 // loop is already rotated.
Andrew Trickfcf79522013-05-06 17:58:18 +0000295 if (OrigLatch == 0)
296 return false;
297
298 // Rotate if either the loop latch does *not* exit the loop, or if the loop
299 // latch was just simplified.
300 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
Devang Patelc4625da2007-04-07 01:25:15 +0000301 return false;
302
James Molloy67ae1352012-12-20 16:04:27 +0000303 // Check size of original header and reject loop if it is very big or we can't
304 // duplicate blocks inside it.
Chris Lattnerd9e07972011-01-02 07:35:53 +0000305 {
306 CodeMetrics Metrics;
Chandler Carrutha5157e62013-01-21 13:04:33 +0000307 Metrics.analyzeBasicBlock(OrigHeader, *TTI);
James Molloy67ae1352012-12-20 16:04:27 +0000308 if (Metrics.notDuplicatable) {
Stephen Hines36b56882014-04-23 16:57:46 -0700309 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
James Molloy67ae1352012-12-20 16:04:27 +0000310 << " instructions: "; L->dump());
311 return false;
312 }
Chris Lattnerd9e07972011-01-02 07:35:53 +0000313 if (Metrics.NumInsts > MAX_HEADER_SIZE)
314 return false;
Devang Patel3f43a702009-03-06 03:51:30 +0000315 }
316
Devang Patel990e8662007-07-11 23:47:28 +0000317 // Now, this loop is suitable for rotation.
Chris Lattner64c24db2011-01-08 19:26:33 +0000318 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000319
Chris Lattnerf5bf4642011-04-09 07:25:58 +0000320 // If the loop could not be converted to canonical form, it must have an
321 // indirectbr in it, just give up.
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000322 if (OrigPreheader == 0)
Chris Lattnerf5bf4642011-04-09 07:25:58 +0000323 return false;
Devang Patel990e8662007-07-11 23:47:28 +0000324
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000325 // Anything ScalarEvolution may know about this loop or the PHI nodes
326 // in its header will soon be invalidated.
327 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman4c7279a2009-10-31 15:04:55 +0000328 SE->forgetLoop(L);
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000329
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000330 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
331
Devang Patelc4625da2007-04-07 01:25:15 +0000332 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000333 // that is inside loop. Header's other successor is outside the
334 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000335 BasicBlock *Exit = BI->getSuccessor(0);
336 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel32231332007-04-09 16:11:48 +0000337 if (L->contains(Exit))
338 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000339 assert(NewHeader && "Unable to determine new loop header");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000340 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel32231332007-04-09 16:11:48 +0000341 "Unable to determine loop header and exit blocks");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000342
Dan Gohmancc4e6052009-06-25 00:22:44 +0000343 // This code assumes that the new header has exactly one predecessor.
344 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000345 assert(NewHeader->getSinglePredecessor() &&
346 "New header doesn't have one pred!");
347 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000348
Dan Gohmane6e37b92009-10-24 23:19:52 +0000349 // Begin by walking OrigHeader and populating ValueMap with an entry for
350 // each Instruction.
Devang Patel32231332007-04-09 16:11:48 +0000351 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner6ccb3652011-01-08 07:21:31 +0000352 ValueToValueMapTy ValueMap;
Devang Patele9881542007-04-09 19:04:21 +0000353
Dan Gohmane6e37b92009-10-24 23:19:52 +0000354 // For PHI nodes, the value available in OldPreHeader is just the
355 // incoming value from OldPreHeader.
356 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foadc1371202011-06-20 14:18:48 +0000357 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelc4625da2007-04-07 01:25:15 +0000358
Chris Lattner50fb4692010-09-06 01:10:22 +0000359 // For the rest of the instructions, either hoist to the OrigPreheader if
360 // possible or create a clone in the OldPreHeader if not.
Chris Lattner64c24db2011-01-08 19:26:33 +0000361 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattner50fb4692010-09-06 01:10:22 +0000362 while (I != E) {
363 Instruction *Inst = I++;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000364
Chris Lattner50fb4692010-09-06 01:10:22 +0000365 // If the instruction's operands are invariant and it doesn't read or write
366 // memory, then it is safe to hoist. Doing this doesn't change the order of
367 // execution in the preheader, but does prevent the instruction from
368 // executing in each iteration of the loop. This means it is safe to hoist
369 // something that might trap, but isn't safe to hoist something that reads
370 // memory (without proving that the loop doesn't write).
371 if (L->hasLoopInvariantOperands(Inst) &&
372 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
Eli Friedman5e6162e2012-02-16 00:41:10 +0000373 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
374 !isa<AllocaInst>(Inst)) {
Chris Lattner50fb4692010-09-06 01:10:22 +0000375 Inst->moveBefore(LoopEntryBranch);
376 continue;
377 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000378
Chris Lattner50fb4692010-09-06 01:10:22 +0000379 // Otherwise, create a duplicate of the instruction.
380 Instruction *C = Inst->clone();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000381
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000382 // Eagerly remap the operands of the instruction.
383 RemapInstruction(C, ValueMap,
384 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000385
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000386 // With the operands remapped, see if the instruction constant folds or is
387 // otherwise simplifyable. This commonly occurs because the entry from PHI
388 // nodes allows icmps and other instructions to fold.
Chris Lattner012ca942011-01-08 17:38:45 +0000389 Value *V = SimplifyInstruction(C);
390 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000391 // If so, then delete the temporary instruction and stick the folded value
392 // in the map.
393 delete C;
394 ValueMap[Inst] = V;
395 } else {
396 // Otherwise, stick the new instruction into the new block!
397 C->setName(Inst->getName());
398 C->insertBefore(LoopEntryBranch);
399 ValueMap[Inst] = C;
400 }
Devang Patelc4625da2007-04-07 01:25:15 +0000401 }
402
Dan Gohmane6e37b92009-10-24 23:19:52 +0000403 // Along with all the other instructions, we just cloned OrigHeader's
404 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
405 // successors by duplicating their incoming values for OrigHeader.
406 TerminatorInst *TI = OrigHeader->getTerminator();
407 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
408 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
409 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner64c24db2011-01-08 19:26:33 +0000410 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelc4625da2007-04-07 01:25:15 +0000411
Dan Gohmane6e37b92009-10-24 23:19:52 +0000412 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
413 // OrigPreHeader's old terminator (the original branch into the loop), and
414 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
415 LoopEntryBranch->eraseFromParent();
Devang Patelc4625da2007-04-07 01:25:15 +0000416
Chris Lattner64c24db2011-01-08 19:26:33 +0000417 // If there were any uses of instructions in the duplicated block outside the
418 // loop, update them, inserting PHI nodes as required
419 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelc4625da2007-04-07 01:25:15 +0000420
Dan Gohmane6e37b92009-10-24 23:19:52 +0000421 // NewHeader is now the header of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000422 L->moveToHeader(NewHeader);
Chris Lattner883401a2011-01-08 19:10:28 +0000423 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelc4625da2007-04-07 01:25:15 +0000424
Andrew Trickc3a825b2012-02-14 00:00:19 +0000425
Chris Lattner5d373702011-01-08 19:59:06 +0000426 // At this point, we've finished our major CFG changes. As part of cloning
427 // the loop into the preheader we've simplified instructions and the
428 // duplicated conditional branch may now be branching on a constant. If it is
429 // branching on a constant and if that constant means that we enter the loop,
430 // then we fold away the cond branch to an uncond branch. This simplifies the
431 // loop in cases important for nested loops, and it also means we don't have
432 // to split as many edges.
433 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
434 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
435 if (!isa<ConstantInt>(PHBI->getCondition()) ||
436 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
437 != NewHeader) {
438 // The conditional branch can't be folded, handle the general case.
439 // Update DominatorTree to reflect the CFG change we just made. Then split
440 // edges as necessary to preserve LoopSimplify form.
Stephen Hines36b56882014-04-23 16:57:46 -0700441 if (DominatorTreeWrapperPass *DTWP =
442 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
443 DominatorTree &DT = DTWP->getDomTree();
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000444 // Everything that was dominated by the old loop header is now dominated
445 // by the original loop preheader. Conceptually the header was merged
446 // into the preheader, even though we reuse the actual block as a new
447 // loop latch.
Stephen Hines36b56882014-04-23 16:57:46 -0700448 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000449 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
450 OrigHeaderNode->end());
Stephen Hines36b56882014-04-23 16:57:46 -0700451 DomTreeNode *OrigPreheaderNode = DT.getNode(OrigPreheader);
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000452 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
Stephen Hines36b56882014-04-23 16:57:46 -0700453 DT.changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000454
Stephen Hines36b56882014-04-23 16:57:46 -0700455 assert(DT.getNode(Exit)->getIDom() == OrigPreheaderNode);
456 assert(DT.getNode(NewHeader)->getIDom() == OrigPreheaderNode);
Benjamin Kramer64f30e32012-09-01 12:04:51 +0000457
Chris Lattner5d373702011-01-08 19:59:06 +0000458 // Update OrigHeader to be dominated by the new header block.
Stephen Hines36b56882014-04-23 16:57:46 -0700459 DT.changeImmediateDominator(OrigHeader, OrigLatch);
Chris Lattner5d373702011-01-08 19:59:06 +0000460 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000461
Chris Lattner5d373702011-01-08 19:59:06 +0000462 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotema94d6e82012-07-24 10:51:42 +0000463 // thus is not a preheader anymore.
464 // Split the edge to form a real preheader.
Chris Lattner5d373702011-01-08 19:59:06 +0000465 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
466 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000467
Nadav Rotema94d6e82012-07-24 10:51:42 +0000468 // Preserve canonical loop form, which means that 'Exit' should have only
Stephen Hines36b56882014-04-23 16:57:46 -0700469 // one predecessor. Note that Exit could be an exit block for multiple
470 // nested loops, causing both of the edges to now be critical and need to
471 // be split.
472 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
473 bool SplitLatchEdge = false;
474 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
475 PE = ExitPreds.end();
476 PI != PE; ++PI) {
477 // We only need to split loop exit edges.
478 Loop *PredLoop = LI->getLoopFor(*PI);
479 if (!PredLoop || PredLoop->contains(Exit))
480 continue;
481 SplitLatchEdge |= L->getLoopLatch() == *PI;
482 BasicBlock *ExitSplit = SplitCriticalEdge(*PI, Exit, this);
483 ExitSplit->moveBefore(Exit);
484 }
485 assert(SplitLatchEdge &&
486 "Despite splitting all preds, failed to split latch exit?");
Chris Lattner5d373702011-01-08 19:59:06 +0000487 } else {
488 // We can fold the conditional branch in the preheader, this makes things
489 // simpler. The first step is to remove the extra edge to the Exit block.
490 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelbd5426a2011-04-29 20:38:55 +0000491 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
492 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner5d373702011-01-08 19:59:06 +0000493 PHBI->eraseFromParent();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000494
Chris Lattner5d373702011-01-08 19:59:06 +0000495 // With our CFG finalized, update DomTree if it is available.
Stephen Hines36b56882014-04-23 16:57:46 -0700496 if (DominatorTreeWrapperPass *DTWP =
497 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
498 DominatorTree &DT = DTWP->getDomTree();
Chris Lattner5d373702011-01-08 19:59:06 +0000499 // Update OrigHeader to be dominated by the new header block.
Stephen Hines36b56882014-04-23 16:57:46 -0700500 DT.changeImmediateDominator(NewHeader, OrigPreheader);
501 DT.changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000502
503 // Brute force incremental dominator tree update. Call
504 // findNearestCommonDominator on all CFG predecessors of each child of the
505 // original header.
Stephen Hines36b56882014-04-23 16:57:46 -0700506 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
Benjamin Kramer7de70782012-09-02 11:57:22 +0000507 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
508 OrigHeaderNode->end());
509 bool Changed;
510 do {
511 Changed = false;
512 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
513 DomTreeNode *Node = HeaderChildren[I];
514 BasicBlock *BB = Node->getBlock();
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000515
Benjamin Kramer7de70782012-09-02 11:57:22 +0000516 pred_iterator PI = pred_begin(BB);
517 BasicBlock *NearestDom = *PI;
518 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
Stephen Hines36b56882014-04-23 16:57:46 -0700519 NearestDom = DT.findNearestCommonDominator(NearestDom, *PI);
Benjamin Kramer7de70782012-09-02 11:57:22 +0000520
521 // Remember if this changes the DomTree.
522 if (Node->getIDom()->getBlock() != NearestDom) {
Stephen Hines36b56882014-04-23 16:57:46 -0700523 DT.changeImmediateDominator(BB, NearestDom);
Benjamin Kramer7de70782012-09-02 11:57:22 +0000524 Changed = true;
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000525 }
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000526 }
527
Benjamin Kramer7de70782012-09-02 11:57:22 +0000528 // If the dominator changed, this may have an effect on other
529 // predecessors, continue until we reach a fixpoint.
530 } while (Changed);
Chris Lattner5d373702011-01-08 19:59:06 +0000531 }
Devang Patel990e8662007-07-11 23:47:28 +0000532 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000533
Chris Lattner5d373702011-01-08 19:59:06 +0000534 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner0e4a1542011-01-08 18:52:51 +0000535 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000536
Chris Lattner93767fd2011-01-11 07:47:59 +0000537 // Now that the CFG and DomTree are in a consistent state again, try to merge
538 // the OrigHeader block into OrigLatch. This will succeed if they are
539 // connected by an unconditional branch. This is just a cleanup so the
540 // emitted code isn't too gross in this common case.
541 MergeBlockIntoPredecessor(OrigHeader, this);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000542
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000543 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
544
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000545 ++NumRotated;
546 return true;
Devang Patel5464b962007-04-09 20:19:46 +0000547}