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/ValueTracking.h"
22 #include "llvm/Function.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Support/CFG.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 #include "llvm/Transforms/Utils/Local.h"
28 #include "llvm/Transforms/Utils/SSAUpdater.h"
29 #include "llvm/Transforms/Utils/ValueMapper.h"
32 #define MAX_HEADER_SIZE 16
34 STATISTIC(NumRotated, "Number of loops rotated");
37 class LoopRotate : public LoopPass {
39 static char ID; // Pass ID, replacement for typeid
40 LoopRotate() : LoopPass(ID) {
41 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
44 // LCSSA form makes instruction renaming easier.
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.addPreserved<DominatorTree>();
47 AU.addRequired<LoopInfo>();
48 AU.addPreserved<LoopInfo>();
49 AU.addRequiredID(LoopSimplifyID);
50 AU.addPreservedID(LoopSimplifyID);
51 AU.addRequiredID(LCSSAID);
52 AU.addPreservedID(LCSSAID);
53 AU.addPreserved<ScalarEvolution>();
56 bool runOnLoop(Loop *L, LPPassManager &LPM);
57 void simplifyLoopLatch(Loop *L);
58 bool rotateLoop(Loop *L);
65 char LoopRotate::ID = 0;
66 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
67 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
68 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
69 INITIALIZE_PASS_DEPENDENCY(LCSSA)
70 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
72 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
74 /// Rotate Loop L as many times as possible. Return true if
75 /// the loop is rotated at least once.
76 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
77 LI = &getAnalysis<LoopInfo>();
79 // Simplify the loop latch before attempting to rotate the header
80 // upward. Rotation may not be needed if the loop tail can be folded into the
84 // One loop can be rotated multiple times.
85 bool MadeChange = false;
92 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
93 /// old header into the preheader. If there were uses of the values produced by
94 /// these instruction that were outside of the loop, we have to insert PHI nodes
95 /// to merge the two values. Do this now.
96 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
97 BasicBlock *OrigPreheader,
98 ValueToValueMapTy &ValueMap) {
99 // Remove PHI node entries that are no longer live.
100 BasicBlock::iterator I, E = OrigHeader->end();
101 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
102 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
104 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
107 for (I = OrigHeader->begin(); I != E; ++I) {
108 Value *OrigHeaderVal = I;
110 // If there are no uses of the value (e.g. because it returns void), there
111 // is nothing to rewrite.
112 if (OrigHeaderVal->use_empty())
115 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
117 // The value now exits in two versions: the initial value in the preheader
118 // and the loop "next" value in the original header.
119 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
120 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
121 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
123 // Visit each use of the OrigHeader instruction.
124 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
125 UE = OrigHeaderVal->use_end(); UI != UE; ) {
126 // Grab the use before incrementing the iterator.
127 Use &U = UI.getUse();
129 // Increment the iterator before removing the use from the list.
132 // SSAUpdater can't handle a non-PHI use in the same block as an
133 // earlier def. We can easily handle those cases manually.
134 Instruction *UserInst = cast<Instruction>(U.getUser());
135 if (!isa<PHINode>(UserInst)) {
136 BasicBlock *UserBB = UserInst->getParent();
138 // The original users in the OrigHeader are already using the
139 // original definitions.
140 if (UserBB == OrigHeader)
143 // Users in the OrigPreHeader need to use the value to which the
144 // original definitions are mapped.
145 if (UserBB == OrigPreheader) {
146 U = OrigPreHeaderVal;
151 // Anything else can be handled by SSAUpdater.
157 /// Determine whether the instructions in this range my be safely and cheaply
158 /// speculated. This is not an important enough situation to develop complex
159 /// heuristics. We handle a single arithmetic instruction along with any type
161 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
162 BasicBlock::iterator End) {
163 bool seenIncrement = false;
164 for (BasicBlock::iterator I = Begin; I != End; ++I) {
166 if (!isSafeToSpeculativelyExecute(I))
169 if (isa<DbgInfoIntrinsic>(I))
172 switch (I->getOpcode()) {
175 case Instruction::GetElementPtr:
176 // GEPs are cheap if all indices are constant.
177 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
179 // fall-thru to increment case
180 case Instruction::Add:
181 case Instruction::Sub:
182 case Instruction::And:
183 case Instruction::Or:
184 case Instruction::Xor:
185 case Instruction::Shl:
186 case Instruction::LShr:
187 case Instruction::AShr:
190 seenIncrement = true;
192 case Instruction::Trunc:
193 case Instruction::ZExt:
194 case Instruction::SExt:
195 // ignore type conversions
202 /// Fold the loop tail into the loop exit by speculating the loop tail
203 /// instructions. Typically, this is a single post-increment. In the case of a
204 /// simple 2-block loop, hoisting the increment can be much better than
205 /// duplicating the entire loop header. In the cast of loops with early exits,
206 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
207 /// canonical form so downstream passes can handle it.
209 /// I don't believe this invalidates SCEV.
210 void LoopRotate::simplifyLoopLatch(Loop *L) {
211 BasicBlock *Latch = L->getLoopLatch();
212 if (!Latch || Latch->hasAddressTaken())
215 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
216 if (!Jmp || !Jmp->isUnconditional())
219 BasicBlock *LastExit = Latch->getSinglePredecessor();
220 if (!LastExit || !L->isLoopExiting(LastExit))
223 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
227 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
230 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
231 << LastExit->getName() << "\n");
233 // Hoist the instructions from Latch into LastExit.
234 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
236 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
237 BasicBlock *Header = Jmp->getSuccessor(0);
238 assert(Header == L->getHeader() && "expected a backward branch");
240 // Remove Latch from the CFG so that LastExit becomes the new Latch.
241 BI->setSuccessor(FallThruPath, Header);
242 Latch->replaceSuccessorsPhiUsesWith(LastExit);
243 Jmp->eraseFromParent();
245 // Nuke the Latch block.
246 assert(Latch->empty() && "unable to evacuate Latch");
247 LI->removeBlock(Latch);
248 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
249 DT->eraseNode(Latch);
250 Latch->eraseFromParent();
253 /// Rotate loop LP. Return true if the loop is rotated.
254 bool LoopRotate::rotateLoop(Loop *L) {
255 // If the loop has only one block then there is not much to rotate.
256 if (L->getBlocks().size() == 1)
259 BasicBlock *OrigHeader = L->getHeader();
260 BasicBlock *OrigLatch = L->getLoopLatch();
262 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
263 if (BI == 0 || BI->isUnconditional())
266 // If the loop header is not one of the loop exiting blocks then
267 // either this loop is already rotated or it is not
268 // suitable for loop rotation transformations.
269 if (!L->isLoopExiting(OrigHeader))
272 // If the loop latch already contains a branch that leaves the loop then the
273 // loop is already rotated.
274 if (OrigLatch == 0 || L->isLoopExiting(OrigLatch))
277 // Check size of original header and reject loop if it is very big or we can't
278 // duplicate blocks inside it.
281 Metrics.analyzeBasicBlock(OrigHeader);
282 if (Metrics.notDuplicatable) {
283 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non duplicatable"
284 << " instructions: "; L->dump());
287 if (Metrics.NumInsts > MAX_HEADER_SIZE)
291 // Now, this loop is suitable for rotation.
292 BasicBlock *OrigPreheader = L->getLoopPreheader();
294 // If the loop could not be converted to canonical form, it must have an
295 // indirectbr in it, just give up.
296 if (OrigPreheader == 0)
299 // Anything ScalarEvolution may know about this loop or the PHI nodes
300 // in its header will soon be invalidated.
301 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
304 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
306 // Find new Loop header. NewHeader is a Header's one and only successor
307 // that is inside loop. Header's other successor is outside the
308 // loop. Otherwise loop is not suitable for rotation.
309 BasicBlock *Exit = BI->getSuccessor(0);
310 BasicBlock *NewHeader = BI->getSuccessor(1);
311 if (L->contains(Exit))
312 std::swap(Exit, NewHeader);
313 assert(NewHeader && "Unable to determine new loop header");
314 assert(L->contains(NewHeader) && !L->contains(Exit) &&
315 "Unable to determine loop header and exit blocks");
317 // This code assumes that the new header has exactly one predecessor.
318 // Remove any single-entry PHI nodes in it.
319 assert(NewHeader->getSinglePredecessor() &&
320 "New header doesn't have one pred!");
321 FoldSingleEntryPHINodes(NewHeader);
323 // Begin by walking OrigHeader and populating ValueMap with an entry for
325 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
326 ValueToValueMapTy ValueMap;
328 // For PHI nodes, the value available in OldPreHeader is just the
329 // incoming value from OldPreHeader.
330 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
331 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
333 // For the rest of the instructions, either hoist to the OrigPreheader if
334 // possible or create a clone in the OldPreHeader if not.
335 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
337 Instruction *Inst = I++;
339 // If the instruction's operands are invariant and it doesn't read or write
340 // memory, then it is safe to hoist. Doing this doesn't change the order of
341 // execution in the preheader, but does prevent the instruction from
342 // executing in each iteration of the loop. This means it is safe to hoist
343 // something that might trap, but isn't safe to hoist something that reads
344 // memory (without proving that the loop doesn't write).
345 if (L->hasLoopInvariantOperands(Inst) &&
346 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
347 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
348 !isa<AllocaInst>(Inst)) {
349 Inst->moveBefore(LoopEntryBranch);
353 // Otherwise, create a duplicate of the instruction.
354 Instruction *C = Inst->clone();
356 // Eagerly remap the operands of the instruction.
357 RemapInstruction(C, ValueMap,
358 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
360 // With the operands remapped, see if the instruction constant folds or is
361 // otherwise simplifyable. This commonly occurs because the entry from PHI
362 // nodes allows icmps and other instructions to fold.
363 Value *V = SimplifyInstruction(C);
364 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
365 // If so, then delete the temporary instruction and stick the folded value
370 // Otherwise, stick the new instruction into the new block!
371 C->setName(Inst->getName());
372 C->insertBefore(LoopEntryBranch);
377 // Along with all the other instructions, we just cloned OrigHeader's
378 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
379 // successors by duplicating their incoming values for OrigHeader.
380 TerminatorInst *TI = OrigHeader->getTerminator();
381 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
382 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
383 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
384 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
386 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
387 // OrigPreHeader's old terminator (the original branch into the loop), and
388 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
389 LoopEntryBranch->eraseFromParent();
391 // If there were any uses of instructions in the duplicated block outside the
392 // loop, update them, inserting PHI nodes as required
393 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
395 // NewHeader is now the header of the loop.
396 L->moveToHeader(NewHeader);
397 assert(L->getHeader() == NewHeader && "Latch block is our new header");
400 // At this point, we've finished our major CFG changes. As part of cloning
401 // the loop into the preheader we've simplified instructions and the
402 // duplicated conditional branch may now be branching on a constant. If it is
403 // branching on a constant and if that constant means that we enter the loop,
404 // then we fold away the cond branch to an uncond branch. This simplifies the
405 // loop in cases important for nested loops, and it also means we don't have
406 // to split as many edges.
407 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
408 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
409 if (!isa<ConstantInt>(PHBI->getCondition()) ||
410 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
412 // The conditional branch can't be folded, handle the general case.
413 // Update DominatorTree to reflect the CFG change we just made. Then split
414 // edges as necessary to preserve LoopSimplify form.
415 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
416 // Everything that was dominated by the old loop header is now dominated
417 // by the original loop preheader. Conceptually the header was merged
418 // into the preheader, even though we reuse the actual block as a new
420 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
421 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
422 OrigHeaderNode->end());
423 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
424 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
425 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
427 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
428 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
430 // Update OrigHeader to be dominated by the new header block.
431 DT->changeImmediateDominator(OrigHeader, OrigLatch);
434 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
435 // thus is not a preheader anymore.
436 // Split the edge to form a real preheader.
437 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
438 NewPH->setName(NewHeader->getName() + ".lr.ph");
440 // Preserve canonical loop form, which means that 'Exit' should have only
442 BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
443 ExitSplit->moveBefore(Exit);
445 // We can fold the conditional branch in the preheader, this makes things
446 // simpler. The first step is to remove the extra edge to the Exit block.
447 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
448 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
449 NewBI->setDebugLoc(PHBI->getDebugLoc());
450 PHBI->eraseFromParent();
452 // With our CFG finalized, update DomTree if it is available.
453 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
454 // Update OrigHeader to be dominated by the new header block.
455 DT->changeImmediateDominator(NewHeader, OrigPreheader);
456 DT->changeImmediateDominator(OrigHeader, OrigLatch);
458 // Brute force incremental dominator tree update. Call
459 // findNearestCommonDominator on all CFG predecessors of each child of the
461 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
462 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
463 OrigHeaderNode->end());
467 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
468 DomTreeNode *Node = HeaderChildren[I];
469 BasicBlock *BB = Node->getBlock();
471 pred_iterator PI = pred_begin(BB);
472 BasicBlock *NearestDom = *PI;
473 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
474 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
476 // Remember if this changes the DomTree.
477 if (Node->getIDom()->getBlock() != NearestDom) {
478 DT->changeImmediateDominator(BB, NearestDom);
483 // If the dominator changed, this may have an effect on other
484 // predecessors, continue until we reach a fixpoint.
489 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
490 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
492 // Now that the CFG and DomTree are in a consistent state again, try to merge
493 // the OrigHeader block into OrigLatch. This will succeed if they are
494 // connected by an unconditional branch. This is just a cleanup so the
495 // emitted code isn't too gross in this common case.
496 MergeBlockIntoPredecessor(OrigHeader, this);
498 DEBUG(dbgs() << "LoopRotation: into "; L->dump());