blob: e98ae953e53240fedce114acec83d6cecf07c200 [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"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000023#include "llvm/IR/Function.h"
24#include "llvm/IR/IntrinsicInst.h"
Benjamin Kramerd70846e2012-08-30 15:39:42 +000025#include "llvm/Support/CFG.h"
Devang Patelc4625da2007-04-07 01:25:15 +000026#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
28#include "llvm/Transforms/Utils/Local.h"
29#include "llvm/Transforms/Utils/SSAUpdater.h"
30#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelc4625da2007-04-07 01:25:15 +000031using namespace llvm;
32
33#define MAX_HEADER_SIZE 16
34
35STATISTIC(NumRotated, "Number of loops rotated");
36namespace {
37
Chris Lattner3e8b6632009-09-02 06:11:42 +000038 class LoopRotate : public LoopPass {
Devang Patelc4625da2007-04-07 01:25:15 +000039 public:
Devang Patel19974732007-05-03 01:11:54 +000040 static char ID; // Pass ID, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000041 LoopRotate() : LoopPass(ID) {
42 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
43 }
Devang Patel794fd752007-05-01 21:15:47 +000044
Devang Patel32231332007-04-09 16:11:48 +000045 // LCSSA form makes instruction renaming easier.
Devang Patelc4625da2007-04-07 01:25:15 +000046 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman1e381fc2010-07-16 17:58:45 +000047 AU.addPreserved<DominatorTree>();
Dan Gohman1e381fc2010-07-16 17:58:45 +000048 AU.addRequired<LoopInfo>();
49 AU.addPreserved<LoopInfo>();
Devang Patel9d9b2042008-02-15 01:24:49 +000050 AU.addRequiredID(LoopSimplifyID);
51 AU.addPreservedID(LoopSimplifyID);
Devang Patelc4625da2007-04-07 01:25:15 +000052 AU.addRequiredID(LCSSAID);
53 AU.addPreservedID(LCSSAID);
Devang Patel990e8662007-07-11 23:47:28 +000054 AU.addPreserved<ScalarEvolution>();
Chandler Carrutha5157e62013-01-21 13:04:33 +000055 AU.addRequired<TargetTransformInfo>();
Devang Patelc4625da2007-04-07 01:25:15 +000056 }
57
Chris Lattnera1ae0c72011-01-08 18:55:50 +000058 bool runOnLoop(Loop *L, LPPassManager &LPM);
Andrew Trickf6629ab2012-02-14 00:00:23 +000059 void simplifyLoopLatch(Loop *L);
Chris Lattner4aefc9b2011-01-08 17:48:33 +000060 bool rotateLoop(Loop *L);
Andrew Trickc3a825b2012-02-14 00:00:19 +000061
Devang Patelc4625da2007-04-07 01:25:15 +000062 private:
Chris Lattner012ca942011-01-08 17:38:45 +000063 LoopInfo *LI;
Chandler Carrutha5157e62013-01-21 13:04:33 +000064 const TargetTransformInfo *TTI;
Devang Patelc4625da2007-04-07 01:25:15 +000065 };
Devang Patelc4625da2007-04-07 01:25:15 +000066}
Andrew Trickc3a825b2012-02-14 00:00:19 +000067
Dan Gohman844731a2008-05-13 00:00:25 +000068char LoopRotate::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000069INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Chandler Carrutha5157e62013-01-21 13:04:33 +000070INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +000071INITIALIZE_PASS_DEPENDENCY(LoopInfo)
72INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
73INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +000074INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelc4625da2007-04-07 01:25:15 +000075
Daniel Dunbar394f0442008-10-22 23:32:42 +000076Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +000077
Devang Patel32231332007-04-09 16:11:48 +000078/// Rotate Loop L as many times as possible. Return true if
Dan Gohmancc4e6052009-06-25 00:22:44 +000079/// the loop is rotated at least once.
Chris Lattner4aefc9b2011-01-08 17:48:33 +000080bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner012ca942011-01-08 17:38:45 +000081 LI = &getAnalysis<LoopInfo>();
Chandler Carrutha5157e62013-01-21 13:04:33 +000082 TTI = &getAnalysis<TargetTransformInfo>();
Devang Patel990e8662007-07-11 23:47:28 +000083
Andrew Trickf6629ab2012-02-14 00:00:23 +000084 // Simplify the loop latch before attempting to rotate the header
85 // upward. Rotation may not be needed if the loop tail can be folded into the
86 // loop exit.
87 simplifyLoopLatch(L);
88
Devang Patelc4625da2007-04-07 01:25:15 +000089 // One loop can be rotated multiple times.
Chris Lattner012ca942011-01-08 17:38:45 +000090 bool MadeChange = false;
Chris Lattner4aefc9b2011-01-08 17:48:33 +000091 while (rotateLoop(L))
Chris Lattner012ca942011-01-08 17:38:45 +000092 MadeChange = true;
Devang Patelc4625da2007-04-07 01:25:15 +000093
Chris Lattner012ca942011-01-08 17:38:45 +000094 return MadeChange;
Devang Patelc4625da2007-04-07 01:25:15 +000095}
96
Chris Lattner64c24db2011-01-08 19:26:33 +000097/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
98/// old header into the preheader. If there were uses of the values produced by
99/// these instruction that were outside of the loop, we have to insert PHI nodes
100/// to merge the two values. Do this now.
101static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
102 BasicBlock *OrigPreheader,
103 ValueToValueMapTy &ValueMap) {
104 // Remove PHI node entries that are no longer live.
105 BasicBlock::iterator I, E = OrigHeader->end();
106 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
107 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Trickc3a825b2012-02-14 00:00:19 +0000108
Chris Lattner64c24db2011-01-08 19:26:33 +0000109 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
110 // as necessary.
111 SSAUpdater SSA;
112 for (I = OrigHeader->begin(); I != E; ++I) {
113 Value *OrigHeaderVal = I;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000114
Chris Lattner64c24db2011-01-08 19:26:33 +0000115 // If there are no uses of the value (e.g. because it returns void), there
116 // is nothing to rewrite.
117 if (OrigHeaderVal->use_empty())
118 continue;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000119
Chris Lattner64c24db2011-01-08 19:26:33 +0000120 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
121
122 // The value now exits in two versions: the initial value in the preheader
123 // and the loop "next" value in the original header.
124 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
125 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
126 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000127
Chris Lattner64c24db2011-01-08 19:26:33 +0000128 // Visit each use of the OrigHeader instruction.
129 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
130 UE = OrigHeaderVal->use_end(); UI != UE; ) {
131 // Grab the use before incrementing the iterator.
132 Use &U = UI.getUse();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000133
Chris Lattner64c24db2011-01-08 19:26:33 +0000134 // Increment the iterator before removing the use from the list.
135 ++UI;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000136
Chris Lattner64c24db2011-01-08 19:26:33 +0000137 // SSAUpdater can't handle a non-PHI use in the same block as an
138 // earlier def. We can easily handle those cases manually.
139 Instruction *UserInst = cast<Instruction>(U.getUser());
140 if (!isa<PHINode>(UserInst)) {
141 BasicBlock *UserBB = UserInst->getParent();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000142
Chris Lattner64c24db2011-01-08 19:26:33 +0000143 // The original users in the OrigHeader are already using the
144 // original definitions.
145 if (UserBB == OrigHeader)
146 continue;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000147
Chris Lattner64c24db2011-01-08 19:26:33 +0000148 // Users in the OrigPreHeader need to use the value to which the
149 // original definitions are mapped.
150 if (UserBB == OrigPreheader) {
151 U = OrigPreHeaderVal;
152 continue;
153 }
154 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000155
Chris Lattner64c24db2011-01-08 19:26:33 +0000156 // Anything else can be handled by SSAUpdater.
157 SSA.RewriteUse(U);
158 }
159 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000160}
Chris Lattner64c24db2011-01-08 19:26:33 +0000161
Andrew Trickf6629ab2012-02-14 00:00:23 +0000162/// Determine whether the instructions in this range my be safely and cheaply
163/// speculated. This is not an important enough situation to develop complex
164/// heuristics. We handle a single arithmetic instruction along with any type
165/// conversions.
166static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
167 BasicBlock::iterator End) {
168 bool seenIncrement = false;
169 for (BasicBlock::iterator I = Begin; I != End; ++I) {
170
171 if (!isSafeToSpeculativelyExecute(I))
172 return false;
173
174 if (isa<DbgInfoIntrinsic>(I))
175 continue;
176
177 switch (I->getOpcode()) {
178 default:
179 return false;
180 case Instruction::GetElementPtr:
181 // GEPs are cheap if all indices are constant.
182 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
183 return false;
184 // fall-thru to increment case
185 case Instruction::Add:
186 case Instruction::Sub:
187 case Instruction::And:
188 case Instruction::Or:
189 case Instruction::Xor:
190 case Instruction::Shl:
191 case Instruction::LShr:
192 case Instruction::AShr:
193 if (seenIncrement)
194 return false;
195 seenIncrement = true;
196 break;
197 case Instruction::Trunc:
198 case Instruction::ZExt:
199 case Instruction::SExt:
200 // ignore type conversions
201 break;
202 }
203 }
204 return true;
205}
206
207/// Fold the loop tail into the loop exit by speculating the loop tail
208/// instructions. Typically, this is a single post-increment. In the case of a
209/// simple 2-block loop, hoisting the increment can be much better than
210/// duplicating the entire loop header. In the cast of loops with early exits,
211/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
212/// canonical form so downstream passes can handle it.
213///
214/// I don't believe this invalidates SCEV.
215void LoopRotate::simplifyLoopLatch(Loop *L) {
216 BasicBlock *Latch = L->getLoopLatch();
217 if (!Latch || Latch->hasAddressTaken())
218 return;
219
220 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
221 if (!Jmp || !Jmp->isUnconditional())
222 return;
223
224 BasicBlock *LastExit = Latch->getSinglePredecessor();
225 if (!LastExit || !L->isLoopExiting(LastExit))
226 return;
227
228 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
229 if (!BI)
230 return;
231
232 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
233 return;
234
235 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
236 << LastExit->getName() << "\n");
237
238 // Hoist the instructions from Latch into LastExit.
239 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
240
241 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
242 BasicBlock *Header = Jmp->getSuccessor(0);
243 assert(Header == L->getHeader() && "expected a backward branch");
244
245 // Remove Latch from the CFG so that LastExit becomes the new Latch.
246 BI->setSuccessor(FallThruPath, Header);
247 Latch->replaceSuccessorsPhiUsesWith(LastExit);
248 Jmp->eraseFromParent();
249
250 // Nuke the Latch block.
251 assert(Latch->empty() && "unable to evacuate Latch");
252 LI->removeBlock(Latch);
253 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
254 DT->eraseNode(Latch);
255 Latch->eraseFromParent();
256}
257
Dan Gohman23d9d272007-05-11 21:10:54 +0000258/// Rotate loop LP. Return true if the loop is rotated.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000259bool LoopRotate::rotateLoop(Loop *L) {
Dan Gohmancc4e6052009-06-25 00:22:44 +0000260 // If the loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000261 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000262 return false;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000263
Chris Lattner2aa69082011-01-08 18:06:22 +0000264 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000265 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000266
Chris Lattner2aa69082011-01-08 18:06:22 +0000267 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
268 if (BI == 0 || BI->isUnconditional())
269 return false;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000270
Dan Gohmancc4e6052009-06-25 00:22:44 +0000271 // If the loop header is not one of the loop exiting blocks then
272 // either this loop is already rotated or it is not
Devang Patelc4625da2007-04-07 01:25:15 +0000273 // suitable for loop rotation transformations.
Dan Gohman32663b72009-10-24 23:34:26 +0000274 if (!L->isLoopExiting(OrigHeader))
Devang Patelc4625da2007-04-07 01:25:15 +0000275 return false;
276
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000277 // If the loop latch already contains a branch that leaves the loop then the
278 // loop is already rotated.
279 if (OrigLatch == 0 || L->isLoopExiting(OrigLatch))
Devang Patelc4625da2007-04-07 01:25:15 +0000280 return false;
281
James Molloy67ae1352012-12-20 16:04:27 +0000282 // Check size of original header and reject loop if it is very big or we can't
283 // duplicate blocks inside it.
Chris Lattnerd9e07972011-01-02 07:35:53 +0000284 {
285 CodeMetrics Metrics;
Chandler Carrutha5157e62013-01-21 13:04:33 +0000286 Metrics.analyzeBasicBlock(OrigHeader, *TTI);
James Molloy67ae1352012-12-20 16:04:27 +0000287 if (Metrics.notDuplicatable) {
288 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non duplicatable"
289 << " instructions: "; L->dump());
290 return false;
291 }
Chris Lattnerd9e07972011-01-02 07:35:53 +0000292 if (Metrics.NumInsts > MAX_HEADER_SIZE)
293 return false;
Devang Patel3f43a702009-03-06 03:51:30 +0000294 }
295
Devang Patel990e8662007-07-11 23:47:28 +0000296 // Now, this loop is suitable for rotation.
Chris Lattner64c24db2011-01-08 19:26:33 +0000297 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000298
Chris Lattnerf5bf4642011-04-09 07:25:58 +0000299 // If the loop could not be converted to canonical form, it must have an
300 // indirectbr in it, just give up.
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000301 if (OrigPreheader == 0)
Chris Lattnerf5bf4642011-04-09 07:25:58 +0000302 return false;
Devang Patel990e8662007-07-11 23:47:28 +0000303
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000304 // Anything ScalarEvolution may know about this loop or the PHI nodes
305 // in its header will soon be invalidated.
306 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman4c7279a2009-10-31 15:04:55 +0000307 SE->forgetLoop(L);
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000308
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000309 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
310
Devang Patelc4625da2007-04-07 01:25:15 +0000311 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000312 // that is inside loop. Header's other successor is outside the
313 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000314 BasicBlock *Exit = BI->getSuccessor(0);
315 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel32231332007-04-09 16:11:48 +0000316 if (L->contains(Exit))
317 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000318 assert(NewHeader && "Unable to determine new loop header");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000319 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel32231332007-04-09 16:11:48 +0000320 "Unable to determine loop header and exit blocks");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000321
Dan Gohmancc4e6052009-06-25 00:22:44 +0000322 // This code assumes that the new header has exactly one predecessor.
323 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000324 assert(NewHeader->getSinglePredecessor() &&
325 "New header doesn't have one pred!");
326 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000327
Dan Gohmane6e37b92009-10-24 23:19:52 +0000328 // Begin by walking OrigHeader and populating ValueMap with an entry for
329 // each Instruction.
Devang Patel32231332007-04-09 16:11:48 +0000330 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner6ccb3652011-01-08 07:21:31 +0000331 ValueToValueMapTy ValueMap;
Devang Patele9881542007-04-09 19:04:21 +0000332
Dan Gohmane6e37b92009-10-24 23:19:52 +0000333 // For PHI nodes, the value available in OldPreHeader is just the
334 // incoming value from OldPreHeader.
335 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foadc1371202011-06-20 14:18:48 +0000336 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelc4625da2007-04-07 01:25:15 +0000337
Chris Lattner50fb4692010-09-06 01:10:22 +0000338 // For the rest of the instructions, either hoist to the OrigPreheader if
339 // possible or create a clone in the OldPreHeader if not.
Chris Lattner64c24db2011-01-08 19:26:33 +0000340 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattner50fb4692010-09-06 01:10:22 +0000341 while (I != E) {
342 Instruction *Inst = I++;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000343
Chris Lattner50fb4692010-09-06 01:10:22 +0000344 // If the instruction's operands are invariant and it doesn't read or write
345 // memory, then it is safe to hoist. Doing this doesn't change the order of
346 // execution in the preheader, but does prevent the instruction from
347 // executing in each iteration of the loop. This means it is safe to hoist
348 // something that might trap, but isn't safe to hoist something that reads
349 // memory (without proving that the loop doesn't write).
350 if (L->hasLoopInvariantOperands(Inst) &&
351 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
Eli Friedman5e6162e2012-02-16 00:41:10 +0000352 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
353 !isa<AllocaInst>(Inst)) {
Chris Lattner50fb4692010-09-06 01:10:22 +0000354 Inst->moveBefore(LoopEntryBranch);
355 continue;
356 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000357
Chris Lattner50fb4692010-09-06 01:10:22 +0000358 // Otherwise, create a duplicate of the instruction.
359 Instruction *C = Inst->clone();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000360
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000361 // Eagerly remap the operands of the instruction.
362 RemapInstruction(C, ValueMap,
363 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000364
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000365 // With the operands remapped, see if the instruction constant folds or is
366 // otherwise simplifyable. This commonly occurs because the entry from PHI
367 // nodes allows icmps and other instructions to fold.
Chris Lattner012ca942011-01-08 17:38:45 +0000368 Value *V = SimplifyInstruction(C);
369 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000370 // If so, then delete the temporary instruction and stick the folded value
371 // in the map.
372 delete C;
373 ValueMap[Inst] = V;
374 } else {
375 // Otherwise, stick the new instruction into the new block!
376 C->setName(Inst->getName());
377 C->insertBefore(LoopEntryBranch);
378 ValueMap[Inst] = C;
379 }
Devang Patelc4625da2007-04-07 01:25:15 +0000380 }
381
Dan Gohmane6e37b92009-10-24 23:19:52 +0000382 // Along with all the other instructions, we just cloned OrigHeader's
383 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
384 // successors by duplicating their incoming values for OrigHeader.
385 TerminatorInst *TI = OrigHeader->getTerminator();
386 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
387 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
388 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner64c24db2011-01-08 19:26:33 +0000389 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelc4625da2007-04-07 01:25:15 +0000390
Dan Gohmane6e37b92009-10-24 23:19:52 +0000391 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
392 // OrigPreHeader's old terminator (the original branch into the loop), and
393 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
394 LoopEntryBranch->eraseFromParent();
Devang Patelc4625da2007-04-07 01:25:15 +0000395
Chris Lattner64c24db2011-01-08 19:26:33 +0000396 // If there were any uses of instructions in the duplicated block outside the
397 // loop, update them, inserting PHI nodes as required
398 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelc4625da2007-04-07 01:25:15 +0000399
Dan Gohmane6e37b92009-10-24 23:19:52 +0000400 // NewHeader is now the header of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000401 L->moveToHeader(NewHeader);
Chris Lattner883401a2011-01-08 19:10:28 +0000402 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelc4625da2007-04-07 01:25:15 +0000403
Andrew Trickc3a825b2012-02-14 00:00:19 +0000404
Chris Lattner5d373702011-01-08 19:59:06 +0000405 // At this point, we've finished our major CFG changes. As part of cloning
406 // the loop into the preheader we've simplified instructions and the
407 // duplicated conditional branch may now be branching on a constant. If it is
408 // branching on a constant and if that constant means that we enter the loop,
409 // then we fold away the cond branch to an uncond branch. This simplifies the
410 // loop in cases important for nested loops, and it also means we don't have
411 // to split as many edges.
412 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
413 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
414 if (!isa<ConstantInt>(PHBI->getCondition()) ||
415 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
416 != NewHeader) {
417 // The conditional branch can't be folded, handle the general case.
418 // Update DominatorTree to reflect the CFG change we just made. Then split
419 // edges as necessary to preserve LoopSimplify form.
420 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000421 // Everything that was dominated by the old loop header is now dominated
422 // by the original loop preheader. Conceptually the header was merged
423 // into the preheader, even though we reuse the actual block as a new
424 // loop latch.
425 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
426 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
427 OrigHeaderNode->end());
428 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
429 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
430 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000431
Benjamin Kramer64f30e32012-09-01 12:04:51 +0000432 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
433 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
434
Chris Lattner5d373702011-01-08 19:59:06 +0000435 // Update OrigHeader to be dominated by the new header block.
436 DT->changeImmediateDominator(OrigHeader, OrigLatch);
437 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000438
Chris Lattner5d373702011-01-08 19:59:06 +0000439 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotema94d6e82012-07-24 10:51:42 +0000440 // thus is not a preheader anymore.
441 // Split the edge to form a real preheader.
Chris Lattner5d373702011-01-08 19:59:06 +0000442 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
443 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000444
Nadav Rotema94d6e82012-07-24 10:51:42 +0000445 // Preserve canonical loop form, which means that 'Exit' should have only
446 // one predecessor.
Chris Lattner5d373702011-01-08 19:59:06 +0000447 BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
448 ExitSplit->moveBefore(Exit);
449 } else {
450 // We can fold the conditional branch in the preheader, this makes things
451 // simpler. The first step is to remove the extra edge to the Exit block.
452 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelbd5426a2011-04-29 20:38:55 +0000453 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
454 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner5d373702011-01-08 19:59:06 +0000455 PHBI->eraseFromParent();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000456
Chris Lattner5d373702011-01-08 19:59:06 +0000457 // With our CFG finalized, update DomTree if it is available.
458 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
459 // Update OrigHeader to be dominated by the new header block.
460 DT->changeImmediateDominator(NewHeader, OrigPreheader);
461 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000462
463 // Brute force incremental dominator tree update. Call
464 // findNearestCommonDominator on all CFG predecessors of each child of the
465 // original header.
466 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramer7de70782012-09-02 11:57:22 +0000467 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
468 OrigHeaderNode->end());
469 bool Changed;
470 do {
471 Changed = false;
472 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
473 DomTreeNode *Node = HeaderChildren[I];
474 BasicBlock *BB = Node->getBlock();
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000475
Benjamin Kramer7de70782012-09-02 11:57:22 +0000476 pred_iterator PI = pred_begin(BB);
477 BasicBlock *NearestDom = *PI;
478 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
479 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
480
481 // Remember if this changes the DomTree.
482 if (Node->getIDom()->getBlock() != NearestDom) {
483 DT->changeImmediateDominator(BB, NearestDom);
484 Changed = true;
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000485 }
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000486 }
487
Benjamin Kramer7de70782012-09-02 11:57:22 +0000488 // If the dominator changed, this may have an effect on other
489 // predecessors, continue until we reach a fixpoint.
490 } while (Changed);
Chris Lattner5d373702011-01-08 19:59:06 +0000491 }
Devang Patel990e8662007-07-11 23:47:28 +0000492 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000493
Chris Lattner5d373702011-01-08 19:59:06 +0000494 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner0e4a1542011-01-08 18:52:51 +0000495 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000496
Chris Lattner93767fd2011-01-11 07:47:59 +0000497 // Now that the CFG and DomTree are in a consistent state again, try to merge
498 // the OrigHeader block into OrigLatch. This will succeed if they are
499 // connected by an unconditional branch. This is just a cleanup so the
500 // emitted code isn't too gross in this common case.
501 MergeBlockIntoPredecessor(OrigHeader, this);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000502
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000503 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
504
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000505 ++NumRotated;
506 return true;
Devang Patel5464b962007-04-09 20:19:46 +0000507}
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000508