LLVM  6.0.0svn
LoopRotation.cpp
Go to the documentation of this file.
1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Loop Rotation Pass.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/LoopPass.h"
27 #include "llvm/IR/CFG.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Module.h"
33 #include "llvm/Support/Debug.h"
35 #include "llvm/Transforms/Scalar.h"
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "loop-rotate"
45 
47  "rotation-max-header-size", cl::init(16), cl::Hidden,
48  cl::desc("The default maximum header size for automatic loop rotation"));
49 
50 STATISTIC(NumRotated, "Number of loops rotated");
51 
52 namespace {
53 /// A simple loop rotation transformation.
54 class LoopRotate {
55  const unsigned MaxHeaderSize;
56  LoopInfo *LI;
57  const TargetTransformInfo *TTI;
58  AssumptionCache *AC;
59  DominatorTree *DT;
60  ScalarEvolution *SE;
61  const SimplifyQuery &SQ;
62 
63 public:
64  LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
65  const TargetTransformInfo *TTI, AssumptionCache *AC,
66  DominatorTree *DT, ScalarEvolution *SE, const SimplifyQuery &SQ)
67  : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
68  SQ(SQ) {}
69  bool processLoop(Loop *L);
70 
71 private:
72  bool rotateLoop(Loop *L, bool SimplifiedLatch);
73  bool simplifyLoopLatch(Loop *L);
74 };
75 } // end anonymous namespace
76 
77 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
78 /// old header into the preheader. If there were uses of the values produced by
79 /// these instruction that were outside of the loop, we have to insert PHI nodes
80 /// to merge the two values. Do this now.
82  BasicBlock *OrigPreheader,
84  SmallVectorImpl<PHINode*> *InsertedPHIs) {
85  // Remove PHI node entries that are no longer live.
86  BasicBlock::iterator I, E = OrigHeader->end();
87  for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
88  PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
89 
90  // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
91  // as necessary.
92  SSAUpdater SSA(InsertedPHIs);
93  for (I = OrigHeader->begin(); I != E; ++I) {
94  Value *OrigHeaderVal = &*I;
95 
96  // If there are no uses of the value (e.g. because it returns void), there
97  // is nothing to rewrite.
98  if (OrigHeaderVal->use_empty())
99  continue;
100 
101  Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
102 
103  // The value now exits in two versions: the initial value in the preheader
104  // and the loop "next" value in the original header.
105  SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
106  SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
107  SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
108 
109  // Visit each use of the OrigHeader instruction.
110  for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
111  UE = OrigHeaderVal->use_end();
112  UI != UE;) {
113  // Grab the use before incrementing the iterator.
114  Use &U = *UI;
115 
116  // Increment the iterator before removing the use from the list.
117  ++UI;
118 
119  // SSAUpdater can't handle a non-PHI use in the same block as an
120  // earlier def. We can easily handle those cases manually.
121  Instruction *UserInst = cast<Instruction>(U.getUser());
122  if (!isa<PHINode>(UserInst)) {
123  BasicBlock *UserBB = UserInst->getParent();
124 
125  // The original users in the OrigHeader are already using the
126  // original definitions.
127  if (UserBB == OrigHeader)
128  continue;
129 
130  // Users in the OrigPreHeader need to use the value to which the
131  // original definitions are mapped.
132  if (UserBB == OrigPreheader) {
133  U = OrigPreHeaderVal;
134  continue;
135  }
136  }
137 
138  // Anything else can be handled by SSAUpdater.
139  SSA.RewriteUse(U);
140  }
141 
142  // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
143  // intrinsics.
144  LLVMContext &C = OrigHeader->getContext();
145  if (auto *VAM = ValueAsMetadata::getIfExists(OrigHeaderVal)) {
146  if (auto *MAV = MetadataAsValue::getIfExists(C, VAM)) {
147  for (auto UI = MAV->use_begin(), E = MAV->use_end(); UI != E;) {
148  // Grab the use before incrementing the iterator. Otherwise, altering
149  // the Use will invalidate the iterator.
150  Use &U = *UI++;
152  if (!UserInst)
153  continue;
154 
155  // The original users in the OrigHeader are already using the original
156  // definitions.
157  BasicBlock *UserBB = UserInst->getParent();
158  if (UserBB == OrigHeader)
159  continue;
160 
161  // Users in the OrigPreHeader need to use the value to which the
162  // original definitions are mapped and anything else can be handled by
163  // the SSAUpdater. To avoid adding PHINodes, check if the value is
164  // available in UserBB, if not substitute undef.
165  Value *NewVal;
166  if (UserBB == OrigPreheader)
167  NewVal = OrigPreHeaderVal;
168  else if (SSA.HasValueForBlock(UserBB))
169  NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
170  else
171  NewVal = UndefValue::get(OrigHeaderVal->getType());
173  }
174  }
175  }
176  }
177 }
178 
179 /// Propagate dbg.value intrinsics through the newly inserted Phis.
180 static void insertDebugValues(BasicBlock *OrigHeader,
181  SmallVectorImpl<PHINode*> &InsertedPHIs) {
182  ValueToValueMapTy DbgValueMap;
183 
184  // Map existing PHI nodes to their dbg.values.
185  for (auto &I : *OrigHeader) {
186  if (auto DbgII = dyn_cast<DbgInfoIntrinsic>(&I)) {
187  if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
188  DbgValueMap.insert({Loc, DbgII});
189  }
190  }
191 
192  // Then iterate through the new PHIs and look to see if they use one of the
193  // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
194  // propagate the info through the new PHI.
195  LLVMContext &C = OrigHeader->getContext();
196  for (auto PHI : InsertedPHIs) {
197  for (auto VI : PHI->operand_values()) {
198  auto V = DbgValueMap.find(VI);
199  if (V != DbgValueMap.end()) {
200  auto *DbgII = cast<DbgInfoIntrinsic>(V->second);
201  Instruction *NewDbgII = DbgII->clone();
202  auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
203  NewDbgII->setOperand(0, PhiMAV);
204  BasicBlock *Parent = PHI->getParent();
205  NewDbgII->insertBefore(Parent->getFirstNonPHIOrDbgOrLifetime());
206  }
207  }
208  }
209 }
210 
211 /// Rotate loop LP. Return true if the loop is rotated.
212 ///
213 /// \param SimplifiedLatch is true if the latch was just folded into the final
214 /// loop exit. In this case we may want to rotate even though the new latch is
215 /// now an exiting branch. This rotation would have happened had the latch not
216 /// been simplified. However, if SimplifiedLatch is false, then we avoid
217 /// rotating loops in which the latch exits to avoid excessive or endless
218 /// rotation. LoopRotate should be repeatable and converge to a canonical
219 /// form. This property is satisfied because simplifying the loop latch can only
220 /// happen once across multiple invocations of the LoopRotate pass.
221 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
222  // If the loop has only one block then there is not much to rotate.
223  if (L->getBlocks().size() == 1)
224  return false;
225 
226  BasicBlock *OrigHeader = L->getHeader();
227  BasicBlock *OrigLatch = L->getLoopLatch();
228 
229  BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
230  if (!BI || BI->isUnconditional())
231  return false;
232 
233  // If the loop header is not one of the loop exiting blocks then
234  // either this loop is already rotated or it is not
235  // suitable for loop rotation transformations.
236  if (!L->isLoopExiting(OrigHeader))
237  return false;
238 
239  // If the loop latch already contains a branch that leaves the loop then the
240  // loop is already rotated.
241  if (!OrigLatch)
242  return false;
243 
244  // Rotate if either the loop latch does *not* exit the loop, or if the loop
245  // latch was just simplified.
246  if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
247  return false;
248 
249  // Check size of original header and reject loop if it is very big or we can't
250  // duplicate blocks inside it.
251  {
253  CodeMetrics::collectEphemeralValues(L, AC, EphValues);
254 
256  Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
257  if (Metrics.notDuplicatable) {
258  DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
259  << " instructions: ";
260  L->dump());
261  return false;
262  }
263  if (Metrics.convergent) {
264  DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
265  "instructions: ";
266  L->dump());
267  return false;
268  }
269  if (Metrics.NumInsts > MaxHeaderSize)
270  return false;
271  }
272 
273  // Now, this loop is suitable for rotation.
274  BasicBlock *OrigPreheader = L->getLoopPreheader();
275 
276  // If the loop could not be converted to canonical form, it must have an
277  // indirectbr in it, just give up.
278  if (!OrigPreheader)
279  return false;
280 
281  // Anything ScalarEvolution may know about this loop or the PHI nodes
282  // in its header will soon be invalidated.
283  if (SE)
284  SE->forgetLoop(L);
285 
286  DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
287 
288  // Find new Loop header. NewHeader is a Header's one and only successor
289  // that is inside loop. Header's other successor is outside the
290  // loop. Otherwise loop is not suitable for rotation.
291  BasicBlock *Exit = BI->getSuccessor(0);
292  BasicBlock *NewHeader = BI->getSuccessor(1);
293  if (L->contains(Exit))
294  std::swap(Exit, NewHeader);
295  assert(NewHeader && "Unable to determine new loop header");
296  assert(L->contains(NewHeader) && !L->contains(Exit) &&
297  "Unable to determine loop header and exit blocks");
298 
299  // This code assumes that the new header has exactly one predecessor.
300  // Remove any single-entry PHI nodes in it.
301  assert(NewHeader->getSinglePredecessor() &&
302  "New header doesn't have one pred!");
303  FoldSingleEntryPHINodes(NewHeader);
304 
305  // Begin by walking OrigHeader and populating ValueMap with an entry for
306  // each Instruction.
307  BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
309 
310  // For PHI nodes, the value available in OldPreHeader is just the
311  // incoming value from OldPreHeader.
312  for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
313  ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
314 
315  // For the rest of the instructions, either hoist to the OrigPreheader if
316  // possible or create a clone in the OldPreHeader if not.
317  TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
318  while (I != E) {
319  Instruction *Inst = &*I++;
320 
321  // If the instruction's operands are invariant and it doesn't read or write
322  // memory, then it is safe to hoist. Doing this doesn't change the order of
323  // execution in the preheader, but does prevent the instruction from
324  // executing in each iteration of the loop. This means it is safe to hoist
325  // something that might trap, but isn't safe to hoist something that reads
326  // memory (without proving that the loop doesn't write).
327  if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
328  !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) &&
329  !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
330  Inst->moveBefore(LoopEntryBranch);
331  continue;
332  }
333 
334  // Otherwise, create a duplicate of the instruction.
335  Instruction *C = Inst->clone();
336 
337  // Eagerly remap the operands of the instruction.
338  RemapInstruction(C, ValueMap,
340 
341  // With the operands remapped, see if the instruction constant folds or is
342  // otherwise simplifyable. This commonly occurs because the entry from PHI
343  // nodes allows icmps and other instructions to fold.
344  Value *V = SimplifyInstruction(C, SQ);
345  if (V && LI->replacementPreservesLCSSAForm(C, V)) {
346  // If so, then delete the temporary instruction and stick the folded value
347  // in the map.
348  ValueMap[Inst] = V;
349  if (!C->mayHaveSideEffects()) {
350  C->deleteValue();
351  C = nullptr;
352  }
353  } else {
354  ValueMap[Inst] = C;
355  }
356  if (C) {
357  // Otherwise, stick the new instruction into the new block!
358  C->setName(Inst->getName());
359  C->insertBefore(LoopEntryBranch);
360 
361  if (auto *II = dyn_cast<IntrinsicInst>(C))
362  if (II->getIntrinsicID() == Intrinsic::assume)
363  AC->registerAssumption(II);
364  }
365  }
366 
367  // Along with all the other instructions, we just cloned OrigHeader's
368  // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
369  // successors by duplicating their incoming values for OrigHeader.
370  TerminatorInst *TI = OrigHeader->getTerminator();
371  for (BasicBlock *SuccBB : TI->successors())
372  for (BasicBlock::iterator BI = SuccBB->begin();
373  PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
374  PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
375 
376  // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
377  // OrigPreHeader's old terminator (the original branch into the loop), and
378  // remove the corresponding incoming values from the PHI nodes in OrigHeader.
379  LoopEntryBranch->eraseFromParent();
380 
381 
382  SmallVector<PHINode*, 2> InsertedPHIs;
383  // If there were any uses of instructions in the duplicated block outside the
384  // loop, update them, inserting PHI nodes as required
385  RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
386  &InsertedPHIs);
387 
388  // Attach dbg.value intrinsics to the new phis if that phi uses a value that
389  // previously had debug metadata attached. This keeps the debug info
390  // up-to-date in the loop body.
391  if (!InsertedPHIs.empty())
392  insertDebugValues(OrigHeader, InsertedPHIs);
393 
394  // NewHeader is now the header of the loop.
395  L->moveToHeader(NewHeader);
396  assert(L->getHeader() == NewHeader && "Latch block is our new header");
397 
398  // Inform DT about changes to the CFG.
399  if (DT) {
400  // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
401  // the DT about the removed edge to the OrigHeader (that got removed).
403  Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
404  Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
405  Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
406  DT->applyUpdates(Updates);
407  }
408 
409  // At this point, we've finished our major CFG changes. As part of cloning
410  // the loop into the preheader we've simplified instructions and the
411  // duplicated conditional branch may now be branching on a constant. If it is
412  // branching on a constant and if that constant means that we enter the loop,
413  // then we fold away the cond branch to an uncond branch. This simplifies the
414  // loop in cases important for nested loops, and it also means we don't have
415  // to split as many edges.
416  BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
417  assert(PHBI->isConditional() && "Should be clone of BI condbr!");
418  if (!isa<ConstantInt>(PHBI->getCondition()) ||
419  PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
420  NewHeader) {
421  // The conditional branch can't be folded, handle the general case.
422  // Split edges as necessary to preserve LoopSimplify form.
423 
424  // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
425  // thus is not a preheader anymore.
426  // Split the edge to form a real preheader.
427  BasicBlock *NewPH = SplitCriticalEdge(
428  OrigPreheader, NewHeader,
429  CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
430  NewPH->setName(NewHeader->getName() + ".lr.ph");
431 
432  // Preserve canonical loop form, which means that 'Exit' should have only
433  // one predecessor. Note that Exit could be an exit block for multiple
434  // nested loops, causing both of the edges to now be critical and need to
435  // be split.
436  SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
437  bool SplitLatchEdge = false;
438  for (BasicBlock *ExitPred : ExitPreds) {
439  // We only need to split loop exit edges.
440  Loop *PredLoop = LI->getLoopFor(ExitPred);
441  if (!PredLoop || PredLoop->contains(Exit))
442  continue;
443  if (isa<IndirectBrInst>(ExitPred->getTerminator()))
444  continue;
445  SplitLatchEdge |= L->getLoopLatch() == ExitPred;
446  BasicBlock *ExitSplit = SplitCriticalEdge(
447  ExitPred, Exit,
448  CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
449  ExitSplit->moveBefore(Exit);
450  }
451  assert(SplitLatchEdge &&
452  "Despite splitting all preds, failed to split latch exit?");
453  } else {
454  // We can fold the conditional branch in the preheader, this makes things
455  // simpler. The first step is to remove the extra edge to the Exit block.
456  Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
457  BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
458  NewBI->setDebugLoc(PHBI->getDebugLoc());
459  PHBI->eraseFromParent();
460 
461  // With our CFG finalized, update DomTree if it is available.
462  if (DT) DT->deleteEdge(OrigPreheader, Exit);
463  }
464 
465  assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
466  assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
467 
468  // Now that the CFG and DomTree are in a consistent state again, try to merge
469  // the OrigHeader block into OrigLatch. This will succeed if they are
470  // connected by an unconditional branch. This is just a cleanup so the
471  // emitted code isn't too gross in this common case.
472  MergeBlockIntoPredecessor(OrigHeader, DT, LI);
473 
474  DEBUG(dbgs() << "LoopRotation: into "; L->dump());
475 
476  ++NumRotated;
477  return true;
478 }
479 
480 /// Determine whether the instructions in this range may be safely and cheaply
481 /// speculated. This is not an important enough situation to develop complex
482 /// heuristics. We handle a single arithmetic instruction along with any type
483 /// conversions.
486  bool seenIncrement = false;
487  bool MultiExitLoop = false;
488 
489  if (!L->getExitingBlock())
490  MultiExitLoop = true;
491 
492  for (BasicBlock::iterator I = Begin; I != End; ++I) {
493 
495  return false;
496 
497  if (isa<DbgInfoIntrinsic>(I))
498  continue;
499 
500  switch (I->getOpcode()) {
501  default:
502  return false;
503  case Instruction::GetElementPtr:
504  // GEPs are cheap if all indices are constant.
505  if (!cast<GEPOperator>(I)->hasAllConstantIndices())
506  return false;
507  // fall-thru to increment case
509  case Instruction::Add:
510  case Instruction::Sub:
511  case Instruction::And:
512  case Instruction::Or:
513  case Instruction::Xor:
514  case Instruction::Shl:
515  case Instruction::LShr:
516  case Instruction::AShr: {
517  Value *IVOpnd =
518  !isa<Constant>(I->getOperand(0))
519  ? I->getOperand(0)
520  : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
521  if (!IVOpnd)
522  return false;
523 
524  // If increment operand is used outside of the loop, this speculation
525  // could cause extra live range interference.
526  if (MultiExitLoop) {
527  for (User *UseI : IVOpnd->users()) {
528  auto *UserInst = cast<Instruction>(UseI);
529  if (!L->contains(UserInst))
530  return false;
531  }
532  }
533 
534  if (seenIncrement)
535  return false;
536  seenIncrement = true;
537  break;
538  }
539  case Instruction::Trunc:
540  case Instruction::ZExt:
541  case Instruction::SExt:
542  // ignore type conversions
543  break;
544  }
545  }
546  return true;
547 }
548 
549 /// Fold the loop tail into the loop exit by speculating the loop tail
550 /// instructions. Typically, this is a single post-increment. In the case of a
551 /// simple 2-block loop, hoisting the increment can be much better than
552 /// duplicating the entire loop header. In the case of loops with early exits,
553 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
554 /// canonical form so downstream passes can handle it.
555 ///
556 /// I don't believe this invalidates SCEV.
557 bool LoopRotate::simplifyLoopLatch(Loop *L) {
558  BasicBlock *Latch = L->getLoopLatch();
559  if (!Latch || Latch->hasAddressTaken())
560  return false;
561 
562  BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
563  if (!Jmp || !Jmp->isUnconditional())
564  return false;
565 
566  BasicBlock *LastExit = Latch->getSinglePredecessor();
567  if (!LastExit || !L->isLoopExiting(LastExit))
568  return false;
569 
570  BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
571  if (!BI)
572  return false;
573 
574  if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
575  return false;
576 
577  DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
578  << LastExit->getName() << "\n");
579 
580  // Hoist the instructions from Latch into LastExit.
581  LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
582  Latch->begin(), Jmp->getIterator());
583 
584  unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
585  BasicBlock *Header = Jmp->getSuccessor(0);
586  assert(Header == L->getHeader() && "expected a backward branch");
587 
588  // Remove Latch from the CFG so that LastExit becomes the new Latch.
589  BI->setSuccessor(FallThruPath, Header);
590  Latch->replaceSuccessorsPhiUsesWith(LastExit);
591  Jmp->eraseFromParent();
592 
593  // Nuke the Latch block.
594  assert(Latch->empty() && "unable to evacuate Latch");
595  LI->removeBlock(Latch);
596  if (DT)
597  DT->eraseNode(Latch);
598  Latch->eraseFromParent();
599  return true;
600 }
601 
602 /// Rotate \c L, and return true if any modification was made.
603 bool LoopRotate::processLoop(Loop *L) {
604  // Save the loop metadata.
605  MDNode *LoopMD = L->getLoopID();
606 
607  // Simplify the loop latch before attempting to rotate the header
608  // upward. Rotation may not be needed if the loop tail can be folded into the
609  // loop exit.
610  bool SimplifiedLatch = simplifyLoopLatch(L);
611 
612  bool MadeChange = rotateLoop(L, SimplifiedLatch);
613  assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
614  "Loop latch should be exiting after loop-rotate.");
615 
616  // Restore the loop metadata.
617  // NB! We presume LoopRotation DOESN'T ADD its own metadata.
618  if ((MadeChange || SimplifiedLatch) && LoopMD)
619  L->setLoopID(LoopMD);
620 
621  return MadeChange;
622 }
623 
624 LoopRotatePass::LoopRotatePass(bool EnableHeaderDuplication)
625  : EnableHeaderDuplication(EnableHeaderDuplication) {}
626 
629  LPMUpdater &) {
630  int Threshold = EnableHeaderDuplication ? DefaultRotationThreshold : 0;
631  const DataLayout &DL = L.getHeader()->getModule()->getDataLayout();
632  const SimplifyQuery SQ = getBestSimplifyQuery(AR, DL);
633  LoopRotate LR(Threshold, &AR.LI, &AR.TTI, &AR.AC, &AR.DT, &AR.SE,
634  SQ);
635 
636  bool Changed = LR.processLoop(&L);
637  if (!Changed)
638  return PreservedAnalyses::all();
639 
641 }
642 
643 namespace {
644 
645 class LoopRotateLegacyPass : public LoopPass {
646  unsigned MaxHeaderSize;
647 
648 public:
649  static char ID; // Pass ID, replacement for typeid
650  LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
652  if (SpecifiedMaxHeaderSize == -1)
653  MaxHeaderSize = DefaultRotationThreshold;
654  else
655  MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
656  }
657 
658  // LCSSA form makes instruction renaming easier.
659  void getAnalysisUsage(AnalysisUsage &AU) const override {
663  }
664 
665  bool runOnLoop(Loop *L, LPPassManager &LPM) override {
666  if (skipLoop(L))
667  return false;
668  Function &F = *L->getHeader()->getParent();
669 
670  auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
671  const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
672  auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
673  auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
674  auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
675  auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
676  auto *SE = SEWP ? &SEWP->getSE() : nullptr;
677  const SimplifyQuery SQ = getBestSimplifyQuery(*this, F);
678  LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE, SQ);
679  return LR.processLoop(L);
680  }
681 };
682 }
683 
684 char LoopRotateLegacyPass::ID = 0;
685 INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
686  false, false)
690 INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false,
691  false)
692 
693 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
694  return new LoopRotateLegacyPass(MaxHeaderSize);
695 }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:81
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop&#39;s ephemeral values (those used only by an assume or similar intrinsics in the loop)...
Definition: CodeMetrics.cpp:73
uint64_t CallInst * C
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:69
use_iterator use_end()
Definition: Value.h:342
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition: SSAUpdater.h:39
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:157
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: ValueMap.h:175
This is the interface for a simple mod/ref and alias analysis over globals.
bool convergent
True if this function contains a call to a convergent function.
Definition: CodeMetrics.h:57
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type &#39;Ty&#39;.
Definition: SSAUpdater.cpp:54
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
Definition: SSAUpdater.cpp:67
void moveToHeader(BlockT *BB)
This method is used to move BB (which must be part of this loop) to be the loop header of the loop (t...
Definition: LoopInfo.h:336
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:106
An immutable pass that tracks lazily created AssumptionCache objects.
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
A cache of .assume calls within a function.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:697
void deleteValue()
Delete a pointer to a generic Value.
Definition: Value.cpp:93
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
Metadata node.
Definition: Metadata.h:862
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
F(f)
Value * getCondition() const
const SimplifyQuery getBestSimplifyQuery(Pass &, Function &)
bool notDuplicatable
True if this function cannot be duplicated.
Definition: CodeMetrics.h:54
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:33
static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, BasicBlock *OrigPreheader, ValueToValueMapTy &ValueMap, SmallVectorImpl< PHINode *> *InsertedPHIs)
RewriteUsesOfClonedInstructions - We just cloned the instructions from the old header into the prehea...
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Definition: LoopInfo.cpp:62
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
Definition: BasicBlock.cpp:116
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false, false) INITIALIZE_PASS_END(LoopRotateLegacyPass
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
This is the interface for a SCEV-based alias analysis.
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
Option class for critical edge splitting.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:284
BlockT * getHeader() const
Definition: LoopInfo.h:107
bool empty() const
Definition: BasicBlock.h:263
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
const Instruction * getFirstNonPHIOrDbgOrLifetime() const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic...
Definition: BasicBlock.cpp:185
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Definition: Use.cpp:41
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition: LoopInfo.cpp:249
iterator find(const KeyT &Val)
Definition: ValueMap.h:158
Memory SSA
Definition: MemorySSA.cpp:65
static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, BasicBlock::iterator End, Loop *L)
Determine whether the instructions in this range may be safely and cheaply speculated.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: ValueMap.h:167
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:140
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition: ValueMapper.h:65
use_iterator_impl< Use > use_iterator
Definition: Value.h:327
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:106
void replaceSuccessorsPhiUsesWith(BasicBlock *New)
Update all phi nodes in this basic block&#39;s successors to refer to basic block New instead of to it...
Definition: BasicBlock.cpp:420
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
succ_range successors()
Definition: InstrTypes.h:267
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:406
Value * GetValueInMiddleOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live in the middle of the specified block...
Definition: SSAUpdater.cpp:95
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:54
Wrapper pass for TargetTransformInfo.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:281
void dump() const
Definition: LoopInfo.cpp:411
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:217
static ValueAsMetadata * getIfExists(Value *V)
Definition: Metadata.cpp:360
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Definition: Instruction.cpp:75
static MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:114
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
Definition: LoopInfo.h:180
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
Conditional or Unconditional Branch instruction.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Machine Trace Metrics
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Definition: Instruction.h:504
const std::vector< BlockT * > & getBlocks() const
Get a list of the basic blocks which make up this loop.
Definition: LoopInfo.h:156
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:113
Represent the analysis usage information of a pass.
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value *> &EphValues)
Add information about a block to the current state.
void splice(iterator where, iplist_impl &L2)
Definition: ilist.h:342
static const unsigned End
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:116
self_iterator getIterator()
Definition: ilist_node.h:82
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1320
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
void initializeLoopRotateLegacyPassPass(PassRegistry &)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
iterator end()
Definition: ValueMap.h:138
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:376
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:317
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:117
Iterator for intrusive lists based on ilist_node.
loop Rotate Loops
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:410
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
iterator end()
Definition: BasicBlock.h:254
loop rotate
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:341
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
Module.h This file contains the declarations for the Module class.
This is the common base class for debug info intrinsics.
Definition: IntrinsicInst.h:67
Utility to calculate the size and a few similar metrics for a set of basic blocks.
Definition: CodeMetrics.h:42
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
iterator_range< user_iterator > users()
Definition: Value.h:395
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
Definition: ValueMapper.h:243
void FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
Definition: ValueMapper.h:83
use_iterator use_begin()
Definition: Value.h:334
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:529
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition: LoopInfo.cpp:213
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:284
bool MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemoryDependenceResults *MemDep=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:61
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:404
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:218
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink &#39;this&#39; from the containing function and delete it.
Definition: BasicBlock.cpp:97
#define I(x, y, z)
Definition: MD5.cpp:58
bool mayReadFromMemory() const
Return true if this instruction may read memory.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass&#39;s AnalysisUsage.
Definition: LoopUtils.cpp:1023
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
LoopRotatePass(bool EnableHeaderDuplication=true)
bool isUnconditional() const
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM Value Representation.
Definition: Value.h:73
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:235
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:88
#define DEBUG(X)
Definition: Debug.h:118
This is the interface for LLVM&#39;s primary stateless and local alias analysis.
A container for analyses that lazily runs them and caches their results.
This pass exposes codegen information to IR-level passes.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
unsigned NumInsts
Number of instructions in the analyzed blocks.
Definition: CodeMetrics.h:63
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
Definition: SSAUpdater.cpp:187
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:50
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition: BasicBlock.cpp:103
static void insertDebugValues(BasicBlock *OrigHeader, SmallVectorImpl< PHINode *> &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted Phis.
bool use_empty() const
Definition: Value.h:322
Pass * createLoopRotatePass(int MaxHeaderSize=-1)
static cl::opt< unsigned > DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden, cl::desc("The default maximum header size for automatic loop rotation"))
const BasicBlock * getParent() const
Definition: Instruction.h:66
bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.
Definition: SSAUpdater.cpp:63