1*9880d681SAndroid Build Coastguard Worker //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file implements Loop Rotation Pass.
11*9880d681SAndroid Build Coastguard Worker //
12*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
13*9880d681SAndroid Build Coastguard Worker
14*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar/LoopRotation.h"
15*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AliasAnalysis.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/BasicAliasAnalysis.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CodeMetrics.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopPass.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopPassManager.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolution.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetTransformInfo.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CFG.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Function.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/LoopUtils.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/SSAUpdater.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/ValueMapper.h"
42*9880d681SAndroid Build Coastguard Worker using namespace llvm;
43*9880d681SAndroid Build Coastguard Worker
44*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "loop-rotate"
45*9880d681SAndroid Build Coastguard Worker
46*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned> DefaultRotationThreshold(
47*9880d681SAndroid Build Coastguard Worker "rotation-max-header-size", cl::init(16), cl::Hidden,
48*9880d681SAndroid Build Coastguard Worker cl::desc("The default maximum header size for automatic loop rotation"));
49*9880d681SAndroid Build Coastguard Worker
50*9880d681SAndroid Build Coastguard Worker STATISTIC(NumRotated, "Number of loops rotated");
51*9880d681SAndroid Build Coastguard Worker
52*9880d681SAndroid Build Coastguard Worker namespace {
53*9880d681SAndroid Build Coastguard Worker /// A simple loop rotation transformation.
54*9880d681SAndroid Build Coastguard Worker class LoopRotate {
55*9880d681SAndroid Build Coastguard Worker const unsigned MaxHeaderSize;
56*9880d681SAndroid Build Coastguard Worker LoopInfo *LI;
57*9880d681SAndroid Build Coastguard Worker const TargetTransformInfo *TTI;
58*9880d681SAndroid Build Coastguard Worker AssumptionCache *AC;
59*9880d681SAndroid Build Coastguard Worker DominatorTree *DT;
60*9880d681SAndroid Build Coastguard Worker ScalarEvolution *SE;
61*9880d681SAndroid Build Coastguard Worker
62*9880d681SAndroid Build Coastguard Worker public:
LoopRotate(unsigned MaxHeaderSize,LoopInfo * LI,const TargetTransformInfo * TTI,AssumptionCache * AC,DominatorTree * DT,ScalarEvolution * SE)63*9880d681SAndroid Build Coastguard Worker LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
64*9880d681SAndroid Build Coastguard Worker const TargetTransformInfo *TTI, AssumptionCache *AC,
65*9880d681SAndroid Build Coastguard Worker DominatorTree *DT, ScalarEvolution *SE)
66*9880d681SAndroid Build Coastguard Worker : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE) {
67*9880d681SAndroid Build Coastguard Worker }
68*9880d681SAndroid Build Coastguard Worker bool processLoop(Loop *L);
69*9880d681SAndroid Build Coastguard Worker
70*9880d681SAndroid Build Coastguard Worker private:
71*9880d681SAndroid Build Coastguard Worker bool rotateLoop(Loop *L, bool SimplifiedLatch);
72*9880d681SAndroid Build Coastguard Worker bool simplifyLoopLatch(Loop *L);
73*9880d681SAndroid Build Coastguard Worker };
74*9880d681SAndroid Build Coastguard Worker } // end anonymous namespace
75*9880d681SAndroid Build Coastguard Worker
76*9880d681SAndroid Build Coastguard Worker /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
77*9880d681SAndroid Build Coastguard Worker /// old header into the preheader. If there were uses of the values produced by
78*9880d681SAndroid Build Coastguard Worker /// these instruction that were outside of the loop, we have to insert PHI nodes
79*9880d681SAndroid Build Coastguard Worker /// to merge the two values. Do this now.
RewriteUsesOfClonedInstructions(BasicBlock * OrigHeader,BasicBlock * OrigPreheader,ValueToValueMapTy & ValueMap)80*9880d681SAndroid Build Coastguard Worker static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
81*9880d681SAndroid Build Coastguard Worker BasicBlock *OrigPreheader,
82*9880d681SAndroid Build Coastguard Worker ValueToValueMapTy &ValueMap) {
83*9880d681SAndroid Build Coastguard Worker // Remove PHI node entries that are no longer live.
84*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator I, E = OrigHeader->end();
85*9880d681SAndroid Build Coastguard Worker for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
86*9880d681SAndroid Build Coastguard Worker PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
87*9880d681SAndroid Build Coastguard Worker
88*9880d681SAndroid Build Coastguard Worker // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
89*9880d681SAndroid Build Coastguard Worker // as necessary.
90*9880d681SAndroid Build Coastguard Worker SSAUpdater SSA;
91*9880d681SAndroid Build Coastguard Worker for (I = OrigHeader->begin(); I != E; ++I) {
92*9880d681SAndroid Build Coastguard Worker Value *OrigHeaderVal = &*I;
93*9880d681SAndroid Build Coastguard Worker
94*9880d681SAndroid Build Coastguard Worker // If there are no uses of the value (e.g. because it returns void), there
95*9880d681SAndroid Build Coastguard Worker // is nothing to rewrite.
96*9880d681SAndroid Build Coastguard Worker if (OrigHeaderVal->use_empty())
97*9880d681SAndroid Build Coastguard Worker continue;
98*9880d681SAndroid Build Coastguard Worker
99*9880d681SAndroid Build Coastguard Worker Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
100*9880d681SAndroid Build Coastguard Worker
101*9880d681SAndroid Build Coastguard Worker // The value now exits in two versions: the initial value in the preheader
102*9880d681SAndroid Build Coastguard Worker // and the loop "next" value in the original header.
103*9880d681SAndroid Build Coastguard Worker SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
104*9880d681SAndroid Build Coastguard Worker SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
105*9880d681SAndroid Build Coastguard Worker SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
106*9880d681SAndroid Build Coastguard Worker
107*9880d681SAndroid Build Coastguard Worker // Visit each use of the OrigHeader instruction.
108*9880d681SAndroid Build Coastguard Worker for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
109*9880d681SAndroid Build Coastguard Worker UE = OrigHeaderVal->use_end();
110*9880d681SAndroid Build Coastguard Worker UI != UE;) {
111*9880d681SAndroid Build Coastguard Worker // Grab the use before incrementing the iterator.
112*9880d681SAndroid Build Coastguard Worker Use &U = *UI;
113*9880d681SAndroid Build Coastguard Worker
114*9880d681SAndroid Build Coastguard Worker // Increment the iterator before removing the use from the list.
115*9880d681SAndroid Build Coastguard Worker ++UI;
116*9880d681SAndroid Build Coastguard Worker
117*9880d681SAndroid Build Coastguard Worker // SSAUpdater can't handle a non-PHI use in the same block as an
118*9880d681SAndroid Build Coastguard Worker // earlier def. We can easily handle those cases manually.
119*9880d681SAndroid Build Coastguard Worker Instruction *UserInst = cast<Instruction>(U.getUser());
120*9880d681SAndroid Build Coastguard Worker if (!isa<PHINode>(UserInst)) {
121*9880d681SAndroid Build Coastguard Worker BasicBlock *UserBB = UserInst->getParent();
122*9880d681SAndroid Build Coastguard Worker
123*9880d681SAndroid Build Coastguard Worker // The original users in the OrigHeader are already using the
124*9880d681SAndroid Build Coastguard Worker // original definitions.
125*9880d681SAndroid Build Coastguard Worker if (UserBB == OrigHeader)
126*9880d681SAndroid Build Coastguard Worker continue;
127*9880d681SAndroid Build Coastguard Worker
128*9880d681SAndroid Build Coastguard Worker // Users in the OrigPreHeader need to use the value to which the
129*9880d681SAndroid Build Coastguard Worker // original definitions are mapped.
130*9880d681SAndroid Build Coastguard Worker if (UserBB == OrigPreheader) {
131*9880d681SAndroid Build Coastguard Worker U = OrigPreHeaderVal;
132*9880d681SAndroid Build Coastguard Worker continue;
133*9880d681SAndroid Build Coastguard Worker }
134*9880d681SAndroid Build Coastguard Worker }
135*9880d681SAndroid Build Coastguard Worker
136*9880d681SAndroid Build Coastguard Worker // Anything else can be handled by SSAUpdater.
137*9880d681SAndroid Build Coastguard Worker SSA.RewriteUse(U);
138*9880d681SAndroid Build Coastguard Worker }
139*9880d681SAndroid Build Coastguard Worker
140*9880d681SAndroid Build Coastguard Worker // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
141*9880d681SAndroid Build Coastguard Worker // intrinsics.
142*9880d681SAndroid Build Coastguard Worker LLVMContext &C = OrigHeader->getContext();
143*9880d681SAndroid Build Coastguard Worker if (auto *VAM = ValueAsMetadata::getIfExists(OrigHeaderVal)) {
144*9880d681SAndroid Build Coastguard Worker if (auto *MAV = MetadataAsValue::getIfExists(C, VAM)) {
145*9880d681SAndroid Build Coastguard Worker for (auto UI = MAV->use_begin(), E = MAV->use_end(); UI != E;) {
146*9880d681SAndroid Build Coastguard Worker // Grab the use before incrementing the iterator. Otherwise, altering
147*9880d681SAndroid Build Coastguard Worker // the Use will invalidate the iterator.
148*9880d681SAndroid Build Coastguard Worker Use &U = *UI++;
149*9880d681SAndroid Build Coastguard Worker DbgInfoIntrinsic *UserInst = dyn_cast<DbgInfoIntrinsic>(U.getUser());
150*9880d681SAndroid Build Coastguard Worker if (!UserInst)
151*9880d681SAndroid Build Coastguard Worker continue;
152*9880d681SAndroid Build Coastguard Worker
153*9880d681SAndroid Build Coastguard Worker // The original users in the OrigHeader are already using the original
154*9880d681SAndroid Build Coastguard Worker // definitions.
155*9880d681SAndroid Build Coastguard Worker BasicBlock *UserBB = UserInst->getParent();
156*9880d681SAndroid Build Coastguard Worker if (UserBB == OrigHeader)
157*9880d681SAndroid Build Coastguard Worker continue;
158*9880d681SAndroid Build Coastguard Worker
159*9880d681SAndroid Build Coastguard Worker // Users in the OrigPreHeader need to use the value to which the
160*9880d681SAndroid Build Coastguard Worker // original definitions are mapped and anything else can be handled by
161*9880d681SAndroid Build Coastguard Worker // the SSAUpdater. To avoid adding PHINodes, check if the value is
162*9880d681SAndroid Build Coastguard Worker // available in UserBB, if not substitute undef.
163*9880d681SAndroid Build Coastguard Worker Value *NewVal;
164*9880d681SAndroid Build Coastguard Worker if (UserBB == OrigPreheader)
165*9880d681SAndroid Build Coastguard Worker NewVal = OrigPreHeaderVal;
166*9880d681SAndroid Build Coastguard Worker else if (SSA.HasValueForBlock(UserBB))
167*9880d681SAndroid Build Coastguard Worker NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
168*9880d681SAndroid Build Coastguard Worker else
169*9880d681SAndroid Build Coastguard Worker NewVal = UndefValue::get(OrigHeaderVal->getType());
170*9880d681SAndroid Build Coastguard Worker U = MetadataAsValue::get(C, ValueAsMetadata::get(NewVal));
171*9880d681SAndroid Build Coastguard Worker }
172*9880d681SAndroid Build Coastguard Worker }
173*9880d681SAndroid Build Coastguard Worker }
174*9880d681SAndroid Build Coastguard Worker }
175*9880d681SAndroid Build Coastguard Worker }
176*9880d681SAndroid Build Coastguard Worker
177*9880d681SAndroid Build Coastguard Worker /// Rotate loop LP. Return true if the loop is rotated.
178*9880d681SAndroid Build Coastguard Worker ///
179*9880d681SAndroid Build Coastguard Worker /// \param SimplifiedLatch is true if the latch was just folded into the final
180*9880d681SAndroid Build Coastguard Worker /// loop exit. In this case we may want to rotate even though the new latch is
181*9880d681SAndroid Build Coastguard Worker /// now an exiting branch. This rotation would have happened had the latch not
182*9880d681SAndroid Build Coastguard Worker /// been simplified. However, if SimplifiedLatch is false, then we avoid
183*9880d681SAndroid Build Coastguard Worker /// rotating loops in which the latch exits to avoid excessive or endless
184*9880d681SAndroid Build Coastguard Worker /// rotation. LoopRotate should be repeatable and converge to a canonical
185*9880d681SAndroid Build Coastguard Worker /// form. This property is satisfied because simplifying the loop latch can only
186*9880d681SAndroid Build Coastguard Worker /// happen once across multiple invocations of the LoopRotate pass.
rotateLoop(Loop * L,bool SimplifiedLatch)187*9880d681SAndroid Build Coastguard Worker bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
188*9880d681SAndroid Build Coastguard Worker // If the loop has only one block then there is not much to rotate.
189*9880d681SAndroid Build Coastguard Worker if (L->getBlocks().size() == 1)
190*9880d681SAndroid Build Coastguard Worker return false;
191*9880d681SAndroid Build Coastguard Worker
192*9880d681SAndroid Build Coastguard Worker BasicBlock *OrigHeader = L->getHeader();
193*9880d681SAndroid Build Coastguard Worker BasicBlock *OrigLatch = L->getLoopLatch();
194*9880d681SAndroid Build Coastguard Worker
195*9880d681SAndroid Build Coastguard Worker BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
196*9880d681SAndroid Build Coastguard Worker if (!BI || BI->isUnconditional())
197*9880d681SAndroid Build Coastguard Worker return false;
198*9880d681SAndroid Build Coastguard Worker
199*9880d681SAndroid Build Coastguard Worker // If the loop header is not one of the loop exiting blocks then
200*9880d681SAndroid Build Coastguard Worker // either this loop is already rotated or it is not
201*9880d681SAndroid Build Coastguard Worker // suitable for loop rotation transformations.
202*9880d681SAndroid Build Coastguard Worker if (!L->isLoopExiting(OrigHeader))
203*9880d681SAndroid Build Coastguard Worker return false;
204*9880d681SAndroid Build Coastguard Worker
205*9880d681SAndroid Build Coastguard Worker // If the loop latch already contains a branch that leaves the loop then the
206*9880d681SAndroid Build Coastguard Worker // loop is already rotated.
207*9880d681SAndroid Build Coastguard Worker if (!OrigLatch)
208*9880d681SAndroid Build Coastguard Worker return false;
209*9880d681SAndroid Build Coastguard Worker
210*9880d681SAndroid Build Coastguard Worker // Rotate if either the loop latch does *not* exit the loop, or if the loop
211*9880d681SAndroid Build Coastguard Worker // latch was just simplified.
212*9880d681SAndroid Build Coastguard Worker if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
213*9880d681SAndroid Build Coastguard Worker return false;
214*9880d681SAndroid Build Coastguard Worker
215*9880d681SAndroid Build Coastguard Worker // Check size of original header and reject loop if it is very big or we can't
216*9880d681SAndroid Build Coastguard Worker // duplicate blocks inside it.
217*9880d681SAndroid Build Coastguard Worker {
218*9880d681SAndroid Build Coastguard Worker SmallPtrSet<const Value *, 32> EphValues;
219*9880d681SAndroid Build Coastguard Worker CodeMetrics::collectEphemeralValues(L, AC, EphValues);
220*9880d681SAndroid Build Coastguard Worker
221*9880d681SAndroid Build Coastguard Worker CodeMetrics Metrics;
222*9880d681SAndroid Build Coastguard Worker Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
223*9880d681SAndroid Build Coastguard Worker if (Metrics.notDuplicatable) {
224*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
225*9880d681SAndroid Build Coastguard Worker << " instructions: ";
226*9880d681SAndroid Build Coastguard Worker L->dump());
227*9880d681SAndroid Build Coastguard Worker return false;
228*9880d681SAndroid Build Coastguard Worker }
229*9880d681SAndroid Build Coastguard Worker if (Metrics.convergent) {
230*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
231*9880d681SAndroid Build Coastguard Worker "instructions: ";
232*9880d681SAndroid Build Coastguard Worker L->dump());
233*9880d681SAndroid Build Coastguard Worker return false;
234*9880d681SAndroid Build Coastguard Worker }
235*9880d681SAndroid Build Coastguard Worker if (Metrics.NumInsts > MaxHeaderSize)
236*9880d681SAndroid Build Coastguard Worker return false;
237*9880d681SAndroid Build Coastguard Worker }
238*9880d681SAndroid Build Coastguard Worker
239*9880d681SAndroid Build Coastguard Worker // Now, this loop is suitable for rotation.
240*9880d681SAndroid Build Coastguard Worker BasicBlock *OrigPreheader = L->getLoopPreheader();
241*9880d681SAndroid Build Coastguard Worker
242*9880d681SAndroid Build Coastguard Worker // If the loop could not be converted to canonical form, it must have an
243*9880d681SAndroid Build Coastguard Worker // indirectbr in it, just give up.
244*9880d681SAndroid Build Coastguard Worker if (!OrigPreheader)
245*9880d681SAndroid Build Coastguard Worker return false;
246*9880d681SAndroid Build Coastguard Worker
247*9880d681SAndroid Build Coastguard Worker // Anything ScalarEvolution may know about this loop or the PHI nodes
248*9880d681SAndroid Build Coastguard Worker // in its header will soon be invalidated.
249*9880d681SAndroid Build Coastguard Worker if (SE)
250*9880d681SAndroid Build Coastguard Worker SE->forgetLoop(L);
251*9880d681SAndroid Build Coastguard Worker
252*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
253*9880d681SAndroid Build Coastguard Worker
254*9880d681SAndroid Build Coastguard Worker // Find new Loop header. NewHeader is a Header's one and only successor
255*9880d681SAndroid Build Coastguard Worker // that is inside loop. Header's other successor is outside the
256*9880d681SAndroid Build Coastguard Worker // loop. Otherwise loop is not suitable for rotation.
257*9880d681SAndroid Build Coastguard Worker BasicBlock *Exit = BI->getSuccessor(0);
258*9880d681SAndroid Build Coastguard Worker BasicBlock *NewHeader = BI->getSuccessor(1);
259*9880d681SAndroid Build Coastguard Worker if (L->contains(Exit))
260*9880d681SAndroid Build Coastguard Worker std::swap(Exit, NewHeader);
261*9880d681SAndroid Build Coastguard Worker assert(NewHeader && "Unable to determine new loop header");
262*9880d681SAndroid Build Coastguard Worker assert(L->contains(NewHeader) && !L->contains(Exit) &&
263*9880d681SAndroid Build Coastguard Worker "Unable to determine loop header and exit blocks");
264*9880d681SAndroid Build Coastguard Worker
265*9880d681SAndroid Build Coastguard Worker // This code assumes that the new header has exactly one predecessor.
266*9880d681SAndroid Build Coastguard Worker // Remove any single-entry PHI nodes in it.
267*9880d681SAndroid Build Coastguard Worker assert(NewHeader->getSinglePredecessor() &&
268*9880d681SAndroid Build Coastguard Worker "New header doesn't have one pred!");
269*9880d681SAndroid Build Coastguard Worker FoldSingleEntryPHINodes(NewHeader);
270*9880d681SAndroid Build Coastguard Worker
271*9880d681SAndroid Build Coastguard Worker // Begin by walking OrigHeader and populating ValueMap with an entry for
272*9880d681SAndroid Build Coastguard Worker // each Instruction.
273*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
274*9880d681SAndroid Build Coastguard Worker ValueToValueMapTy ValueMap;
275*9880d681SAndroid Build Coastguard Worker
276*9880d681SAndroid Build Coastguard Worker // For PHI nodes, the value available in OldPreHeader is just the
277*9880d681SAndroid Build Coastguard Worker // incoming value from OldPreHeader.
278*9880d681SAndroid Build Coastguard Worker for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
279*9880d681SAndroid Build Coastguard Worker ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
280*9880d681SAndroid Build Coastguard Worker
281*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
282*9880d681SAndroid Build Coastguard Worker
283*9880d681SAndroid Build Coastguard Worker // For the rest of the instructions, either hoist to the OrigPreheader if
284*9880d681SAndroid Build Coastguard Worker // possible or create a clone in the OldPreHeader if not.
285*9880d681SAndroid Build Coastguard Worker TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
286*9880d681SAndroid Build Coastguard Worker while (I != E) {
287*9880d681SAndroid Build Coastguard Worker Instruction *Inst = &*I++;
288*9880d681SAndroid Build Coastguard Worker
289*9880d681SAndroid Build Coastguard Worker // If the instruction's operands are invariant and it doesn't read or write
290*9880d681SAndroid Build Coastguard Worker // memory, then it is safe to hoist. Doing this doesn't change the order of
291*9880d681SAndroid Build Coastguard Worker // execution in the preheader, but does prevent the instruction from
292*9880d681SAndroid Build Coastguard Worker // executing in each iteration of the loop. This means it is safe to hoist
293*9880d681SAndroid Build Coastguard Worker // something that might trap, but isn't safe to hoist something that reads
294*9880d681SAndroid Build Coastguard Worker // memory (without proving that the loop doesn't write).
295*9880d681SAndroid Build Coastguard Worker if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
296*9880d681SAndroid Build Coastguard Worker !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) &&
297*9880d681SAndroid Build Coastguard Worker !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
298*9880d681SAndroid Build Coastguard Worker Inst->moveBefore(LoopEntryBranch);
299*9880d681SAndroid Build Coastguard Worker continue;
300*9880d681SAndroid Build Coastguard Worker }
301*9880d681SAndroid Build Coastguard Worker
302*9880d681SAndroid Build Coastguard Worker // Otherwise, create a duplicate of the instruction.
303*9880d681SAndroid Build Coastguard Worker Instruction *C = Inst->clone();
304*9880d681SAndroid Build Coastguard Worker
305*9880d681SAndroid Build Coastguard Worker // Eagerly remap the operands of the instruction.
306*9880d681SAndroid Build Coastguard Worker RemapInstruction(C, ValueMap,
307*9880d681SAndroid Build Coastguard Worker RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
308*9880d681SAndroid Build Coastguard Worker
309*9880d681SAndroid Build Coastguard Worker // With the operands remapped, see if the instruction constant folds or is
310*9880d681SAndroid Build Coastguard Worker // otherwise simplifyable. This commonly occurs because the entry from PHI
311*9880d681SAndroid Build Coastguard Worker // nodes allows icmps and other instructions to fold.
312*9880d681SAndroid Build Coastguard Worker // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
313*9880d681SAndroid Build Coastguard Worker Value *V = SimplifyInstruction(C, DL);
314*9880d681SAndroid Build Coastguard Worker if (V && LI->replacementPreservesLCSSAForm(C, V)) {
315*9880d681SAndroid Build Coastguard Worker // If so, then delete the temporary instruction and stick the folded value
316*9880d681SAndroid Build Coastguard Worker // in the map.
317*9880d681SAndroid Build Coastguard Worker ValueMap[Inst] = V;
318*9880d681SAndroid Build Coastguard Worker if (!C->mayHaveSideEffects()) {
319*9880d681SAndroid Build Coastguard Worker delete C;
320*9880d681SAndroid Build Coastguard Worker C = nullptr;
321*9880d681SAndroid Build Coastguard Worker }
322*9880d681SAndroid Build Coastguard Worker } else {
323*9880d681SAndroid Build Coastguard Worker ValueMap[Inst] = C;
324*9880d681SAndroid Build Coastguard Worker }
325*9880d681SAndroid Build Coastguard Worker if (C) {
326*9880d681SAndroid Build Coastguard Worker // Otherwise, stick the new instruction into the new block!
327*9880d681SAndroid Build Coastguard Worker C->setName(Inst->getName());
328*9880d681SAndroid Build Coastguard Worker C->insertBefore(LoopEntryBranch);
329*9880d681SAndroid Build Coastguard Worker }
330*9880d681SAndroid Build Coastguard Worker }
331*9880d681SAndroid Build Coastguard Worker
332*9880d681SAndroid Build Coastguard Worker // Along with all the other instructions, we just cloned OrigHeader's
333*9880d681SAndroid Build Coastguard Worker // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
334*9880d681SAndroid Build Coastguard Worker // successors by duplicating their incoming values for OrigHeader.
335*9880d681SAndroid Build Coastguard Worker TerminatorInst *TI = OrigHeader->getTerminator();
336*9880d681SAndroid Build Coastguard Worker for (BasicBlock *SuccBB : TI->successors())
337*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator BI = SuccBB->begin();
338*9880d681SAndroid Build Coastguard Worker PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
339*9880d681SAndroid Build Coastguard Worker PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
340*9880d681SAndroid Build Coastguard Worker
341*9880d681SAndroid Build Coastguard Worker // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
342*9880d681SAndroid Build Coastguard Worker // OrigPreHeader's old terminator (the original branch into the loop), and
343*9880d681SAndroid Build Coastguard Worker // remove the corresponding incoming values from the PHI nodes in OrigHeader.
344*9880d681SAndroid Build Coastguard Worker LoopEntryBranch->eraseFromParent();
345*9880d681SAndroid Build Coastguard Worker
346*9880d681SAndroid Build Coastguard Worker // If there were any uses of instructions in the duplicated block outside the
347*9880d681SAndroid Build Coastguard Worker // loop, update them, inserting PHI nodes as required
348*9880d681SAndroid Build Coastguard Worker RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
349*9880d681SAndroid Build Coastguard Worker
350*9880d681SAndroid Build Coastguard Worker // NewHeader is now the header of the loop.
351*9880d681SAndroid Build Coastguard Worker L->moveToHeader(NewHeader);
352*9880d681SAndroid Build Coastguard Worker assert(L->getHeader() == NewHeader && "Latch block is our new header");
353*9880d681SAndroid Build Coastguard Worker
354*9880d681SAndroid Build Coastguard Worker // At this point, we've finished our major CFG changes. As part of cloning
355*9880d681SAndroid Build Coastguard Worker // the loop into the preheader we've simplified instructions and the
356*9880d681SAndroid Build Coastguard Worker // duplicated conditional branch may now be branching on a constant. If it is
357*9880d681SAndroid Build Coastguard Worker // branching on a constant and if that constant means that we enter the loop,
358*9880d681SAndroid Build Coastguard Worker // then we fold away the cond branch to an uncond branch. This simplifies the
359*9880d681SAndroid Build Coastguard Worker // loop in cases important for nested loops, and it also means we don't have
360*9880d681SAndroid Build Coastguard Worker // to split as many edges.
361*9880d681SAndroid Build Coastguard Worker BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
362*9880d681SAndroid Build Coastguard Worker assert(PHBI->isConditional() && "Should be clone of BI condbr!");
363*9880d681SAndroid Build Coastguard Worker if (!isa<ConstantInt>(PHBI->getCondition()) ||
364*9880d681SAndroid Build Coastguard Worker PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
365*9880d681SAndroid Build Coastguard Worker NewHeader) {
366*9880d681SAndroid Build Coastguard Worker // The conditional branch can't be folded, handle the general case.
367*9880d681SAndroid Build Coastguard Worker // Update DominatorTree to reflect the CFG change we just made. Then split
368*9880d681SAndroid Build Coastguard Worker // edges as necessary to preserve LoopSimplify form.
369*9880d681SAndroid Build Coastguard Worker if (DT) {
370*9880d681SAndroid Build Coastguard Worker // Everything that was dominated by the old loop header is now dominated
371*9880d681SAndroid Build Coastguard Worker // by the original loop preheader. Conceptually the header was merged
372*9880d681SAndroid Build Coastguard Worker // into the preheader, even though we reuse the actual block as a new
373*9880d681SAndroid Build Coastguard Worker // loop latch.
374*9880d681SAndroid Build Coastguard Worker DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
375*9880d681SAndroid Build Coastguard Worker SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
376*9880d681SAndroid Build Coastguard Worker OrigHeaderNode->end());
377*9880d681SAndroid Build Coastguard Worker DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
378*9880d681SAndroid Build Coastguard Worker for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
379*9880d681SAndroid Build Coastguard Worker DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
380*9880d681SAndroid Build Coastguard Worker
381*9880d681SAndroid Build Coastguard Worker assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
382*9880d681SAndroid Build Coastguard Worker assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
383*9880d681SAndroid Build Coastguard Worker
384*9880d681SAndroid Build Coastguard Worker // Update OrigHeader to be dominated by the new header block.
385*9880d681SAndroid Build Coastguard Worker DT->changeImmediateDominator(OrigHeader, OrigLatch);
386*9880d681SAndroid Build Coastguard Worker }
387*9880d681SAndroid Build Coastguard Worker
388*9880d681SAndroid Build Coastguard Worker // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
389*9880d681SAndroid Build Coastguard Worker // thus is not a preheader anymore.
390*9880d681SAndroid Build Coastguard Worker // Split the edge to form a real preheader.
391*9880d681SAndroid Build Coastguard Worker BasicBlock *NewPH = SplitCriticalEdge(
392*9880d681SAndroid Build Coastguard Worker OrigPreheader, NewHeader,
393*9880d681SAndroid Build Coastguard Worker CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
394*9880d681SAndroid Build Coastguard Worker NewPH->setName(NewHeader->getName() + ".lr.ph");
395*9880d681SAndroid Build Coastguard Worker
396*9880d681SAndroid Build Coastguard Worker // Preserve canonical loop form, which means that 'Exit' should have only
397*9880d681SAndroid Build Coastguard Worker // one predecessor. Note that Exit could be an exit block for multiple
398*9880d681SAndroid Build Coastguard Worker // nested loops, causing both of the edges to now be critical and need to
399*9880d681SAndroid Build Coastguard Worker // be split.
400*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
401*9880d681SAndroid Build Coastguard Worker bool SplitLatchEdge = false;
402*9880d681SAndroid Build Coastguard Worker for (BasicBlock *ExitPred : ExitPreds) {
403*9880d681SAndroid Build Coastguard Worker // We only need to split loop exit edges.
404*9880d681SAndroid Build Coastguard Worker Loop *PredLoop = LI->getLoopFor(ExitPred);
405*9880d681SAndroid Build Coastguard Worker if (!PredLoop || PredLoop->contains(Exit))
406*9880d681SAndroid Build Coastguard Worker continue;
407*9880d681SAndroid Build Coastguard Worker if (isa<IndirectBrInst>(ExitPred->getTerminator()))
408*9880d681SAndroid Build Coastguard Worker continue;
409*9880d681SAndroid Build Coastguard Worker SplitLatchEdge |= L->getLoopLatch() == ExitPred;
410*9880d681SAndroid Build Coastguard Worker BasicBlock *ExitSplit = SplitCriticalEdge(
411*9880d681SAndroid Build Coastguard Worker ExitPred, Exit,
412*9880d681SAndroid Build Coastguard Worker CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
413*9880d681SAndroid Build Coastguard Worker ExitSplit->moveBefore(Exit);
414*9880d681SAndroid Build Coastguard Worker }
415*9880d681SAndroid Build Coastguard Worker assert(SplitLatchEdge &&
416*9880d681SAndroid Build Coastguard Worker "Despite splitting all preds, failed to split latch exit?");
417*9880d681SAndroid Build Coastguard Worker } else {
418*9880d681SAndroid Build Coastguard Worker // We can fold the conditional branch in the preheader, this makes things
419*9880d681SAndroid Build Coastguard Worker // simpler. The first step is to remove the extra edge to the Exit block.
420*9880d681SAndroid Build Coastguard Worker Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
421*9880d681SAndroid Build Coastguard Worker BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
422*9880d681SAndroid Build Coastguard Worker NewBI->setDebugLoc(PHBI->getDebugLoc());
423*9880d681SAndroid Build Coastguard Worker PHBI->eraseFromParent();
424*9880d681SAndroid Build Coastguard Worker
425*9880d681SAndroid Build Coastguard Worker // With our CFG finalized, update DomTree if it is available.
426*9880d681SAndroid Build Coastguard Worker if (DT) {
427*9880d681SAndroid Build Coastguard Worker // Update OrigHeader to be dominated by the new header block.
428*9880d681SAndroid Build Coastguard Worker DT->changeImmediateDominator(NewHeader, OrigPreheader);
429*9880d681SAndroid Build Coastguard Worker DT->changeImmediateDominator(OrigHeader, OrigLatch);
430*9880d681SAndroid Build Coastguard Worker
431*9880d681SAndroid Build Coastguard Worker // Brute force incremental dominator tree update. Call
432*9880d681SAndroid Build Coastguard Worker // findNearestCommonDominator on all CFG predecessors of each child of the
433*9880d681SAndroid Build Coastguard Worker // original header.
434*9880d681SAndroid Build Coastguard Worker DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
435*9880d681SAndroid Build Coastguard Worker SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
436*9880d681SAndroid Build Coastguard Worker OrigHeaderNode->end());
437*9880d681SAndroid Build Coastguard Worker bool Changed;
438*9880d681SAndroid Build Coastguard Worker do {
439*9880d681SAndroid Build Coastguard Worker Changed = false;
440*9880d681SAndroid Build Coastguard Worker for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
441*9880d681SAndroid Build Coastguard Worker DomTreeNode *Node = HeaderChildren[I];
442*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = Node->getBlock();
443*9880d681SAndroid Build Coastguard Worker
444*9880d681SAndroid Build Coastguard Worker pred_iterator PI = pred_begin(BB);
445*9880d681SAndroid Build Coastguard Worker BasicBlock *NearestDom = *PI;
446*9880d681SAndroid Build Coastguard Worker for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
447*9880d681SAndroid Build Coastguard Worker NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
448*9880d681SAndroid Build Coastguard Worker
449*9880d681SAndroid Build Coastguard Worker // Remember if this changes the DomTree.
450*9880d681SAndroid Build Coastguard Worker if (Node->getIDom()->getBlock() != NearestDom) {
451*9880d681SAndroid Build Coastguard Worker DT->changeImmediateDominator(BB, NearestDom);
452*9880d681SAndroid Build Coastguard Worker Changed = true;
453*9880d681SAndroid Build Coastguard Worker }
454*9880d681SAndroid Build Coastguard Worker }
455*9880d681SAndroid Build Coastguard Worker
456*9880d681SAndroid Build Coastguard Worker // If the dominator changed, this may have an effect on other
457*9880d681SAndroid Build Coastguard Worker // predecessors, continue until we reach a fixpoint.
458*9880d681SAndroid Build Coastguard Worker } while (Changed);
459*9880d681SAndroid Build Coastguard Worker }
460*9880d681SAndroid Build Coastguard Worker }
461*9880d681SAndroid Build Coastguard Worker
462*9880d681SAndroid Build Coastguard Worker assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
463*9880d681SAndroid Build Coastguard Worker assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
464*9880d681SAndroid Build Coastguard Worker
465*9880d681SAndroid Build Coastguard Worker // Now that the CFG and DomTree are in a consistent state again, try to merge
466*9880d681SAndroid Build Coastguard Worker // the OrigHeader block into OrigLatch. This will succeed if they are
467*9880d681SAndroid Build Coastguard Worker // connected by an unconditional branch. This is just a cleanup so the
468*9880d681SAndroid Build Coastguard Worker // emitted code isn't too gross in this common case.
469*9880d681SAndroid Build Coastguard Worker MergeBlockIntoPredecessor(OrigHeader, DT, LI);
470*9880d681SAndroid Build Coastguard Worker
471*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "LoopRotation: into "; L->dump());
472*9880d681SAndroid Build Coastguard Worker
473*9880d681SAndroid Build Coastguard Worker ++NumRotated;
474*9880d681SAndroid Build Coastguard Worker return true;
475*9880d681SAndroid Build Coastguard Worker }
476*9880d681SAndroid Build Coastguard Worker
477*9880d681SAndroid Build Coastguard Worker /// Determine whether the instructions in this range may be safely and cheaply
478*9880d681SAndroid Build Coastguard Worker /// speculated. This is not an important enough situation to develop complex
479*9880d681SAndroid Build Coastguard Worker /// heuristics. We handle a single arithmetic instruction along with any type
480*9880d681SAndroid Build Coastguard Worker /// conversions.
shouldSpeculateInstrs(BasicBlock::iterator Begin,BasicBlock::iterator End,Loop * L)481*9880d681SAndroid Build Coastguard Worker static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
482*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator End, Loop *L) {
483*9880d681SAndroid Build Coastguard Worker bool seenIncrement = false;
484*9880d681SAndroid Build Coastguard Worker bool MultiExitLoop = false;
485*9880d681SAndroid Build Coastguard Worker
486*9880d681SAndroid Build Coastguard Worker if (!L->getExitingBlock())
487*9880d681SAndroid Build Coastguard Worker MultiExitLoop = true;
488*9880d681SAndroid Build Coastguard Worker
489*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator I = Begin; I != End; ++I) {
490*9880d681SAndroid Build Coastguard Worker
491*9880d681SAndroid Build Coastguard Worker if (!isSafeToSpeculativelyExecute(&*I))
492*9880d681SAndroid Build Coastguard Worker return false;
493*9880d681SAndroid Build Coastguard Worker
494*9880d681SAndroid Build Coastguard Worker if (isa<DbgInfoIntrinsic>(I))
495*9880d681SAndroid Build Coastguard Worker continue;
496*9880d681SAndroid Build Coastguard Worker
497*9880d681SAndroid Build Coastguard Worker switch (I->getOpcode()) {
498*9880d681SAndroid Build Coastguard Worker default:
499*9880d681SAndroid Build Coastguard Worker return false;
500*9880d681SAndroid Build Coastguard Worker case Instruction::GetElementPtr:
501*9880d681SAndroid Build Coastguard Worker // GEPs are cheap if all indices are constant.
502*9880d681SAndroid Build Coastguard Worker if (!cast<GEPOperator>(I)->hasAllConstantIndices())
503*9880d681SAndroid Build Coastguard Worker return false;
504*9880d681SAndroid Build Coastguard Worker // fall-thru to increment case
505*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
506*9880d681SAndroid Build Coastguard Worker case Instruction::Sub:
507*9880d681SAndroid Build Coastguard Worker case Instruction::And:
508*9880d681SAndroid Build Coastguard Worker case Instruction::Or:
509*9880d681SAndroid Build Coastguard Worker case Instruction::Xor:
510*9880d681SAndroid Build Coastguard Worker case Instruction::Shl:
511*9880d681SAndroid Build Coastguard Worker case Instruction::LShr:
512*9880d681SAndroid Build Coastguard Worker case Instruction::AShr: {
513*9880d681SAndroid Build Coastguard Worker Value *IVOpnd =
514*9880d681SAndroid Build Coastguard Worker !isa<Constant>(I->getOperand(0))
515*9880d681SAndroid Build Coastguard Worker ? I->getOperand(0)
516*9880d681SAndroid Build Coastguard Worker : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
517*9880d681SAndroid Build Coastguard Worker if (!IVOpnd)
518*9880d681SAndroid Build Coastguard Worker return false;
519*9880d681SAndroid Build Coastguard Worker
520*9880d681SAndroid Build Coastguard Worker // If increment operand is used outside of the loop, this speculation
521*9880d681SAndroid Build Coastguard Worker // could cause extra live range interference.
522*9880d681SAndroid Build Coastguard Worker if (MultiExitLoop) {
523*9880d681SAndroid Build Coastguard Worker for (User *UseI : IVOpnd->users()) {
524*9880d681SAndroid Build Coastguard Worker auto *UserInst = cast<Instruction>(UseI);
525*9880d681SAndroid Build Coastguard Worker if (!L->contains(UserInst))
526*9880d681SAndroid Build Coastguard Worker return false;
527*9880d681SAndroid Build Coastguard Worker }
528*9880d681SAndroid Build Coastguard Worker }
529*9880d681SAndroid Build Coastguard Worker
530*9880d681SAndroid Build Coastguard Worker if (seenIncrement)
531*9880d681SAndroid Build Coastguard Worker return false;
532*9880d681SAndroid Build Coastguard Worker seenIncrement = true;
533*9880d681SAndroid Build Coastguard Worker break;
534*9880d681SAndroid Build Coastguard Worker }
535*9880d681SAndroid Build Coastguard Worker case Instruction::Trunc:
536*9880d681SAndroid Build Coastguard Worker case Instruction::ZExt:
537*9880d681SAndroid Build Coastguard Worker case Instruction::SExt:
538*9880d681SAndroid Build Coastguard Worker // ignore type conversions
539*9880d681SAndroid Build Coastguard Worker break;
540*9880d681SAndroid Build Coastguard Worker }
541*9880d681SAndroid Build Coastguard Worker }
542*9880d681SAndroid Build Coastguard Worker return true;
543*9880d681SAndroid Build Coastguard Worker }
544*9880d681SAndroid Build Coastguard Worker
545*9880d681SAndroid Build Coastguard Worker /// Fold the loop tail into the loop exit by speculating the loop tail
546*9880d681SAndroid Build Coastguard Worker /// instructions. Typically, this is a single post-increment. In the case of a
547*9880d681SAndroid Build Coastguard Worker /// simple 2-block loop, hoisting the increment can be much better than
548*9880d681SAndroid Build Coastguard Worker /// duplicating the entire loop header. In the case of loops with early exits,
549*9880d681SAndroid Build Coastguard Worker /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
550*9880d681SAndroid Build Coastguard Worker /// canonical form so downstream passes can handle it.
551*9880d681SAndroid Build Coastguard Worker ///
552*9880d681SAndroid Build Coastguard Worker /// I don't believe this invalidates SCEV.
simplifyLoopLatch(Loop * L)553*9880d681SAndroid Build Coastguard Worker bool LoopRotate::simplifyLoopLatch(Loop *L) {
554*9880d681SAndroid Build Coastguard Worker BasicBlock *Latch = L->getLoopLatch();
555*9880d681SAndroid Build Coastguard Worker if (!Latch || Latch->hasAddressTaken())
556*9880d681SAndroid Build Coastguard Worker return false;
557*9880d681SAndroid Build Coastguard Worker
558*9880d681SAndroid Build Coastguard Worker BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
559*9880d681SAndroid Build Coastguard Worker if (!Jmp || !Jmp->isUnconditional())
560*9880d681SAndroid Build Coastguard Worker return false;
561*9880d681SAndroid Build Coastguard Worker
562*9880d681SAndroid Build Coastguard Worker BasicBlock *LastExit = Latch->getSinglePredecessor();
563*9880d681SAndroid Build Coastguard Worker if (!LastExit || !L->isLoopExiting(LastExit))
564*9880d681SAndroid Build Coastguard Worker return false;
565*9880d681SAndroid Build Coastguard Worker
566*9880d681SAndroid Build Coastguard Worker BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
567*9880d681SAndroid Build Coastguard Worker if (!BI)
568*9880d681SAndroid Build Coastguard Worker return false;
569*9880d681SAndroid Build Coastguard Worker
570*9880d681SAndroid Build Coastguard Worker if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
571*9880d681SAndroid Build Coastguard Worker return false;
572*9880d681SAndroid Build Coastguard Worker
573*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
574*9880d681SAndroid Build Coastguard Worker << LastExit->getName() << "\n");
575*9880d681SAndroid Build Coastguard Worker
576*9880d681SAndroid Build Coastguard Worker // Hoist the instructions from Latch into LastExit.
577*9880d681SAndroid Build Coastguard Worker LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
578*9880d681SAndroid Build Coastguard Worker Latch->begin(), Jmp->getIterator());
579*9880d681SAndroid Build Coastguard Worker
580*9880d681SAndroid Build Coastguard Worker unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
581*9880d681SAndroid Build Coastguard Worker BasicBlock *Header = Jmp->getSuccessor(0);
582*9880d681SAndroid Build Coastguard Worker assert(Header == L->getHeader() && "expected a backward branch");
583*9880d681SAndroid Build Coastguard Worker
584*9880d681SAndroid Build Coastguard Worker // Remove Latch from the CFG so that LastExit becomes the new Latch.
585*9880d681SAndroid Build Coastguard Worker BI->setSuccessor(FallThruPath, Header);
586*9880d681SAndroid Build Coastguard Worker Latch->replaceSuccessorsPhiUsesWith(LastExit);
587*9880d681SAndroid Build Coastguard Worker Jmp->eraseFromParent();
588*9880d681SAndroid Build Coastguard Worker
589*9880d681SAndroid Build Coastguard Worker // Nuke the Latch block.
590*9880d681SAndroid Build Coastguard Worker assert(Latch->empty() && "unable to evacuate Latch");
591*9880d681SAndroid Build Coastguard Worker LI->removeBlock(Latch);
592*9880d681SAndroid Build Coastguard Worker if (DT)
593*9880d681SAndroid Build Coastguard Worker DT->eraseNode(Latch);
594*9880d681SAndroid Build Coastguard Worker Latch->eraseFromParent();
595*9880d681SAndroid Build Coastguard Worker return true;
596*9880d681SAndroid Build Coastguard Worker }
597*9880d681SAndroid Build Coastguard Worker
598*9880d681SAndroid Build Coastguard Worker /// Rotate \c L, and return true if any modification was made.
processLoop(Loop * L)599*9880d681SAndroid Build Coastguard Worker bool LoopRotate::processLoop(Loop *L) {
600*9880d681SAndroid Build Coastguard Worker // Save the loop metadata.
601*9880d681SAndroid Build Coastguard Worker MDNode *LoopMD = L->getLoopID();
602*9880d681SAndroid Build Coastguard Worker
603*9880d681SAndroid Build Coastguard Worker // Simplify the loop latch before attempting to rotate the header
604*9880d681SAndroid Build Coastguard Worker // upward. Rotation may not be needed if the loop tail can be folded into the
605*9880d681SAndroid Build Coastguard Worker // loop exit.
606*9880d681SAndroid Build Coastguard Worker bool SimplifiedLatch = simplifyLoopLatch(L);
607*9880d681SAndroid Build Coastguard Worker
608*9880d681SAndroid Build Coastguard Worker bool MadeChange = rotateLoop(L, SimplifiedLatch);
609*9880d681SAndroid Build Coastguard Worker assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
610*9880d681SAndroid Build Coastguard Worker "Loop latch should be exiting after loop-rotate.");
611*9880d681SAndroid Build Coastguard Worker
612*9880d681SAndroid Build Coastguard Worker // Restore the loop metadata.
613*9880d681SAndroid Build Coastguard Worker // NB! We presume LoopRotation DOESN'T ADD its own metadata.
614*9880d681SAndroid Build Coastguard Worker if ((MadeChange || SimplifiedLatch) && LoopMD)
615*9880d681SAndroid Build Coastguard Worker L->setLoopID(LoopMD);
616*9880d681SAndroid Build Coastguard Worker
617*9880d681SAndroid Build Coastguard Worker return MadeChange;
618*9880d681SAndroid Build Coastguard Worker }
619*9880d681SAndroid Build Coastguard Worker
LoopRotatePass()620*9880d681SAndroid Build Coastguard Worker LoopRotatePass::LoopRotatePass() {}
621*9880d681SAndroid Build Coastguard Worker
run(Loop & L,AnalysisManager<Loop> & AM)622*9880d681SAndroid Build Coastguard Worker PreservedAnalyses LoopRotatePass::run(Loop &L, AnalysisManager<Loop> &AM) {
623*9880d681SAndroid Build Coastguard Worker auto &FAM = AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
624*9880d681SAndroid Build Coastguard Worker Function *F = L.getHeader()->getParent();
625*9880d681SAndroid Build Coastguard Worker
626*9880d681SAndroid Build Coastguard Worker auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
627*9880d681SAndroid Build Coastguard Worker const auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F);
628*9880d681SAndroid Build Coastguard Worker auto *AC = FAM.getCachedResult<AssumptionAnalysis>(*F);
629*9880d681SAndroid Build Coastguard Worker assert((LI && TTI && AC) && "Analyses for loop rotation not available");
630*9880d681SAndroid Build Coastguard Worker
631*9880d681SAndroid Build Coastguard Worker // Optional analyses.
632*9880d681SAndroid Build Coastguard Worker auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
633*9880d681SAndroid Build Coastguard Worker auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
634*9880d681SAndroid Build Coastguard Worker LoopRotate LR(DefaultRotationThreshold, LI, TTI, AC, DT, SE);
635*9880d681SAndroid Build Coastguard Worker
636*9880d681SAndroid Build Coastguard Worker bool Changed = LR.processLoop(&L);
637*9880d681SAndroid Build Coastguard Worker if (!Changed)
638*9880d681SAndroid Build Coastguard Worker return PreservedAnalyses::all();
639*9880d681SAndroid Build Coastguard Worker return getLoopPassPreservedAnalyses();
640*9880d681SAndroid Build Coastguard Worker }
641*9880d681SAndroid Build Coastguard Worker
642*9880d681SAndroid Build Coastguard Worker namespace {
643*9880d681SAndroid Build Coastguard Worker
644*9880d681SAndroid Build Coastguard Worker class LoopRotateLegacyPass : public LoopPass {
645*9880d681SAndroid Build Coastguard Worker unsigned MaxHeaderSize;
646*9880d681SAndroid Build Coastguard Worker
647*9880d681SAndroid Build Coastguard Worker public:
648*9880d681SAndroid Build Coastguard Worker static char ID; // Pass ID, replacement for typeid
LoopRotateLegacyPass(int SpecifiedMaxHeaderSize=-1)649*9880d681SAndroid Build Coastguard Worker LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
650*9880d681SAndroid Build Coastguard Worker initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry());
651*9880d681SAndroid Build Coastguard Worker if (SpecifiedMaxHeaderSize == -1)
652*9880d681SAndroid Build Coastguard Worker MaxHeaderSize = DefaultRotationThreshold;
653*9880d681SAndroid Build Coastguard Worker else
654*9880d681SAndroid Build Coastguard Worker MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
655*9880d681SAndroid Build Coastguard Worker }
656*9880d681SAndroid Build Coastguard Worker
657*9880d681SAndroid Build Coastguard Worker // LCSSA form makes instruction renaming easier.
getAnalysisUsage(AnalysisUsage & AU) const658*9880d681SAndroid Build Coastguard Worker void getAnalysisUsage(AnalysisUsage &AU) const override {
659*9880d681SAndroid Build Coastguard Worker AU.addRequired<AssumptionCacheTracker>();
660*9880d681SAndroid Build Coastguard Worker AU.addRequired<TargetTransformInfoWrapperPass>();
661*9880d681SAndroid Build Coastguard Worker getLoopAnalysisUsage(AU);
662*9880d681SAndroid Build Coastguard Worker }
663*9880d681SAndroid Build Coastguard Worker
runOnLoop(Loop * L,LPPassManager & LPM)664*9880d681SAndroid Build Coastguard Worker bool runOnLoop(Loop *L, LPPassManager &LPM) override {
665*9880d681SAndroid Build Coastguard Worker if (skipLoop(L))
666*9880d681SAndroid Build Coastguard Worker return false;
667*9880d681SAndroid Build Coastguard Worker Function &F = *L->getHeader()->getParent();
668*9880d681SAndroid Build Coastguard Worker
669*9880d681SAndroid Build Coastguard Worker auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
670*9880d681SAndroid Build Coastguard Worker const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
671*9880d681SAndroid Build Coastguard Worker auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
672*9880d681SAndroid Build Coastguard Worker auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
673*9880d681SAndroid Build Coastguard Worker auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
674*9880d681SAndroid Build Coastguard Worker auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
675*9880d681SAndroid Build Coastguard Worker auto *SE = SEWP ? &SEWP->getSE() : nullptr;
676*9880d681SAndroid Build Coastguard Worker LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE);
677*9880d681SAndroid Build Coastguard Worker return LR.processLoop(L);
678*9880d681SAndroid Build Coastguard Worker }
679*9880d681SAndroid Build Coastguard Worker };
680*9880d681SAndroid Build Coastguard Worker }
681*9880d681SAndroid Build Coastguard Worker
682*9880d681SAndroid Build Coastguard Worker char LoopRotateLegacyPass::ID = 0;
683*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
684*9880d681SAndroid Build Coastguard Worker false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)685*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
686*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(LoopPass)
687*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
688*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false,
689*9880d681SAndroid Build Coastguard Worker false)
690*9880d681SAndroid Build Coastguard Worker
691*9880d681SAndroid Build Coastguard Worker Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
692*9880d681SAndroid Build Coastguard Worker return new LoopRotateLegacyPass(MaxHeaderSize);
693*9880d681SAndroid Build Coastguard Worker }
694