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 #define DEBUG_TYPE "loop-rotate"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/Statistic.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/Support/Debug.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Transforms/Utils/SSAUpdater.h"
31 #include "llvm/Transforms/Utils/ValueMapper.h"
34 #define MAX_HEADER_SIZE 16
36 STATISTIC(NumRotated, "Number of loops rotated");
39 class LoopRotate : public LoopPass {
41 static char ID; // Pass ID, replacement for typeid
42 LoopRotate() : LoopPass(ID) {
43 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
46 // LCSSA form makes instruction renaming easier.
47 void getAnalysisUsage(AnalysisUsage &AU) const override {
48 AU.addPreserved<DominatorTreeWrapperPass>();
49 AU.addRequired<LoopInfo>();
50 AU.addPreserved<LoopInfo>();
51 AU.addRequiredID(LoopSimplifyID);
52 AU.addPreservedID(LoopSimplifyID);
53 AU.addRequiredID(LCSSAID);
54 AU.addPreservedID(LCSSAID);
55 AU.addPreserved<ScalarEvolution>();
56 AU.addRequired<TargetTransformInfo>();
59 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
60 bool simplifyLoopLatch(Loop *L);
61 bool rotateLoop(Loop *L, bool SimplifiedLatch);
65 const TargetTransformInfo *TTI;
69 char LoopRotate::ID = 0;
70 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
71 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
72 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
73 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
74 INITIALIZE_PASS_DEPENDENCY(LCSSA)
75 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
77 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
79 /// Rotate Loop L as many times as possible. Return true if
80 /// the loop is rotated at least once.
81 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
82 if (skipOptnoneFunction(L))
85 // Save the loop metadata.
86 MDNode *LoopMD = L->getLoopID();
88 LI = &getAnalysis<LoopInfo>();
89 TTI = &getAnalysis<TargetTransformInfo>();
91 // Simplify the loop latch before attempting to rotate the header
92 // upward. Rotation may not be needed if the loop tail can be folded into the
94 bool SimplifiedLatch = simplifyLoopLatch(L);
96 // One loop can be rotated multiple times.
97 bool MadeChange = false;
98 while (rotateLoop(L, SimplifiedLatch)) {
100 SimplifiedLatch = false;
103 // Restore the loop metadata.
104 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
105 if ((MadeChange || SimplifiedLatch) && LoopMD)
106 L->setLoopID(LoopMD);
111 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
112 /// old header into the preheader. If there were uses of the values produced by
113 /// these instruction that were outside of the loop, we have to insert PHI nodes
114 /// to merge the two values. Do this now.
115 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
116 BasicBlock *OrigPreheader,
117 ValueToValueMapTy &ValueMap) {
118 // Remove PHI node entries that are no longer live.
119 BasicBlock::iterator I, E = OrigHeader->end();
120 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
121 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
123 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
126 for (I = OrigHeader->begin(); I != E; ++I) {
127 Value *OrigHeaderVal = I;
129 // If there are no uses of the value (e.g. because it returns void), there
130 // is nothing to rewrite.
131 if (OrigHeaderVal->use_empty())
134 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
136 // The value now exits in two versions: the initial value in the preheader
137 // and the loop "next" value in the original header.
138 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
139 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
140 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
142 // Visit each use of the OrigHeader instruction.
143 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
144 UE = OrigHeaderVal->use_end(); UI != UE; ) {
145 // Grab the use before incrementing the iterator.
148 // Increment the iterator before removing the use from the list.
151 // SSAUpdater can't handle a non-PHI use in the same block as an
152 // earlier def. We can easily handle those cases manually.
153 Instruction *UserInst = cast<Instruction>(U.getUser());
154 if (!isa<PHINode>(UserInst)) {
155 BasicBlock *UserBB = UserInst->getParent();
157 // The original users in the OrigHeader are already using the
158 // original definitions.
159 if (UserBB == OrigHeader)
162 // Users in the OrigPreHeader need to use the value to which the
163 // original definitions are mapped.
164 if (UserBB == OrigPreheader) {
165 U = OrigPreHeaderVal;
170 // Anything else can be handled by SSAUpdater.
176 /// Determine whether the instructions in this range my be safely and cheaply
177 /// speculated. This is not an important enough situation to develop complex
178 /// heuristics. We handle a single arithmetic instruction along with any type
180 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
181 BasicBlock::iterator End) {
182 bool seenIncrement = false;
183 for (BasicBlock::iterator I = Begin; I != End; ++I) {
185 if (!isSafeToSpeculativelyExecute(I))
188 if (isa<DbgInfoIntrinsic>(I))
191 switch (I->getOpcode()) {
194 case Instruction::GetElementPtr:
195 // GEPs are cheap if all indices are constant.
196 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
198 // fall-thru to increment case
199 case Instruction::Add:
200 case Instruction::Sub:
201 case Instruction::And:
202 case Instruction::Or:
203 case Instruction::Xor:
204 case Instruction::Shl:
205 case Instruction::LShr:
206 case Instruction::AShr:
209 seenIncrement = true;
211 case Instruction::Trunc:
212 case Instruction::ZExt:
213 case Instruction::SExt:
214 // ignore type conversions
221 /// Fold the loop tail into the loop exit by speculating the loop tail
222 /// instructions. Typically, this is a single post-increment. In the case of a
223 /// simple 2-block loop, hoisting the increment can be much better than
224 /// duplicating the entire loop header. In the cast of loops with early exits,
225 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
226 /// canonical form so downstream passes can handle it.
228 /// I don't believe this invalidates SCEV.
229 bool LoopRotate::simplifyLoopLatch(Loop *L) {
230 BasicBlock *Latch = L->getLoopLatch();
231 if (!Latch || Latch->hasAddressTaken())
234 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
235 if (!Jmp || !Jmp->isUnconditional())
238 BasicBlock *LastExit = Latch->getSinglePredecessor();
239 if (!LastExit || !L->isLoopExiting(LastExit))
242 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
246 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
249 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
250 << LastExit->getName() << "\n");
252 // Hoist the instructions from Latch into LastExit.
253 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
255 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
256 BasicBlock *Header = Jmp->getSuccessor(0);
257 assert(Header == L->getHeader() && "expected a backward branch");
259 // Remove Latch from the CFG so that LastExit becomes the new Latch.
260 BI->setSuccessor(FallThruPath, Header);
261 Latch->replaceSuccessorsPhiUsesWith(LastExit);
262 Jmp->eraseFromParent();
264 // Nuke the Latch block.
265 assert(Latch->empty() && "unable to evacuate Latch");
266 LI->removeBlock(Latch);
267 if (DominatorTreeWrapperPass *DTWP =
268 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
269 DTWP->getDomTree().eraseNode(Latch);
270 Latch->eraseFromParent();
274 /// Rotate loop LP. Return true if the loop is rotated.
276 /// \param SimplifiedLatch is true if the latch was just folded into the final
277 /// loop exit. In this case we may want to rotate even though the new latch is
278 /// now an exiting branch. This rotation would have happened had the latch not
279 /// been simplified. However, if SimplifiedLatch is false, then we avoid
280 /// rotating loops in which the latch exits to avoid excessive or endless
281 /// rotation. LoopRotate should be repeatable and converge to a canonical
282 /// form. This property is satisfied because simplifying the loop latch can only
283 /// happen once across multiple invocations of the LoopRotate pass.
284 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
285 // If the loop has only one block then there is not much to rotate.
286 if (L->getBlocks().size() == 1)
289 BasicBlock *OrigHeader = L->getHeader();
290 BasicBlock *OrigLatch = L->getLoopLatch();
292 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
293 if (BI == 0 || BI->isUnconditional())
296 // If the loop header is not one of the loop exiting blocks then
297 // either this loop is already rotated or it is not
298 // suitable for loop rotation transformations.
299 if (!L->isLoopExiting(OrigHeader))
302 // If the loop latch already contains a branch that leaves the loop then the
303 // loop is already rotated.
307 // Rotate if either the loop latch does *not* exit the loop, or if the loop
308 // latch was just simplified.
309 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
312 // Check size of original header and reject loop if it is very big or we can't
313 // duplicate blocks inside it.
316 Metrics.analyzeBasicBlock(OrigHeader, *TTI);
317 if (Metrics.notDuplicatable) {
318 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
319 << " instructions: "; L->dump());
322 if (Metrics.NumInsts > MAX_HEADER_SIZE)
326 // Now, this loop is suitable for rotation.
327 BasicBlock *OrigPreheader = L->getLoopPreheader();
329 // If the loop could not be converted to canonical form, it must have an
330 // indirectbr in it, just give up.
331 if (OrigPreheader == 0)
334 // Anything ScalarEvolution may know about this loop or the PHI nodes
335 // in its header will soon be invalidated.
336 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
339 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
341 // Find new Loop header. NewHeader is a Header's one and only successor
342 // that is inside loop. Header's other successor is outside the
343 // loop. Otherwise loop is not suitable for rotation.
344 BasicBlock *Exit = BI->getSuccessor(0);
345 BasicBlock *NewHeader = BI->getSuccessor(1);
346 if (L->contains(Exit))
347 std::swap(Exit, NewHeader);
348 assert(NewHeader && "Unable to determine new loop header");
349 assert(L->contains(NewHeader) && !L->contains(Exit) &&
350 "Unable to determine loop header and exit blocks");
352 // This code assumes that the new header has exactly one predecessor.
353 // Remove any single-entry PHI nodes in it.
354 assert(NewHeader->getSinglePredecessor() &&
355 "New header doesn't have one pred!");
356 FoldSingleEntryPHINodes(NewHeader);
358 // Begin by walking OrigHeader and populating ValueMap with an entry for
360 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
361 ValueToValueMapTy ValueMap;
363 // For PHI nodes, the value available in OldPreHeader is just the
364 // incoming value from OldPreHeader.
365 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
366 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
368 // For the rest of the instructions, either hoist to the OrigPreheader if
369 // possible or create a clone in the OldPreHeader if not.
370 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
372 Instruction *Inst = I++;
374 // If the instruction's operands are invariant and it doesn't read or write
375 // memory, then it is safe to hoist. Doing this doesn't change the order of
376 // execution in the preheader, but does prevent the instruction from
377 // executing in each iteration of the loop. This means it is safe to hoist
378 // something that might trap, but isn't safe to hoist something that reads
379 // memory (without proving that the loop doesn't write).
380 if (L->hasLoopInvariantOperands(Inst) &&
381 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
382 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
383 !isa<AllocaInst>(Inst)) {
384 Inst->moveBefore(LoopEntryBranch);
388 // Otherwise, create a duplicate of the instruction.
389 Instruction *C = Inst->clone();
391 // Eagerly remap the operands of the instruction.
392 RemapInstruction(C, ValueMap,
393 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
395 // With the operands remapped, see if the instruction constant folds or is
396 // otherwise simplifyable. This commonly occurs because the entry from PHI
397 // nodes allows icmps and other instructions to fold.
398 Value *V = SimplifyInstruction(C);
399 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
400 // If so, then delete the temporary instruction and stick the folded value
405 // Otherwise, stick the new instruction into the new block!
406 C->setName(Inst->getName());
407 C->insertBefore(LoopEntryBranch);
412 // Along with all the other instructions, we just cloned OrigHeader's
413 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
414 // successors by duplicating their incoming values for OrigHeader.
415 TerminatorInst *TI = OrigHeader->getTerminator();
416 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
417 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
418 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
419 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
421 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
422 // OrigPreHeader's old terminator (the original branch into the loop), and
423 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
424 LoopEntryBranch->eraseFromParent();
426 // If there were any uses of instructions in the duplicated block outside the
427 // loop, update them, inserting PHI nodes as required
428 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
430 // NewHeader is now the header of the loop.
431 L->moveToHeader(NewHeader);
432 assert(L->getHeader() == NewHeader && "Latch block is our new header");
435 // At this point, we've finished our major CFG changes. As part of cloning
436 // the loop into the preheader we've simplified instructions and the
437 // duplicated conditional branch may now be branching on a constant. If it is
438 // branching on a constant and if that constant means that we enter the loop,
439 // then we fold away the cond branch to an uncond branch. This simplifies the
440 // loop in cases important for nested loops, and it also means we don't have
441 // to split as many edges.
442 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
443 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
444 if (!isa<ConstantInt>(PHBI->getCondition()) ||
445 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
447 // The conditional branch can't be folded, handle the general case.
448 // Update DominatorTree to reflect the CFG change we just made. Then split
449 // edges as necessary to preserve LoopSimplify form.
450 if (DominatorTreeWrapperPass *DTWP =
451 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
452 DominatorTree &DT = DTWP->getDomTree();
453 // Everything that was dominated by the old loop header is now dominated
454 // by the original loop preheader. Conceptually the header was merged
455 // into the preheader, even though we reuse the actual block as a new
457 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
458 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
459 OrigHeaderNode->end());
460 DomTreeNode *OrigPreheaderNode = DT.getNode(OrigPreheader);
461 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
462 DT.changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
464 assert(DT.getNode(Exit)->getIDom() == OrigPreheaderNode);
465 assert(DT.getNode(NewHeader)->getIDom() == OrigPreheaderNode);
467 // Update OrigHeader to be dominated by the new header block.
468 DT.changeImmediateDominator(OrigHeader, OrigLatch);
471 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
472 // thus is not a preheader anymore.
473 // Split the edge to form a real preheader.
474 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
475 NewPH->setName(NewHeader->getName() + ".lr.ph");
477 // Preserve canonical loop form, which means that 'Exit' should have only
478 // one predecessor. Note that Exit could be an exit block for multiple
479 // nested loops, causing both of the edges to now be critical and need to
481 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
482 bool SplitLatchEdge = false;
483 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
484 PE = ExitPreds.end();
486 // We only need to split loop exit edges.
487 Loop *PredLoop = LI->getLoopFor(*PI);
488 if (!PredLoop || PredLoop->contains(Exit))
490 SplitLatchEdge |= L->getLoopLatch() == *PI;
491 BasicBlock *ExitSplit = SplitCriticalEdge(*PI, Exit, this);
492 ExitSplit->moveBefore(Exit);
494 assert(SplitLatchEdge &&
495 "Despite splitting all preds, failed to split latch exit?");
497 // We can fold the conditional branch in the preheader, this makes things
498 // simpler. The first step is to remove the extra edge to the Exit block.
499 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
500 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
501 NewBI->setDebugLoc(PHBI->getDebugLoc());
502 PHBI->eraseFromParent();
504 // With our CFG finalized, update DomTree if it is available.
505 if (DominatorTreeWrapperPass *DTWP =
506 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
507 DominatorTree &DT = DTWP->getDomTree();
508 // Update OrigHeader to be dominated by the new header block.
509 DT.changeImmediateDominator(NewHeader, OrigPreheader);
510 DT.changeImmediateDominator(OrigHeader, OrigLatch);
512 // Brute force incremental dominator tree update. Call
513 // findNearestCommonDominator on all CFG predecessors of each child of the
515 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
516 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
517 OrigHeaderNode->end());
521 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
522 DomTreeNode *Node = HeaderChildren[I];
523 BasicBlock *BB = Node->getBlock();
525 pred_iterator PI = pred_begin(BB);
526 BasicBlock *NearestDom = *PI;
527 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
528 NearestDom = DT.findNearestCommonDominator(NearestDom, *PI);
530 // Remember if this changes the DomTree.
531 if (Node->getIDom()->getBlock() != NearestDom) {
532 DT.changeImmediateDominator(BB, NearestDom);
537 // If the dominator changed, this may have an effect on other
538 // predecessors, continue until we reach a fixpoint.
543 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
544 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
546 // Now that the CFG and DomTree are in a consistent state again, try to merge
547 // the OrigHeader block into OrigLatch. This will succeed if they are
548 // connected by an unconditional branch. This is just a cleanup so the
549 // emitted code isn't too gross in this common case.
550 MergeBlockIntoPredecessor(OrigHeader, this);
552 DEBUG(dbgs() << "LoopRotation: into "; L->dump());