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