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.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/AssumptionCache.h"
17 #include "llvm/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/ScalarEvolution.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Transforms/Utils/SSAUpdater.h"
33 #include "llvm/Transforms/Utils/ValueMapper.h"
36 #define DEBUG_TYPE "loop-rotate"
38 static cl::opt<unsigned>
39 DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
40 cl::desc("The default maximum header size for automatic loop rotation"));
42 STATISTIC(NumRotated, "Number of loops rotated");
45 class LoopRotate : public LoopPass {
47 static char ID; // Pass ID, replacement for typeid
48 LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
49 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
50 if (SpecifiedMaxHeaderSize == -1)
51 MaxHeaderSize = DefaultRotationThreshold;
53 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
56 // LCSSA form makes instruction renaming easier.
57 void getAnalysisUsage(AnalysisUsage &AU) const override {
58 AU.addRequired<AssumptionCacheTracker>();
59 AU.addPreserved<DominatorTreeWrapperPass>();
60 AU.addRequired<LoopInfoWrapperPass>();
61 AU.addPreserved<LoopInfoWrapperPass>();
62 AU.addRequiredID(LoopSimplifyID);
63 AU.addPreservedID(LoopSimplifyID);
64 AU.addRequiredID(LCSSAID);
65 AU.addPreservedID(LCSSAID);
66 AU.addPreserved<ScalarEvolution>();
67 AU.addRequired<TargetTransformInfoWrapperPass>();
70 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
71 bool simplifyLoopLatch(Loop *L);
72 bool rotateLoop(Loop *L, bool SimplifiedLatch);
75 unsigned MaxHeaderSize;
77 const TargetTransformInfo *TTI;
83 char LoopRotate::ID = 0;
84 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
85 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
86 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
87 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
88 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
89 INITIALIZE_PASS_DEPENDENCY(LCSSA)
90 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
92 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
93 return new LoopRotate(MaxHeaderSize);
96 /// Rotate Loop L as many times as possible. Return true if
97 /// the loop is rotated at least once.
98 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
99 if (skipOptnoneFunction(L))
102 // Save the loop metadata.
103 MDNode *LoopMD = L->getLoopID();
105 Function &F = *L->getHeader()->getParent();
107 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
108 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
109 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
110 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
111 DT = DTWP ? &DTWP->getDomTree() : nullptr;
113 // Simplify the loop latch before attempting to rotate the header
114 // upward. Rotation may not be needed if the loop tail can be folded into the
116 bool SimplifiedLatch = simplifyLoopLatch(L);
118 // One loop can be rotated multiple times.
119 bool MadeChange = false;
120 while (rotateLoop(L, SimplifiedLatch)) {
122 SimplifiedLatch = false;
125 // Restore the loop metadata.
126 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
127 if ((MadeChange || SimplifiedLatch) && LoopMD)
128 L->setLoopID(LoopMD);
133 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
134 /// old header into the preheader. If there were uses of the values produced by
135 /// these instruction that were outside of the loop, we have to insert PHI nodes
136 /// to merge the two values. Do this now.
137 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
138 BasicBlock *OrigPreheader,
139 ValueToValueMapTy &ValueMap) {
140 // Remove PHI node entries that are no longer live.
141 BasicBlock::iterator I, E = OrigHeader->end();
142 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
143 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
145 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
148 for (I = OrigHeader->begin(); I != E; ++I) {
149 Value *OrigHeaderVal = I;
151 // If there are no uses of the value (e.g. because it returns void), there
152 // is nothing to rewrite.
153 if (OrigHeaderVal->use_empty())
156 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
158 // The value now exits in two versions: the initial value in the preheader
159 // and the loop "next" value in the original header.
160 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
161 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
162 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
164 // Visit each use of the OrigHeader instruction.
165 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
166 UE = OrigHeaderVal->use_end(); UI != UE; ) {
167 // Grab the use before incrementing the iterator.
170 // Increment the iterator before removing the use from the list.
173 // SSAUpdater can't handle a non-PHI use in the same block as an
174 // earlier def. We can easily handle those cases manually.
175 Instruction *UserInst = cast<Instruction>(U.getUser());
176 if (!isa<PHINode>(UserInst)) {
177 BasicBlock *UserBB = UserInst->getParent();
179 // The original users in the OrigHeader are already using the
180 // original definitions.
181 if (UserBB == OrigHeader)
184 // Users in the OrigPreHeader need to use the value to which the
185 // original definitions are mapped.
186 if (UserBB == OrigPreheader) {
187 U = OrigPreHeaderVal;
192 // Anything else can be handled by SSAUpdater.
198 /// Determine whether the instructions in this range may be safely and cheaply
199 /// speculated. This is not an important enough situation to develop complex
200 /// heuristics. We handle a single arithmetic instruction along with any type
202 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
203 BasicBlock::iterator End, Loop *L) {
204 bool seenIncrement = false;
205 bool MultiExitLoop = false;
207 if (!L->getExitingBlock())
208 MultiExitLoop = true;
210 for (BasicBlock::iterator I = Begin; I != End; ++I) {
212 if (!isSafeToSpeculativelyExecute(I))
215 if (isa<DbgInfoIntrinsic>(I))
218 switch (I->getOpcode()) {
221 case Instruction::GetElementPtr:
222 // GEPs are cheap if all indices are constant.
223 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
225 // fall-thru to increment case
226 case Instruction::Add:
227 case Instruction::Sub:
228 case Instruction::And:
229 case Instruction::Or:
230 case Instruction::Xor:
231 case Instruction::Shl:
232 case Instruction::LShr:
233 case Instruction::AShr: {
234 Value *IVOpnd = !isa<Constant>(I->getOperand(0))
236 : !isa<Constant>(I->getOperand(1))
242 // If increment operand is used outside of the loop, this speculation
243 // could cause extra live range interference.
245 for (User *UseI : IVOpnd->users()) {
246 auto *UserInst = cast<Instruction>(UseI);
247 if (!L->contains(UserInst))
254 seenIncrement = true;
257 case Instruction::Trunc:
258 case Instruction::ZExt:
259 case Instruction::SExt:
260 // ignore type conversions
267 /// Fold the loop tail into the loop exit by speculating the loop tail
268 /// instructions. Typically, this is a single post-increment. In the case of a
269 /// simple 2-block loop, hoisting the increment can be much better than
270 /// duplicating the entire loop header. In the case of loops with early exits,
271 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
272 /// canonical form so downstream passes can handle it.
274 /// I don't believe this invalidates SCEV.
275 bool LoopRotate::simplifyLoopLatch(Loop *L) {
276 BasicBlock *Latch = L->getLoopLatch();
277 if (!Latch || Latch->hasAddressTaken())
280 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
281 if (!Jmp || !Jmp->isUnconditional())
284 BasicBlock *LastExit = Latch->getSinglePredecessor();
285 if (!LastExit || !L->isLoopExiting(LastExit))
288 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
292 if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
295 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
296 << LastExit->getName() << "\n");
298 // Hoist the instructions from Latch into LastExit.
299 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
301 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
302 BasicBlock *Header = Jmp->getSuccessor(0);
303 assert(Header == L->getHeader() && "expected a backward branch");
305 // Remove Latch from the CFG so that LastExit becomes the new Latch.
306 BI->setSuccessor(FallThruPath, Header);
307 Latch->replaceSuccessorsPhiUsesWith(LastExit);
308 Jmp->eraseFromParent();
310 // Nuke the Latch block.
311 assert(Latch->empty() && "unable to evacuate Latch");
312 LI->removeBlock(Latch);
314 DT->eraseNode(Latch);
315 Latch->eraseFromParent();
319 /// Rotate loop LP. Return true if the loop is rotated.
321 /// \param SimplifiedLatch is true if the latch was just folded into the final
322 /// loop exit. In this case we may want to rotate even though the new latch is
323 /// now an exiting branch. This rotation would have happened had the latch not
324 /// been simplified. However, if SimplifiedLatch is false, then we avoid
325 /// rotating loops in which the latch exits to avoid excessive or endless
326 /// rotation. LoopRotate should be repeatable and converge to a canonical
327 /// form. This property is satisfied because simplifying the loop latch can only
328 /// happen once across multiple invocations of the LoopRotate pass.
329 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
330 // If the loop has only one block then there is not much to rotate.
331 if (L->getBlocks().size() == 1)
334 BasicBlock *OrigHeader = L->getHeader();
335 BasicBlock *OrigLatch = L->getLoopLatch();
337 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
338 if (!BI || BI->isUnconditional())
341 // If the loop header is not one of the loop exiting blocks then
342 // either this loop is already rotated or it is not
343 // suitable for loop rotation transformations.
344 if (!L->isLoopExiting(OrigHeader))
347 // If the loop latch already contains a branch that leaves the loop then the
348 // loop is already rotated.
352 // Rotate if either the loop latch does *not* exit the loop, or if the loop
353 // latch was just simplified.
354 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
357 // Check size of original header and reject loop if it is very big or we can't
358 // duplicate blocks inside it.
360 SmallPtrSet<const Value *, 32> EphValues;
361 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
364 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
365 if (Metrics.notDuplicatable) {
366 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
367 << " instructions: "; L->dump());
370 if (Metrics.NumInsts > MaxHeaderSize)
374 // Now, this loop is suitable for rotation.
375 BasicBlock *OrigPreheader = L->getLoopPreheader();
377 // If the loop could not be converted to canonical form, it must have an
378 // indirectbr in it, just give up.
382 // Anything ScalarEvolution may know about this loop or the PHI nodes
383 // in its header will soon be invalidated.
384 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
387 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
389 // Find new Loop header. NewHeader is a Header's one and only successor
390 // that is inside loop. Header's other successor is outside the
391 // loop. Otherwise loop is not suitable for rotation.
392 BasicBlock *Exit = BI->getSuccessor(0);
393 BasicBlock *NewHeader = BI->getSuccessor(1);
394 if (L->contains(Exit))
395 std::swap(Exit, NewHeader);
396 assert(NewHeader && "Unable to determine new loop header");
397 assert(L->contains(NewHeader) && !L->contains(Exit) &&
398 "Unable to determine loop header and exit blocks");
400 // This code assumes that the new header has exactly one predecessor.
401 // Remove any single-entry PHI nodes in it.
402 assert(NewHeader->getSinglePredecessor() &&
403 "New header doesn't have one pred!");
404 FoldSingleEntryPHINodes(NewHeader);
406 // Begin by walking OrigHeader and populating ValueMap with an entry for
408 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
409 ValueToValueMapTy ValueMap;
411 // For PHI nodes, the value available in OldPreHeader is just the
412 // incoming value from OldPreHeader.
413 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
414 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
416 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
418 // For the rest of the instructions, either hoist to the OrigPreheader if
419 // possible or create a clone in the OldPreHeader if not.
420 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
422 Instruction *Inst = I++;
424 // If the instruction's operands are invariant and it doesn't read or write
425 // memory, then it is safe to hoist. Doing this doesn't change the order of
426 // execution in the preheader, but does prevent the instruction from
427 // executing in each iteration of the loop. This means it is safe to hoist
428 // something that might trap, but isn't safe to hoist something that reads
429 // memory (without proving that the loop doesn't write).
430 if (L->hasLoopInvariantOperands(Inst) &&
431 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
432 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
433 !isa<AllocaInst>(Inst)) {
434 Inst->moveBefore(LoopEntryBranch);
438 // Otherwise, create a duplicate of the instruction.
439 Instruction *C = Inst->clone();
441 // Eagerly remap the operands of the instruction.
442 RemapInstruction(C, ValueMap,
443 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
445 // With the operands remapped, see if the instruction constant folds or is
446 // otherwise simplifyable. This commonly occurs because the entry from PHI
447 // nodes allows icmps and other instructions to fold.
448 // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
449 Value *V = SimplifyInstruction(C, DL);
450 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
451 // If so, then delete the temporary instruction and stick the folded value
456 // Otherwise, stick the new instruction into the new block!
457 C->setName(Inst->getName());
458 C->insertBefore(LoopEntryBranch);
463 // Along with all the other instructions, we just cloned OrigHeader's
464 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
465 // successors by duplicating their incoming values for OrigHeader.
466 TerminatorInst *TI = OrigHeader->getTerminator();
467 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
468 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
469 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
470 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
472 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
473 // OrigPreHeader's old terminator (the original branch into the loop), and
474 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
475 LoopEntryBranch->eraseFromParent();
477 // If there were any uses of instructions in the duplicated block outside the
478 // loop, update them, inserting PHI nodes as required
479 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
481 // NewHeader is now the header of the loop.
482 L->moveToHeader(NewHeader);
483 assert(L->getHeader() == NewHeader && "Latch block is our new header");
486 // At this point, we've finished our major CFG changes. As part of cloning
487 // the loop into the preheader we've simplified instructions and the
488 // duplicated conditional branch may now be branching on a constant. If it is
489 // branching on a constant and if that constant means that we enter the loop,
490 // then we fold away the cond branch to an uncond branch. This simplifies the
491 // loop in cases important for nested loops, and it also means we don't have
492 // to split as many edges.
493 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
494 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
495 if (!isa<ConstantInt>(PHBI->getCondition()) ||
496 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
498 // The conditional branch can't be folded, handle the general case.
499 // Update DominatorTree to reflect the CFG change we just made. Then split
500 // edges as necessary to preserve LoopSimplify form.
502 // Everything that was dominated by the old loop header is now dominated
503 // by the original loop preheader. Conceptually the header was merged
504 // into the preheader, even though we reuse the actual block as a new
506 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
507 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
508 OrigHeaderNode->end());
509 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
510 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
511 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
513 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
514 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
516 // Update OrigHeader to be dominated by the new header block.
517 DT->changeImmediateDominator(OrigHeader, OrigLatch);
520 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
521 // thus is not a preheader anymore.
522 // Split the edge to form a real preheader.
523 BasicBlock *NewPH = SplitCriticalEdge(
524 OrigPreheader, NewHeader,
525 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
526 NewPH->setName(NewHeader->getName() + ".lr.ph");
528 // Preserve canonical loop form, which means that 'Exit' should have only
529 // one predecessor. Note that Exit could be an exit block for multiple
530 // nested loops, causing both of the edges to now be critical and need to
532 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
533 bool SplitLatchEdge = false;
534 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
535 PE = ExitPreds.end();
537 // We only need to split loop exit edges.
538 Loop *PredLoop = LI->getLoopFor(*PI);
539 if (!PredLoop || PredLoop->contains(Exit))
541 if (isa<IndirectBrInst>((*PI)->getTerminator()))
543 SplitLatchEdge |= L->getLoopLatch() == *PI;
544 BasicBlock *ExitSplit = SplitCriticalEdge(
545 *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
546 ExitSplit->moveBefore(Exit);
548 assert(SplitLatchEdge &&
549 "Despite splitting all preds, failed to split latch exit?");
551 // We can fold the conditional branch in the preheader, this makes things
552 // simpler. The first step is to remove the extra edge to the Exit block.
553 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
554 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
555 NewBI->setDebugLoc(PHBI->getDebugLoc());
556 PHBI->eraseFromParent();
558 // With our CFG finalized, update DomTree if it is available.
560 // Update OrigHeader to be dominated by the new header block.
561 DT->changeImmediateDominator(NewHeader, OrigPreheader);
562 DT->changeImmediateDominator(OrigHeader, OrigLatch);
564 // Brute force incremental dominator tree update. Call
565 // findNearestCommonDominator on all CFG predecessors of each child of the
567 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
568 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
569 OrigHeaderNode->end());
573 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
574 DomTreeNode *Node = HeaderChildren[I];
575 BasicBlock *BB = Node->getBlock();
577 pred_iterator PI = pred_begin(BB);
578 BasicBlock *NearestDom = *PI;
579 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
580 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
582 // Remember if this changes the DomTree.
583 if (Node->getIDom()->getBlock() != NearestDom) {
584 DT->changeImmediateDominator(BB, NearestDom);
589 // If the dominator changed, this may have an effect on other
590 // predecessors, continue until we reach a fixpoint.
595 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
596 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
598 // Now that the CFG and DomTree are in a consistent state again, try to merge
599 // the OrigHeader block into OrigLatch. This will succeed if they are
600 // connected by an unconditional branch. This is just a cleanup so the
601 // emitted code isn't too gross in this common case.
602 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
604 DEBUG(dbgs() << "LoopRotation: into "; L->dump());