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"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Module.h"
34 #include "llvm/Support/Debug.h"
36 #include "llvm/Transforms/Scalar.h"
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "loop-rotate"
46 
48  "rotation-max-header-size", cl::init(16), cl::Hidden,
49  cl::desc("The default maximum header size for automatic loop rotation"));
50 
51 STATISTIC(NumRotated, "Number of loops rotated");
52 
53 namespace {
54 /// A simple loop rotation transformation.
55 class LoopRotate {
56  const unsigned MaxHeaderSize;
57  LoopInfo *LI;
58  const TargetTransformInfo *TTI;
59  AssumptionCache *AC;
60  DominatorTree *DT;
61  ScalarEvolution *SE;
62  const SimplifyQuery &SQ;
63 
64 public:
65  LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
66  const TargetTransformInfo *TTI, AssumptionCache *AC,
67  DominatorTree *DT, ScalarEvolution *SE, const SimplifyQuery &SQ)
68  : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
69  SQ(SQ) {}
70  bool processLoop(Loop *L);
71 
72 private:
73  bool rotateLoop(Loop *L, bool SimplifiedLatch);
74  bool simplifyLoopLatch(Loop *L);
75 };
76 } // end anonymous namespace
77 
78 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
79 /// old header into the preheader. If there were uses of the values produced by
80 /// these instruction that were outside of the loop, we have to insert PHI nodes
81 /// to merge the two values. Do this now.
83  BasicBlock *OrigPreheader,
85  SmallVectorImpl<PHINode*> *InsertedPHIs) {
86  // Remove PHI node entries that are no longer live.
87  BasicBlock::iterator I, E = OrigHeader->end();
88  for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
89  PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
90 
91  // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
92  // as necessary.
93  SSAUpdater SSA(InsertedPHIs);
94  for (I = OrigHeader->begin(); I != E; ++I) {
95  Value *OrigHeaderVal = &*I;
96 
97  // If there are no uses of the value (e.g. because it returns void), there
98  // is nothing to rewrite.
99  if (OrigHeaderVal->use_empty())
100  continue;
101 
102  Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
103 
104  // The value now exits in two versions: the initial value in the preheader
105  // and the loop "next" value in the original header.
106  SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
107  SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
108  SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
109 
110  // Visit each use of the OrigHeader instruction.
111  for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
112  UE = OrigHeaderVal->use_end();
113  UI != UE;) {
114  // Grab the use before incrementing the iterator.
115  Use &U = *UI;
116 
117  // Increment the iterator before removing the use from the list.
118  ++UI;
119 
120  // SSAUpdater can't handle a non-PHI use in the same block as an
121  // earlier def. We can easily handle those cases manually.
122  Instruction *UserInst = cast<Instruction>(U.getUser());
123  if (!isa<PHINode>(UserInst)) {
124  BasicBlock *UserBB = UserInst->getParent();
125 
126  // The original users in the OrigHeader are already using the
127  // original definitions.
128  if (UserBB == OrigHeader)
129  continue;
130 
131  // Users in the OrigPreHeader need to use the value to which the
132  // original definitions are mapped.
133  if (UserBB == OrigPreheader) {
134  U = OrigPreHeaderVal;
135  continue;
136  }
137  }
138 
139  // Anything else can be handled by SSAUpdater.
140  SSA.RewriteUse(U);
141  }
142 
143  // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
144  // intrinsics.
146  llvm::findDbgValues(DbgValues, OrigHeaderVal);
147  for (auto &DbgValue : DbgValues) {
148  // The original users in the OrigHeader are already using the original
149  // definitions.
150  BasicBlock *UserBB = DbgValue->getParent();
151  if (UserBB == OrigHeader)
152  continue;
153 
154  // Users in the OrigPreHeader need to use the value to which the
155  // original definitions are mapped and anything else can be handled by
156  // the SSAUpdater. To avoid adding PHINodes, check if the value is
157  // available in UserBB, if not substitute undef.
158  Value *NewVal;
159  if (UserBB == OrigPreheader)
160  NewVal = OrigPreHeaderVal;
161  else if (SSA.HasValueForBlock(UserBB))
162  NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
163  else
164  NewVal = UndefValue::get(OrigHeaderVal->getType());
165  DbgValue->setOperand(0,
166  MetadataAsValue::get(OrigHeaderVal->getContext(),
167  ValueAsMetadata::get(NewVal)));
168  }
169  }
170 }
171 
172 /// Propagate dbg.value intrinsics through the newly inserted Phis.
173 static void insertDebugValues(BasicBlock *OrigHeader,
174  SmallVectorImpl<PHINode*> &InsertedPHIs) {
175  ValueToValueMapTy DbgValueMap;
176 
177  // Map existing PHI nodes to their dbg.values.
178  for (auto &I : *OrigHeader) {
179  if (auto DbgII = dyn_cast<DbgInfoIntrinsic>(&I)) {
180  if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
181  DbgValueMap.insert({Loc, DbgII});
182  }
183  }
184 
185  // Then iterate through the new PHIs and look to see if they use one of the
186  // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
187  // propagate the info through the new PHI.
188  LLVMContext &C = OrigHeader->getContext();
189  for (auto PHI : InsertedPHIs) {
190  for (auto VI : PHI->operand_values()) {
191  auto V = DbgValueMap.find(VI);
192  if (V != DbgValueMap.end()) {
193  auto *DbgII = cast<DbgInfoIntrinsic>(V->second);
194  Instruction *NewDbgII = DbgII->clone();
195  auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
196  NewDbgII->setOperand(0, PhiMAV);
197  BasicBlock *Parent = PHI->getParent();
198  NewDbgII->insertBefore(Parent->getFirstNonPHIOrDbgOrLifetime());
199  }
200  }
201  }
202 }
203 
204 /// Rotate loop LP. Return true if the loop is rotated.
205 ///
206 /// \param SimplifiedLatch is true if the latch was just folded into the final
207 /// loop exit. In this case we may want to rotate even though the new latch is
208 /// now an exiting branch. This rotation would have happened had the latch not
209 /// been simplified. However, if SimplifiedLatch is false, then we avoid
210 /// rotating loops in which the latch exits to avoid excessive or endless
211 /// rotation. LoopRotate should be repeatable and converge to a canonical
212 /// form. This property is satisfied because simplifying the loop latch can only
213 /// happen once across multiple invocations of the LoopRotate pass.
214 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
215  // If the loop has only one block then there is not much to rotate.
216  if (L->getBlocks().size() == 1)
217  return false;
218 
219  BasicBlock *OrigHeader = L->getHeader();
220  BasicBlock *OrigLatch = L->getLoopLatch();
221 
222  BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
223  if (!BI || BI->isUnconditional())
224  return false;
225 
226  // If the loop header is not one of the loop exiting blocks then
227  // either this loop is already rotated or it is not
228  // suitable for loop rotation transformations.
229  if (!L->isLoopExiting(OrigHeader))
230  return false;
231 
232  // If the loop latch already contains a branch that leaves the loop then the
233  // loop is already rotated.
234  if (!OrigLatch)
235  return false;
236 
237  // Rotate if either the loop latch does *not* exit the loop, or if the loop
238  // latch was just simplified.
239  if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
240  return false;
241 
242  // Check size of original header and reject loop if it is very big or we can't
243  // duplicate blocks inside it.
244  {
246  CodeMetrics::collectEphemeralValues(L, AC, EphValues);
247 
249  Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
250  if (Metrics.notDuplicatable) {
251  DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
252  << " instructions: ";
253  L->dump());
254  return false;
255  }
256  if (Metrics.convergent) {
257  DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
258  "instructions: ";
259  L->dump());
260  return false;
261  }
262  if (Metrics.NumInsts > MaxHeaderSize)
263  return false;
264  }
265 
266  // Now, this loop is suitable for rotation.
267  BasicBlock *OrigPreheader = L->getLoopPreheader();
268 
269  // If the loop could not be converted to canonical form, it must have an
270  // indirectbr in it, just give up.
271  if (!OrigPreheader)
272  return false;
273 
274  // Anything ScalarEvolution may know about this loop or the PHI nodes
275  // in its header will soon be invalidated.
276  if (SE)
277  SE->forgetLoop(L);
278 
279  DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
280 
281  // Find new Loop header. NewHeader is a Header's one and only successor
282  // that is inside loop. Header's other successor is outside the
283  // loop. Otherwise loop is not suitable for rotation.
284  BasicBlock *Exit = BI->getSuccessor(0);
285  BasicBlock *NewHeader = BI->getSuccessor(1);
286  if (L->contains(Exit))
287  std::swap(Exit, NewHeader);
288  assert(NewHeader && "Unable to determine new loop header");
289  assert(L->contains(NewHeader) && !L->contains(Exit) &&
290  "Unable to determine loop header and exit blocks");
291 
292  // This code assumes that the new header has exactly one predecessor.
293  // Remove any single-entry PHI nodes in it.
294  assert(NewHeader->getSinglePredecessor() &&
295  "New header doesn't have one pred!");
296  FoldSingleEntryPHINodes(NewHeader);
297 
298  // Begin by walking OrigHeader and populating ValueMap with an entry for
299  // each Instruction.
300  BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
302 
303  // For PHI nodes, the value available in OldPreHeader is just the
304  // incoming value from OldPreHeader.
305  for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
306  ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
307 
308  // For the rest of the instructions, either hoist to the OrigPreheader if
309  // possible or create a clone in the OldPreHeader if not.
310  TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
311 
312  // Record all debug intrinsics preceding LoopEntryBranch to avoid duplication.
313  using DbgIntrinsicHash =
314  std::pair<std::pair<Value *, DILocalVariable *>, DIExpression *>;
315  auto makeHash = [](DbgInfoIntrinsic *D) -> DbgIntrinsicHash {
316  return {{D->getVariableLocation(), D->getVariable()}, D->getExpression()};
317  };
319  for (auto I = std::next(OrigPreheader->rbegin()), E = OrigPreheader->rend();
320  I != E; ++I) {
321  if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&*I))
322  DbgIntrinsics.insert(makeHash(DII));
323  else
324  break;
325  }
326 
327  while (I != E) {
328  Instruction *Inst = &*I++;
329 
330  // If the instruction's operands are invariant and it doesn't read or write
331  // memory, then it is safe to hoist. Doing this doesn't change the order of
332  // execution in the preheader, but does prevent the instruction from
333  // executing in each iteration of the loop. This means it is safe to hoist
334  // something that might trap, but isn't safe to hoist something that reads
335  // memory (without proving that the loop doesn't write).
336  if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
337  !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) &&
338  !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
339  Inst->moveBefore(LoopEntryBranch);
340  continue;
341  }
342 
343  // Otherwise, create a duplicate of the instruction.
344  Instruction *C = Inst->clone();
345 
346  // Eagerly remap the operands of the instruction.
347  RemapInstruction(C, ValueMap,
349 
350  // Avoid inserting the same intrinsic twice.
351  if (auto *DII = dyn_cast<DbgInfoIntrinsic>(C))
352  if (DbgIntrinsics.count(makeHash(DII))) {
353  C->deleteValue();
354  continue;
355  }
356 
357  // With the operands remapped, see if the instruction constant folds or is
358  // otherwise simplifyable. This commonly occurs because the entry from PHI
359  // nodes allows icmps and other instructions to fold.
360  Value *V = SimplifyInstruction(C, SQ);
361  if (V && LI->replacementPreservesLCSSAForm(C, V)) {
362  // If so, then delete the temporary instruction and stick the folded value
363  // in the map.
364  ValueMap[Inst] = V;
365  if (!C->mayHaveSideEffects()) {
366  C->deleteValue();
367  C = nullptr;
368  }
369  } else {
370  ValueMap[Inst] = C;
371  }
372  if (C) {
373  // Otherwise, stick the new instruction into the new block!
374  C->setName(Inst->getName());
375  C->insertBefore(LoopEntryBranch);
376 
377  if (auto *II = dyn_cast<IntrinsicInst>(C))
378  if (II->getIntrinsicID() == Intrinsic::assume)
379  AC->registerAssumption(II);
380  }
381  }
382 
383  // Along with all the other instructions, we just cloned OrigHeader's
384  // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
385  // successors by duplicating their incoming values for OrigHeader.
386  TerminatorInst *TI = OrigHeader->getTerminator();
387  for (BasicBlock *SuccBB : TI->successors())
388  for (BasicBlock::iterator BI = SuccBB->begin();
389  PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
390  PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
391 
392  // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
393  // OrigPreHeader's old terminator (the original branch into the loop), and
394  // remove the corresponding incoming values from the PHI nodes in OrigHeader.
395  LoopEntryBranch->eraseFromParent();
396 
397 
398  SmallVector<PHINode*, 2> InsertedPHIs;
399  // If there were any uses of instructions in the duplicated block outside the
400  // loop, update them, inserting PHI nodes as required
401  RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
402  &InsertedPHIs);
403 
404  // Attach dbg.value intrinsics to the new phis if that phi uses a value that
405  // previously had debug metadata attached. This keeps the debug info
406  // up-to-date in the loop body.
407  if (!InsertedPHIs.empty())
408  insertDebugValues(OrigHeader, InsertedPHIs);
409 
410  // NewHeader is now the header of the loop.
411  L->moveToHeader(NewHeader);
412  assert(L->getHeader() == NewHeader && "Latch block is our new header");
413 
414  // Inform DT about changes to the CFG.
415  if (DT) {
416  // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
417  // the DT about the removed edge to the OrigHeader (that got removed).
419  Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
420  Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
421  Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
422  DT->applyUpdates(Updates);
423  }
424 
425  // At this point, we've finished our major CFG changes. As part of cloning
426  // the loop into the preheader we've simplified instructions and the
427  // duplicated conditional branch may now be branching on a constant. If it is
428  // branching on a constant and if that constant means that we enter the loop,
429  // then we fold away the cond branch to an uncond branch. This simplifies the
430  // loop in cases important for nested loops, and it also means we don't have
431  // to split as many edges.
432  BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
433  assert(PHBI->isConditional() && "Should be clone of BI condbr!");
434  if (!isa<ConstantInt>(PHBI->getCondition()) ||
435  PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
436  NewHeader) {
437  // The conditional branch can't be folded, handle the general case.
438  // Split edges as necessary to preserve LoopSimplify form.
439 
440  // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
441  // thus is not a preheader anymore.
442  // Split the edge to form a real preheader.
443  BasicBlock *NewPH = SplitCriticalEdge(
444  OrigPreheader, NewHeader,
445  CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
446  NewPH->setName(NewHeader->getName() + ".lr.ph");
447 
448  // Preserve canonical loop form, which means that 'Exit' should have only
449  // one predecessor. Note that Exit could be an exit block for multiple
450  // nested loops, causing both of the edges to now be critical and need to
451  // be split.
452  SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
453  bool SplitLatchEdge = false;
454  for (BasicBlock *ExitPred : ExitPreds) {
455  // We only need to split loop exit edges.
456  Loop *PredLoop = LI->getLoopFor(ExitPred);
457  if (!PredLoop || PredLoop->contains(Exit))
458  continue;
459  if (isa<IndirectBrInst>(ExitPred->getTerminator()))
460  continue;
461  SplitLatchEdge |= L->getLoopLatch() == ExitPred;
462  BasicBlock *ExitSplit = SplitCriticalEdge(
463  ExitPred, Exit,
464  CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
465  ExitSplit->moveBefore(Exit);
466  }
467  assert(SplitLatchEdge &&
468  "Despite splitting all preds, failed to split latch exit?");
469  } else {
470  // We can fold the conditional branch in the preheader, this makes things
471  // simpler. The first step is to remove the extra edge to the Exit block.
472  Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
473  BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
474  NewBI->setDebugLoc(PHBI->getDebugLoc());
475  PHBI->eraseFromParent();
476 
477  // With our CFG finalized, update DomTree if it is available.
478  if (DT) DT->deleteEdge(OrigPreheader, Exit);
479  }
480 
481  assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
482  assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
483 
484  // Now that the CFG and DomTree are in a consistent state again, try to merge
485  // the OrigHeader block into OrigLatch. This will succeed if they are
486  // connected by an unconditional branch. This is just a cleanup so the
487  // emitted code isn't too gross in this common case.
488  MergeBlockIntoPredecessor(OrigHeader, DT, LI);
489 
490  DEBUG(dbgs() << "LoopRotation: into "; L->dump());
491 
492  ++NumRotated;
493  return true;
494 }
495 
496 /// Determine whether the instructions in this range may be safely and cheaply
497 /// speculated. This is not an important enough situation to develop complex
498 /// heuristics. We handle a single arithmetic instruction along with any type
499 /// conversions.
502  bool seenIncrement = false;
503  bool MultiExitLoop = false;
504 
505  if (!L->getExitingBlock())
506  MultiExitLoop = true;
507 
508  for (BasicBlock::iterator I = Begin; I != End; ++I) {
509 
511  return false;
512 
513  if (isa<DbgInfoIntrinsic>(I))
514  continue;
515 
516  switch (I->getOpcode()) {
517  default:
518  return false;
519  case Instruction::GetElementPtr:
520  // GEPs are cheap if all indices are constant.
521  if (!cast<GEPOperator>(I)->hasAllConstantIndices())
522  return false;
523  // fall-thru to increment case
525  case Instruction::Add:
526  case Instruction::Sub:
527  case Instruction::And:
528  case Instruction::Or:
529  case Instruction::Xor:
530  case Instruction::Shl:
531  case Instruction::LShr:
532  case Instruction::AShr: {
533  Value *IVOpnd =
534  !isa<Constant>(I->getOperand(0))
535  ? I->getOperand(0)
536  : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
537  if (!IVOpnd)
538  return false;
539 
540  // If increment operand is used outside of the loop, this speculation
541  // could cause extra live range interference.
542  if (MultiExitLoop) {
543  for (User *UseI : IVOpnd->users()) {
544  auto *UserInst = cast<Instruction>(UseI);
545  if (!L->contains(UserInst))
546  return false;
547  }
548  }
549 
550  if (seenIncrement)
551  return false;
552  seenIncrement = true;
553  break;
554  }
555  case Instruction::Trunc:
556  case Instruction::ZExt:
557  case Instruction::SExt:
558  // ignore type conversions
559  break;
560  }
561  }
562  return true;
563 }
564 
565 /// Fold the loop tail into the loop exit by speculating the loop tail
566 /// instructions. Typically, this is a single post-increment. In the case of a
567 /// simple 2-block loop, hoisting the increment can be much better than
568 /// duplicating the entire loop header. In the case of loops with early exits,
569 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
570 /// canonical form so downstream passes can handle it.
571 ///
572 /// I don't believe this invalidates SCEV.
573 bool LoopRotate::simplifyLoopLatch(Loop *L) {
574  BasicBlock *Latch = L->getLoopLatch();
575  if (!Latch || Latch->hasAddressTaken())
576  return false;
577 
578  BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
579  if (!Jmp || !Jmp->isUnconditional())
580  return false;
581 
582  BasicBlock *LastExit = Latch->getSinglePredecessor();
583  if (!LastExit || !L->isLoopExiting(LastExit))
584  return false;
585 
586  BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
587  if (!BI)
588  return false;
589 
590  if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
591  return false;
592 
593  DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
594  << LastExit->getName() << "\n");
595 
596  // Hoist the instructions from Latch into LastExit.
597  LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
598  Latch->begin(), Jmp->getIterator());
599 
600  unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
601  BasicBlock *Header = Jmp->getSuccessor(0);
602  assert(Header == L->getHeader() && "expected a backward branch");
603 
604  // Remove Latch from the CFG so that LastExit becomes the new Latch.
605  BI->setSuccessor(FallThruPath, Header);
606  Latch->replaceSuccessorsPhiUsesWith(LastExit);
607  Jmp->eraseFromParent();
608 
609  // Nuke the Latch block.
610  assert(Latch->empty() && "unable to evacuate Latch");
611  LI->removeBlock(Latch);
612  if (DT)
613  DT->eraseNode(Latch);
614  Latch->eraseFromParent();
615  return true;
616 }
617 
618 /// Rotate \c L, and return true if any modification was made.
619 bool LoopRotate::processLoop(Loop *L) {
620  // Save the loop metadata.
621  MDNode *LoopMD = L->getLoopID();
622 
623  // Simplify the loop latch before attempting to rotate the header
624  // upward. Rotation may not be needed if the loop tail can be folded into the
625  // loop exit.
626  bool SimplifiedLatch = simplifyLoopLatch(L);
627 
628  bool MadeChange = rotateLoop(L, SimplifiedLatch);
629  assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
630  "Loop latch should be exiting after loop-rotate.");
631 
632  // Restore the loop metadata.
633  // NB! We presume LoopRotation DOESN'T ADD its own metadata.
634  if ((MadeChange || SimplifiedLatch) && LoopMD)
635  L->setLoopID(LoopMD);
636 
637  return MadeChange || SimplifiedLatch;
638 }
639 
640 LoopRotatePass::LoopRotatePass(bool EnableHeaderDuplication)
641  : EnableHeaderDuplication(EnableHeaderDuplication) {}
642 
645  LPMUpdater &) {
646  int Threshold = EnableHeaderDuplication ? DefaultRotationThreshold : 0;
647  const DataLayout &DL = L.getHeader()->getModule()->getDataLayout();
648  const SimplifyQuery SQ = getBestSimplifyQuery(AR, DL);
649  LoopRotate LR(Threshold, &AR.LI, &AR.TTI, &AR.AC, &AR.DT, &AR.SE,
650  SQ);
651 
652  bool Changed = LR.processLoop(&L);
653  if (!Changed)
654  return PreservedAnalyses::all();
655 
657 }
658 
659 namespace {
660 
661 class LoopRotateLegacyPass : public LoopPass {
662  unsigned MaxHeaderSize;
663 
664 public:
665  static char ID; // Pass ID, replacement for typeid
666  LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
668  if (SpecifiedMaxHeaderSize == -1)
669  MaxHeaderSize = DefaultRotationThreshold;
670  else
671  MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
672  }
673 
674  // LCSSA form makes instruction renaming easier.
675  void getAnalysisUsage(AnalysisUsage &AU) const override {
679  }
680 
681  bool runOnLoop(Loop *L, LPPassManager &LPM) override {
682  if (skipLoop(L))
683  return false;
684  Function &F = *L->getHeader()->getParent();
685 
686  auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
687  const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
688  auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
689  auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
690  auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
691  auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
692  auto *SE = SEWP ? &SEWP->getSE() : nullptr;
693  const SimplifyQuery SQ = getBestSimplifyQuery(*this, F);
694  LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE, SQ);
695  return LR.processLoop(L);
696  }
697 };
698 }
699 
700 char LoopRotateLegacyPass::ID = 0;
701 INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
702  false, false)
706 INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false,
707  false)
708 
709 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
710  return new LoopRotateLegacyPass(MaxHeaderSize);
711 }
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:72
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:67
use_iterator use_end()
Definition: Value.h:352
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:359
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:728
void deleteValue()
Delete a pointer to a generic Value.
Definition: Value.cpp:95
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)
reverse_iterator rend()
Definition: BasicBlock.h:259
reverse_iterator rbegin()
Definition: BasicBlock.h:257
Value * getCondition() const
const SimplifyQuery getBestSimplifyQuery(Pass &, Function &)
bool notDuplicatable
True if this function cannot be duplicated.
Definition: CodeMetrics.h:54
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:286
BlockT * getHeader() const
Definition: LoopInfo.h:100
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
void findDbgValues(SmallVectorImpl< DbgValueInst *> &DbgValues, Value *V)
Finds the llvm.dbg.value intrinsics describing a value.
Definition: Local.cpp:1288
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:73
use_iterator_impl< Use > use_iterator
Definition: Value.h:337
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:282
void dump() const
Definition: LoopInfo.cpp:444
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:217
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Definition: Instruction.cpp:73
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:197
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:536
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:1319
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:110
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:418
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 GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
DWARF expression.
void setOperand(unsigned i, Value *Val)
Definition: User.h:159
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Implements a dense probed hash-table based set with some number of buckets stored inline...
Definition: DenseSet.h:239
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:405
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:251
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:91
use_iterator use_begin()
Definition: Value.h:344
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:538
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:285
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:439
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
Definition: LoopInfo.h:149
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:220
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:1148
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)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:91
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:86
#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:328
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:67
bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.
Definition: SSAUpdater.cpp:63