blob: c6709d5334a0f1a1b51f0e124401057cbf40debe [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
Justin Bognerd0d23412016-05-03 22:02:31 +000014#include "llvm/Transforms/Scalar/LoopRotation.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Statistic.h"
Chandler Carruth08eebe22015-07-23 09:34:01 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000017#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000018#include "llvm/Analysis/AssumptionCache.h"
Chris Lattner679572e2011-01-02 07:35:53 +000019#include "llvm/Analysis/CodeMetrics.h"
Chris Lattner8c5defd2011-01-08 08:24:46 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000021#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/LoopPass.h"
Justin Bognerd0d23412016-05-03 22:02:31 +000023#include "llvm/Analysis/LoopPassManager.h"
Devang Patelfac4d1f2007-07-11 23:47:28 +000024#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000025#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000026#include "llvm/Analysis/TargetTransformInfo.h"
Andrew Trick10cc4532012-02-14 00:00:23 +000027#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000028#include "llvm/IR/CFG.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/IntrinsicInst.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000032#include "llvm/IR/Module.h"
Owen Anderson115aa162014-05-26 08:58:51 +000033#include "llvm/Support/CommandLine.h"
Devang Patelf42389f2007-04-07 01:25:15 +000034#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000035#include "llvm/Support/raw_ostream.h"
Justin Bognerd0d23412016-05-03 22:02:31 +000036#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
38#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000039#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Transforms/Utils/SSAUpdater.h"
41#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelf42389f2007-04-07 01:25:15 +000042using namespace llvm;
43
Chandler Carruth964daaa2014-04-22 02:55:47 +000044#define DEBUG_TYPE "loop-rotate"
45
Sebastian Popdfb66a12016-06-14 14:44:05 +000046static cl::opt<unsigned> DefaultRotationThreshold(
47 "rotation-max-header-size", cl::init(16), cl::Hidden,
48 cl::desc("The default maximum header size for automatic loop rotation"));
Devang Patelf42389f2007-04-07 01:25:15 +000049
50STATISTIC(NumRotated, "Number of loops rotated");
Devang Patelf42389f2007-04-07 01:25:15 +000051
Sebastian Popdfb66a12016-06-14 14:44:05 +000052/// A simple loop rotation transformation.
53class LoopRotate {
54 const unsigned MaxHeaderSize;
55 LoopInfo *LI;
56 const TargetTransformInfo *TTI;
57 AssumptionCache *AC;
58 DominatorTree *DT;
59 ScalarEvolution *SE;
60
61public:
62 LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
63 const TargetTransformInfo *TTI, AssumptionCache *AC,
64 DominatorTree *DT, ScalarEvolution *SE)
65 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE) {
66 }
67 bool processLoop(Loop *L);
68
69private:
70 bool rotateLoop(Loop *L, bool SimplifiedLatch);
71 bool simplifyLoopLatch(Loop *L);
72};
73
Chris Lattner30f318e2011-01-08 19:26:33 +000074/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
75/// old header into the preheader. If there were uses of the values produced by
76/// these instruction that were outside of the loop, we have to insert PHI nodes
77/// to merge the two values. Do this now.
78static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
79 BasicBlock *OrigPreheader,
80 ValueToValueMapTy &ValueMap) {
81 // Remove PHI node entries that are no longer live.
82 BasicBlock::iterator I, E = OrigHeader->end();
83 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
84 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Tricka20f1982012-02-14 00:00:19 +000085
Chris Lattner30f318e2011-01-08 19:26:33 +000086 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
87 // as necessary.
88 SSAUpdater SSA;
89 for (I = OrigHeader->begin(); I != E; ++I) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +000090 Value *OrigHeaderVal = &*I;
Andrew Tricka20f1982012-02-14 00:00:19 +000091
Chris Lattner30f318e2011-01-08 19:26:33 +000092 // If there are no uses of the value (e.g. because it returns void), there
93 // is nothing to rewrite.
94 if (OrigHeaderVal->use_empty())
95 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +000096
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +000097 Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
Chris Lattner30f318e2011-01-08 19:26:33 +000098
99 // The value now exits in two versions: the initial value in the preheader
100 // and the loop "next" value in the original header.
101 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
102 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
103 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Tricka20f1982012-02-14 00:00:19 +0000104
Chris Lattner30f318e2011-01-08 19:26:33 +0000105 // Visit each use of the OrigHeader instruction.
106 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
Sebastian Popdfb66a12016-06-14 14:44:05 +0000107 UE = OrigHeaderVal->use_end();
108 UI != UE;) {
Chris Lattner30f318e2011-01-08 19:26:33 +0000109 // Grab the use before incrementing the iterator.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000110 Use &U = *UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000111
Chris Lattner30f318e2011-01-08 19:26:33 +0000112 // Increment the iterator before removing the use from the list.
113 ++UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000114
Chris Lattner30f318e2011-01-08 19:26:33 +0000115 // SSAUpdater can't handle a non-PHI use in the same block as an
116 // earlier def. We can easily handle those cases manually.
117 Instruction *UserInst = cast<Instruction>(U.getUser());
118 if (!isa<PHINode>(UserInst)) {
119 BasicBlock *UserBB = UserInst->getParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000120
Chris Lattner30f318e2011-01-08 19:26:33 +0000121 // The original users in the OrigHeader are already using the
122 // original definitions.
123 if (UserBB == OrigHeader)
124 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000125
Chris Lattner30f318e2011-01-08 19:26:33 +0000126 // Users in the OrigPreHeader need to use the value to which the
127 // original definitions are mapped.
128 if (UserBB == OrigPreheader) {
129 U = OrigPreHeaderVal;
130 continue;
131 }
132 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000133
Chris Lattner30f318e2011-01-08 19:26:33 +0000134 // Anything else can be handled by SSAUpdater.
135 SSA.RewriteUse(U);
136 }
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000137
138 // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
139 // intrinsics.
140 LLVMContext &C = OrigHeader->getContext();
141 if (auto *VAM = ValueAsMetadata::getIfExists(OrigHeaderVal)) {
142 if (auto *MAV = MetadataAsValue::getIfExists(C, VAM)) {
Sebastian Popdfb66a12016-06-14 14:44:05 +0000143 for (auto UI = MAV->use_begin(), E = MAV->use_end(); UI != E;) {
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000144 // Grab the use before incrementing the iterator. Otherwise, altering
145 // the Use will invalidate the iterator.
146 Use &U = *UI++;
147 DbgInfoIntrinsic *UserInst = dyn_cast<DbgInfoIntrinsic>(U.getUser());
Sebastian Popdfb66a12016-06-14 14:44:05 +0000148 if (!UserInst)
149 continue;
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000150
151 // The original users in the OrigHeader are already using the original
152 // definitions.
153 BasicBlock *UserBB = UserInst->getParent();
154 if (UserBB == OrigHeader)
155 continue;
156
157 // Users in the OrigPreHeader need to use the value to which the
158 // original definitions are mapped and anything else can be handled by
159 // the SSAUpdater. To avoid adding PHINodes, check if the value is
160 // available in UserBB, if not substitute undef.
161 Value *NewVal;
162 if (UserBB == OrigPreheader)
163 NewVal = OrigPreHeaderVal;
164 else if (SSA.HasValueForBlock(UserBB))
165 NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
166 else
167 NewVal = UndefValue::get(OrigHeaderVal->getType());
168 U = MetadataAsValue::get(C, ValueAsMetadata::get(NewVal));
169 }
170 }
171 }
Chris Lattner30f318e2011-01-08 19:26:33 +0000172 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000173}
Chris Lattner30f318e2011-01-08 19:26:33 +0000174
Dan Gohmanb5650eb2007-05-11 21:10:54 +0000175/// Rotate loop LP. Return true if the loop is rotated.
Andrew Trick9c72b072013-05-06 17:58:18 +0000176///
177/// \param SimplifiedLatch is true if the latch was just folded into the final
178/// loop exit. In this case we may want to rotate even though the new latch is
179/// now an exiting branch. This rotation would have happened had the latch not
180/// been simplified. However, if SimplifiedLatch is false, then we avoid
181/// rotating loops in which the latch exits to avoid excessive or endless
182/// rotation. LoopRotate should be repeatable and converge to a canonical
183/// form. This property is satisfied because simplifying the loop latch can only
184/// happen once across multiple invocations of the LoopRotate pass.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000185bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
Dan Gohman091e4402009-06-25 00:22:44 +0000186 // If the loop has only one block then there is not much to rotate.
Devang Patel88bc2c62007-04-09 16:11:48 +0000187 if (L->getBlocks().size() == 1)
Devang Patelf42389f2007-04-07 01:25:15 +0000188 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000189
Chris Lattner7fab23b2011-01-08 18:06:22 +0000190 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000191 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Tricka20f1982012-02-14 00:00:19 +0000192
Chris Lattner7fab23b2011-01-08 18:06:22 +0000193 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000194 if (!BI || BI->isUnconditional())
Chris Lattner7fab23b2011-01-08 18:06:22 +0000195 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000196
Dan Gohman091e4402009-06-25 00:22:44 +0000197 // If the loop header is not one of the loop exiting blocks then
198 // either this loop is already rotated or it is not
Devang Patelf42389f2007-04-07 01:25:15 +0000199 // suitable for loop rotation transformations.
Dan Gohman8f4078b2009-10-24 23:34:26 +0000200 if (!L->isLoopExiting(OrigHeader))
Devang Patelf42389f2007-04-07 01:25:15 +0000201 return false;
202
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000203 // If the loop latch already contains a branch that leaves the loop then the
204 // loop is already rotated.
Craig Topperf40110f2014-04-25 05:29:35 +0000205 if (!OrigLatch)
Andrew Trick9c72b072013-05-06 17:58:18 +0000206 return false;
207
208 // Rotate if either the loop latch does *not* exit the loop, or if the loop
209 // latch was just simplified.
210 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
Devang Patelf42389f2007-04-07 01:25:15 +0000211 return false;
212
James Molloy4f6fb952012-12-20 16:04:27 +0000213 // Check size of original header and reject loop if it is very big or we can't
214 // duplicate blocks inside it.
Chris Lattner679572e2011-01-02 07:35:53 +0000215 {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000216 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000217 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000218
Chris Lattner679572e2011-01-02 07:35:53 +0000219 CodeMetrics Metrics;
Hal Finkel57f03dd2014-09-07 13:49:57 +0000220 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
James Molloy4f6fb952012-12-20 16:04:27 +0000221 if (Metrics.notDuplicatable) {
Alp Tokerf907b892013-12-05 05:44:44 +0000222 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
Sebastian Popdfb66a12016-06-14 14:44:05 +0000223 << " instructions: ";
224 L->dump());
James Molloy4f6fb952012-12-20 16:04:27 +0000225 return false;
226 }
Justin Lebardf04d2a2016-02-12 21:01:33 +0000227 if (Metrics.convergent) {
228 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
Sebastian Popdfb66a12016-06-14 14:44:05 +0000229 "instructions: ";
230 L->dump());
Justin Lebardf04d2a2016-02-12 21:01:33 +0000231 return false;
232 }
Owen Anderson115aa162014-05-26 08:58:51 +0000233 if (Metrics.NumInsts > MaxHeaderSize)
Chris Lattner679572e2011-01-02 07:35:53 +0000234 return false;
Devang Patelbab43b42009-03-06 03:51:30 +0000235 }
236
Devang Patelfac4d1f2007-07-11 23:47:28 +0000237 // Now, this loop is suitable for rotation.
Chris Lattner30f318e2011-01-08 19:26:33 +0000238 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Tricka20f1982012-02-14 00:00:19 +0000239
Chris Lattner88974f42011-04-09 07:25:58 +0000240 // If the loop could not be converted to canonical form, it must have an
241 // indirectbr in it, just give up.
Craig Topperf40110f2014-04-25 05:29:35 +0000242 if (!OrigPreheader)
Chris Lattner88974f42011-04-09 07:25:58 +0000243 return false;
Devang Patelfac4d1f2007-07-11 23:47:28 +0000244
Dan Gohmanfc20b672009-09-27 15:37:03 +0000245 // Anything ScalarEvolution may know about this loop or the PHI nodes
246 // in its header will soon be invalidated.
Justin Bogner6291b582015-12-14 23:22:48 +0000247 if (SE)
248 SE->forgetLoop(L);
Dan Gohmanfc20b672009-09-27 15:37:03 +0000249
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000250 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
251
Devang Patelf42389f2007-04-07 01:25:15 +0000252 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattner57cb4722009-01-26 01:57:01 +0000253 // that is inside loop. Header's other successor is outside the
254 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner385f2ec2011-01-08 17:48:33 +0000255 BasicBlock *Exit = BI->getSuccessor(0);
256 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel88bc2c62007-04-09 16:11:48 +0000257 if (L->contains(Exit))
258 std::swap(Exit, NewHeader);
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000259 assert(NewHeader && "Unable to determine new loop header");
Andrew Tricka20f1982012-02-14 00:00:19 +0000260 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel88bc2c62007-04-09 16:11:48 +0000261 "Unable to determine loop header and exit blocks");
Andrew Tricka20f1982012-02-14 00:00:19 +0000262
Dan Gohman091e4402009-06-25 00:22:44 +0000263 // This code assumes that the new header has exactly one predecessor.
264 // Remove any single-entry PHI nodes in it.
Chris Lattner7b6647c2009-01-26 02:11:30 +0000265 assert(NewHeader->getSinglePredecessor() &&
266 "New header doesn't have one pred!");
267 FoldSingleEntryPHINodes(NewHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000268
Dan Gohmanb9797942009-10-24 23:19:52 +0000269 // Begin by walking OrigHeader and populating ValueMap with an entry for
270 // each Instruction.
Devang Patel88bc2c62007-04-09 16:11:48 +0000271 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000272 ValueToValueMapTy ValueMap;
Devang Patelb9af5742007-04-09 19:04:21 +0000273
Dan Gohmanb9797942009-10-24 23:19:52 +0000274 // For PHI nodes, the value available in OldPreHeader is just the
275 // incoming value from OldPreHeader.
276 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foad372ad642011-06-20 14:18:48 +0000277 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000278
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000279 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
280
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000281 // For the rest of the instructions, either hoist to the OrigPreheader if
282 // possible or create a clone in the OldPreHeader if not.
Chris Lattner30f318e2011-01-08 19:26:33 +0000283 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000284 while (I != E) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000285 Instruction *Inst = &*I++;
Andrew Tricka20f1982012-02-14 00:00:19 +0000286
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000287 // If the instruction's operands are invariant and it doesn't read or write
288 // memory, then it is safe to hoist. Doing this doesn't change the order of
289 // execution in the preheader, but does prevent the instruction from
290 // executing in each iteration of the loop. This means it is safe to hoist
291 // something that might trap, but isn't safe to hoist something that reads
292 // memory (without proving that the loop doesn't write).
Sebastian Popdfb66a12016-06-14 14:44:05 +0000293 if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
294 !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) &&
295 !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000296 Inst->moveBefore(LoopEntryBranch);
297 continue;
298 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000299
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000300 // Otherwise, create a duplicate of the instruction.
301 Instruction *C = Inst->clone();
Andrew Tricka20f1982012-02-14 00:00:19 +0000302
Chris Lattner8c5defd2011-01-08 08:24:46 +0000303 // Eagerly remap the operands of the instruction.
304 RemapInstruction(C, ValueMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000305 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Tricka20f1982012-02-14 00:00:19 +0000306
Chris Lattner8c5defd2011-01-08 08:24:46 +0000307 // With the operands remapped, see if the instruction constant folds or is
308 // otherwise simplifyable. This commonly occurs because the entry from PHI
309 // nodes allows icmps and other instructions to fold.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000310 // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
311 Value *V = SimplifyInstruction(C, DL);
Chris Lattner25ba40a2011-01-08 17:38:45 +0000312 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000313 // If so, then delete the temporary instruction and stick the folded value
314 // in the map.
315 delete C;
316 ValueMap[Inst] = V;
317 } else {
318 // Otherwise, stick the new instruction into the new block!
319 C->setName(Inst->getName());
320 C->insertBefore(LoopEntryBranch);
321 ValueMap[Inst] = C;
322 }
Devang Patelf42389f2007-04-07 01:25:15 +0000323 }
324
Dan Gohmanb9797942009-10-24 23:19:52 +0000325 // Along with all the other instructions, we just cloned OrigHeader's
326 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
327 // successors by duplicating their incoming values for OrigHeader.
328 TerminatorInst *TI = OrigHeader->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +0000329 for (BasicBlock *SuccBB : TI->successors())
330 for (BasicBlock::iterator BI = SuccBB->begin();
Dan Gohmanb9797942009-10-24 23:19:52 +0000331 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner30f318e2011-01-08 19:26:33 +0000332 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000333
Dan Gohmanb9797942009-10-24 23:19:52 +0000334 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
335 // OrigPreHeader's old terminator (the original branch into the loop), and
336 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
337 LoopEntryBranch->eraseFromParent();
Devang Patelf42389f2007-04-07 01:25:15 +0000338
Chris Lattner30f318e2011-01-08 19:26:33 +0000339 // If there were any uses of instructions in the duplicated block outside the
340 // loop, update them, inserting PHI nodes as required
341 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelf42389f2007-04-07 01:25:15 +0000342
Dan Gohmanb9797942009-10-24 23:19:52 +0000343 // NewHeader is now the header of the loop.
Devang Patelf42389f2007-04-07 01:25:15 +0000344 L->moveToHeader(NewHeader);
Chris Lattner26151302011-01-08 19:10:28 +0000345 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelf42389f2007-04-07 01:25:15 +0000346
Chris Lattner59c82f82011-01-08 19:59:06 +0000347 // At this point, we've finished our major CFG changes. As part of cloning
348 // the loop into the preheader we've simplified instructions and the
349 // duplicated conditional branch may now be branching on a constant. If it is
350 // branching on a constant and if that constant means that we enter the loop,
351 // then we fold away the cond branch to an uncond branch. This simplifies the
352 // loop in cases important for nested loops, and it also means we don't have
353 // to split as many edges.
354 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
355 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
356 if (!isa<ConstantInt>(PHBI->getCondition()) ||
Sebastian Popdfb66a12016-06-14 14:44:05 +0000357 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
358 NewHeader) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000359 // The conditional branch can't be folded, handle the general case.
360 // Update DominatorTree to reflect the CFG change we just made. Then split
361 // edges as necessary to preserve LoopSimplify form.
Chandler Carruth94209092015-01-18 02:08:05 +0000362 if (DT) {
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000363 // Everything that was dominated by the old loop header is now dominated
364 // by the original loop preheader. Conceptually the header was merged
365 // into the preheader, even though we reuse the actual block as a new
366 // loop latch.
Chandler Carruth94209092015-01-18 02:08:05 +0000367 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000368 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
369 OrigHeaderNode->end());
Chandler Carruth94209092015-01-18 02:08:05 +0000370 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000371 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
Chandler Carruth94209092015-01-18 02:08:05 +0000372 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Tricka20f1982012-02-14 00:00:19 +0000373
Chandler Carruth94209092015-01-18 02:08:05 +0000374 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
375 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
Benjamin Kramer3be6a482012-09-01 12:04:51 +0000376
Chris Lattner59c82f82011-01-08 19:59:06 +0000377 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000378 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Chris Lattner59c82f82011-01-08 19:59:06 +0000379 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000380
Chris Lattner59c82f82011-01-08 19:59:06 +0000381 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotem465834c2012-07-24 10:51:42 +0000382 // thus is not a preheader anymore.
383 // Split the edge to form a real preheader.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000384 BasicBlock *NewPH = SplitCriticalEdge(
385 OrigPreheader, NewHeader,
386 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chris Lattner59c82f82011-01-08 19:59:06 +0000387 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Tricka20f1982012-02-14 00:00:19 +0000388
Nadav Rotem465834c2012-07-24 10:51:42 +0000389 // Preserve canonical loop form, which means that 'Exit' should have only
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000390 // one predecessor. Note that Exit could be an exit block for multiple
391 // nested loops, causing both of the edges to now be critical and need to
392 // be split.
393 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
394 bool SplitLatchEdge = false;
395 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
396 PE = ExitPreds.end();
397 PI != PE; ++PI) {
398 // We only need to split loop exit edges.
399 Loop *PredLoop = LI->getLoopFor(*PI);
400 if (!PredLoop || PredLoop->contains(Exit))
401 continue;
Benjamin Kramer911d5b32015-02-20 20:49:25 +0000402 if (isa<IndirectBrInst>((*PI)->getTerminator()))
403 continue;
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000404 SplitLatchEdge |= L->getLoopLatch() == *PI;
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000405 BasicBlock *ExitSplit = SplitCriticalEdge(
406 *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000407 ExitSplit->moveBefore(Exit);
408 }
409 assert(SplitLatchEdge &&
410 "Despite splitting all preds, failed to split latch exit?");
Chris Lattner59c82f82011-01-08 19:59:06 +0000411 } else {
412 // We can fold the conditional branch in the preheader, this makes things
413 // simpler. The first step is to remove the extra edge to the Exit block.
414 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelc1f7c1d2011-04-29 20:38:55 +0000415 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
416 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner59c82f82011-01-08 19:59:06 +0000417 PHBI->eraseFromParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000418
Chris Lattner59c82f82011-01-08 19:59:06 +0000419 // With our CFG finalized, update DomTree if it is available.
Chandler Carruth94209092015-01-18 02:08:05 +0000420 if (DT) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000421 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000422 DT->changeImmediateDominator(NewHeader, OrigPreheader);
423 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000424
425 // Brute force incremental dominator tree update. Call
426 // findNearestCommonDominator on all CFG predecessors of each child of the
427 // original header.
Chandler Carruth94209092015-01-18 02:08:05 +0000428 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000429 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
430 OrigHeaderNode->end());
431 bool Changed;
432 do {
433 Changed = false;
434 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
435 DomTreeNode *Node = HeaderChildren[I];
436 BasicBlock *BB = Node->getBlock();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000437
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000438 pred_iterator PI = pred_begin(BB);
439 BasicBlock *NearestDom = *PI;
440 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
Chandler Carruth94209092015-01-18 02:08:05 +0000441 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000442
443 // Remember if this changes the DomTree.
444 if (Node->getIDom()->getBlock() != NearestDom) {
Chandler Carruth94209092015-01-18 02:08:05 +0000445 DT->changeImmediateDominator(BB, NearestDom);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000446 Changed = true;
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000447 }
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000448 }
449
Sebastian Popdfb66a12016-06-14 14:44:05 +0000450 // If the dominator changed, this may have an effect on other
451 // predecessors, continue until we reach a fixpoint.
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000452 } while (Changed);
Chris Lattner59c82f82011-01-08 19:59:06 +0000453 }
Devang Patelfac4d1f2007-07-11 23:47:28 +0000454 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000455
Chris Lattner59c82f82011-01-08 19:59:06 +0000456 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner063dca02011-01-08 18:52:51 +0000457 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000458
Chris Lattner63fe78d2011-01-11 07:47:59 +0000459 // Now that the CFG and DomTree are in a consistent state again, try to merge
460 // the OrigHeader block into OrigLatch. This will succeed if they are
461 // connected by an unconditional branch. This is just a cleanup so the
462 // emitted code isn't too gross in this common case.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000463 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
Andrew Tricka20f1982012-02-14 00:00:19 +0000464
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000465 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
466
Chris Lattnerfee37c52011-01-08 18:55:50 +0000467 ++NumRotated;
468 return true;
Devang Patel85419782007-04-09 20:19:46 +0000469}
Justin Bognera7300452015-12-14 23:22:44 +0000470
471/// Determine whether the instructions in this range may be safely and cheaply
472/// speculated. This is not an important enough situation to develop complex
473/// heuristics. We handle a single arithmetic instruction along with any type
474/// conversions.
475static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
476 BasicBlock::iterator End, Loop *L) {
477 bool seenIncrement = false;
478 bool MultiExitLoop = false;
479
480 if (!L->getExitingBlock())
481 MultiExitLoop = true;
482
483 for (BasicBlock::iterator I = Begin; I != End; ++I) {
484
485 if (!isSafeToSpeculativelyExecute(&*I))
486 return false;
487
488 if (isa<DbgInfoIntrinsic>(I))
489 continue;
490
491 switch (I->getOpcode()) {
492 default:
493 return false;
494 case Instruction::GetElementPtr:
495 // GEPs are cheap if all indices are constant.
496 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
497 return false;
Sebastian Popdfb66a12016-06-14 14:44:05 +0000498 // fall-thru to increment case
Justin Bognera7300452015-12-14 23:22:44 +0000499 case Instruction::Add:
500 case Instruction::Sub:
501 case Instruction::And:
502 case Instruction::Or:
503 case Instruction::Xor:
504 case Instruction::Shl:
505 case Instruction::LShr:
506 case Instruction::AShr: {
Sebastian Popdfb66a12016-06-14 14:44:05 +0000507 Value *IVOpnd =
508 !isa<Constant>(I->getOperand(0))
509 ? I->getOperand(0)
510 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
Justin Bognera7300452015-12-14 23:22:44 +0000511 if (!IVOpnd)
512 return false;
513
514 // If increment operand is used outside of the loop, this speculation
515 // could cause extra live range interference.
516 if (MultiExitLoop) {
517 for (User *UseI : IVOpnd->users()) {
518 auto *UserInst = cast<Instruction>(UseI);
519 if (!L->contains(UserInst))
520 return false;
521 }
522 }
523
524 if (seenIncrement)
525 return false;
526 seenIncrement = true;
527 break;
528 }
529 case Instruction::Trunc:
530 case Instruction::ZExt:
531 case Instruction::SExt:
532 // ignore type conversions
533 break;
534 }
535 }
536 return true;
537}
538
539/// Fold the loop tail into the loop exit by speculating the loop tail
540/// instructions. Typically, this is a single post-increment. In the case of a
541/// simple 2-block loop, hoisting the increment can be much better than
542/// duplicating the entire loop header. In the case of loops with early exits,
543/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
544/// canonical form so downstream passes can handle it.
545///
546/// I don't believe this invalidates SCEV.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000547bool LoopRotate::simplifyLoopLatch(Loop *L) {
Justin Bognera7300452015-12-14 23:22:44 +0000548 BasicBlock *Latch = L->getLoopLatch();
549 if (!Latch || Latch->hasAddressTaken())
550 return false;
551
552 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
553 if (!Jmp || !Jmp->isUnconditional())
554 return false;
555
556 BasicBlock *LastExit = Latch->getSinglePredecessor();
557 if (!LastExit || !L->isLoopExiting(LastExit))
558 return false;
559
560 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
561 if (!BI)
562 return false;
563
564 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
565 return false;
566
567 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
Sebastian Popdfb66a12016-06-14 14:44:05 +0000568 << LastExit->getName() << "\n");
Justin Bognera7300452015-12-14 23:22:44 +0000569
570 // Hoist the instructions from Latch into LastExit.
571 LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
572 Latch->begin(), Jmp->getIterator());
573
574 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
575 BasicBlock *Header = Jmp->getSuccessor(0);
576 assert(Header == L->getHeader() && "expected a backward branch");
577
578 // Remove Latch from the CFG so that LastExit becomes the new Latch.
579 BI->setSuccessor(FallThruPath, Header);
580 Latch->replaceSuccessorsPhiUsesWith(LastExit);
581 Jmp->eraseFromParent();
582
583 // Nuke the Latch block.
584 assert(Latch->empty() && "unable to evacuate Latch");
585 LI->removeBlock(Latch);
586 if (DT)
587 DT->eraseNode(Latch);
588 Latch->eraseFromParent();
589 return true;
590}
591
Michael Zolotukhinb98294d2016-06-10 22:03:56 +0000592/// Rotate \c L, and return true if any modification was made.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000593bool LoopRotate::processLoop(Loop *L) {
Justin Bognera7300452015-12-14 23:22:44 +0000594 // Save the loop metadata.
595 MDNode *LoopMD = L->getLoopID();
596
Justin Bognera7300452015-12-14 23:22:44 +0000597 // Simplify the loop latch before attempting to rotate the header
598 // upward. Rotation may not be needed if the loop tail can be folded into the
599 // loop exit.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000600 bool SimplifiedLatch = simplifyLoopLatch(L);
Justin Bognera7300452015-12-14 23:22:44 +0000601
Sebastian Popdfb66a12016-06-14 14:44:05 +0000602 bool MadeChange = rotateLoop(L, SimplifiedLatch);
Michael Zolotukhinb98294d2016-06-10 22:03:56 +0000603 assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
604 "Loop latch should be exiting after loop-rotate.");
Justin Bognera7300452015-12-14 23:22:44 +0000605
606 // Restore the loop metadata.
607 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
608 if ((MadeChange || SimplifiedLatch) && LoopMD)
609 L->setLoopID(LoopMD);
610
611 return MadeChange;
612}
Justin Bogner6291b582015-12-14 23:22:48 +0000613
Sebastian Popdfb66a12016-06-14 14:44:05 +0000614LoopRotatePass::LoopRotatePass() {}
Justin Bognerd0d23412016-05-03 22:02:31 +0000615
616PreservedAnalyses LoopRotatePass::run(Loop &L, AnalysisManager<Loop> &AM) {
617 auto &FAM = AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
618 Function *F = L.getHeader()->getParent();
619
620 auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
621 const auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F);
622 auto *AC = FAM.getCachedResult<AssumptionAnalysis>(*F);
623 assert((LI && TTI && AC) && "Analyses for loop rotation not available");
624
625 // Optional analyses.
626 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
627 auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
Sebastian Popdfb66a12016-06-14 14:44:05 +0000628 LoopRotate LR(DefaultRotationThreshold, LI, TTI, AC, DT, SE);
Justin Bognerd0d23412016-05-03 22:02:31 +0000629
Sebastian Popdfb66a12016-06-14 14:44:05 +0000630 bool Changed = LR.processLoop(&L);
Justin Bognerd0d23412016-05-03 22:02:31 +0000631 if (!Changed)
632 return PreservedAnalyses::all();
633 return getLoopPassPreservedAnalyses();
634}
635
Justin Bogner6291b582015-12-14 23:22:48 +0000636namespace {
637
Justin Bognerd0d23412016-05-03 22:02:31 +0000638class LoopRotateLegacyPass : public LoopPass {
Justin Bogner6291b582015-12-14 23:22:48 +0000639 unsigned MaxHeaderSize;
640
641public:
642 static char ID; // Pass ID, replacement for typeid
Justin Bognerd0d23412016-05-03 22:02:31 +0000643 LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
644 initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry());
Justin Bogner6291b582015-12-14 23:22:48 +0000645 if (SpecifiedMaxHeaderSize == -1)
646 MaxHeaderSize = DefaultRotationThreshold;
647 else
648 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
649 }
650
651 // LCSSA form makes instruction renaming easier.
652 void getAnalysisUsage(AnalysisUsage &AU) const override {
Justin Bogner6291b582015-12-14 23:22:48 +0000653 AU.addRequired<AssumptionCacheTracker>();
Justin Bogner6291b582015-12-14 23:22:48 +0000654 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000655 getLoopAnalysisUsage(AU);
Justin Bogner6291b582015-12-14 23:22:48 +0000656 }
657
658 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000659 if (skipLoop(L))
Justin Bogner6291b582015-12-14 23:22:48 +0000660 return false;
661 Function &F = *L->getHeader()->getParent();
662
663 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
664 const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
665 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
666 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
667 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
668 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
669 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
Sebastian Popdfb66a12016-06-14 14:44:05 +0000670 LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE);
671 return LR.processLoop(L);
Justin Bogner6291b582015-12-14 23:22:48 +0000672 }
673};
674}
675
Justin Bognerd0d23412016-05-03 22:02:31 +0000676char LoopRotateLegacyPass::ID = 0;
677INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
678 false, false)
Justin Bogner6291b582015-12-14 23:22:48 +0000679INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +0000680INITIALIZE_PASS_DEPENDENCY(LoopPass)
681INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Sebastian Popdfb66a12016-06-14 14:44:05 +0000682INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false,
683 false)
Justin Bogner6291b582015-12-14 23:22:48 +0000684
685Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
Justin Bognerd0d23412016-05-03 22:02:31 +0000686 return new LoopRotateLegacyPass(MaxHeaderSize);
Justin Bogner6291b582015-12-14 23:22:48 +0000687}