LLVM 24.0.0git
GenericLoopInfoImpl.h
Go to the documentation of this file.
1//===- GenericLoopInfoImp.h - Generic Loop Info Implementation --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This fle contains the implementation of GenericLoopInfo. It should only be
10// included in files that explicitly instantiate a GenericLoopInfo.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_GENERICLOOPINFOIMPL_H
15#define LLVM_SUPPORT_GENERICLOOPINFOIMPL_H
16
17#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/STLExtras.h"
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// APIs for simple analysis of the loop. See header notes.
28
29/// getExitingBlocks - Return all blocks inside the loop that have successors
30/// outside of the loop. These are the blocks _inside of the current loop_
31/// which branch out. The returned list is always unique.
32///
33template <class BlockT, class LoopT>
35 SmallVectorImpl<BlockT *> &ExitingBlocks) const {
36 assert(!isInvalid() && "Loop not in a valid state!");
37 for (const auto BB : blocks())
38 for (auto *Succ : children<BlockT *>(BB))
39 if (!contains(Succ)) {
40 // Not in current loop? It must be an exit block.
41 ExitingBlocks.push_back(BB);
42 break;
43 }
44}
45
46/// getExitingBlock - If getExitingBlocks would return exactly one block,
47/// return that block. Otherwise return null.
48template <class BlockT, class LoopT>
50 assert(!isInvalid() && "Loop not in a valid state!");
51 auto notInLoop = [&](BlockT *BB) { return !contains(BB); };
52 auto isExitBlock = [&](BlockT *BB, bool AllowRepeats) -> BlockT * {
53 assert(!AllowRepeats && "Unexpected parameter value.");
54 // Child not in current loop? It must be an exit block.
55 return any_of(children<BlockT *>(BB), notInLoop) ? BB : nullptr;
56 };
57
59}
60
61/// getExitBlocks - Return all of the successor blocks of this loop. These
62/// are the blocks _outside of the current loop_ which are branched to.
63///
64template <class BlockT, class LoopT>
66 SmallVectorImpl<BlockT *> &ExitBlocks) const {
67 assert(!isInvalid() && "Loop not in a valid state!");
68 for (const auto BB : blocks())
69 for (auto *Succ : children<BlockT *>(BB))
70 if (!contains(Succ))
71 // Not in current loop? It must be an exit block.
72 ExitBlocks.push_back(Succ);
73}
74
75/// getExitBlock - If getExitBlocks would return exactly one block,
76/// return that block. Otherwise return null.
77template <class BlockT, class LoopT>
78std::pair<BlockT *, bool> getExitBlockHelper(const LoopBase<BlockT, LoopT> *L,
79 bool Unique) {
80 assert(!L->isInvalid() && "Loop not in a valid state!");
81 auto notInLoop = [&](BlockT *BB,
82 bool AllowRepeats) -> std::pair<BlockT *, bool> {
83 assert(AllowRepeats == Unique && "Unexpected parameter value.");
84 return {!L->contains(BB) ? BB : nullptr, false};
85 };
86 auto singleExitBlock = [&](BlockT *BB,
87 bool AllowRepeats) -> std::pair<BlockT *, bool> {
88 assert(AllowRepeats == Unique && "Unexpected parameter value.");
90 AllowRepeats);
91 };
92 return find_singleton_nested<BlockT>(L->blocks(), singleExitBlock, Unique);
93}
94
95template <class BlockT, class LoopT>
97 auto RC = getExitBlockHelper(&L, false);
98 if (RC.second)
99 // found multiple exit blocks
100 return false;
101 // return true if there is no exit block
102 return !RC.first;
103}
104
105/// getExitBlock - If getExitBlocks would return exactly one block,
106/// return that block. Otherwise return null.
107template <class BlockT, class LoopT>
109 return getExitBlockHelper(this, false).first;
110}
111
112template <class BlockT, class LoopT>
114 // Each predecessor of each exit block of a normal loop is contained
115 // within the loop.
116 SmallVector<BlockT *, 4> UniqueExitBlocks;
117 getUniqueExitBlocks(UniqueExitBlocks);
118 for (BlockT *EB : UniqueExitBlocks)
119 for (BlockT *Predecessor : inverse_children<BlockT *>(EB))
120 if (!contains(Predecessor))
121 return false;
122 // All the requirements are met.
123 return true;
124}
125
126// Helper function to get unique loop exits. Pred is a predicate pointing to
127// BasicBlocks in a loop which should be considered to find loop exits.
128template <class BlockT, class LoopT, typename PredicateT>
129void getUniqueExitBlocksHelper(const LoopT *L,
130 SmallVectorImpl<BlockT *> &ExitBlocks,
131 PredicateT Pred) {
132 assert(!L->isInvalid() && "Loop not in a valid state!");
134 auto Filtered = make_filter_range(L->blocks(), Pred);
135 for (BlockT *BB : Filtered)
136 for (BlockT *Successor : children<BlockT *>(BB))
137 if (!L->contains(Successor))
138 if (Visited.insert(Successor).second)
139 ExitBlocks.push_back(Successor);
140}
141
142template <class BlockT, class LoopT>
144 SmallVectorImpl<BlockT *> &ExitBlocks) const {
145 getUniqueExitBlocksHelper(this, ExitBlocks,
146 [](const BlockT *BB) { return true; });
147}
148
149template <class BlockT, class LoopT>
151 SmallVectorImpl<BlockT *> &ExitBlocks) const {
152 const BlockT *Latch = getLoopLatch();
153 assert(Latch && "Latch block must exists");
154 getUniqueExitBlocksHelper(this, ExitBlocks,
155 [Latch](const BlockT *BB) { return BB != Latch; });
156}
157
158template <class BlockT, class LoopT>
160 return getExitBlockHelper(this, true).first;
161}
162
163template <class BlockT, class LoopT>
164BlockT *
166 BlockT *Latch = L.getLoopLatch();
167 assert(Latch && "Latch block must exists");
168 auto IsExitBlock = [&L](BlockT *BB, bool AllowRepeats) -> BlockT * {
169 assert(!AllowRepeats && "Unexpected parameter value.");
170 return !L.contains(BB) ? BB : nullptr;
171 };
172 return find_singleton<BlockT>(children<BlockT *>(Latch), IsExitBlock);
173}
174
175/// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
176template <class BlockT, class LoopT>
178 const LoopT &L, SmallVectorImpl<Edge> &ExitEdges) const {
179 for (const auto BB : L.blocks())
180 for (auto *Succ : children<BlockT *>(BB))
181 if (!L.contains(Succ))
182 // Not in current loop? It must be an exit block.
183 ExitEdges.emplace_back(BB, Succ);
184}
185
186namespace detail {
187template <class BlockT>
188using has_hoist_check = decltype(&BlockT::isLegalToHoistInto);
189
190template <class BlockT>
192
193/// SFINAE functions that dispatch to the isLegalToHoistInto member function or
194/// return false, if it doesn't exist.
195template <class BlockT> bool isLegalToHoistInto(BlockT *Block) {
197 return Block->isLegalToHoistInto();
198 return false;
199}
200} // namespace detail
201
202/// getLoopPreheader - If there is a preheader for this loop, return it. A
203/// loop has a preheader if there is only one edge to the header of the loop
204/// from outside of the loop and it is legal to hoist instructions into the
205/// predecessor. If this is the case, the block branching to the header of the
206/// loop is the preheader node.
207///
208/// This method returns null if there is no preheader for the loop.
209///
210template <class BlockT, class LoopT>
212 assert(!isInvalid() && "Loop not in a valid state!");
213 // Keep track of nodes outside the loop branching to the header...
214 BlockT *Out = getLoopPredecessor();
215 if (!Out)
216 return nullptr;
217
218 // Make sure we are allowed to hoist instructions into the predecessor.
220 return nullptr;
221
222 // Make sure there is only one exit out of the preheader.
224 return nullptr; // Multiple exits from the block, must not be a preheader.
225
226 // The predecessor has exactly one successor, so it is a preheader.
227 return Out;
228}
229
230/// getLoopPredecessor - If the given loop's header has exactly one unique
231/// predecessor outside the loop, return it. Otherwise return null.
232/// This is less strict that the loop "preheader" concept, which requires
233/// the predecessor to have exactly one successor.
234///
235template <class BlockT, class LoopT>
237 assert(!isInvalid() && "Loop not in a valid state!");
238 // Keep track of nodes outside the loop branching to the header...
239 BlockT *Out = nullptr;
240
241 // Loop over the predecessors of the header node...
242 BlockT *Header = getHeader();
243 for (const auto Pred : inverse_children<BlockT *>(Header)) {
244 if (!contains(Pred)) { // If the block is not in the loop...
245 if (Out && Out != Pred)
246 return nullptr; // Multiple predecessors outside the loop
247 Out = Pred;
248 }
249 }
250
251 return Out;
252}
253
254/// getLoopLatch - If there is a single latch block for this loop, return it.
255/// A latch block is a block that contains a branch back to the header.
256template <class BlockT, class LoopT>
258 assert(!isInvalid() && "Loop not in a valid state!");
259 BlockT *Header = getHeader();
260 BlockT *Latch = nullptr;
261 for (const auto Pred : inverse_children<BlockT *>(Header)) {
262 if (contains(Pred)) {
263 if (Latch)
264 return nullptr;
265 Latch = Pred;
266 }
267 }
268
269 return Latch;
270}
271
272//===----------------------------------------------------------------------===//
273// APIs for updating loop information after changing the CFG
274//
275
276/// addBasicBlockToLoop - This method is used by other analyses to update loop
277/// information. NewBB is set to be a new member of the current loop.
278/// Because of this, it is added as a member of all parent loops, and is added
279/// to the specified LoopInfo object as being in the current basic block. It
280/// is not valid to replace the loop header with this method.
281///
282template <class BlockT, class LoopT>
284 BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LIB) {
285 assert(!isInvalid() && "Loop not in a valid state!");
286#ifndef NDEBUG
287 if (!getBlocks().empty()) {
288 auto SameHeader = LIB[getHeader()];
289 assert(contains(SameHeader) && getHeader() == SameHeader->getHeader() &&
290 "Incorrect LI specified for this loop!");
291 }
292#endif
293 assert(NewBB && "Cannot add a null basic block to the loop!");
294 assert(!LIB[NewBB] && "BasicBlock already in the loop!");
295
296 LoopT *L = static_cast<LoopT *>(this);
297
298 // Add the loop mapping to the LoopInfo object...
299 LIB.changeLoopFor(NewBB, L);
300
301 // Add the basic block to this loop and all parent loops...
302 while (L) {
303 L->addBlockEntry(NewBB);
304 L = L->getParentLoop();
305 }
306}
307
308/// verifyLoop - Verify loop structure
309template <class BlockT, class LoopT>
311 assert(!isInvalid() && "Loop not in a valid state!");
312#ifndef NDEBUG
313 assert(!getBlocks().empty() && "Loop header is missing");
314
315 // Setup for using a depth-first iterator to visit every block in the loop.
317 getExitBlocks(ExitBBs);
319 VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
321 // Keep track of the BBs visited.
322 SmallPtrSet<BlockT *, 8> VisitedBBs;
323
324 // Check the individual blocks.
325 for (BlockT *BB : depth_first_ext(getHeader(), VisitSet)) {
327 [&](BlockT *B) { return contains(B); }) &&
328 "Loop block has no in-loop successors!");
329
331 [&](BlockT *B) { return contains(B); }) &&
332 "Loop block has no in-loop predecessors!");
333
334 SmallVector<BlockT *, 2> OutsideLoopPreds;
335 for (BlockT *B : inverse_children<BlockT *>(BB))
336 if (!contains(B))
337 OutsideLoopPreds.push_back(B);
338
339 if (BB == getHeader()) {
340 assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
341 } else if (!OutsideLoopPreds.empty()) {
342 // A non-header loop block shouldn't be reachable from outside the loop,
343 // though it is permitted if the predecessor is not itself actually
344 // reachable.
345 BlockT *EntryBB = &BB->getParent()->front();
346 for (BlockT *CB : depth_first(EntryBB))
347 for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
348 assert(CB != OutsideLoopPreds[i] &&
349 "Loop has multiple entry points!");
350 }
351 assert(BB != &getHeader()->getParent()->front() &&
352 "Loop contains function entry block!");
353
354 VisitedBBs.insert(BB);
355 }
356
357 if (VisitedBBs.size() != getNumBlocks()) {
358 dbgs() << "The following blocks are unreachable in the loop: ";
359 for (auto *BB : getBlocks()) {
360 if (!VisitedBBs.count(BB)) {
361 dbgs() << *BB << "\n";
362 }
363 }
364 assert(false && "Unreachable block in loop");
365 }
366
367 // Check the subloops.
368 for (iterator I = begin(), E = end(); I != E; ++I)
369 // Each block in each subloop should be contained within this loop.
370 for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
371 BI != BE; ++BI) {
372 assert(contains(*BI) &&
373 "Loop does not contain all the blocks of a subloop!");
374 }
376 // Check the parent loop pointer.
377 if (ParentLoop) {
378 assert(is_contained(ParentLoop->getSubLoops(), this) &&
379 "Loop is not a subloop of its parent!");
380 }
381#endif
382}
383
384/// verifyLoop - Verify loop structure of this loop and all nested loops.
385template <class BlockT, class LoopT>
388 assert(!isInvalid() && "Loop not in a valid state!");
389 Loops->insert(static_cast<const LoopT *>(this));
390 // Verify this loop.
391 verifyLoop();
392 // Verify the subloops.
393 for (iterator I = begin(), E = end(); I != E; ++I)
394 (*I)->verifyLoopNest(Loops);
395}
396
397template <class BlockT, class LoopT>
399 bool PrintNested, unsigned Depth) const {
400 OS.indent(Depth * 2);
401 if (static_cast<const LoopT *>(this)->isAnnotatedParallel())
402 OS << "Parallel ";
403 OS << "Loop at depth " << getLoopDepth() << " containing: ";
404
405 BlockT *H = getHeader();
406 for (unsigned i = 0; i < getBlocks().size(); ++i) {
407 BlockT *BB = getBlocks()[i];
408 if (!Verbose) {
409 if (i)
410 OS << ",";
411 BB->printAsOperand(OS, false);
412 } else {
413 OS << '\n';
414 }
415
416 if (BB == H)
417 OS << "<header>";
418 if (isLoopLatch(BB))
419 OS << "<latch>";
420 if (isLoopExiting(BB))
421 OS << "<exiting>";
422 if (Verbose)
423 BB->print(OS);
424 }
425
426 if (PrintNested) {
427 OS << "\n";
428
429 for (iterator I = begin(), E = end(); I != E; ++I)
430 (*I)->print(OS, /*Verbose*/ false, PrintNested, Depth + 2);
431 }
432}
433
434//===----------------------------------------------------------------------===//
435/// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
436/// result does / not depend on use list (block predecessor) order.
437///
438
439/// Analyze LoopInfo identifies the loops during a single forward depth-first
440/// search of the CFG.
441///
442/// Then build a loop-contiguous reverse postorder for in-loops blocks. Lists
443/// are header-first with each subloop's blocks contiguous, ordered by first
444/// appearance in RPO; SubLoops keep program order, TopLevelLoops reverse
445/// program order.
446template <class BlockT, class LoopT>
448 analyzeImpl(DomTree, /*ReuseLoop=*/{});
449}
450
451template <class BlockT, class LoopT>
452void LoopInfoBase<BlockT, LoopT>::analyzeImpl(
453 const DomTreeBase<BlockT> &DomTree, ReuseLoopT ReuseLoop) {
454 analyzeImpl(
455 DomTree.getRootNode()->getBlock()->getParent(),
456 [&]() -> const DomTreeBase<BlockT> & { return DomTree; }, ReuseLoop);
457}
459template <class BlockT, class LoopT>
461 DomTreeBase<BlockT> DomTree;
462 analyze(F, [&]() -> const DomTreeBase<BlockT> & {
463 DomTree.recalculate(*F);
464 return DomTree;
465 });
466}
468template <class BlockT, class LoopT>
470 ParentT F, function_ref<const DomTreeBase<BlockT> &()> GetDomTree) {
471 analyzeImpl(F, GetDomTree, /*ReuseLoop=*/{});
472}
473
474template <class BlockT, class LoopT>
477 // Index the loops by header so the analysis can find them again, and empty
478 // them out for it to refill.
479 MapVector<BlockT *, LoopT *> ReuseByHeader;
480 for (LoopT *L : getLoopsInPreorder()) {
481 ReuseByHeader[L->getHeader()] = L;
482 L->clear();
483 }
484 BBMap.clear();
485 TopLevelLoops.clear();
486 BlockLayout.reset();
487
488 analyzeImpl(DomTree,
489 [&](BlockT *Header) { return ReuseByHeader.lookup(Header); });
490
491 // ReuseByHeader is in preorder, so the report is deterministic.
493 for (auto [Header, L] : ReuseByHeader)
494 if (lookupLoopFor(Header) != L)
495 Removed.emplace_back(L, Header);
496 return Removed;
497}
498
499template <class BlockT, class LoopT>
500void LoopInfoBase<BlockT, LoopT>::analyzeImpl(
501 ParentT F, function_ref<const DomTreeBase<BlockT> &()> GetDomTree,
502 ReuseLoopT ReuseLoop) {
503 using BlockTraits = GraphTraits<BlockT *>;
504 auto num = [](const BlockT *BB) {
506 };
507
508 ParentPtr = F;
509 BlockNumberEpoch = GraphTraits<ParentT>::getNumberEpoch(ParentPtr);
510 unsigned MaxNumber = GraphTraits<ParentT>::getMaxNumber(ParentPtr);
511
512 // Sentinel block number meaning "no block".
513 constexpr unsigned NoBlock = ~0u;
514 // States during DFS (Unvisited, OffPath, >=FirstOnPath) and post-DFS
515 // (IsHeader, IsReentered).
516 constexpr unsigned Unvisited = 0;
517 constexpr unsigned OffPath = 1;
518 constexpr unsigned IsHeader = 2;
519 constexpr unsigned IsReentered = 3;
520 constexpr unsigned FirstOnPath = IsReentered + 1;
521
522 // Per-block search state, indexed by block number.
523 struct BlockInfo {
524 // Unvisited. Spelled 0 to work around GCC 11 ICE.
525 unsigned Pos = 0;
526 // Block number of the innermost enclosing header; NoBlock if none. Set to
527 // NoBlock when the block is visited, then woven by tagLoopHeader.
528 unsigned LoopHeader = 0;
529 };
531 // The loop headers, repeated once per backedge.
533 // The headers of the loops that an edge re-enters. They mark irreducible
534 // loops that need to be reduced to natural loop subsets.
535 DenseSet<unsigned> Reentries;
536
537 // Weave loop header \p H (and its own header chain) into the loop header
538 // chain of \p B, keeping the chain ordered from innermost to outermost by
539 // search path position. Building this chain on the fly is why the algorithm
540 // needs no union-find (used in the Havlak algorithm) at all.
541 auto tagLoopHeader = [&](unsigned B, unsigned H) {
542 assert(H != NoBlock);
543 // Invariant: Info[B].Pos >= Info[H].Pos.
544 while (B != H) {
545 unsigned IH = Info[B].LoopHeader;
546 if (IH == NoBlock) {
547 // B's chain ended: append the rest of H's chain.
548 Info[B].LoopHeader = H;
549 return;
550 }
551 // Keep whichever candidate header is inner (larger search path position).
552 if (Info[IH].Pos >= Info[H].Pos) {
553 B = IH;
554 } else {
555 Info[B].LoopHeader = H;
556 B = H;
557 H = IH;
558 }
559 }
560 };
561
562 // Identify loops with the algorithm of Wei et al., "A New Algorithm for
563 // Identifying Loops in Decompilation" (SAS 2007): tag each block with its
564 // innermost enclosing header. It also records the postorder the layout below
565 // needs.
567 Postorder.reserve(MaxNumber);
568 struct Frame {
569 BlockT *Block;
570 typename BlockTraits::ChildIteratorType Cur, End;
571 };
573 unsigned Counter = FirstOnPath;
574 auto open = [&](BlockT *BB) {
575 unsigned B = num(BB);
576 Info[B].Pos = Counter++;
577 Info[B].LoopHeader = NoBlock;
578 Stack.push_back(
579 {BB, BlockTraits::child_begin(BB), BlockTraits::child_end(BB)});
580 };
581
582 open(GraphTraits<ParentT>::getEntryNode(ParentPtr));
583 while (!Stack.empty()) {
584 Frame &Top = Stack.back();
585 if (Top.Cur == Top.End) {
586 // Leave the search path, and weave into the parent's chain.
587 unsigned B0 = num(Top.Block);
588 Info[B0].Pos = OffPath;
589 Postorder.push_back(Top.Block);
590 Stack.pop_back();
591 if (!Stack.empty() && Info[B0].LoopHeader != NoBlock)
592 tagLoopHeader(num(Stack.back().Block), Info[B0].LoopHeader);
593 continue;
594 }
595 BlockT *B0P = Top.Block;
596 BlockT *B1P = *Top.Cur++;
597 unsigned B1 = num(B1P);
598 if (Info[B1].Pos == Unvisited) {
599 // Tree edge; the weaving happens when B1's frame is popped.
600 open(B1P);
601 } else if (Info[B1].Pos >= FirstOnPath) {
602 // Retreating edge, including a self edge: B1 heads a loop.
603 Headers.push_back(B1);
604 tagLoopHeader(num(B0P), B1);
605 } else {
606 // Climb B1's header chain: each enclosing header still off the DFS path
607 // heads a closed cycle this edge re-enters, so B1 is a non-header entry
608 // of it (and it is irreducible). Stop at the first on-path header and
609 // attribute B0 to it.
610 for (unsigned H = Info[B1].LoopHeader; H != NoBlock;
611 H = Info[H].LoopHeader) {
612 if (Info[H].Pos >= FirstOnPath) {
613 tagLoopHeader(num(B0P), H);
614 break;
615 }
616 Reentries.insert(H);
617 }
618 }
619 }
620 // Most functions have no loops; skip the layout construction.
621 if (Headers.empty())
622 return;
623 // Every block is off the search path now, so marking the headers cannot be
624 // mistaken for a position on it.
625 for (unsigned H : Headers)
626 Info[H].Pos = IsHeader;
627
628 if (!Reentries.empty()) {
629 // A re-entered loop has more than one entry, so it is not a natural loop.
630 // Reduce it, innermost first, to the natural loop of its header's
631 // backedges: a backward search from the latches finds the blocks to keep;
632 // splice the header out of the chain of every other block.
633 for (unsigned H : Reentries)
634 Info[H].Pos = IsReentered;
635 const DomTreeBase<BlockT> &DomTree = GetDomTree();
636 assert(DomTree.getRootNode()->getBlock() ==
638 DomTree.updateDFSNumbers();
639 SmallVector<unsigned, 0> Mark(MaxNumber, NoBlock);
641 // Invert the chains into the loop forest, so that a header visits only its
642 // own blocks.
643 SmallVector<unsigned, 0> FirstChild(MaxNumber, NoBlock);
644 SmallVector<unsigned, 0> NextSibling(MaxNumber, NoBlock);
645 SmallVector<BlockT *, 0> Blocks(MaxNumber);
646 for (BlockT *BB : Postorder) {
647 unsigned B = num(BB);
648 Blocks[B] = BB;
649 if (unsigned P = Info[B].LoopHeader; P != NoBlock) {
650 NextSibling[B] = FirstChild[P];
651 FirstChild[P] = B;
652 }
653 }
654 for (BlockT *Header : Postorder) {
655 unsigned H = num(Header);
656 if (Info[H].Pos != IsReentered)
657 continue;
658 Mark[H] = H;
659 Worklist.clear();
660 auto enqueue = [&](BlockT *Pred) {
661 unsigned P = num(Pred);
662 // If Pred is in a natural loop, mark its header and skip interior
663 // blocks.
664 for (unsigned A = P; A != NoBlock; A = Info[A].LoopHeader)
665 if (Info[A].LoopHeader == H) {
666 P = A;
667 Pred = Blocks[A];
668 break;
669 }
670 if (Mark[P] == H)
671 return;
672 Mark[P] = H;
673 Worklist.push_back(Pred);
674 };
675 // Place the latches, the predecessors the header dominates, into a
676 // worklist.
677 const DomTreeNodeBase<BlockT> *DomNode = DomTree.getNode(Header);
678 assert(DomNode && "header missing from the dominator tree");
679 bool HasBackedge = false;
680 for (BlockT *Pred : inverse_children<BlockT *>(Header)) {
681 const DomTreeNodeBase<BlockT> *PredNode = DomTree.getNode(Pred);
682 if (PredNode && DomTree.dominates(DomNode, PredNode)) {
683 HasBackedge = true;
684 enqueue(Pred);
685 }
686 }
687 // Whatever reaches a latch without passing the header is in the loop.
688 for (unsigned I = 0; I != Worklist.size(); ++I)
689 for (BlockT *Pred : inverse_children<BlockT *>(Worklist[I]))
690 // Do not enqueue any unreachable nodes.
691 if (Blocks[num(Pred)])
692 enqueue(Pred);
693 // Without a backedge the header forms no loop at all.
694 Info[H].Pos = HasBackedge ? IsHeader : OffPath;
695 // Partition the header's blocks: the loop keeps the ones the traversal
696 // reached, and the enclosing header takes the rest, which its own turn
697 // then tests. Both arms relink the block, so step first.
698 unsigned Parent = Info[H].LoopHeader;
699 unsigned Kept = NoBlock;
700 for (unsigned B = FirstChild[H], Next; B != NoBlock; B = Next) {
701 Next = NextSibling[B];
702 if (Mark[B] == H) {
703 NextSibling[B] = Kept;
704 Kept = B;
705 } else {
706 // Leaving the loop; the block is top level if it had no other header.
707 Info[B].LoopHeader = Parent;
708 if (Parent != NoBlock) {
709 NextSibling[B] = FirstChild[Parent];
710 FirstChild[Parent] = B;
711 }
712 }
713 }
714 FirstChild[H] = Kept;
716 if (none_of(Headers, [&](unsigned H) { return Info[H].Pos == IsHeader; }))
717 return;
719
720 // Resolve the chains in reverse postorder: a block's innermost header is
721 // one of its search tree ancestors, so it is mapped to its loop first.
722 BBMap.resize(MaxNumber);
723 for (BlockT *BB : llvm::reverse(Postorder)) {
724 unsigned B = num(BB);
725 unsigned H = Info[B].LoopHeader;
726 LoopT *Enclosing = H == NoBlock ? nullptr : BBMap[H];
727 LoopT *L = Enclosing;
728 if (Info[B].Pos == IsHeader) {
729 L = allocateLoop(BB, ReuseLoop);
730 L->setParentLoop(Enclosing);
731 }
732 BBMap[B] = L;
733 }
734
735 // Record each in-loop block with its innermost loop in forward CFG postorder,
736 // and build the loop list in PO.
739 PO.reserve(Postorder.size());
740 for (BlockT *BB : Postorder) {
741 LoopT *L = lookupLoopFor(BB);
742 if (!L)
743 continue;
744 PO.emplace_back(BB, L);
745 ++L->BlockLen;
746 if (BB != pendingHeader(L))
747 continue;
748 LoopsPO.push_back(L);
749 if (LoopT *Parent = L->getParentLoop())
750 Parent->BlockLen += L->BlockLen;
751 else
752 TopLevelLoops.push_back(L);
753 }
754 // Headers are dominator-tree nodes, hence reachable and in the postorder.
755 assert(!LoopsPO.empty() && "discovered loops but found no header");
757 BlockLayout.reset(new BlockT *[PO.size()]);
758 BlockT **RootCursor = BlockLayout.get();
759 for (auto &[BB, L] : llvm::reverse(PO)) {
760 if (L->BlockCapacity == 0) {
761 // The first block of a L is its the header. Carve its slice from the
762 // parent (already visited)'s cursor.
763 if (LoopT *Parent = L->getParentLoop()) {
764 assert(Parent->BlockCapacity != 0 &&
765 "parent slice not carved before child");
766 L->BlockData = Parent->BlockData + Parent->BlockCapacity;
767 Parent->BlockCapacity += L->BlockLen;
768 Parent->SubLoops.push_back(L);
769 } else {
770 L->BlockData = RootCursor;
771 RootCursor += L->BlockLen;
772 }
773 }
774 // Each block lands once, at its innermost loop's cursor.
775 L->BlockData[L->BlockCapacity++] = BB;
776 }
777
778 // Mark every slice as borrowed from BlockLayout; a later mutation copies it
779 // into private storage (see materializeBlocks).
780 for (LoopT *L : LoopsPO) {
781 assert(L->BlockCapacity == L->BlockLen && "layout slice not fully used");
782 L->BlockCapacity = LoopT::BorrowedCapacity;
783 }
784}
785
786template <class BlockT, class LoopT>
789 SmallVector<LoopT *, 4> PreOrderLoops;
790 // The outer-most loop actually goes into the result in the same relative
791 // order as we walk it. But LoopInfo stores the top level loops in reverse
792 // program order so for here we reverse it to get forward program order.
793 // FIXME: If we change the order of LoopInfo we will want to remove the
794 // reverse here.
795 for (LoopT *RootL : reverse(*this)) {
796 PreOrderLoops.push_back(RootL);
797 LoopT::getInnerLoopsInPreorder(*RootL, PreOrderLoops);
798 }
799
800 return PreOrderLoops;
801}
802
803template <class BlockT, class LoopT>
806 SmallVector<LoopT *, 4> PreOrderLoops, PreOrderWorklist;
807 // The outer-most loop actually goes into the result in the same relative
808 // order as we walk it. LoopInfo stores the top level loops in reverse
809 // program order so we walk in order here.
810 // FIXME: If we change the order of LoopInfo we will want to add a reverse
811 // here.
812 for (LoopT *RootL : *this) {
813 assert(PreOrderWorklist.empty() &&
814 "Must start with an empty preorder walk worklist.");
815 PreOrderWorklist.push_back(RootL);
816 do {
817 LoopT *L = PreOrderWorklist.pop_back_val();
818 // Sub-loops are stored in forward program order, but will process the
819 // worklist backwards so we can just append them in order.
820 PreOrderWorklist.append(L->begin(), L->end());
821 PreOrderLoops.push_back(L);
822 } while (!PreOrderWorklist.empty());
823 }
824
825 return PreOrderLoops;
826}
827
828template <class BlockT, class LoopT>
830 LoopT *B) const {
831 if (!A || !B)
832 return nullptr;
833
834 // If loops A and B have different depth replace them with parent loop
835 // until they have the same depth.
836 unsigned DepthA = A->getLoopDepth(), DepthB = B->getLoopDepth();
837 for (; DepthA > DepthB; --DepthA)
838 A = A->getParentLoop();
839 for (; DepthB > DepthA; --DepthB)
840 B = B->getParentLoop();
841
842 // Loops A and B are at same depth but may be disjoint, replace them with
843 // parent loops until we find loop that contains both or we run out of
844 // parent loops.
845 while (A != B) {
846 A = A->getParentLoop();
847 B = B->getParentLoop();
848 }
849
850 return A;
851}
852
853template <class BlockT, class LoopT>
855 BlockT *B) const {
857}
858
859// Debugging
860template <class BlockT, class LoopT>
862 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
863 TopLevelLoops[i]->print(OS);
864}
865
866template <typename T>
867bool compareVectors(std::vector<T> &BB1, std::vector<T> &BB2) {
868 llvm::sort(BB1);
870 return BB1 == BB2;
872
873template <class BlockT, class LoopT>
876 const LoopT &L) {
877 LoopHeaders[L.getHeader()] = &L;
878 for (LoopT *SL : L)
879 addInnerLoopsToHeadersMap(LoopHeaders, LI, *SL);
880}
881
882#ifndef NDEBUG
883template <class BlockT, class LoopT>
884static void compareLoops(const LoopT *L, const LoopT *OtherL,
885 DenseMap<BlockT *, const LoopT *> &OtherLoopHeaders) {
886 BlockT *H = L->getHeader();
887 BlockT *OtherH = OtherL->getHeader();
888 assert(H == OtherH &&
889 "Mismatched headers even though found in the same map entry!");
890
891 assert(L->getLoopDepth() == OtherL->getLoopDepth() &&
892 "Mismatched loop depth!");
893 const LoopT *ParentL = L, *OtherParentL = OtherL;
894 do {
895 assert(ParentL->getHeader() == OtherParentL->getHeader() &&
896 "Mismatched parent loop headers!");
897 ParentL = ParentL->getParentLoop();
898 OtherParentL = OtherParentL->getParentLoop();
899 } while (ParentL);
900
901 for (const LoopT *SubL : *L) {
902 BlockT *SubH = SubL->getHeader();
903 const LoopT *OtherSubL = OtherLoopHeaders.lookup(SubH);
904 assert(OtherSubL && "Inner loop is missing in computed loop info!");
905 OtherLoopHeaders.erase(SubH);
906 compareLoops(SubL, OtherSubL, OtherLoopHeaders);
907 }
908
909 std::vector<BlockT *> BBs = L->getBlocks();
910 std::vector<BlockT *> OtherBBs = OtherL->getBlocks();
911 assert(compareVectors(BBs, OtherBBs) &&
912 "Mismatched basic blocks in the loops!");
913}
914#endif
915
916template <class BlockT, class LoopT>
919 for (iterator I = begin(), E = end(); I != E; ++I) {
920 assert((*I)->isOutermost() && "Top-level loop has a parent!");
921 (*I)->verifyLoopNest(&Loops);
922 }
923
924// Verify that blocks are mapped to valid loops.
925#ifndef NDEBUG
926 // Every loop must point back at this LoopInfo (see resetLoopInfoOwners).
927 for (const LoopT *L : Loops)
928 assert(L->LI == this && "Loop has a stale owning-LoopInfo back-pointer");
929
930 // Recompute the innermost loop of each block from the loops' block lists,
931 // which are maintained independently of BBMap. Using contains() here would
932 // derive from BBMap itself and check nothing.
933 SmallVector<const LoopT *> Innermost(BBMap.size());
935 while (!Worklist.empty()) {
936 const LoopT *L = Worklist.pop_back_val();
937 // A loop is visited before its children, so a child's blocks overwrite the
938 // entries written by its ancestors.
939 for (const BlockT *BB : L->getBlocks()) {
941 assert(Number < Innermost.size() && "block missing from BBMap");
942 Innermost[Number] = L;
943 }
944 Worklist.append(L->begin(), L->end());
945 }
946
947 for (auto [Number, L] : enumerate(BBMap)) {
948 assert((!L || Loops.count(L)) && "orphaned loop");
949 assert(L == Innermost[Number] &&
950 "BBMap should point to the innermost loop containing the block");
951 }
952
953 // Recompute LoopInfo to verify loops structure.
954 LoopInfoBase<BlockT, LoopT> OtherLI;
955 OtherLI.analyze(ParentPtr);
956
957 // Build a map we can use to move from our LI to the computed one. This
958 // allows us to ignore the particular order in any layer of the loop forest
959 // while still comparing the structure.
960 DenseMap<BlockT *, const LoopT *> OtherLoopHeaders;
961 for (LoopT *L : OtherLI)
962 addInnerLoopsToHeadersMap(OtherLoopHeaders, OtherLI, *L);
963
964 // Walk the top level loops and ensure there is a corresponding top-level
965 // loop in the computed version and then recursively compare those loop
966 // nests.
967 for (LoopT *L : *this) {
968 BlockT *Header = L->getHeader();
969 const LoopT *OtherL = OtherLoopHeaders.lookup(Header);
970 assert(OtherL && "Top level loop is missing in computed loop info!");
971 // Now that we've matched this loop, erase its header from the map.
972 OtherLoopHeaders.erase(Header);
973 // And recursively compare these loops.
974 compareLoops(L, OtherL, OtherLoopHeaders);
975 }
976
977 // Any remaining entries in the map are loops which were found when computing
978 // a fresh LoopInfo but not present in the current one.
979 if (!OtherLoopHeaders.empty()) {
980 for (const auto &HeaderAndLoop : OtherLoopHeaders)
981 dbgs() << "Found new loop: " << *HeaderAndLoop.second << "\n";
982 llvm_unreachable("Found new loops when recomputing LoopInfo!");
983 }
984#endif
985}
986
987} // namespace llvm
988
989#endif // LLVM_SUPPORT_GENERICLOOPINFOIMPL_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static const Function * getParent(const Value *V)
bbsections Prepares for basic block by splitting functions into clusters of basic blocks
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
Hexagon Hardware Loops
static bool isExitBlock(BasicBlock *BB, const SmallVectorImpl< BasicBlock * > &ExitBlocks)
Return true if the specified block is in the list.
Definition LCSSA.cpp:68
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
This file implements a map that provides insertion order iteration.
#define P(N)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
bool erase(const KeyT &Val)
Definition DenseMap.h:377
bool empty() const
Definition DenseMap.h:171
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Base class for the actual dominator tree node.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
Instances of this class are used to represent loops that are detected in the flow graph.
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
typename std::vector< LoopT * >::const_iterator iterator
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
void verifyLoop() const
Verify loop structure.
void verifyLoopNest(DenseSet< const LoopT * > *Loops) const
Verify loop structure of this loop and all nested loops.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
void print(raw_ostream &OS, bool Verbose=false, bool PrintNested=true, unsigned Depth=0) const
Print loop with all the BBs inside it.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
bool isInvalid() const
Return true if this loop is no longer valid.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
bool isLoopLatch(const BlockT *BB) const
iterator end() const
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BasicBlock * > getBlocks() const
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
void getUniqueNonLatchExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop except successors from Latch block are not considered...
iterator begin() const
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
This class builds and contains all of the top-level loop structures in the specified function.
SmallVector< std::pair< LoopT *, BlockT * >, 4 > recompute(const DominatorTreeBase< BlockT, false > &DomTree)
Rebuild the loop forest from the CFG, refilling the existing loop object of every block that still he...
bool hasNoExitBlocks(const LoopT &L) const
Return true if L does not have any exit blocks.
SmallVector< LoopT *, 4 > getLoopsInReverseSiblingPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in reverse p...
void print(raw_ostream &OS) const
iterator end() const
SmallVector< LoopT *, 4 > getLoopsInPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
LoopT * getSmallestCommonLoop(LoopT *A, LoopT *B) const
Find the innermost loop containing both given loops.
typename std::vector< LoopT * >::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
void analyze(ParentT F)
Create the loop forest for a function.
iterator begin() const
BlockT * getUniqueLatchExitBlock(const LoopT &L) const
Return the unique exit block for the latch of L, or null if there are multiple different exit blocks ...
void getExitEdges(const LoopT &L, SmallVectorImpl< Edge > &ExitEdges) const
Return all pairs of (inside_block,outside_block).
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void changeLoopFor(const BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
ValueT lookup(const KeyT &Key) const
Definition MapVector.h:110
size_type size() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
decltype(&BlockT::isLegalToHoistInto) has_hoist_check
llvm::is_detected< has_hoist_check, BlockT > detect_has_hoist_check
bool isLegalToHoistInto(BlockT *Block)
SFINAE functions that dispatch to the isLegalToHoistInto member function or return false,...
NodeAddr< BlockNode * > Block
Definition RDFGraph.h:392
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
static void compareLoops(const LoopT *L, const LoopT *OtherL, DenseMap< BlockT *, const LoopT * > &OtherLoopHeaders)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
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:1746
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
DominatorTreeBase< T, false > DomTreeBase
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
Definition STLExtras.h:299
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:551
std::pair< BlockT *, bool > getExitBlockHelper(const LoopBase< BlockT, LoopT > *L, bool Unique)
getExitBlock - If getExitBlocks would return exactly one block, return that block.
std::pair< T *, bool > find_singleton_nested(R &&Range, Predicate P, bool AllowRepeats=false)
Return a pair consisting of the single value in Range that satisfies P(<member of Range> ,...
Definition STLExtras.h:1862
T * find_singleton(R &&Range, Predicate P, bool AllowRepeats=false)
Return the single value in Range that satisfies P(<member of Range> *, AllowRepeats)->T * returning n...
Definition STLExtras.h:1837
iterator_range< typename GraphTraits< Inverse< GraphType > >::ChildIteratorType > inverse_children(const typename GraphTraits< GraphType >::NodeRef &G)
void addInnerLoopsToHeadersMap(DenseMap< BlockT *, const LoopT * > &LoopHeaders, const LoopInfoBase< BlockT, LoopT > &LI, const LoopT &L)
void getUniqueExitBlocksHelper(const LoopT *L, SmallVectorImpl< BlockT * > &ExitBlocks, PredicateT Pred)
typename detail::detector< void, Op, Args... >::value_t is_detected
Detects if a given trait holds for some set of arguments 'Args'.
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
bool compareVectors(std::vector< T > &BB1, std::vector< T > &BB2)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
iterator_range< df_iterator< T > > depth_first(const T &G)
std::pair< iterator, bool > insert(NodeRef N)