blob: a675e1289bafc570e2552baed39e193f2c1655cf [file] [log] [blame]
Devang Patelf42389f2007-04-07 01:25:15 +00001//===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Patelf42389f2007-04-07 01:25:15 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Rotation Pass.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelf42389f2007-04-07 01:25:15 +000014#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000016#include "llvm/Analysis/AssumptionCache.h"
Chris Lattner679572e2011-01-02 07:35:53 +000017#include "llvm/Analysis/CodeMetrics.h"
Chris Lattner8c5defd2011-01-08 08:24:46 +000018#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/LoopPass.h"
Devang Patelfac4d1f2007-07-11 23:47:28 +000020#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Andrew Trick10cc4532012-02-14 00:00:23 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000023#include "llvm/IR/CFG.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000024#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Function.h"
26#include "llvm/IR/IntrinsicInst.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000027#include "llvm/IR/Module.h"
Owen Anderson115aa162014-05-26 08:58:51 +000028#include "llvm/Support/CommandLine.h"
Devang Patelf42389f2007-04-07 01:25:15 +000029#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000030#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Transforms/Utils/BasicBlockUtils.h"
32#include "llvm/Transforms/Utils/Local.h"
33#include "llvm/Transforms/Utils/SSAUpdater.h"
34#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelf42389f2007-04-07 01:25:15 +000035using namespace llvm;
36
Chandler Carruth964daaa2014-04-22 02:55:47 +000037#define DEBUG_TYPE "loop-rotate"
38
Owen Anderson115aa162014-05-26 08:58:51 +000039static cl::opt<unsigned>
40DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
41 cl::desc("The default maximum header size for automatic loop rotation"));
Devang Patelf42389f2007-04-07 01:25:15 +000042
43STATISTIC(NumRotated, "Number of loops rotated");
44namespace {
45
Chris Lattner2dd09db2009-09-02 06:11:42 +000046 class LoopRotate : public LoopPass {
Devang Patelf42389f2007-04-07 01:25:15 +000047 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000048 static char ID; // Pass ID, replacement for typeid
Owen Anderson115aa162014-05-26 08:58:51 +000049 LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +000050 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
Owen Anderson115aa162014-05-26 08:58:51 +000051 if (SpecifiedMaxHeaderSize == -1)
52 MaxHeaderSize = DefaultRotationThreshold;
53 else
54 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
Owen Anderson6c18d1a2010-10-19 17:21:58 +000055 }
Devang Patel09f162c2007-05-01 21:15:47 +000056
Devang Patel88bc2c62007-04-09 16:11:48 +000057 // LCSSA form makes instruction renaming easier.
Craig Topper3e4c6972014-03-05 09:10:37 +000058 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +000059 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth73523022014-01-13 13:07:17 +000060 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +000061 AU.addRequired<LoopInfoWrapperPass>();
62 AU.addPreserved<LoopInfoWrapperPass>();
Devang Patela42c3142008-02-15 01:24:49 +000063 AU.addRequiredID(LoopSimplifyID);
64 AU.addPreservedID(LoopSimplifyID);
Devang Patelf42389f2007-04-07 01:25:15 +000065 AU.addRequiredID(LCSSAID);
66 AU.addPreservedID(LCSSAID);
Devang Patelfac4d1f2007-07-11 23:47:28 +000067 AU.addPreserved<ScalarEvolution>();
Chandler Carruth705b1852015-01-31 03:43:40 +000068 AU.addRequired<TargetTransformInfoWrapperPass>();
Devang Patelf42389f2007-04-07 01:25:15 +000069 }
70
Craig Topper3e4c6972014-03-05 09:10:37 +000071 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Andrew Trick9c72b072013-05-06 17:58:18 +000072 bool simplifyLoopLatch(Loop *L);
73 bool rotateLoop(Loop *L, bool SimplifiedLatch);
Andrew Tricka20f1982012-02-14 00:00:19 +000074
Devang Patelf42389f2007-04-07 01:25:15 +000075 private:
Owen Anderson115aa162014-05-26 08:58:51 +000076 unsigned MaxHeaderSize;
Chris Lattner25ba40a2011-01-08 17:38:45 +000077 LoopInfo *LI;
Chandler Carruthbb9caa92013-01-21 13:04:33 +000078 const TargetTransformInfo *TTI;
Chandler Carruth66b31302015-01-04 12:03:27 +000079 AssumptionCache *AC;
Chandler Carruth94209092015-01-18 02:08:05 +000080 DominatorTree *DT;
Devang Patelf42389f2007-04-07 01:25:15 +000081 };
Devang Patelf42389f2007-04-07 01:25:15 +000082}
Andrew Tricka20f1982012-02-14 00:00:19 +000083
Dan Gohmand78c4002008-05-13 00:00:25 +000084char LoopRotate::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000085INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +000086INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +000087INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth4f8f3072015-01-17 14:16:18 +000088INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +000089INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
90INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson8ac477f2010-10-12 19:48:12 +000091INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelf42389f2007-04-07 01:25:15 +000092
Owen Anderson115aa162014-05-26 08:58:51 +000093Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
94 return new LoopRotate(MaxHeaderSize);
95}
Devang Patelf42389f2007-04-07 01:25:15 +000096
Devang Patel88bc2c62007-04-09 16:11:48 +000097/// Rotate Loop L as many times as possible. Return true if
Dan Gohman091e4402009-06-25 00:22:44 +000098/// the loop is rotated at least once.
Chris Lattner385f2ec2011-01-08 17:48:33 +000099bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000100 if (skipOptnoneFunction(L))
101 return false;
102
Alexey Bataevb97f9e82014-04-15 09:37:30 +0000103 // Save the loop metadata.
104 MDNode *LoopMD = L->getLoopID();
105
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000106 Function &F = *L->getHeader()->getParent();
107
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000108 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000109 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
110 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth94209092015-01-18 02:08:05 +0000111 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
112 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Devang Patelfac4d1f2007-07-11 23:47:28 +0000113
Andrew Trick10cc4532012-02-14 00:00:23 +0000114 // Simplify the loop latch before attempting to rotate the header
115 // upward. Rotation may not be needed if the loop tail can be folded into the
116 // loop exit.
Andrew Trick9c72b072013-05-06 17:58:18 +0000117 bool SimplifiedLatch = simplifyLoopLatch(L);
Andrew Trick10cc4532012-02-14 00:00:23 +0000118
Devang Patelf42389f2007-04-07 01:25:15 +0000119 // One loop can be rotated multiple times.
Chris Lattner25ba40a2011-01-08 17:38:45 +0000120 bool MadeChange = false;
Andrew Trick9c72b072013-05-06 17:58:18 +0000121 while (rotateLoop(L, SimplifiedLatch)) {
Chris Lattner25ba40a2011-01-08 17:38:45 +0000122 MadeChange = true;
Andrew Trick9c72b072013-05-06 17:58:18 +0000123 SimplifiedLatch = false;
124 }
Alexey Bataevb97f9e82014-04-15 09:37:30 +0000125
126 // Restore the loop metadata.
127 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
128 if ((MadeChange || SimplifiedLatch) && LoopMD)
129 L->setLoopID(LoopMD);
130
Chris Lattner25ba40a2011-01-08 17:38:45 +0000131 return MadeChange;
Devang Patelf42389f2007-04-07 01:25:15 +0000132}
133
Chris Lattner30f318e2011-01-08 19:26:33 +0000134/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
135/// old header into the preheader. If there were uses of the values produced by
136/// these instruction that were outside of the loop, we have to insert PHI nodes
137/// to merge the two values. Do this now.
138static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
139 BasicBlock *OrigPreheader,
140 ValueToValueMapTy &ValueMap) {
141 // Remove PHI node entries that are no longer live.
142 BasicBlock::iterator I, E = OrigHeader->end();
143 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
144 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Tricka20f1982012-02-14 00:00:19 +0000145
Chris Lattner30f318e2011-01-08 19:26:33 +0000146 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
147 // as necessary.
148 SSAUpdater SSA;
149 for (I = OrigHeader->begin(); I != E; ++I) {
150 Value *OrigHeaderVal = I;
Andrew Tricka20f1982012-02-14 00:00:19 +0000151
Chris Lattner30f318e2011-01-08 19:26:33 +0000152 // If there are no uses of the value (e.g. because it returns void), there
153 // is nothing to rewrite.
154 if (OrigHeaderVal->use_empty())
155 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000156
Chris Lattner30f318e2011-01-08 19:26:33 +0000157 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
158
159 // The value now exits in two versions: the initial value in the preheader
160 // and the loop "next" value in the original header.
161 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
162 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
163 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Tricka20f1982012-02-14 00:00:19 +0000164
Chris Lattner30f318e2011-01-08 19:26:33 +0000165 // Visit each use of the OrigHeader instruction.
166 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
167 UE = OrigHeaderVal->use_end(); UI != UE; ) {
168 // Grab the use before incrementing the iterator.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000169 Use &U = *UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000170
Chris Lattner30f318e2011-01-08 19:26:33 +0000171 // Increment the iterator before removing the use from the list.
172 ++UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000173
Chris Lattner30f318e2011-01-08 19:26:33 +0000174 // SSAUpdater can't handle a non-PHI use in the same block as an
175 // earlier def. We can easily handle those cases manually.
176 Instruction *UserInst = cast<Instruction>(U.getUser());
177 if (!isa<PHINode>(UserInst)) {
178 BasicBlock *UserBB = UserInst->getParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000179
Chris Lattner30f318e2011-01-08 19:26:33 +0000180 // The original users in the OrigHeader are already using the
181 // original definitions.
182 if (UserBB == OrigHeader)
183 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000184
Chris Lattner30f318e2011-01-08 19:26:33 +0000185 // Users in the OrigPreHeader need to use the value to which the
186 // original definitions are mapped.
187 if (UserBB == OrigPreheader) {
188 U = OrigPreHeaderVal;
189 continue;
190 }
191 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000192
Chris Lattner30f318e2011-01-08 19:26:33 +0000193 // Anything else can be handled by SSAUpdater.
194 SSA.RewriteUse(U);
195 }
196 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000197}
Chris Lattner30f318e2011-01-08 19:26:33 +0000198
JF Bastienac8b66b2014-08-05 23:27:34 +0000199/// Determine whether the instructions in this range may be safely and cheaply
Andrew Trick10cc4532012-02-14 00:00:23 +0000200/// speculated. This is not an important enough situation to develop complex
201/// heuristics. We handle a single arithmetic instruction along with any type
202/// conversions.
203static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
Yi Jiangab19fff2014-10-29 20:19:47 +0000204 BasicBlock::iterator End, Loop *L) {
Andrew Trick10cc4532012-02-14 00:00:23 +0000205 bool seenIncrement = false;
Yi Jiangab19fff2014-10-29 20:19:47 +0000206 bool MultiExitLoop = false;
207
208 if (!L->getExitingBlock())
209 MultiExitLoop = true;
210
Andrew Trick10cc4532012-02-14 00:00:23 +0000211 for (BasicBlock::iterator I = Begin; I != End; ++I) {
212
213 if (!isSafeToSpeculativelyExecute(I))
214 return false;
215
216 if (isa<DbgInfoIntrinsic>(I))
217 continue;
218
219 switch (I->getOpcode()) {
220 default:
221 return false;
222 case Instruction::GetElementPtr:
223 // GEPs are cheap if all indices are constant.
224 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
225 return false;
226 // fall-thru to increment case
227 case Instruction::Add:
228 case Instruction::Sub:
229 case Instruction::And:
230 case Instruction::Or:
231 case Instruction::Xor:
232 case Instruction::Shl:
233 case Instruction::LShr:
Yi Jiangab19fff2014-10-29 20:19:47 +0000234 case Instruction::AShr: {
David Majnemer4c82dae2015-01-27 06:21:43 +0000235 Value *IVOpnd = !isa<Constant>(I->getOperand(0))
236 ? I->getOperand(0)
237 : !isa<Constant>(I->getOperand(1))
238 ? I->getOperand(1)
239 : nullptr;
240 if (!IVOpnd)
241 return false;
Yi Jiangab19fff2014-10-29 20:19:47 +0000242
243 // If increment operand is used outside of the loop, this speculation
244 // could cause extra live range interference.
David Majnemer4c82dae2015-01-27 06:21:43 +0000245 if (MultiExitLoop) {
Yi Jiangab19fff2014-10-29 20:19:47 +0000246 for (User *UseI : IVOpnd->users()) {
247 auto *UserInst = cast<Instruction>(UseI);
248 if (!L->contains(UserInst))
249 return false;
250 }
251 }
252
Andrew Trick10cc4532012-02-14 00:00:23 +0000253 if (seenIncrement)
254 return false;
255 seenIncrement = true;
256 break;
Yi Jiangab19fff2014-10-29 20:19:47 +0000257 }
Andrew Trick10cc4532012-02-14 00:00:23 +0000258 case Instruction::Trunc:
259 case Instruction::ZExt:
260 case Instruction::SExt:
261 // ignore type conversions
262 break;
263 }
264 }
265 return true;
266}
267
268/// Fold the loop tail into the loop exit by speculating the loop tail
269/// instructions. Typically, this is a single post-increment. In the case of a
270/// simple 2-block loop, hoisting the increment can be much better than
JF Bastienac8b66b2014-08-05 23:27:34 +0000271/// duplicating the entire loop header. In the case of loops with early exits,
Andrew Trick10cc4532012-02-14 00:00:23 +0000272/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
273/// canonical form so downstream passes can handle it.
274///
275/// I don't believe this invalidates SCEV.
Andrew Trick9c72b072013-05-06 17:58:18 +0000276bool LoopRotate::simplifyLoopLatch(Loop *L) {
Andrew Trick10cc4532012-02-14 00:00:23 +0000277 BasicBlock *Latch = L->getLoopLatch();
278 if (!Latch || Latch->hasAddressTaken())
Andrew Trick9c72b072013-05-06 17:58:18 +0000279 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000280
281 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
282 if (!Jmp || !Jmp->isUnconditional())
Andrew Trick9c72b072013-05-06 17:58:18 +0000283 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000284
285 BasicBlock *LastExit = Latch->getSinglePredecessor();
286 if (!LastExit || !L->isLoopExiting(LastExit))
Andrew Trick9c72b072013-05-06 17:58:18 +0000287 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000288
289 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
290 if (!BI)
Andrew Trick9c72b072013-05-06 17:58:18 +0000291 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000292
Yi Jiangab19fff2014-10-29 20:19:47 +0000293 if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
Andrew Trick9c72b072013-05-06 17:58:18 +0000294 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000295
296 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
297 << LastExit->getName() << "\n");
298
299 // Hoist the instructions from Latch into LastExit.
300 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
301
302 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
303 BasicBlock *Header = Jmp->getSuccessor(0);
304 assert(Header == L->getHeader() && "expected a backward branch");
305
306 // Remove Latch from the CFG so that LastExit becomes the new Latch.
307 BI->setSuccessor(FallThruPath, Header);
308 Latch->replaceSuccessorsPhiUsesWith(LastExit);
309 Jmp->eraseFromParent();
310
311 // Nuke the Latch block.
312 assert(Latch->empty() && "unable to evacuate Latch");
313 LI->removeBlock(Latch);
Chandler Carruth94209092015-01-18 02:08:05 +0000314 if (DT)
315 DT->eraseNode(Latch);
Andrew Trick10cc4532012-02-14 00:00:23 +0000316 Latch->eraseFromParent();
Andrew Trick9c72b072013-05-06 17:58:18 +0000317 return true;
Andrew Trick10cc4532012-02-14 00:00:23 +0000318}
319
Dan Gohmanb5650eb2007-05-11 21:10:54 +0000320/// Rotate loop LP. Return true if the loop is rotated.
Andrew Trick9c72b072013-05-06 17:58:18 +0000321///
322/// \param SimplifiedLatch is true if the latch was just folded into the final
323/// loop exit. In this case we may want to rotate even though the new latch is
324/// now an exiting branch. This rotation would have happened had the latch not
325/// been simplified. However, if SimplifiedLatch is false, then we avoid
326/// rotating loops in which the latch exits to avoid excessive or endless
327/// rotation. LoopRotate should be repeatable and converge to a canonical
328/// form. This property is satisfied because simplifying the loop latch can only
329/// happen once across multiple invocations of the LoopRotate pass.
330bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
Dan Gohman091e4402009-06-25 00:22:44 +0000331 // If the loop has only one block then there is not much to rotate.
Devang Patel88bc2c62007-04-09 16:11:48 +0000332 if (L->getBlocks().size() == 1)
Devang Patelf42389f2007-04-07 01:25:15 +0000333 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000334
Chris Lattner7fab23b2011-01-08 18:06:22 +0000335 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000336 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Tricka20f1982012-02-14 00:00:19 +0000337
Chris Lattner7fab23b2011-01-08 18:06:22 +0000338 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000339 if (!BI || BI->isUnconditional())
Chris Lattner7fab23b2011-01-08 18:06:22 +0000340 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000341
Dan Gohman091e4402009-06-25 00:22:44 +0000342 // If the loop header is not one of the loop exiting blocks then
343 // either this loop is already rotated or it is not
Devang Patelf42389f2007-04-07 01:25:15 +0000344 // suitable for loop rotation transformations.
Dan Gohman8f4078b2009-10-24 23:34:26 +0000345 if (!L->isLoopExiting(OrigHeader))
Devang Patelf42389f2007-04-07 01:25:15 +0000346 return false;
347
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000348 // If the loop latch already contains a branch that leaves the loop then the
349 // loop is already rotated.
Craig Topperf40110f2014-04-25 05:29:35 +0000350 if (!OrigLatch)
Andrew Trick9c72b072013-05-06 17:58:18 +0000351 return false;
352
353 // Rotate if either the loop latch does *not* exit the loop, or if the loop
354 // latch was just simplified.
355 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
Devang Patelf42389f2007-04-07 01:25:15 +0000356 return false;
357
James Molloy4f6fb952012-12-20 16:04:27 +0000358 // Check size of original header and reject loop if it is very big or we can't
359 // duplicate blocks inside it.
Chris Lattner679572e2011-01-02 07:35:53 +0000360 {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000361 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000362 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000363
Chris Lattner679572e2011-01-02 07:35:53 +0000364 CodeMetrics Metrics;
Hal Finkel57f03dd2014-09-07 13:49:57 +0000365 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
James Molloy4f6fb952012-12-20 16:04:27 +0000366 if (Metrics.notDuplicatable) {
Alp Tokerf907b892013-12-05 05:44:44 +0000367 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
James Molloy4f6fb952012-12-20 16:04:27 +0000368 << " instructions: "; L->dump());
369 return false;
370 }
Owen Anderson115aa162014-05-26 08:58:51 +0000371 if (Metrics.NumInsts > MaxHeaderSize)
Chris Lattner679572e2011-01-02 07:35:53 +0000372 return false;
Devang Patelbab43b42009-03-06 03:51:30 +0000373 }
374
Devang Patelfac4d1f2007-07-11 23:47:28 +0000375 // Now, this loop is suitable for rotation.
Chris Lattner30f318e2011-01-08 19:26:33 +0000376 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Tricka20f1982012-02-14 00:00:19 +0000377
Chris Lattner88974f42011-04-09 07:25:58 +0000378 // If the loop could not be converted to canonical form, it must have an
379 // indirectbr in it, just give up.
Craig Topperf40110f2014-04-25 05:29:35 +0000380 if (!OrigPreheader)
Chris Lattner88974f42011-04-09 07:25:58 +0000381 return false;
Devang Patelfac4d1f2007-07-11 23:47:28 +0000382
Dan Gohmanfc20b672009-09-27 15:37:03 +0000383 // Anything ScalarEvolution may know about this loop or the PHI nodes
384 // in its header will soon be invalidated.
385 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman880c92a2009-10-31 15:04:55 +0000386 SE->forgetLoop(L);
Dan Gohmanfc20b672009-09-27 15:37:03 +0000387
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000388 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
389
Devang Patelf42389f2007-04-07 01:25:15 +0000390 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattner57cb4722009-01-26 01:57:01 +0000391 // that is inside loop. Header's other successor is outside the
392 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner385f2ec2011-01-08 17:48:33 +0000393 BasicBlock *Exit = BI->getSuccessor(0);
394 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel88bc2c62007-04-09 16:11:48 +0000395 if (L->contains(Exit))
396 std::swap(Exit, NewHeader);
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000397 assert(NewHeader && "Unable to determine new loop header");
Andrew Tricka20f1982012-02-14 00:00:19 +0000398 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel88bc2c62007-04-09 16:11:48 +0000399 "Unable to determine loop header and exit blocks");
Andrew Tricka20f1982012-02-14 00:00:19 +0000400
Dan Gohman091e4402009-06-25 00:22:44 +0000401 // This code assumes that the new header has exactly one predecessor.
402 // Remove any single-entry PHI nodes in it.
Chris Lattner7b6647c2009-01-26 02:11:30 +0000403 assert(NewHeader->getSinglePredecessor() &&
404 "New header doesn't have one pred!");
405 FoldSingleEntryPHINodes(NewHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000406
Dan Gohmanb9797942009-10-24 23:19:52 +0000407 // Begin by walking OrigHeader and populating ValueMap with an entry for
408 // each Instruction.
Devang Patel88bc2c62007-04-09 16:11:48 +0000409 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000410 ValueToValueMapTy ValueMap;
Devang Patelb9af5742007-04-09 19:04:21 +0000411
Dan Gohmanb9797942009-10-24 23:19:52 +0000412 // For PHI nodes, the value available in OldPreHeader is just the
413 // incoming value from OldPreHeader.
414 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foad372ad642011-06-20 14:18:48 +0000415 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000416
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000417 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
418
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000419 // For the rest of the instructions, either hoist to the OrigPreheader if
420 // possible or create a clone in the OldPreHeader if not.
Chris Lattner30f318e2011-01-08 19:26:33 +0000421 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000422 while (I != E) {
423 Instruction *Inst = I++;
Andrew Tricka20f1982012-02-14 00:00:19 +0000424
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000425 // If the instruction's operands are invariant and it doesn't read or write
426 // memory, then it is safe to hoist. Doing this doesn't change the order of
427 // execution in the preheader, but does prevent the instruction from
428 // executing in each iteration of the loop. This means it is safe to hoist
429 // something that might trap, but isn't safe to hoist something that reads
430 // memory (without proving that the loop doesn't write).
431 if (L->hasLoopInvariantOperands(Inst) &&
432 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
Eli Friedmanc4588852012-02-16 00:41:10 +0000433 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
434 !isa<AllocaInst>(Inst)) {
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000435 Inst->moveBefore(LoopEntryBranch);
436 continue;
437 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000438
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000439 // Otherwise, create a duplicate of the instruction.
440 Instruction *C = Inst->clone();
Andrew Tricka20f1982012-02-14 00:00:19 +0000441
Chris Lattner8c5defd2011-01-08 08:24:46 +0000442 // Eagerly remap the operands of the instruction.
443 RemapInstruction(C, ValueMap,
444 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Tricka20f1982012-02-14 00:00:19 +0000445
Chris Lattner8c5defd2011-01-08 08:24:46 +0000446 // With the operands remapped, see if the instruction constant folds or is
447 // otherwise simplifyable. This commonly occurs because the entry from PHI
448 // nodes allows icmps and other instructions to fold.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000449 // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
450 Value *V = SimplifyInstruction(C, DL);
Chris Lattner25ba40a2011-01-08 17:38:45 +0000451 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000452 // If so, then delete the temporary instruction and stick the folded value
453 // in the map.
454 delete C;
455 ValueMap[Inst] = V;
456 } else {
457 // Otherwise, stick the new instruction into the new block!
458 C->setName(Inst->getName());
459 C->insertBefore(LoopEntryBranch);
460 ValueMap[Inst] = C;
461 }
Devang Patelf42389f2007-04-07 01:25:15 +0000462 }
463
Dan Gohmanb9797942009-10-24 23:19:52 +0000464 // Along with all the other instructions, we just cloned OrigHeader's
465 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
466 // successors by duplicating their incoming values for OrigHeader.
467 TerminatorInst *TI = OrigHeader->getTerminator();
468 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
469 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
470 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner30f318e2011-01-08 19:26:33 +0000471 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000472
Dan Gohmanb9797942009-10-24 23:19:52 +0000473 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
474 // OrigPreHeader's old terminator (the original branch into the loop), and
475 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
476 LoopEntryBranch->eraseFromParent();
Devang Patelf42389f2007-04-07 01:25:15 +0000477
Chris Lattner30f318e2011-01-08 19:26:33 +0000478 // If there were any uses of instructions in the duplicated block outside the
479 // loop, update them, inserting PHI nodes as required
480 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelf42389f2007-04-07 01:25:15 +0000481
Dan Gohmanb9797942009-10-24 23:19:52 +0000482 // NewHeader is now the header of the loop.
Devang Patelf42389f2007-04-07 01:25:15 +0000483 L->moveToHeader(NewHeader);
Chris Lattner26151302011-01-08 19:10:28 +0000484 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelf42389f2007-04-07 01:25:15 +0000485
Andrew Tricka20f1982012-02-14 00:00:19 +0000486
Chris Lattner59c82f82011-01-08 19:59:06 +0000487 // At this point, we've finished our major CFG changes. As part of cloning
488 // the loop into the preheader we've simplified instructions and the
489 // duplicated conditional branch may now be branching on a constant. If it is
490 // branching on a constant and if that constant means that we enter the loop,
491 // then we fold away the cond branch to an uncond branch. This simplifies the
492 // loop in cases important for nested loops, and it also means we don't have
493 // to split as many edges.
494 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
495 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
496 if (!isa<ConstantInt>(PHBI->getCondition()) ||
497 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
498 != NewHeader) {
499 // The conditional branch can't be folded, handle the general case.
500 // Update DominatorTree to reflect the CFG change we just made. Then split
501 // edges as necessary to preserve LoopSimplify form.
Chandler Carruth94209092015-01-18 02:08:05 +0000502 if (DT) {
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000503 // Everything that was dominated by the old loop header is now dominated
504 // by the original loop preheader. Conceptually the header was merged
505 // into the preheader, even though we reuse the actual block as a new
506 // loop latch.
Chandler Carruth94209092015-01-18 02:08:05 +0000507 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000508 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
509 OrigHeaderNode->end());
Chandler Carruth94209092015-01-18 02:08:05 +0000510 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000511 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
Chandler Carruth94209092015-01-18 02:08:05 +0000512 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Tricka20f1982012-02-14 00:00:19 +0000513
Chandler Carruth94209092015-01-18 02:08:05 +0000514 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
515 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
Benjamin Kramer3be6a482012-09-01 12:04:51 +0000516
Chris Lattner59c82f82011-01-08 19:59:06 +0000517 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000518 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Chris Lattner59c82f82011-01-08 19:59:06 +0000519 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000520
Chris Lattner59c82f82011-01-08 19:59:06 +0000521 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotem465834c2012-07-24 10:51:42 +0000522 // thus is not a preheader anymore.
523 // Split the edge to form a real preheader.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000524 BasicBlock *NewPH = SplitCriticalEdge(
525 OrigPreheader, NewHeader,
526 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chris Lattner59c82f82011-01-08 19:59:06 +0000527 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Tricka20f1982012-02-14 00:00:19 +0000528
Nadav Rotem465834c2012-07-24 10:51:42 +0000529 // Preserve canonical loop form, which means that 'Exit' should have only
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000530 // one predecessor. Note that Exit could be an exit block for multiple
531 // nested loops, causing both of the edges to now be critical and need to
532 // be split.
533 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
534 bool SplitLatchEdge = false;
535 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
536 PE = ExitPreds.end();
537 PI != PE; ++PI) {
538 // We only need to split loop exit edges.
539 Loop *PredLoop = LI->getLoopFor(*PI);
540 if (!PredLoop || PredLoop->contains(Exit))
541 continue;
Benjamin Kramer911d5b32015-02-20 20:49:25 +0000542 if (isa<IndirectBrInst>((*PI)->getTerminator()))
543 continue;
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000544 SplitLatchEdge |= L->getLoopLatch() == *PI;
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000545 BasicBlock *ExitSplit = SplitCriticalEdge(
546 *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000547 ExitSplit->moveBefore(Exit);
548 }
549 assert(SplitLatchEdge &&
550 "Despite splitting all preds, failed to split latch exit?");
Chris Lattner59c82f82011-01-08 19:59:06 +0000551 } else {
552 // We can fold the conditional branch in the preheader, this makes things
553 // simpler. The first step is to remove the extra edge to the Exit block.
554 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelc1f7c1d2011-04-29 20:38:55 +0000555 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
556 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner59c82f82011-01-08 19:59:06 +0000557 PHBI->eraseFromParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000558
Chris Lattner59c82f82011-01-08 19:59:06 +0000559 // With our CFG finalized, update DomTree if it is available.
Chandler Carruth94209092015-01-18 02:08:05 +0000560 if (DT) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000561 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000562 DT->changeImmediateDominator(NewHeader, OrigPreheader);
563 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000564
565 // Brute force incremental dominator tree update. Call
566 // findNearestCommonDominator on all CFG predecessors of each child of the
567 // original header.
Chandler Carruth94209092015-01-18 02:08:05 +0000568 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000569 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
570 OrigHeaderNode->end());
571 bool Changed;
572 do {
573 Changed = false;
574 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
575 DomTreeNode *Node = HeaderChildren[I];
576 BasicBlock *BB = Node->getBlock();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000577
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000578 pred_iterator PI = pred_begin(BB);
579 BasicBlock *NearestDom = *PI;
580 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
Chandler Carruth94209092015-01-18 02:08:05 +0000581 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000582
583 // Remember if this changes the DomTree.
584 if (Node->getIDom()->getBlock() != NearestDom) {
Chandler Carruth94209092015-01-18 02:08:05 +0000585 DT->changeImmediateDominator(BB, NearestDom);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000586 Changed = true;
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000587 }
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000588 }
589
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000590 // If the dominator changed, this may have an effect on other
591 // predecessors, continue until we reach a fixpoint.
592 } while (Changed);
Chris Lattner59c82f82011-01-08 19:59:06 +0000593 }
Devang Patelfac4d1f2007-07-11 23:47:28 +0000594 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000595
Chris Lattner59c82f82011-01-08 19:59:06 +0000596 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner063dca02011-01-08 18:52:51 +0000597 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000598
Chris Lattner63fe78d2011-01-11 07:47:59 +0000599 // Now that the CFG and DomTree are in a consistent state again, try to merge
600 // the OrigHeader block into OrigLatch. This will succeed if they are
601 // connected by an unconditional branch. This is just a cleanup so the
602 // emitted code isn't too gross in this common case.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000603 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
Andrew Tricka20f1982012-02-14 00:00:19 +0000604
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000605 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
606
Chris Lattnerfee37c52011-01-08 18:55:50 +0000607 ++NumRotated;
608 return true;
Devang Patel85419782007-04-09 20:19:46 +0000609}