LLVM  8.0.1
LoopInfoImpl.h
Go to the documentation of this file.
1 //===- llvm/Analysis/LoopInfoImpl.h - Natural Loop Calculator ---*- C++ -*-===//
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 is the generic implementation of LoopInfo used for both Loops and
11 // MachineLoops.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_ANALYSIS_LOOPINFOIMPL_H
16 #define LLVM_ANALYSIS_LOOPINFOIMPL_H
17 
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/IR/Dominators.h"
24 
25 namespace llvm {
26 
27 //===----------------------------------------------------------------------===//
28 // APIs for simple analysis of the loop. See header notes.
29 
30 /// getExitingBlocks - Return all blocks inside the loop that have successors
31 /// outside of the loop. These are the blocks _inside of the current loop_
32 /// which branch out. The returned list is always unique.
33 ///
34 template <class BlockT, class LoopT>
36  SmallVectorImpl<BlockT *> &ExitingBlocks) const {
37  assert(!isInvalid() && "Loop not in a valid state!");
38  for (const auto BB : blocks())
39  for (const auto &Succ : children<BlockT *>(BB))
40  if (!contains(Succ)) {
41  // Not in current loop? It must be an exit block.
42  ExitingBlocks.push_back(BB);
43  break;
44  }
45 }
46 
47 /// getExitingBlock - If getExitingBlocks would return exactly one block,
48 /// return that block. Otherwise return null.
49 template <class BlockT, class LoopT>
51  assert(!isInvalid() && "Loop not in a valid state!");
52  SmallVector<BlockT *, 8> ExitingBlocks;
53  getExitingBlocks(ExitingBlocks);
54  if (ExitingBlocks.size() == 1)
55  return ExitingBlocks[0];
56  return nullptr;
57 }
58 
59 /// getExitBlocks - Return all of the successor blocks of this loop. These
60 /// are the blocks _outside of the current loop_ which are branched to.
61 ///
62 template <class BlockT, class LoopT>
64  SmallVectorImpl<BlockT *> &ExitBlocks) const {
65  assert(!isInvalid() && "Loop not in a valid state!");
66  for (const auto BB : blocks())
67  for (const auto &Succ : children<BlockT *>(BB))
68  if (!contains(Succ))
69  // Not in current loop? It must be an exit block.
70  ExitBlocks.push_back(Succ);
71 }
72 
73 /// getExitBlock - If getExitBlocks would return exactly one block,
74 /// return that block. Otherwise return null.
75 template <class BlockT, class LoopT>
77  assert(!isInvalid() && "Loop not in a valid state!");
78  SmallVector<BlockT *, 8> ExitBlocks;
79  getExitBlocks(ExitBlocks);
80  if (ExitBlocks.size() == 1)
81  return ExitBlocks[0];
82  return nullptr;
83 }
84 
85 template <class BlockT, class LoopT>
87  // Each predecessor of each exit block of a normal loop is contained
88  // within the loop.
89  SmallVector<BlockT *, 4> ExitBlocks;
90  getExitBlocks(ExitBlocks);
91  for (BlockT *EB : ExitBlocks)
92  for (BlockT *Predecessor : children<Inverse<BlockT *>>(EB))
93  if (!contains(Predecessor))
94  return false;
95  // All the requirements are met.
96  return true;
97 }
98 
99 template <class BlockT, class LoopT>
101  SmallVectorImpl<BlockT *> &ExitBlocks) const {
102  typedef GraphTraits<BlockT *> BlockTraits;
103  typedef GraphTraits<Inverse<BlockT *>> InvBlockTraits;
104 
105  assert(hasDedicatedExits() &&
106  "getUniqueExitBlocks assumes the loop has canonical form exits!");
107 
108  SmallVector<BlockT *, 32> SwitchExitBlocks;
109  for (BlockT *Block : this->blocks()) {
110  SwitchExitBlocks.clear();
111  for (BlockT *Successor : children<BlockT *>(Block)) {
112  // If block is inside the loop then it is not an exit block.
113  if (contains(Successor))
114  continue;
115 
116  BlockT *FirstPred = *InvBlockTraits::child_begin(Successor);
117 
118  // If current basic block is this exit block's first predecessor then only
119  // insert exit block in to the output ExitBlocks vector. This ensures that
120  // same exit block is not inserted twice into ExitBlocks vector.
121  if (Block != FirstPred)
122  continue;
123 
124  // If a terminator has more then two successors, for example SwitchInst,
125  // then it is possible that there are multiple edges from current block to
126  // one exit block.
127  if (std::distance(BlockTraits::child_begin(Block),
128  BlockTraits::child_end(Block)) <= 2) {
129  ExitBlocks.push_back(Successor);
130  continue;
131  }
132 
133  // In case of multiple edges from current block to exit block, collect
134  // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
135  // duplicate edges.
136  if (!is_contained(SwitchExitBlocks, Successor)) {
137  SwitchExitBlocks.push_back(Successor);
138  ExitBlocks.push_back(Successor);
139  }
140  }
141  }
142 }
143 
144 template <class BlockT, class LoopT>
146  SmallVector<BlockT *, 8> UniqueExitBlocks;
147  getUniqueExitBlocks(UniqueExitBlocks);
148  if (UniqueExitBlocks.size() == 1)
149  return UniqueExitBlocks[0];
150  return nullptr;
151 }
152 
153 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
154 template <class BlockT, class LoopT>
156  SmallVectorImpl<Edge> &ExitEdges) const {
157  assert(!isInvalid() && "Loop not in a valid state!");
158  for (const auto BB : blocks())
159  for (const auto &Succ : children<BlockT *>(BB))
160  if (!contains(Succ))
161  // Not in current loop? It must be an exit block.
162  ExitEdges.emplace_back(BB, Succ);
163 }
164 
165 /// getLoopPreheader - If there is a preheader for this loop, return it. A
166 /// loop has a preheader if there is only one edge to the header of the loop
167 /// from outside of the loop and it is legal to hoist instructions into the
168 /// predecessor. If this is the case, the block branching to the header of the
169 /// loop is the preheader node.
170 ///
171 /// This method returns null if there is no preheader for the loop.
172 ///
173 template <class BlockT, class LoopT>
175  assert(!isInvalid() && "Loop not in a valid state!");
176  // Keep track of nodes outside the loop branching to the header...
177  BlockT *Out = getLoopPredecessor();
178  if (!Out)
179  return nullptr;
180 
181  // Make sure we are allowed to hoist instructions into the predecessor.
182  if (!Out->isLegalToHoistInto())
183  return nullptr;
184 
185  // Make sure there is only one exit out of the preheader.
186  typedef GraphTraits<BlockT *> BlockTraits;
187  typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
188  ++SI;
189  if (SI != BlockTraits::child_end(Out))
190  return nullptr; // Multiple exits from the block, must not be a preheader.
191 
192  // The predecessor has exactly one successor, so it is a preheader.
193  return Out;
194 }
195 
196 /// getLoopPredecessor - If the given loop's header has exactly one unique
197 /// predecessor outside the loop, return it. Otherwise return null.
198 /// This is less strict that the loop "preheader" concept, which requires
199 /// the predecessor to have exactly one successor.
200 ///
201 template <class BlockT, class LoopT>
203  assert(!isInvalid() && "Loop not in a valid state!");
204  // Keep track of nodes outside the loop branching to the header...
205  BlockT *Out = nullptr;
206 
207  // Loop over the predecessors of the header node...
208  BlockT *Header = getHeader();
209  for (const auto Pred : children<Inverse<BlockT *>>(Header)) {
210  if (!contains(Pred)) { // If the block is not in the loop...
211  if (Out && Out != Pred)
212  return nullptr; // Multiple predecessors outside the loop
213  Out = Pred;
214  }
215  }
216 
217  // Make sure there is only one exit out of the preheader.
218  assert(Out && "Header of loop has no predecessors from outside loop?");
219  return Out;
220 }
221 
222 /// getLoopLatch - If there is a single latch block for this loop, return it.
223 /// A latch block is a block that contains a branch back to the header.
224 template <class BlockT, class LoopT>
226  assert(!isInvalid() && "Loop not in a valid state!");
227  BlockT *Header = getHeader();
228  BlockT *Latch = nullptr;
229  for (const auto Pred : children<Inverse<BlockT *>>(Header)) {
230  if (contains(Pred)) {
231  if (Latch)
232  return nullptr;
233  Latch = Pred;
234  }
235  }
236 
237  return Latch;
238 }
239 
240 //===----------------------------------------------------------------------===//
241 // APIs for updating loop information after changing the CFG
242 //
243 
244 /// addBasicBlockToLoop - This method is used by other analyses to update loop
245 /// information. NewBB is set to be a new member of the current loop.
246 /// Because of this, it is added as a member of all parent loops, and is added
247 /// to the specified LoopInfo object as being in the current basic block. It
248 /// is not valid to replace the loop header with this method.
249 ///
250 template <class BlockT, class LoopT>
252  BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LIB) {
253  assert(!isInvalid() && "Loop not in a valid state!");
254 #ifndef NDEBUG
255  if (!Blocks.empty()) {
256  auto SameHeader = LIB[getHeader()];
257  assert(contains(SameHeader) && getHeader() == SameHeader->getHeader() &&
258  "Incorrect LI specified for this loop!");
259  }
260 #endif
261  assert(NewBB && "Cannot add a null basic block to the loop!");
262  assert(!LIB[NewBB] && "BasicBlock already in the loop!");
263 
264  LoopT *L = static_cast<LoopT *>(this);
265 
266  // Add the loop mapping to the LoopInfo object...
267  LIB.BBMap[NewBB] = L;
268 
269  // Add the basic block to this loop and all parent loops...
270  while (L) {
271  L->addBlockEntry(NewBB);
272  L = L->getParentLoop();
273  }
274 }
275 
276 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
277 /// the OldChild entry in our children list with NewChild, and updates the
278 /// parent pointer of OldChild to be null and the NewChild to be this loop.
279 /// This updates the loop depth of the new child.
280 template <class BlockT, class LoopT>
282  LoopT *NewChild) {
283  assert(!isInvalid() && "Loop not in a valid state!");
284  assert(OldChild->ParentLoop == this && "This loop is already broken!");
285  assert(!NewChild->ParentLoop && "NewChild already has a parent!");
286  typename std::vector<LoopT *>::iterator I = find(SubLoops, OldChild);
287  assert(I != SubLoops.end() && "OldChild not in loop!");
288  *I = NewChild;
289  OldChild->ParentLoop = nullptr;
290  NewChild->ParentLoop = static_cast<LoopT *>(this);
291 }
292 
293 /// verifyLoop - Verify loop structure
294 template <class BlockT, class LoopT>
296  assert(!isInvalid() && "Loop not in a valid state!");
297 #ifndef NDEBUG
298  assert(!Blocks.empty() && "Loop header is missing");
299 
300  // Setup for using a depth-first iterator to visit every block in the loop.
301  SmallVector<BlockT *, 8> ExitBBs;
302  getExitBlocks(ExitBBs);
304  VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
306  BI = df_ext_begin(getHeader(), VisitSet),
307  BE = df_ext_end(getHeader(), VisitSet);
308 
309  // Keep track of the BBs visited.
310  SmallPtrSet<BlockT *, 8> VisitedBBs;
311 
312  // Check the individual blocks.
313  for (; BI != BE; ++BI) {
314  BlockT *BB = *BI;
315 
318  [&](BlockT *B) { return contains(B); }) &&
319  "Loop block has no in-loop successors!");
320 
322  GraphTraits<Inverse<BlockT *>>::child_end(BB),
323  [&](BlockT *B) { return contains(B); }) &&
324  "Loop block has no in-loop predecessors!");
325 
326  SmallVector<BlockT *, 2> OutsideLoopPreds;
327  std::for_each(GraphTraits<Inverse<BlockT *>>::child_begin(BB),
328  GraphTraits<Inverse<BlockT *>>::child_end(BB),
329  [&](BlockT *B) {
330  if (!contains(B))
331  OutsideLoopPreds.push_back(B);
332  });
333 
334  if (BB == getHeader()) {
335  assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
336  } else if (!OutsideLoopPreds.empty()) {
337  // A non-header loop shouldn't be reachable from outside the loop,
338  // though it is permitted if the predecessor is not itself actually
339  // reachable.
340  BlockT *EntryBB = &BB->getParent()->front();
341  for (BlockT *CB : depth_first(EntryBB))
342  for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
343  assert(CB != OutsideLoopPreds[i] &&
344  "Loop has multiple entry points!");
345  }
346  assert(BB != &getHeader()->getParent()->front() &&
347  "Loop contains function entry block!");
348 
349  VisitedBBs.insert(BB);
350  }
351 
352  if (VisitedBBs.size() != getNumBlocks()) {
353  dbgs() << "The following blocks are unreachable in the loop: ";
354  for (auto BB : Blocks) {
355  if (!VisitedBBs.count(BB)) {
356  dbgs() << *BB << "\n";
357  }
358  }
359  assert(false && "Unreachable block in loop");
360  }
361 
362  // Check the subloops.
363  for (iterator I = begin(), E = end(); I != E; ++I)
364  // Each block in each subloop should be contained within this loop.
365  for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
366  BI != BE; ++BI) {
367  assert(contains(*BI) &&
368  "Loop does not contain all the blocks of a subloop!");
369  }
370 
371  // Check the parent loop pointer.
372  if (ParentLoop) {
373  assert(is_contained(*ParentLoop, this) &&
374  "Loop is not a subloop of its parent!");
375  }
376 #endif
377 }
378 
379 /// verifyLoop - Verify loop structure of this loop and all nested loops.
380 template <class BlockT, class LoopT>
383  assert(!isInvalid() && "Loop not in a valid state!");
384  Loops->insert(static_cast<const LoopT *>(this));
385  // Verify this loop.
386  verifyLoop();
387  // Verify the subloops.
388  for (iterator I = begin(), E = end(); I != E; ++I)
389  (*I)->verifyLoopNest(Loops);
390 }
391 
392 template <class BlockT, class LoopT>
394  bool Verbose) const {
395  OS.indent(Depth * 2);
396  if (static_cast<const LoopT *>(this)->isAnnotatedParallel())
397  OS << "Parallel ";
398  OS << "Loop at depth " << getLoopDepth() << " containing: ";
399 
400  BlockT *H = getHeader();
401  for (unsigned i = 0; i < getBlocks().size(); ++i) {
402  BlockT *BB = getBlocks()[i];
403  if (!Verbose) {
404  if (i)
405  OS << ",";
406  BB->printAsOperand(OS, false);
407  } else
408  OS << "\n";
409 
410  if (BB == H)
411  OS << "<header>";
412  if (isLoopLatch(BB))
413  OS << "<latch>";
414  if (isLoopExiting(BB))
415  OS << "<exiting>";
416  if (Verbose)
417  BB->print(OS);
418  }
419  OS << "\n";
420 
421  for (iterator I = begin(), E = end(); I != E; ++I)
422  (*I)->print(OS, Depth + 2);
423 }
424 
425 //===----------------------------------------------------------------------===//
426 /// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
427 /// result does / not depend on use list (block predecessor) order.
428 ///
429 
430 /// Discover a subloop with the specified backedges such that: All blocks within
431 /// this loop are mapped to this loop or a subloop. And all subloops within this
432 /// loop have their parent loop set to this loop or a subloop.
433 template <class BlockT, class LoopT>
434 static void discoverAndMapSubloop(LoopT *L, ArrayRef<BlockT *> Backedges,
436  const DomTreeBase<BlockT> &DomTree) {
437  typedef GraphTraits<Inverse<BlockT *>> InvBlockTraits;
438 
439  unsigned NumBlocks = 0;
440  unsigned NumSubloops = 0;
441 
442  // Perform a backward CFG traversal using a worklist.
443  std::vector<BlockT *> ReverseCFGWorklist(Backedges.begin(), Backedges.end());
444  while (!ReverseCFGWorklist.empty()) {
445  BlockT *PredBB = ReverseCFGWorklist.back();
446  ReverseCFGWorklist.pop_back();
447 
448  LoopT *Subloop = LI->getLoopFor(PredBB);
449  if (!Subloop) {
450  if (!DomTree.isReachableFromEntry(PredBB))
451  continue;
452 
453  // This is an undiscovered block. Map it to the current loop.
454  LI->changeLoopFor(PredBB, L);
455  ++NumBlocks;
456  if (PredBB == L->getHeader())
457  continue;
458  // Push all block predecessors on the worklist.
459  ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
460  InvBlockTraits::child_begin(PredBB),
461  InvBlockTraits::child_end(PredBB));
462  } else {
463  // This is a discovered block. Find its outermost discovered loop.
464  while (LoopT *Parent = Subloop->getParentLoop())
465  Subloop = Parent;
466 
467  // If it is already discovered to be a subloop of this loop, continue.
468  if (Subloop == L)
469  continue;
470 
471  // Discover a subloop of this loop.
472  Subloop->setParentLoop(L);
473  ++NumSubloops;
474  NumBlocks += Subloop->getBlocksVector().capacity();
475  PredBB = Subloop->getHeader();
476  // Continue traversal along predecessors that are not loop-back edges from
477  // within this subloop tree itself. Note that a predecessor may directly
478  // reach another subloop that is not yet discovered to be a subloop of
479  // this loop, which we must traverse.
480  for (const auto Pred : children<Inverse<BlockT *>>(PredBB)) {
481  if (LI->getLoopFor(Pred) != Subloop)
482  ReverseCFGWorklist.push_back(Pred);
483  }
484  }
485  }
486  L->getSubLoopsVector().reserve(NumSubloops);
487  L->reserveBlocks(NumBlocks);
488 }
489 
490 /// Populate all loop data in a stable order during a single forward DFS.
491 template <class BlockT, class LoopT> class PopulateLoopsDFS {
493  typedef typename BlockTraits::ChildIteratorType SuccIterTy;
494 
496 
497 public:
499 
500  void traverse(BlockT *EntryBlock);
501 
502 protected:
503  void insertIntoLoop(BlockT *Block);
504 };
505 
506 /// Top-level driver for the forward DFS within the loop.
507 template <class BlockT, class LoopT>
509  for (BlockT *BB : post_order(EntryBlock))
510  insertIntoLoop(BB);
511 }
512 
513 /// Add a single Block to its ancestor loops in PostOrder. If the block is a
514 /// subloop header, add the subloop to its parent in PostOrder, then reverse the
515 /// Block and Subloop vectors of the now complete subloop to achieve RPO.
516 template <class BlockT, class LoopT>
518  LoopT *Subloop = LI->getLoopFor(Block);
519  if (Subloop && Block == Subloop->getHeader()) {
520  // We reach this point once per subloop after processing all the blocks in
521  // the subloop.
522  if (Subloop->getParentLoop())
523  Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
524  else
525  LI->addTopLevelLoop(Subloop);
526 
527  // For convenience, Blocks and Subloops are inserted in postorder. Reverse
528  // the lists, except for the loop header, which is always at the beginning.
529  Subloop->reverseBlock(1);
530  std::reverse(Subloop->getSubLoopsVector().begin(),
531  Subloop->getSubLoopsVector().end());
532 
533  Subloop = Subloop->getParentLoop();
534  }
535  for (; Subloop; Subloop = Subloop->getParentLoop())
536  Subloop->addBlockEntry(Block);
537 }
538 
539 /// Analyze LoopInfo discovers loops during a postorder DominatorTree traversal
540 /// interleaved with backward CFG traversals within each subloop
541 /// (discoverAndMapSubloop). The backward traversal skips inner subloops, so
542 /// this part of the algorithm is linear in the number of CFG edges. Subloop and
543 /// Block vectors are then populated during a single forward CFG traversal
544 /// (PopulateLoopDFS).
545 ///
546 /// During the two CFG traversals each block is seen three times:
547 /// 1) Discovered and mapped by a reverse CFG traversal.
548 /// 2) Visited during a forward DFS CFG traversal.
549 /// 3) Reverse-inserted in the loop in postorder following forward DFS.
550 ///
551 /// The Block vectors are inclusive, so step 3 requires loop-depth number of
552 /// insertions per block.
553 template <class BlockT, class LoopT>
555  // Postorder traversal of the dominator tree.
556  const DomTreeNodeBase<BlockT> *DomRoot = DomTree.getRootNode();
557  for (auto DomNode : post_order(DomRoot)) {
558 
559  BlockT *Header = DomNode->getBlock();
560  SmallVector<BlockT *, 4> Backedges;
561 
562  // Check each predecessor of the potential loop header.
563  for (const auto Backedge : children<Inverse<BlockT *>>(Header)) {
564  // If Header dominates predBB, this is a new loop. Collect the backedges.
565  if (DomTree.dominates(Header, Backedge) &&
566  DomTree.isReachableFromEntry(Backedge)) {
567  Backedges.push_back(Backedge);
568  }
569  }
570  // Perform a backward CFG traversal to discover and map blocks in this loop.
571  if (!Backedges.empty()) {
572  LoopT *L = AllocateLoop(Header);
573  discoverAndMapSubloop(L, ArrayRef<BlockT *>(Backedges), this, DomTree);
574  }
575  }
576  // Perform a single forward CFG traversal to populate block and subloop
577  // vectors for all loops.
579  DFS.traverse(DomRoot->getBlock());
580 }
581 
582 template <class BlockT, class LoopT>
584  SmallVector<LoopT *, 4> PreOrderLoops, PreOrderWorklist;
585  // The outer-most loop actually goes into the result in the same relative
586  // order as we walk it. But LoopInfo stores the top level loops in reverse
587  // program order so for here we reverse it to get forward program order.
588  // FIXME: If we change the order of LoopInfo we will want to remove the
589  // reverse here.
590  for (LoopT *RootL : reverse(*this)) {
591  assert(PreOrderWorklist.empty() &&
592  "Must start with an empty preorder walk worklist.");
593  PreOrderWorklist.push_back(RootL);
594  do {
595  LoopT *L = PreOrderWorklist.pop_back_val();
596  // Sub-loops are stored in forward program order, but will process the
597  // worklist backwards so append them in reverse order.
598  PreOrderWorklist.append(L->rbegin(), L->rend());
599  PreOrderLoops.push_back(L);
600  } while (!PreOrderWorklist.empty());
601  }
602 
603  return PreOrderLoops;
604 }
605 
606 template <class BlockT, class LoopT>
609  SmallVector<LoopT *, 4> PreOrderLoops, PreOrderWorklist;
610  // The outer-most loop actually goes into the result in the same relative
611  // order as we walk it. LoopInfo stores the top level loops in reverse
612  // program order so we walk in order here.
613  // FIXME: If we change the order of LoopInfo we will want to add a reverse
614  // here.
615  for (LoopT *RootL : *this) {
616  assert(PreOrderWorklist.empty() &&
617  "Must start with an empty preorder walk worklist.");
618  PreOrderWorklist.push_back(RootL);
619  do {
620  LoopT *L = PreOrderWorklist.pop_back_val();
621  // Sub-loops are stored in forward program order, but will process the
622  // worklist backwards so we can just append them in order.
623  PreOrderWorklist.append(L->begin(), L->end());
624  PreOrderLoops.push_back(L);
625  } while (!PreOrderWorklist.empty());
626  }
627 
628  return PreOrderLoops;
629 }
630 
631 // Debugging
632 template <class BlockT, class LoopT>
634  for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
635  TopLevelLoops[i]->print(OS);
636 #if 0
638  E = BBMap.end(); I != E; ++I)
639  OS << "BB '" << I->first->getName() << "' level = "
640  << I->second->getLoopDepth() << "\n";
641 #endif
642 }
643 
644 template <typename T>
645 bool compareVectors(std::vector<T> &BB1, std::vector<T> &BB2) {
646  llvm::sort(BB1);
647  llvm::sort(BB2);
648  return BB1 == BB2;
649 }
650 
651 template <class BlockT, class LoopT>
653  const LoopInfoBase<BlockT, LoopT> &LI,
654  const LoopT &L) {
655  LoopHeaders[L.getHeader()] = &L;
656  for (LoopT *SL : L)
657  addInnerLoopsToHeadersMap(LoopHeaders, LI, *SL);
658 }
659 
660 #ifndef NDEBUG
661 template <class BlockT, class LoopT>
662 static void compareLoops(const LoopT *L, const LoopT *OtherL,
663  DenseMap<BlockT *, const LoopT *> &OtherLoopHeaders) {
664  BlockT *H = L->getHeader();
665  BlockT *OtherH = OtherL->getHeader();
666  assert(H == OtherH &&
667  "Mismatched headers even though found in the same map entry!");
668 
669  assert(L->getLoopDepth() == OtherL->getLoopDepth() &&
670  "Mismatched loop depth!");
671  const LoopT *ParentL = L, *OtherParentL = OtherL;
672  do {
673  assert(ParentL->getHeader() == OtherParentL->getHeader() &&
674  "Mismatched parent loop headers!");
675  ParentL = ParentL->getParentLoop();
676  OtherParentL = OtherParentL->getParentLoop();
677  } while (ParentL);
678 
679  for (const LoopT *SubL : *L) {
680  BlockT *SubH = SubL->getHeader();
681  const LoopT *OtherSubL = OtherLoopHeaders.lookup(SubH);
682  assert(OtherSubL && "Inner loop is missing in computed loop info!");
683  OtherLoopHeaders.erase(SubH);
684  compareLoops(SubL, OtherSubL, OtherLoopHeaders);
685  }
686 
687  std::vector<BlockT *> BBs = L->getBlocks();
688  std::vector<BlockT *> OtherBBs = OtherL->getBlocks();
689  assert(compareVectors(BBs, OtherBBs) &&
690  "Mismatched basic blocks in the loops!");
691 
692  const SmallPtrSetImpl<const BlockT *> &BlocksSet = L->getBlocksSet();
693  const SmallPtrSetImpl<const BlockT *> &OtherBlocksSet = L->getBlocksSet();
694  assert(BlocksSet.size() == OtherBlocksSet.size() &&
695  std::all_of(BlocksSet.begin(), BlocksSet.end(),
696  [&OtherBlocksSet](const BlockT *BB) {
697  return OtherBlocksSet.count(BB);
698  }) &&
699  "Mismatched basic blocks in BlocksSets!");
700 }
701 #endif
702 
703 template <class BlockT, class LoopT>
705  const DomTreeBase<BlockT> &DomTree) const {
707  for (iterator I = begin(), E = end(); I != E; ++I) {
708  assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
709  (*I)->verifyLoopNest(&Loops);
710  }
711 
712 // Verify that blocks are mapped to valid loops.
713 #ifndef NDEBUG
714  for (auto &Entry : BBMap) {
715  const BlockT *BB = Entry.first;
716  LoopT *L = Entry.second;
717  assert(Loops.count(L) && "orphaned loop");
718  assert(L->contains(BB) && "orphaned block");
719  for (LoopT *ChildLoop : *L)
720  assert(!ChildLoop->contains(BB) &&
721  "BBMap should point to the innermost loop containing BB");
722  }
723 
724  // Recompute LoopInfo to verify loops structure.
726  OtherLI.analyze(DomTree);
727 
728  // Build a map we can use to move from our LI to the computed one. This
729  // allows us to ignore the particular order in any layer of the loop forest
730  // while still comparing the structure.
731  DenseMap<BlockT *, const LoopT *> OtherLoopHeaders;
732  for (LoopT *L : OtherLI)
733  addInnerLoopsToHeadersMap(OtherLoopHeaders, OtherLI, *L);
734 
735  // Walk the top level loops and ensure there is a corresponding top-level
736  // loop in the computed version and then recursively compare those loop
737  // nests.
738  for (LoopT *L : *this) {
739  BlockT *Header = L->getHeader();
740  const LoopT *OtherL = OtherLoopHeaders.lookup(Header);
741  assert(OtherL && "Top level loop is missing in computed loop info!");
742  // Now that we've matched this loop, erase its header from the map.
743  OtherLoopHeaders.erase(Header);
744  // And recursively compare these loops.
745  compareLoops(L, OtherL, OtherLoopHeaders);
746  }
747 
748  // Any remaining entries in the map are loops which were found when computing
749  // a fresh LoopInfo but not present in the current one.
750  if (!OtherLoopHeaders.empty()) {
751  for (const auto &HeaderAndLoop : OtherLoopHeaders)
752  dbgs() << "Found new loop: " << *HeaderAndLoop.second << "\n";
753  llvm_unreachable("Found new loops when recomputing LoopInfo!");
754  }
755 #endif
756 }
757 
758 } // End llvm namespace
759 
760 #endif
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:259
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
Definition: GraphTraits.h:122
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:225
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:250
This class represents lattice values for constants.
Definition: AllocatorList.h:24
static void compareLoops(const LoopT *L, const LoopT *OtherL, DenseMap< BlockT *, const LoopT *> &OtherLoopHeaders)
Definition: LoopInfoImpl.h:662
iterator begin() const
Definition: ArrayRef.h:137
bool compareVectors(std::vector< T > &BB1, std::vector< T > &BB2)
Definition: LoopInfoImpl.h:645
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
Definition: LoopInfoImpl.h:86
Implements a dense probed hash-table based set.
Definition: DenseSet.h:250
void push_back(const T &Elt)
Definition: SmallVector.h:218
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:174
static void discoverAndMapSubloop(LoopT *L, ArrayRef< BlockT *> Backedges, LoopInfoBase< BlockT, LoopT > *LI, const DomTreeBase< BlockT > &DomTree)
Stable LoopInfo Analysis - Build a loop tree using stable iterators so the result does / not depend o...
Definition: LoopInfoImpl.h:434
raw_ostream & indent(unsigned NumSpaces)
indent - Insert &#39;NumSpaces&#39; spaces.
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild)
This is used when splitting loops up.
Definition: LoopInfoImpl.h:281
void insertIntoLoop(BlockT *Block)
Add a single Block to its ancestor loops in PostOrder.
Definition: LoopInfoImpl.h:517
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1186
return AArch64::GPR64RegClass contains(Reg)
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
Definition: LoopInfoImpl.h:704
void print(raw_ostream &OS, unsigned Depth=0, bool Verbose=false) const
Print loop with all the BBs inside it.
Definition: LoopInfoImpl.h:393
Hexagon Hardware Loops
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Definition: LoopInfo.h:690
std::vector< Loop *>::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
Definition: LoopInfo.h:662
void addInnerLoopsToHeadersMap(DenseMap< BlockT *, const LoopT *> &LoopHeaders, const LoopInfoBase< BlockT, LoopT > &LI, const LoopT &L)
Definition: LoopInfoImpl.h:652
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
Definition: LoopInfoImpl.h:63
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:267
std::vector< Loop *>::const_iterator iterator
Definition: LoopInfo.h:139
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
Definition: LoopInfoImpl.h:251
void traverse(BlockT *EntryBlock)
Top-level driver for the forward DFS within the loop.
Definition: LoopInfoImpl.h:508
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
Core dominator tree base class.
Definition: LoopInfo.h:61
NodeT * getBlock() const
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
PopulateLoopsDFS(LoopInfoBase< BlockT, LoopT > *li)
Definition: LoopInfoImpl.h:498
df_ext_iterator< T, SetTy > df_ext_end(const T &G, SetTy &S)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define H(x, y, z)
Definition: MD5.cpp:57
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:371
void analyze(const DominatorTreeBase< BlockT, false > &DomTree)
Create the loop forest using a stable algorithm.
Definition: LoopInfoImpl.h:554
df_ext_iterator< T, SetTy > df_ext_begin(const T &G, SetTy &S)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1193
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
iterator_range< po_iterator< T > > post_order(const T &G)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:382
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:76
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
Definition: LoopInfoImpl.h:35
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:145
size_t size() const
Definition: SmallVector.h:53
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1207
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1116
void getExitEdges(SmallVectorImpl< Edge > &ExitEdges) const
Return all pairs of (inside_block,outside_block).
Definition: LoopInfoImpl.h:155
size_type size() const
Definition: SmallPtrSet.h:93
BlockT * getLoopPredecessor() const
If the given loop&#39;s header has exactly one unique predecessor outside the loop, return it...
Definition: LoopInfoImpl.h:202
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
void print(raw_ostream &OS) const
Definition: LoopInfoImpl.h:633
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
iterator end() const
Definition: ArrayRef.h:138
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:381
std::pair< iterator, bool > insert(NodeRef N)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
static void DFS(BasicBlock *Root, SetVector< BasicBlock *> &Set)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:394
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void verifyLoopNest(DenseSet< const LoopT *> *Loops) const
Verify loop structure of this loop and all nested loops.
Definition: LoopInfoImpl.h:381
iterator begin() const
Definition: SmallPtrSet.h:397
void emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:652
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
SmallVector< LoopT *, 4 > getLoopsInReverseSiblingPreorder()
Return all of the loops in the function in preorder across the loop nests, with siblings in reverse p...
Definition: LoopInfoImpl.h:608
#define I(x, y, z)
Definition: MD5.cpp:58
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
Definition: LoopInfo.h:722
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:92
iterator end() const
Definition: SmallPtrSet.h:402
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:211
SmallVector< LoopT *, 4 > getLoopsInPreorder()
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
Definition: LoopInfoImpl.h:583
iterator_range< df_iterator< T > > depth_first(const T &G)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const Function * getParent(const Value *V)
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
void verifyLoop() const
Verify loop structure.
Definition: LoopInfoImpl.h:295
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
Definition: LoopInfoImpl.h:100
UnaryPredicate for_each(R &&Range, UnaryPredicate P)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1179
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:50
Populate all loop data in a stable order during a single forward DFS.
Definition: LoopInfoImpl.h:491
This class builds and contains all of the top-level loop structures in the specified function...
Definition: LoopInfo.h:62
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:1245