blob: 5e6c2da08cc3276d4e83e8963c1924577cf3a7f0 [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 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"
Devang Patelfac4d1f2007-07-11 23:47:28 +000023#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000024#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Andrew Trick10cc4532012-02-14 00:00:23 +000026#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000027#include "llvm/IR/CFG.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/IntrinsicInst.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000031#include "llvm/IR/Module.h"
Owen Anderson115aa162014-05-26 08:58:51 +000032#include "llvm/Support/CommandLine.h"
Devang Patelf42389f2007-04-07 01:25:15 +000033#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Transforms/Utils/BasicBlockUtils.h"
36#include "llvm/Transforms/Utils/Local.h"
37#include "llvm/Transforms/Utils/SSAUpdater.h"
38#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelf42389f2007-04-07 01:25:15 +000039using namespace llvm;
40
Chandler Carruth964daaa2014-04-22 02:55:47 +000041#define DEBUG_TYPE "loop-rotate"
42
Owen Anderson115aa162014-05-26 08:58:51 +000043static cl::opt<unsigned>
44DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
45 cl::desc("The default maximum header size for automatic loop rotation"));
Devang Patelf42389f2007-04-07 01:25:15 +000046
47STATISTIC(NumRotated, "Number of loops rotated");
Devang Patelf42389f2007-04-07 01:25:15 +000048
Chris Lattner30f318e2011-01-08 19:26:33 +000049/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
50/// old header into the preheader. If there were uses of the values produced by
51/// these instruction that were outside of the loop, we have to insert PHI nodes
52/// to merge the two values. Do this now.
53static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
54 BasicBlock *OrigPreheader,
55 ValueToValueMapTy &ValueMap) {
56 // Remove PHI node entries that are no longer live.
57 BasicBlock::iterator I, E = OrigHeader->end();
58 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
59 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Tricka20f1982012-02-14 00:00:19 +000060
Chris Lattner30f318e2011-01-08 19:26:33 +000061 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
62 // as necessary.
63 SSAUpdater SSA;
64 for (I = OrigHeader->begin(); I != E; ++I) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +000065 Value *OrigHeaderVal = &*I;
Andrew Tricka20f1982012-02-14 00:00:19 +000066
Chris Lattner30f318e2011-01-08 19:26:33 +000067 // If there are no uses of the value (e.g. because it returns void), there
68 // is nothing to rewrite.
69 if (OrigHeaderVal->use_empty())
70 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +000071
Chris Lattner30f318e2011-01-08 19:26:33 +000072 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
73
74 // The value now exits in two versions: the initial value in the preheader
75 // and the loop "next" value in the original header.
76 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
77 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
78 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Tricka20f1982012-02-14 00:00:19 +000079
Chris Lattner30f318e2011-01-08 19:26:33 +000080 // Visit each use of the OrigHeader instruction.
81 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
82 UE = OrigHeaderVal->use_end(); UI != UE; ) {
83 // Grab the use before incrementing the iterator.
Chandler Carruthcdf47882014-03-09 03:16:01 +000084 Use &U = *UI;
Andrew Tricka20f1982012-02-14 00:00:19 +000085
Chris Lattner30f318e2011-01-08 19:26:33 +000086 // Increment the iterator before removing the use from the list.
87 ++UI;
Andrew Tricka20f1982012-02-14 00:00:19 +000088
Chris Lattner30f318e2011-01-08 19:26:33 +000089 // SSAUpdater can't handle a non-PHI use in the same block as an
90 // earlier def. We can easily handle those cases manually.
91 Instruction *UserInst = cast<Instruction>(U.getUser());
92 if (!isa<PHINode>(UserInst)) {
93 BasicBlock *UserBB = UserInst->getParent();
Andrew Tricka20f1982012-02-14 00:00:19 +000094
Chris Lattner30f318e2011-01-08 19:26:33 +000095 // The original users in the OrigHeader are already using the
96 // original definitions.
97 if (UserBB == OrigHeader)
98 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +000099
Chris Lattner30f318e2011-01-08 19:26:33 +0000100 // Users in the OrigPreHeader need to use the value to which the
101 // original definitions are mapped.
102 if (UserBB == OrigPreheader) {
103 U = OrigPreHeaderVal;
104 continue;
105 }
106 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000107
Chris Lattner30f318e2011-01-08 19:26:33 +0000108 // Anything else can be handled by SSAUpdater.
109 SSA.RewriteUse(U);
110 }
111 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000112}
Chris Lattner30f318e2011-01-08 19:26:33 +0000113
Dan Gohmanb5650eb2007-05-11 21:10:54 +0000114/// Rotate loop LP. Return true if the loop is rotated.
Andrew Trick9c72b072013-05-06 17:58:18 +0000115///
116/// \param SimplifiedLatch is true if the latch was just folded into the final
117/// loop exit. In this case we may want to rotate even though the new latch is
118/// now an exiting branch. This rotation would have happened had the latch not
119/// been simplified. However, if SimplifiedLatch is false, then we avoid
120/// rotating loops in which the latch exits to avoid excessive or endless
121/// rotation. LoopRotate should be repeatable and converge to a canonical
122/// form. This property is satisfied because simplifying the loop latch can only
123/// happen once across multiple invocations of the LoopRotate pass.
Justin Bogner6291b582015-12-14 23:22:48 +0000124static bool rotateLoop(Loop *L, unsigned MaxHeaderSize, LoopInfo *LI,
125 const TargetTransformInfo *TTI, AssumptionCache *AC,
126 DominatorTree *DT, ScalarEvolution *SE,
127 bool SimplifiedLatch) {
Dan Gohman091e4402009-06-25 00:22:44 +0000128 // If the loop has only one block then there is not much to rotate.
Devang Patel88bc2c62007-04-09 16:11:48 +0000129 if (L->getBlocks().size() == 1)
Devang Patelf42389f2007-04-07 01:25:15 +0000130 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000131
Chris Lattner7fab23b2011-01-08 18:06:22 +0000132 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000133 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Tricka20f1982012-02-14 00:00:19 +0000134
Chris Lattner7fab23b2011-01-08 18:06:22 +0000135 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000136 if (!BI || BI->isUnconditional())
Chris Lattner7fab23b2011-01-08 18:06:22 +0000137 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000138
Dan Gohman091e4402009-06-25 00:22:44 +0000139 // If the loop header is not one of the loop exiting blocks then
140 // either this loop is already rotated or it is not
Devang Patelf42389f2007-04-07 01:25:15 +0000141 // suitable for loop rotation transformations.
Dan Gohman8f4078b2009-10-24 23:34:26 +0000142 if (!L->isLoopExiting(OrigHeader))
Devang Patelf42389f2007-04-07 01:25:15 +0000143 return false;
144
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000145 // If the loop latch already contains a branch that leaves the loop then the
146 // loop is already rotated.
Craig Topperf40110f2014-04-25 05:29:35 +0000147 if (!OrigLatch)
Andrew Trick9c72b072013-05-06 17:58:18 +0000148 return false;
149
150 // Rotate if either the loop latch does *not* exit the loop, or if the loop
151 // latch was just simplified.
152 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
Devang Patelf42389f2007-04-07 01:25:15 +0000153 return false;
154
James Molloy4f6fb952012-12-20 16:04:27 +0000155 // Check size of original header and reject loop if it is very big or we can't
156 // duplicate blocks inside it.
Chris Lattner679572e2011-01-02 07:35:53 +0000157 {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000158 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000159 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000160
Chris Lattner679572e2011-01-02 07:35:53 +0000161 CodeMetrics Metrics;
Hal Finkel57f03dd2014-09-07 13:49:57 +0000162 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
James Molloy4f6fb952012-12-20 16:04:27 +0000163 if (Metrics.notDuplicatable) {
Alp Tokerf907b892013-12-05 05:44:44 +0000164 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
James Molloy4f6fb952012-12-20 16:04:27 +0000165 << " instructions: "; L->dump());
166 return false;
167 }
Owen Anderson115aa162014-05-26 08:58:51 +0000168 if (Metrics.NumInsts > MaxHeaderSize)
Chris Lattner679572e2011-01-02 07:35:53 +0000169 return false;
Devang Patelbab43b42009-03-06 03:51:30 +0000170 }
171
Devang Patelfac4d1f2007-07-11 23:47:28 +0000172 // Now, this loop is suitable for rotation.
Chris Lattner30f318e2011-01-08 19:26:33 +0000173 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Tricka20f1982012-02-14 00:00:19 +0000174
Chris Lattner88974f42011-04-09 07:25:58 +0000175 // If the loop could not be converted to canonical form, it must have an
176 // indirectbr in it, just give up.
Craig Topperf40110f2014-04-25 05:29:35 +0000177 if (!OrigPreheader)
Chris Lattner88974f42011-04-09 07:25:58 +0000178 return false;
Devang Patelfac4d1f2007-07-11 23:47:28 +0000179
Dan Gohmanfc20b672009-09-27 15:37:03 +0000180 // Anything ScalarEvolution may know about this loop or the PHI nodes
181 // in its header will soon be invalidated.
Justin Bogner6291b582015-12-14 23:22:48 +0000182 if (SE)
183 SE->forgetLoop(L);
Dan Gohmanfc20b672009-09-27 15:37:03 +0000184
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000185 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
186
Devang Patelf42389f2007-04-07 01:25:15 +0000187 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattner57cb4722009-01-26 01:57:01 +0000188 // that is inside loop. Header's other successor is outside the
189 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner385f2ec2011-01-08 17:48:33 +0000190 BasicBlock *Exit = BI->getSuccessor(0);
191 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel88bc2c62007-04-09 16:11:48 +0000192 if (L->contains(Exit))
193 std::swap(Exit, NewHeader);
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000194 assert(NewHeader && "Unable to determine new loop header");
Andrew Tricka20f1982012-02-14 00:00:19 +0000195 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel88bc2c62007-04-09 16:11:48 +0000196 "Unable to determine loop header and exit blocks");
Andrew Tricka20f1982012-02-14 00:00:19 +0000197
Dan Gohman091e4402009-06-25 00:22:44 +0000198 // This code assumes that the new header has exactly one predecessor.
199 // Remove any single-entry PHI nodes in it.
Chris Lattner7b6647c2009-01-26 02:11:30 +0000200 assert(NewHeader->getSinglePredecessor() &&
201 "New header doesn't have one pred!");
202 FoldSingleEntryPHINodes(NewHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000203
Dan Gohmanb9797942009-10-24 23:19:52 +0000204 // Begin by walking OrigHeader and populating ValueMap with an entry for
205 // each Instruction.
Devang Patel88bc2c62007-04-09 16:11:48 +0000206 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000207 ValueToValueMapTy ValueMap;
Devang Patelb9af5742007-04-09 19:04:21 +0000208
Dan Gohmanb9797942009-10-24 23:19:52 +0000209 // For PHI nodes, the value available in OldPreHeader is just the
210 // incoming value from OldPreHeader.
211 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foad372ad642011-06-20 14:18:48 +0000212 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000213
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000214 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
215
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000216 // For the rest of the instructions, either hoist to the OrigPreheader if
217 // possible or create a clone in the OldPreHeader if not.
Chris Lattner30f318e2011-01-08 19:26:33 +0000218 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000219 while (I != E) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000220 Instruction *Inst = &*I++;
Andrew Tricka20f1982012-02-14 00:00:19 +0000221
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000222 // If the instruction's operands are invariant and it doesn't read or write
223 // memory, then it is safe to hoist. Doing this doesn't change the order of
224 // execution in the preheader, but does prevent the instruction from
225 // executing in each iteration of the loop. This means it is safe to hoist
226 // something that might trap, but isn't safe to hoist something that reads
227 // memory (without proving that the loop doesn't write).
228 if (L->hasLoopInvariantOperands(Inst) &&
229 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
Eli Friedmanc4588852012-02-16 00:41:10 +0000230 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
231 !isa<AllocaInst>(Inst)) {
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000232 Inst->moveBefore(LoopEntryBranch);
233 continue;
234 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000235
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000236 // Otherwise, create a duplicate of the instruction.
237 Instruction *C = Inst->clone();
Andrew Tricka20f1982012-02-14 00:00:19 +0000238
Chris Lattner8c5defd2011-01-08 08:24:46 +0000239 // Eagerly remap the operands of the instruction.
240 RemapInstruction(C, ValueMap,
241 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Tricka20f1982012-02-14 00:00:19 +0000242
Chris Lattner8c5defd2011-01-08 08:24:46 +0000243 // With the operands remapped, see if the instruction constant folds or is
244 // otherwise simplifyable. This commonly occurs because the entry from PHI
245 // nodes allows icmps and other instructions to fold.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000246 // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
247 Value *V = SimplifyInstruction(C, DL);
Chris Lattner25ba40a2011-01-08 17:38:45 +0000248 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000249 // If so, then delete the temporary instruction and stick the folded value
250 // in the map.
251 delete C;
252 ValueMap[Inst] = V;
253 } else {
254 // Otherwise, stick the new instruction into the new block!
255 C->setName(Inst->getName());
256 C->insertBefore(LoopEntryBranch);
257 ValueMap[Inst] = C;
258 }
Devang Patelf42389f2007-04-07 01:25:15 +0000259 }
260
Dan Gohmanb9797942009-10-24 23:19:52 +0000261 // Along with all the other instructions, we just cloned OrigHeader's
262 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
263 // successors by duplicating their incoming values for OrigHeader.
264 TerminatorInst *TI = OrigHeader->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +0000265 for (BasicBlock *SuccBB : TI->successors())
266 for (BasicBlock::iterator BI = SuccBB->begin();
Dan Gohmanb9797942009-10-24 23:19:52 +0000267 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner30f318e2011-01-08 19:26:33 +0000268 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000269
Dan Gohmanb9797942009-10-24 23:19:52 +0000270 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
271 // OrigPreHeader's old terminator (the original branch into the loop), and
272 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
273 LoopEntryBranch->eraseFromParent();
Devang Patelf42389f2007-04-07 01:25:15 +0000274
Chris Lattner30f318e2011-01-08 19:26:33 +0000275 // If there were any uses of instructions in the duplicated block outside the
276 // loop, update them, inserting PHI nodes as required
277 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelf42389f2007-04-07 01:25:15 +0000278
Dan Gohmanb9797942009-10-24 23:19:52 +0000279 // NewHeader is now the header of the loop.
Devang Patelf42389f2007-04-07 01:25:15 +0000280 L->moveToHeader(NewHeader);
Chris Lattner26151302011-01-08 19:10:28 +0000281 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelf42389f2007-04-07 01:25:15 +0000282
Andrew Tricka20f1982012-02-14 00:00:19 +0000283
Chris Lattner59c82f82011-01-08 19:59:06 +0000284 // At this point, we've finished our major CFG changes. As part of cloning
285 // the loop into the preheader we've simplified instructions and the
286 // duplicated conditional branch may now be branching on a constant. If it is
287 // branching on a constant and if that constant means that we enter the loop,
288 // then we fold away the cond branch to an uncond branch. This simplifies the
289 // loop in cases important for nested loops, and it also means we don't have
290 // to split as many edges.
291 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
292 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
293 if (!isa<ConstantInt>(PHBI->getCondition()) ||
294 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
295 != NewHeader) {
296 // The conditional branch can't be folded, handle the general case.
297 // Update DominatorTree to reflect the CFG change we just made. Then split
298 // edges as necessary to preserve LoopSimplify form.
Chandler Carruth94209092015-01-18 02:08:05 +0000299 if (DT) {
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000300 // Everything that was dominated by the old loop header is now dominated
301 // by the original loop preheader. Conceptually the header was merged
302 // into the preheader, even though we reuse the actual block as a new
303 // loop latch.
Chandler Carruth94209092015-01-18 02:08:05 +0000304 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000305 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
306 OrigHeaderNode->end());
Chandler Carruth94209092015-01-18 02:08:05 +0000307 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000308 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
Chandler Carruth94209092015-01-18 02:08:05 +0000309 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Tricka20f1982012-02-14 00:00:19 +0000310
Chandler Carruth94209092015-01-18 02:08:05 +0000311 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
312 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
Benjamin Kramer3be6a482012-09-01 12:04:51 +0000313
Chris Lattner59c82f82011-01-08 19:59:06 +0000314 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000315 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Chris Lattner59c82f82011-01-08 19:59:06 +0000316 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000317
Chris Lattner59c82f82011-01-08 19:59:06 +0000318 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotem465834c2012-07-24 10:51:42 +0000319 // thus is not a preheader anymore.
320 // Split the edge to form a real preheader.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000321 BasicBlock *NewPH = SplitCriticalEdge(
322 OrigPreheader, NewHeader,
323 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chris Lattner59c82f82011-01-08 19:59:06 +0000324 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Tricka20f1982012-02-14 00:00:19 +0000325
Nadav Rotem465834c2012-07-24 10:51:42 +0000326 // Preserve canonical loop form, which means that 'Exit' should have only
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000327 // one predecessor. Note that Exit could be an exit block for multiple
328 // nested loops, causing both of the edges to now be critical and need to
329 // be split.
330 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
331 bool SplitLatchEdge = false;
332 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
333 PE = ExitPreds.end();
334 PI != PE; ++PI) {
335 // We only need to split loop exit edges.
336 Loop *PredLoop = LI->getLoopFor(*PI);
337 if (!PredLoop || PredLoop->contains(Exit))
338 continue;
Benjamin Kramer911d5b32015-02-20 20:49:25 +0000339 if (isa<IndirectBrInst>((*PI)->getTerminator()))
340 continue;
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000341 SplitLatchEdge |= L->getLoopLatch() == *PI;
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000342 BasicBlock *ExitSplit = SplitCriticalEdge(
343 *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000344 ExitSplit->moveBefore(Exit);
345 }
346 assert(SplitLatchEdge &&
347 "Despite splitting all preds, failed to split latch exit?");
Chris Lattner59c82f82011-01-08 19:59:06 +0000348 } else {
349 // We can fold the conditional branch in the preheader, this makes things
350 // simpler. The first step is to remove the extra edge to the Exit block.
351 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelc1f7c1d2011-04-29 20:38:55 +0000352 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
353 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner59c82f82011-01-08 19:59:06 +0000354 PHBI->eraseFromParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000355
Chris Lattner59c82f82011-01-08 19:59:06 +0000356 // With our CFG finalized, update DomTree if it is available.
Chandler Carruth94209092015-01-18 02:08:05 +0000357 if (DT) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000358 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000359 DT->changeImmediateDominator(NewHeader, OrigPreheader);
360 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000361
362 // Brute force incremental dominator tree update. Call
363 // findNearestCommonDominator on all CFG predecessors of each child of the
364 // original header.
Chandler Carruth94209092015-01-18 02:08:05 +0000365 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000366 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
367 OrigHeaderNode->end());
368 bool Changed;
369 do {
370 Changed = false;
371 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
372 DomTreeNode *Node = HeaderChildren[I];
373 BasicBlock *BB = Node->getBlock();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000374
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000375 pred_iterator PI = pred_begin(BB);
376 BasicBlock *NearestDom = *PI;
377 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
Chandler Carruth94209092015-01-18 02:08:05 +0000378 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000379
380 // Remember if this changes the DomTree.
381 if (Node->getIDom()->getBlock() != NearestDom) {
Chandler Carruth94209092015-01-18 02:08:05 +0000382 DT->changeImmediateDominator(BB, NearestDom);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000383 Changed = true;
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000384 }
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000385 }
386
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000387 // If the dominator changed, this may have an effect on other
388 // predecessors, continue until we reach a fixpoint.
389 } while (Changed);
Chris Lattner59c82f82011-01-08 19:59:06 +0000390 }
Devang Patelfac4d1f2007-07-11 23:47:28 +0000391 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000392
Chris Lattner59c82f82011-01-08 19:59:06 +0000393 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner063dca02011-01-08 18:52:51 +0000394 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000395
Chris Lattner63fe78d2011-01-11 07:47:59 +0000396 // Now that the CFG and DomTree are in a consistent state again, try to merge
397 // the OrigHeader block into OrigLatch. This will succeed if they are
398 // connected by an unconditional branch. This is just a cleanup so the
399 // emitted code isn't too gross in this common case.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000400 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
Andrew Tricka20f1982012-02-14 00:00:19 +0000401
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000402 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
403
Chris Lattnerfee37c52011-01-08 18:55:50 +0000404 ++NumRotated;
405 return true;
Devang Patel85419782007-04-09 20:19:46 +0000406}
Justin Bognera7300452015-12-14 23:22:44 +0000407
408/// Determine whether the instructions in this range may be safely and cheaply
409/// speculated. This is not an important enough situation to develop complex
410/// heuristics. We handle a single arithmetic instruction along with any type
411/// conversions.
412static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
413 BasicBlock::iterator End, Loop *L) {
414 bool seenIncrement = false;
415 bool MultiExitLoop = false;
416
417 if (!L->getExitingBlock())
418 MultiExitLoop = true;
419
420 for (BasicBlock::iterator I = Begin; I != End; ++I) {
421
422 if (!isSafeToSpeculativelyExecute(&*I))
423 return false;
424
425 if (isa<DbgInfoIntrinsic>(I))
426 continue;
427
428 switch (I->getOpcode()) {
429 default:
430 return false;
431 case Instruction::GetElementPtr:
432 // GEPs are cheap if all indices are constant.
433 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
434 return false;
435 // fall-thru to increment case
436 case Instruction::Add:
437 case Instruction::Sub:
438 case Instruction::And:
439 case Instruction::Or:
440 case Instruction::Xor:
441 case Instruction::Shl:
442 case Instruction::LShr:
443 case Instruction::AShr: {
444 Value *IVOpnd = !isa<Constant>(I->getOperand(0))
445 ? I->getOperand(0)
446 : !isa<Constant>(I->getOperand(1))
447 ? I->getOperand(1)
448 : nullptr;
449 if (!IVOpnd)
450 return false;
451
452 // If increment operand is used outside of the loop, this speculation
453 // could cause extra live range interference.
454 if (MultiExitLoop) {
455 for (User *UseI : IVOpnd->users()) {
456 auto *UserInst = cast<Instruction>(UseI);
457 if (!L->contains(UserInst))
458 return false;
459 }
460 }
461
462 if (seenIncrement)
463 return false;
464 seenIncrement = true;
465 break;
466 }
467 case Instruction::Trunc:
468 case Instruction::ZExt:
469 case Instruction::SExt:
470 // ignore type conversions
471 break;
472 }
473 }
474 return true;
475}
476
477/// Fold the loop tail into the loop exit by speculating the loop tail
478/// instructions. Typically, this is a single post-increment. In the case of a
479/// simple 2-block loop, hoisting the increment can be much better than
480/// duplicating the entire loop header. In the case of loops with early exits,
481/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
482/// canonical form so downstream passes can handle it.
483///
484/// I don't believe this invalidates SCEV.
Justin Bogner6291b582015-12-14 23:22:48 +0000485static bool simplifyLoopLatch(Loop *L, LoopInfo *LI, DominatorTree *DT) {
Justin Bognera7300452015-12-14 23:22:44 +0000486 BasicBlock *Latch = L->getLoopLatch();
487 if (!Latch || Latch->hasAddressTaken())
488 return false;
489
490 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
491 if (!Jmp || !Jmp->isUnconditional())
492 return false;
493
494 BasicBlock *LastExit = Latch->getSinglePredecessor();
495 if (!LastExit || !L->isLoopExiting(LastExit))
496 return false;
497
498 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
499 if (!BI)
500 return false;
501
502 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
503 return false;
504
505 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
506 << LastExit->getName() << "\n");
507
508 // Hoist the instructions from Latch into LastExit.
509 LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
510 Latch->begin(), Jmp->getIterator());
511
512 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
513 BasicBlock *Header = Jmp->getSuccessor(0);
514 assert(Header == L->getHeader() && "expected a backward branch");
515
516 // Remove Latch from the CFG so that LastExit becomes the new Latch.
517 BI->setSuccessor(FallThruPath, Header);
518 Latch->replaceSuccessorsPhiUsesWith(LastExit);
519 Jmp->eraseFromParent();
520
521 // Nuke the Latch block.
522 assert(Latch->empty() && "unable to evacuate Latch");
523 LI->removeBlock(Latch);
524 if (DT)
525 DT->eraseNode(Latch);
526 Latch->eraseFromParent();
527 return true;
528}
529
Justin Bogner6291b582015-12-14 23:22:48 +0000530/// Rotate \c L as many times as possible. Return true if the loop is rotated
531/// at least once.
532static bool iterativelyRotateLoop(Loop *L, unsigned MaxHeaderSize, LoopInfo *LI,
533 const TargetTransformInfo *TTI,
534 AssumptionCache *AC, DominatorTree *DT,
535 ScalarEvolution *SE) {
Justin Bognera7300452015-12-14 23:22:44 +0000536 // Save the loop metadata.
537 MDNode *LoopMD = L->getLoopID();
538
Justin Bognera7300452015-12-14 23:22:44 +0000539 // Simplify the loop latch before attempting to rotate the header
540 // upward. Rotation may not be needed if the loop tail can be folded into the
541 // loop exit.
Justin Bogner6291b582015-12-14 23:22:48 +0000542 bool SimplifiedLatch = simplifyLoopLatch(L, LI, DT);
Justin Bognera7300452015-12-14 23:22:44 +0000543
544 // One loop can be rotated multiple times.
545 bool MadeChange = false;
Justin Bogner6291b582015-12-14 23:22:48 +0000546 while (rotateLoop(L, MaxHeaderSize, LI, TTI, AC, DT, SE, SimplifiedLatch)) {
Justin Bognera7300452015-12-14 23:22:44 +0000547 MadeChange = true;
548 SimplifiedLatch = false;
549 }
550
551 // Restore the loop metadata.
552 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
553 if ((MadeChange || SimplifiedLatch) && LoopMD)
554 L->setLoopID(LoopMD);
555
556 return MadeChange;
557}
Justin Bogner6291b582015-12-14 23:22:48 +0000558
559namespace {
560
561class LoopRotate : public LoopPass {
562 unsigned MaxHeaderSize;
563
564public:
565 static char ID; // Pass ID, replacement for typeid
566 LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
567 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
568 if (SpecifiedMaxHeaderSize == -1)
569 MaxHeaderSize = DefaultRotationThreshold;
570 else
571 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
572 }
573
574 // LCSSA form makes instruction renaming easier.
575 void getAnalysisUsage(AnalysisUsage &AU) const override {
576 AU.addPreserved<AAResultsWrapperPass>();
577 AU.addRequired<AssumptionCacheTracker>();
578 AU.addPreserved<DominatorTreeWrapperPass>();
579 AU.addRequired<LoopInfoWrapperPass>();
580 AU.addPreserved<LoopInfoWrapperPass>();
581 AU.addRequiredID(LoopSimplifyID);
582 AU.addPreservedID(LoopSimplifyID);
583 AU.addRequiredID(LCSSAID);
584 AU.addPreservedID(LCSSAID);
585 AU.addPreserved<ScalarEvolutionWrapperPass>();
586 AU.addPreserved<SCEVAAWrapperPass>();
587 AU.addRequired<TargetTransformInfoWrapperPass>();
588 AU.addPreserved<BasicAAWrapperPass>();
589 AU.addPreserved<GlobalsAAWrapperPass>();
590 }
591
592 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
593 if (skipOptnoneFunction(L))
594 return false;
595 Function &F = *L->getHeader()->getParent();
596
597 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
598 const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
599 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
600 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
601 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
602 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
603 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
604
605 return iterativelyRotateLoop(L, MaxHeaderSize, LI, TTI, AC, DT, SE);
606 }
607};
608}
609
610char LoopRotate::ID = 0;
611INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
612INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
613INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
614INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
615INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
616INITIALIZE_PASS_DEPENDENCY(LCSSA)
617INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
618INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
619INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
620INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
621
622Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
623 return new LoopRotate(MaxHeaderSize);
624}