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"
20#include "llvm/ADT/STLExtras.h"
22
23namespace llvm {
24
25//===----------------------------------------------------------------------===//
26// APIs for simple analysis of the loop. See header notes.
27
28/// getExitingBlocks - Return all blocks inside the loop that have successors
29/// outside of the loop. These are the blocks _inside of the current loop_
30/// which branch out. The returned list is always unique.
31///
32template <class BlockT, class LoopT>
34 SmallVectorImpl<BlockT *> &ExitingBlocks) const {
35 assert(!isInvalid() && "Loop not in a valid state!");
36 for (const auto BB : blocks())
37 for (auto *Succ : children<BlockT *>(BB))
38 if (!contains(Succ)) {
39 // Not in current loop? It must be an exit block.
40 ExitingBlocks.push_back(BB);
41 break;
42 }
43}
44
45/// getExitingBlock - If getExitingBlocks would return exactly one block,
46/// return that block. Otherwise return null.
47template <class BlockT, class LoopT>
49 assert(!isInvalid() && "Loop not in a valid state!");
50 auto notInLoop = [&](BlockT *BB) { return !contains(BB); };
51 auto isExitBlock = [&](BlockT *BB, bool AllowRepeats) -> BlockT * {
52 assert(!AllowRepeats && "Unexpected parameter value.");
53 // Child not in current loop? It must be an exit block.
54 return any_of(children<BlockT *>(BB), notInLoop) ? BB : nullptr;
55 };
56
58}
59
60/// getExitBlocks - Return all of the successor blocks of this loop. These
61/// are the blocks _outside of the current loop_ which are branched to.
62///
63template <class BlockT, class LoopT>
65 SmallVectorImpl<BlockT *> &ExitBlocks) const {
66 assert(!isInvalid() && "Loop not in a valid state!");
67 for (const auto BB : blocks())
68 for (auto *Succ : children<BlockT *>(BB))
69 if (!contains(Succ))
70 // Not in current loop? It must be an exit block.
71 ExitBlocks.push_back(Succ);
72}
73
74/// getExitBlock - If getExitBlocks would return exactly one block,
75/// return that block. Otherwise return null.
76template <class BlockT, class LoopT>
77std::pair<BlockT *, bool> getExitBlockHelper(const LoopBase<BlockT, LoopT> *L,
78 bool Unique) {
79 assert(!L->isInvalid() && "Loop not in a valid state!");
80 auto notInLoop = [&](BlockT *BB,
81 bool AllowRepeats) -> std::pair<BlockT *, bool> {
82 assert(AllowRepeats == Unique && "Unexpected parameter value.");
83 return {!L->contains(BB) ? BB : nullptr, false};
84 };
85 auto singleExitBlock = [&](BlockT *BB,
86 bool AllowRepeats) -> std::pair<BlockT *, bool> {
87 assert(AllowRepeats == Unique && "Unexpected parameter value.");
89 AllowRepeats);
90 };
91 return find_singleton_nested<BlockT>(L->blocks(), singleExitBlock, Unique);
92}
93
94template <class BlockT, class LoopT>
96 auto RC = getExitBlockHelper(&L, false);
97 if (RC.second)
98 // found multiple exit blocks
99 return false;
100 // return true if there is no exit block
101 return !RC.first;
102}
103
104/// getExitBlock - If getExitBlocks would return exactly one block,
105/// return that block. Otherwise return null.
106template <class BlockT, class LoopT>
108 return getExitBlockHelper(this, false).first;
109}
110
111template <class BlockT, class LoopT>
113 // Each predecessor of each exit block of a normal loop is contained
114 // within the loop.
115 SmallVector<BlockT *, 4> UniqueExitBlocks;
116 getUniqueExitBlocks(UniqueExitBlocks);
117 for (BlockT *EB : UniqueExitBlocks)
118 for (BlockT *Predecessor : inverse_children<BlockT *>(EB))
119 if (!contains(Predecessor))
120 return false;
121 // All the requirements are met.
122 return true;
123}
124
125// Helper function to get unique loop exits. Pred is a predicate pointing to
126// BasicBlocks in a loop which should be considered to find loop exits.
127template <class BlockT, class LoopT, typename PredicateT>
128void getUniqueExitBlocksHelper(const LoopT *L,
129 SmallVectorImpl<BlockT *> &ExitBlocks,
130 PredicateT Pred) {
131 assert(!L->isInvalid() && "Loop not in a valid state!");
133 auto Filtered = make_filter_range(L->blocks(), Pred);
134 for (BlockT *BB : Filtered)
135 for (BlockT *Successor : children<BlockT *>(BB))
136 if (!L->contains(Successor))
137 if (Visited.insert(Successor).second)
138 ExitBlocks.push_back(Successor);
139}
140
141template <class BlockT, class LoopT>
143 SmallVectorImpl<BlockT *> &ExitBlocks) const {
144 getUniqueExitBlocksHelper(this, ExitBlocks,
145 [](const BlockT *BB) { return true; });
146}
147
148template <class BlockT, class LoopT>
150 SmallVectorImpl<BlockT *> &ExitBlocks) const {
151 const BlockT *Latch = getLoopLatch();
152 assert(Latch && "Latch block must exists");
153 getUniqueExitBlocksHelper(this, ExitBlocks,
154 [Latch](const BlockT *BB) { return BB != Latch; });
155}
156
157template <class BlockT, class LoopT>
159 return getExitBlockHelper(this, true).first;
160}
161
162template <class BlockT, class LoopT>
163BlockT *
165 BlockT *Latch = L.getLoopLatch();
166 assert(Latch && "Latch block must exists");
167 auto IsExitBlock = [&L](BlockT *BB, bool AllowRepeats) -> BlockT * {
168 assert(!AllowRepeats && "Unexpected parameter value.");
169 return !L.contains(BB) ? BB : nullptr;
170 };
171 return find_singleton<BlockT>(children<BlockT *>(Latch), IsExitBlock);
172}
173
174/// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
175template <class BlockT, class LoopT>
177 const LoopT &L, SmallVectorImpl<Edge> &ExitEdges) const {
178 for (const auto BB : L.blocks())
179 for (auto *Succ : children<BlockT *>(BB))
180 if (!L.contains(Succ))
181 // Not in current loop? It must be an exit block.
182 ExitEdges.emplace_back(BB, Succ);
183}
184
185namespace detail {
186template <class BlockT>
187using has_hoist_check = decltype(&BlockT::isLegalToHoistInto);
188
189template <class BlockT>
191
192/// SFINAE functions that dispatch to the isLegalToHoistInto member function or
193/// return false, if it doesn't exist.
194template <class BlockT> bool isLegalToHoistInto(BlockT *Block) {
196 return Block->isLegalToHoistInto();
197 return false;
198}
199} // namespace detail
200
201/// getLoopPreheader - If there is a preheader for this loop, return it. A
202/// loop has a preheader if there is only one edge to the header of the loop
203/// from outside of the loop and it is legal to hoist instructions into the
204/// predecessor. If this is the case, the block branching to the header of the
205/// loop is the preheader node.
206///
207/// This method returns null if there is no preheader for the loop.
208///
209template <class BlockT, class LoopT>
211 assert(!isInvalid() && "Loop not in a valid state!");
212 // Keep track of nodes outside the loop branching to the header...
213 BlockT *Out = getLoopPredecessor();
214 if (!Out)
215 return nullptr;
216
217 // Make sure we are allowed to hoist instructions into the predecessor.
219 return nullptr;
220
221 // Make sure there is only one exit out of the preheader.
223 return nullptr; // Multiple exits from the block, must not be a preheader.
224
225 // The predecessor has exactly one successor, so it is a preheader.
226 return Out;
227}
228
229/// getLoopPredecessor - If the given loop's header has exactly one unique
230/// predecessor outside the loop, return it. Otherwise return null.
231/// This is less strict that the loop "preheader" concept, which requires
232/// the predecessor to have exactly one successor.
233///
234template <class BlockT, class LoopT>
236 assert(!isInvalid() && "Loop not in a valid state!");
237 // Keep track of nodes outside the loop branching to the header...
238 BlockT *Out = nullptr;
239
240 // Loop over the predecessors of the header node...
241 BlockT *Header = getHeader();
242 for (const auto Pred : inverse_children<BlockT *>(Header)) {
243 if (!contains(Pred)) { // If the block is not in the loop...
244 if (Out && Out != Pred)
245 return nullptr; // Multiple predecessors outside the loop
246 Out = Pred;
247 }
248 }
249
250 return Out;
251}
252
253/// getLoopLatch - If there is a single latch block for this loop, return it.
254/// A latch block is a block that contains a branch back to the header.
255template <class BlockT, class LoopT>
257 assert(!isInvalid() && "Loop not in a valid state!");
258 BlockT *Header = getHeader();
259 BlockT *Latch = nullptr;
260 for (const auto Pred : inverse_children<BlockT *>(Header)) {
261 if (contains(Pred)) {
262 if (Latch)
263 return nullptr;
264 Latch = Pred;
265 }
266 }
267
268 return Latch;
269}
270
271//===----------------------------------------------------------------------===//
272// APIs for updating loop information after changing the CFG
273//
274
275/// addBasicBlockToLoop - This method is used by other analyses to update loop
276/// information. NewBB is set to be a new member of the current loop.
277/// Because of this, it is added as a member of all parent loops, and is added
278/// to the specified LoopInfo object as being in the current basic block. It
279/// is not valid to replace the loop header with this method.
280///
281template <class BlockT, class LoopT>
283 BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LIB) {
284 assert(!isInvalid() && "Loop not in a valid state!");
285#ifndef NDEBUG
286 if (!getBlocks().empty()) {
287 auto SameHeader = LIB[getHeader()];
288 assert(contains(SameHeader) && getHeader() == SameHeader->getHeader() &&
289 "Incorrect LI specified for this loop!");
290 }
291#endif
292 assert(NewBB && "Cannot add a null basic block to the loop!");
293 assert(!LIB[NewBB] && "BasicBlock already in the loop!");
294
295 LoopT *L = static_cast<LoopT *>(this);
296
297 // Add the loop mapping to the LoopInfo object...
298 LIB.changeLoopFor(NewBB, L);
299
300 // Add the basic block to this loop and all parent loops...
301 while (L) {
302 L->addBlockEntry(NewBB);
303 L = L->getParentLoop();
304 }
305}
306
307/// replaceChildLoopWith - This is used when splitting loops up. It replaces
308/// the OldChild entry in our children list with NewChild, and updates the
309/// parent pointer of OldChild to be null and the NewChild to be this loop.
310/// This updates the loop depth of the new child.
311template <class BlockT, class LoopT>
313 LoopT *NewChild) {
314 assert(!isInvalid() && "Loop not in a valid state!");
315 assert(OldChild->ParentLoop == this && "This loop is already broken!");
316 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
317 typename std::vector<LoopT *>::iterator I = find(SubLoops, OldChild);
318 assert(I != SubLoops.end() && "OldChild not in loop!");
319 *I = NewChild;
320 OldChild->ParentLoop = nullptr;
321 NewChild->ParentLoop = static_cast<LoopT *>(this);
322}
323
324/// verifyLoop - Verify loop structure
325template <class BlockT, class LoopT>
327 assert(!isInvalid() && "Loop not in a valid state!");
328#ifndef NDEBUG
329 assert(!getBlocks().empty() && "Loop header is missing");
330
331 // Setup for using a depth-first iterator to visit every block in the loop.
333 getExitBlocks(ExitBBs);
335 VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
336
337 // Keep track of the BBs visited.
338 SmallPtrSet<BlockT *, 8> VisitedBBs;
339
340 // Check the individual blocks.
341 for (BlockT *BB : depth_first_ext(getHeader(), VisitSet)) {
343 [&](BlockT *B) { return contains(B); }) &&
344 "Loop block has no in-loop successors!");
345
347 [&](BlockT *B) { return contains(B); }) &&
348 "Loop block has no in-loop predecessors!");
349
350 SmallVector<BlockT *, 2> OutsideLoopPreds;
351 for (BlockT *B : inverse_children<BlockT *>(BB))
352 if (!contains(B))
353 OutsideLoopPreds.push_back(B);
354
355 if (BB == getHeader()) {
356 assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
357 } else if (!OutsideLoopPreds.empty()) {
358 // A non-header loop block shouldn't be reachable from outside the loop,
359 // though it is permitted if the predecessor is not itself actually
360 // reachable.
361 BlockT *EntryBB = &BB->getParent()->front();
362 for (BlockT *CB : depth_first(EntryBB))
363 for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
364 assert(CB != OutsideLoopPreds[i] &&
365 "Loop has multiple entry points!");
366 }
367 assert(BB != &getHeader()->getParent()->front() &&
368 "Loop contains function entry block!");
369
370 VisitedBBs.insert(BB);
371 }
372
373 if (VisitedBBs.size() != getNumBlocks()) {
374 dbgs() << "The following blocks are unreachable in the loop: ";
375 for (auto *BB : getBlocks()) {
376 if (!VisitedBBs.count(BB)) {
377 dbgs() << *BB << "\n";
378 }
379 }
380 assert(false && "Unreachable block in loop");
382
383 // Check the subloops.
384 for (iterator I = begin(), E = end(); I != E; ++I)
385 // Each block in each subloop should be contained within this loop.
386 for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
387 BI != BE; ++BI) {
388 assert(contains(*BI) &&
389 "Loop does not contain all the blocks of a subloop!");
390 }
391
392 // Check the parent loop pointer.
393 if (ParentLoop) {
394 assert(is_contained(ParentLoop->getSubLoops(), this) &&
395 "Loop is not a subloop of its parent!");
396 }
397#endif
398}
399
400/// verifyLoop - Verify loop structure of this loop and all nested loops.
401template <class BlockT, class LoopT>
404 assert(!isInvalid() && "Loop not in a valid state!");
405 Loops->insert(static_cast<const LoopT *>(this));
406 // Verify this loop.
407 verifyLoop();
408 // Verify the subloops.
409 for (iterator I = begin(), E = end(); I != E; ++I)
410 (*I)->verifyLoopNest(Loops);
411}
412
413template <class BlockT, class LoopT>
415 bool PrintNested, unsigned Depth) const {
416 OS.indent(Depth * 2);
417 if (static_cast<const LoopT *>(this)->isAnnotatedParallel())
418 OS << "Parallel ";
419 OS << "Loop at depth " << getLoopDepth() << " containing: ";
420
421 BlockT *H = getHeader();
422 for (unsigned i = 0; i < getBlocks().size(); ++i) {
423 BlockT *BB = getBlocks()[i];
424 if (!Verbose) {
425 if (i)
426 OS << ",";
427 BB->printAsOperand(OS, false);
428 } else {
429 OS << '\n';
430 }
431
432 if (BB == H)
433 OS << "<header>";
434 if (isLoopLatch(BB))
435 OS << "<latch>";
436 if (isLoopExiting(BB))
437 OS << "<exiting>";
438 if (Verbose)
439 BB->print(OS);
440 }
441
442 if (PrintNested) {
443 OS << "\n";
444
445 for (iterator I = begin(), E = end(); I != E; ++I)
446 (*I)->print(OS, /*Verbose*/ false, PrintNested, Depth + 2);
447 }
448}
449
450//===----------------------------------------------------------------------===//
451/// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
452/// result does / not depend on use list (block predecessor) order.
453///
454
455/// Analyze LoopInfo identifies the loops during a single forward depth-first
456/// search of the CFG.
457///
458/// Then build a loop-contiguous reverse postorder for in-loops blocks. Lists
459/// are header-first with each subloop's blocks contiguous, ordered by first
460/// appearance in RPO; SubLoops keep program order, TopLevelLoops reverse
461/// program order.
462template <class BlockT, class LoopT>
464 analyze(DomTree.getRootNode()->getBlock()->getParent(),
465 [&]() -> const DomTreeBase<BlockT> & { return DomTree; });
466}
467
468template <class BlockT, class LoopT>
470 DomTreeBase<BlockT> DomTree;
471 analyze(F, [&]() -> const DomTreeBase<BlockT> & {
472 DomTree.recalculate(*F);
473 return DomTree;
474 });
475}
476
477template <class BlockT, class LoopT>
479 ParentT F, function_ref<const DomTreeBase<BlockT> &()> GetDomTree) {
480 using BlockTraits = GraphTraits<BlockT *>;
481 auto num = [](const BlockT *BB) {
482 return GraphTraits<const BlockT *>::getNumber(BB);
483 };
484
485 ParentPtr = F;
486 BlockNumberEpoch = GraphTraits<ParentT>::getNumberEpoch(ParentPtr);
487 unsigned MaxNumber = GraphTraits<ParentT>::getMaxNumber(ParentPtr);
488
489 // Sentinel block number meaning "no block".
490 constexpr unsigned NoBlock = ~0u;
491 // States during DFS (Unvisited, OffPath, >=FirstOnPath) and post-DFS
492 // (IsHeader, IsReentered).
493 constexpr unsigned Unvisited = 0;
494 constexpr unsigned OffPath = 1;
495 constexpr unsigned IsHeader = 2;
496 constexpr unsigned IsReentered = 3;
497 constexpr unsigned FirstOnPath = IsReentered + 1;
498
499 // Per-block search state, indexed by block number.
500 struct BlockInfo {
501 // Unvisited. Spelled 0 to work around GCC 11 ICE.
502 unsigned Pos = 0;
503 // Block number of the innermost enclosing header; NoBlock if none. Set to
504 // NoBlock when the block is visited, then woven by tagLoopHeader.
505 unsigned LoopHeader = 0;
506 };
508 // The loop headers, repeated once per backedge.
510 // The headers of the loops that an edge re-enters. They mark irreducible
511 // loops that need to be reduced to natural loop subsets.
512 DenseSet<unsigned> Reentries;
513
514 // Weave loop header \p H (and its own header chain) into the loop header
515 // chain of \p B, keeping the chain ordered from innermost to outermost by
516 // search path position. Building this chain on the fly is why the algorithm
517 // needs no union-find (used in the Havlak algorithm) at all.
518 auto tagLoopHeader = [&](unsigned B, unsigned H) {
519 assert(H != NoBlock);
520 // Invariant: Info[B].Pos >= Info[H].Pos.
521 while (B != H) {
522 unsigned IH = Info[B].LoopHeader;
523 if (IH == NoBlock) {
524 // B's chain ended: append the rest of H's chain.
525 Info[B].LoopHeader = H;
526 return;
527 }
528 // Keep whichever candidate header is inner (larger search path position).
529 if (Info[IH].Pos >= Info[H].Pos) {
530 B = IH;
531 } else {
532 Info[B].LoopHeader = H;
533 B = H;
534 H = IH;
535 }
536 }
537 };
538
539 // Identify loops with the algorithm of Wei et al., "A New Algorithm for
540 // Identifying Loops in Decompilation" (SAS 2007): tag each block with its
541 // innermost enclosing header. It also records the postorder the layout below
542 // needs.
544 Postorder.reserve(MaxNumber);
545 struct Frame {
546 BlockT *Block;
547 typename BlockTraits::ChildIteratorType Cur, End;
548 };
550 unsigned Counter = FirstOnPath;
551 auto open = [&](BlockT *BB) {
552 unsigned B = num(BB);
553 Info[B].Pos = Counter++;
554 Info[B].LoopHeader = NoBlock;
555 Stack.push_back(
556 {BB, BlockTraits::child_begin(BB), BlockTraits::child_end(BB)});
557 };
558
559 open(GraphTraits<ParentT>::getEntryNode(ParentPtr));
560 while (!Stack.empty()) {
561 Frame &Top = Stack.back();
562 if (Top.Cur == Top.End) {
563 // Leave the search path, and weave into the parent's chain.
564 unsigned B0 = num(Top.Block);
565 Info[B0].Pos = OffPath;
566 Postorder.push_back(Top.Block);
567 Stack.pop_back();
568 if (!Stack.empty() && Info[B0].LoopHeader != NoBlock)
569 tagLoopHeader(num(Stack.back().Block), Info[B0].LoopHeader);
570 continue;
571 }
572 BlockT *B0P = Top.Block;
573 BlockT *B1P = *Top.Cur++;
574 unsigned B1 = num(B1P);
575 if (Info[B1].Pos == Unvisited) {
576 // Tree edge; the weaving happens when B1's frame is popped.
577 open(B1P);
578 } else if (Info[B1].Pos >= FirstOnPath) {
579 // Retreating edge, including a self edge: B1 heads a loop.
580 Headers.push_back(B1);
581 tagLoopHeader(num(B0P), B1);
582 } else {
583 // Climb B1's header chain: each enclosing header still off the DFS path
584 // heads a closed cycle this edge re-enters, so B1 is a non-header entry
585 // of it (and it is irreducible). Stop at the first on-path header and
586 // attribute B0 to it.
587 for (unsigned H = Info[B1].LoopHeader; H != NoBlock;
588 H = Info[H].LoopHeader) {
589 if (Info[H].Pos >= FirstOnPath) {
590 tagLoopHeader(num(B0P), H);
591 break;
592 }
593 Reentries.insert(H);
594 }
595 }
596 }
597 // Most functions have no loops; skip the layout construction.
598 if (Headers.empty())
599 return;
600 // Every block is off the search path now, so marking the headers cannot be
601 // mistaken for a position on it.
602 for (unsigned H : Headers)
603 Info[H].Pos = IsHeader;
604
605 if (!Reentries.empty()) {
606 // A re-entered loop has more than one entry, so it is not a natural loop.
607 // Reduce it, innermost first, to the natural loop of its header's
608 // backedges: a backward search from the latches finds the blocks to keep;
609 // splice the header out of the chain of every other block.
610 for (unsigned H : Reentries)
611 Info[H].Pos = IsReentered;
612 const DomTreeBase<BlockT> &DomTree = GetDomTree();
613 assert(DomTree.getRootNode()->getBlock() ==
615 DomTree.updateDFSNumbers();
616 SmallVector<unsigned, 0> Mark(MaxNumber, NoBlock);
618 // Invert the chains into the loop forest, so that a header visits only its
619 // own blocks.
620 SmallVector<unsigned, 0> FirstChild(MaxNumber, NoBlock);
621 SmallVector<unsigned, 0> NextSibling(MaxNumber, NoBlock);
622 SmallVector<BlockT *, 0> Blocks(MaxNumber);
623 for (BlockT *BB : Postorder) {
624 unsigned B = num(BB);
625 Blocks[B] = BB;
626 if (unsigned P = Info[B].LoopHeader; P != NoBlock) {
627 NextSibling[B] = FirstChild[P];
628 FirstChild[P] = B;
629 }
630 }
631 for (BlockT *Header : Postorder) {
632 unsigned H = num(Header);
633 if (Info[H].Pos != IsReentered)
634 continue;
635 Mark[H] = H;
636 Worklist.clear();
637 auto enqueue = [&](BlockT *Pred) {
638 unsigned P = num(Pred);
639 // If Pred is in a natural loop, mark its header and skip interior
640 // blocks.
641 for (unsigned A = P; A != NoBlock; A = Info[A].LoopHeader)
642 if (Info[A].LoopHeader == H) {
643 P = A;
644 Pred = Blocks[A];
645 break;
646 }
647 if (Mark[P] == H)
648 return;
649 Mark[P] = H;
650 Worklist.push_back(Pred);
651 };
652 // Place the latches, the predecessors the header dominates, into a
653 // worklist.
654 const DomTreeNodeBase<BlockT> *DomNode = DomTree.getNode(Header);
655 assert(DomNode && "header missing from the dominator tree");
656 bool HasBackedge = false;
657 for (BlockT *Pred : inverse_children<BlockT *>(Header)) {
658 const DomTreeNodeBase<BlockT> *PredNode = DomTree.getNode(Pred);
659 if (PredNode && DomTree.dominates(DomNode, PredNode)) {
660 HasBackedge = true;
661 enqueue(Pred);
662 }
663 }
664 // Whatever reaches a latch without passing the header is in the loop.
665 for (unsigned I = 0; I != Worklist.size(); ++I)
666 for (BlockT *Pred : inverse_children<BlockT *>(Worklist[I]))
667 // Do not enqueue any unreachable nodes.
668 if (Blocks[num(Pred)])
669 enqueue(Pred);
670 // Without a backedge the header forms no loop at all.
671 Info[H].Pos = HasBackedge ? IsHeader : OffPath;
672 // Partition the header's blocks: the loop keeps the ones the traversal
673 // reached, and the enclosing header takes the rest, which its own turn
674 // then tests. Both arms relink the block, so step first.
675 unsigned Parent = Info[H].LoopHeader;
676 unsigned Kept = NoBlock;
677 for (unsigned B = FirstChild[H], Next; B != NoBlock; B = Next) {
678 Next = NextSibling[B];
679 if (Mark[B] == H) {
680 NextSibling[B] = Kept;
681 Kept = B;
682 } else {
683 // Leaving the loop; the block is top level if it had no other header.
684 Info[B].LoopHeader = Parent;
685 if (Parent != NoBlock) {
686 NextSibling[B] = FirstChild[Parent];
687 FirstChild[Parent] = B;
688 }
689 }
690 }
691 FirstChild[H] = Kept;
692 }
693 if (none_of(Headers, [&](unsigned H) { return Info[H].Pos == IsHeader; }))
694 return;
695 }
696
697 // Resolve the chains in reverse postorder: a block's innermost header is
698 // one of its search tree ancestors, so it is mapped to its loop first.
699 BBMap.resize(MaxNumber);
700 for (BlockT *BB : llvm::reverse(Postorder)) {
701 unsigned B = num(BB);
702 unsigned H = Info[B].LoopHeader;
703 LoopT *Enclosing = H == NoBlock ? nullptr : BBMap[H];
704 LoopT *L = Enclosing;
705 if (Info[B].Pos == IsHeader) {
706 L = allocateLoop(BB);
707 L->setParentLoop(Enclosing);
708 }
709 BBMap[B] = L;
710 }
711
712 // Record each in-loop block with its innermost loop in forward CFG postorder,
713 // and build the loop list in PO.
716 PO.reserve(Postorder.size());
717 for (BlockT *BB : Postorder) {
718 LoopT *L = lookupLoopFor(BB);
719 if (!L)
720 continue;
721 PO.emplace_back(BB, L);
722 ++L->BlockLen;
723 if (BB != pendingHeader(L))
724 continue;
725 LoopsPO.push_back(L);
726 if (LoopT *Parent = L->getParentLoop())
727 Parent->BlockLen += L->BlockLen;
728 else
729 TopLevelLoops.push_back(L);
730 }
731 // Headers are dominator-tree nodes, hence reachable and in the postorder.
732 assert(!LoopsPO.empty() && "discovered loops but found no header");
733
734 BlockLayout.reset(new BlockT *[PO.size()]);
735 BlockT **RootCursor = BlockLayout.get();
736 for (auto &[BB, L] : llvm::reverse(PO)) {
737 if (L->BlockCapacity == 0) {
738 // The first block of a L is its the header. Carve its slice from the
739 // parent (already visited)'s cursor.
740 if (LoopT *Parent = L->getParentLoop()) {
741 assert(Parent->BlockCapacity != 0 &&
742 "parent slice not carved before child");
743 L->BlockData = Parent->BlockData + Parent->BlockCapacity;
744 Parent->BlockCapacity += L->BlockLen;
745 Parent->SubLoops.push_back(L);
746 } else {
747 L->BlockData = RootCursor;
748 RootCursor += L->BlockLen;
749 }
750 }
751 // Each block lands once, at its innermost loop's cursor.
752 L->BlockData[L->BlockCapacity++] = BB;
753 }
754
755 // Mark every slice as borrowed from BlockLayout; a later mutation copies it
756 // into private storage (see materializeBlocks).
757 for (LoopT *L : LoopsPO) {
758 assert(L->BlockCapacity == L->BlockLen && "layout slice not fully used");
759 L->BlockCapacity = LoopT::BorrowedCapacity;
761}
762
763template <class BlockT, class LoopT>
766 SmallVector<LoopT *, 4> PreOrderLoops;
767 // The outer-most loop actually goes into the result in the same relative
768 // order as we walk it. But LoopInfo stores the top level loops in reverse
769 // program order so for here we reverse it to get forward program order.
770 // FIXME: If we change the order of LoopInfo we will want to remove the
771 // reverse here.
772 for (LoopT *RootL : reverse(*this)) {
773 PreOrderLoops.push_back(RootL);
774 LoopT::getInnerLoopsInPreorder(*RootL, PreOrderLoops);
775 }
776
777 return PreOrderLoops;
778}
779
780template <class BlockT, class LoopT>
783 SmallVector<LoopT *, 4> PreOrderLoops, PreOrderWorklist;
784 // The outer-most loop actually goes into the result in the same relative
785 // order as we walk it. LoopInfo stores the top level loops in reverse
786 // program order so we walk in order here.
787 // FIXME: If we change the order of LoopInfo we will want to add a reverse
788 // here.
789 for (LoopT *RootL : *this) {
790 assert(PreOrderWorklist.empty() &&
791 "Must start with an empty preorder walk worklist.");
792 PreOrderWorklist.push_back(RootL);
793 do {
794 LoopT *L = PreOrderWorklist.pop_back_val();
795 // Sub-loops are stored in forward program order, but will process the
796 // worklist backwards so we can just append them in order.
797 PreOrderWorklist.append(L->begin(), L->end());
798 PreOrderLoops.push_back(L);
799 } while (!PreOrderWorklist.empty());
800 }
801
802 return PreOrderLoops;
803}
804
805template <class BlockT, class LoopT>
807 LoopT *B) const {
808 if (!A || !B)
809 return nullptr;
810
811 // If loops A and B have different depth replace them with parent loop
812 // until they have the same depth.
813 unsigned DepthA = A->getLoopDepth(), DepthB = B->getLoopDepth();
814 for (; DepthA > DepthB; --DepthA)
815 A = A->getParentLoop();
816 for (; DepthB > DepthA; --DepthB)
817 B = B->getParentLoop();
818
819 // Loops A and B are at same depth but may be disjoint, replace them with
820 // parent loops until we find loop that contains both or we run out of
821 // parent loops.
822 while (A != B) {
823 A = A->getParentLoop();
824 B = B->getParentLoop();
825 }
826
827 return A;
828}
829
830template <class BlockT, class LoopT>
832 BlockT *B) const {
834}
835
836// Debugging
837template <class BlockT, class LoopT>
839 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
840 TopLevelLoops[i]->print(OS);
841}
842
843template <typename T>
844bool compareVectors(std::vector<T> &BB1, std::vector<T> &BB2) {
845 llvm::sort(BB1);
846 llvm::sort(BB2);
847 return BB1 == BB2;
849
850template <class BlockT, class LoopT>
853 const LoopT &L) {
854 LoopHeaders[L.getHeader()] = &L;
855 for (LoopT *SL : L)
856 addInnerLoopsToHeadersMap(LoopHeaders, LI, *SL);
857}
859#ifndef NDEBUG
860template <class BlockT, class LoopT>
861static void compareLoops(const LoopT *L, const LoopT *OtherL,
862 DenseMap<BlockT *, const LoopT *> &OtherLoopHeaders) {
863 BlockT *H = L->getHeader();
864 BlockT *OtherH = OtherL->getHeader();
865 assert(H == OtherH &&
866 "Mismatched headers even though found in the same map entry!");
867
868 assert(L->getLoopDepth() == OtherL->getLoopDepth() &&
869 "Mismatched loop depth!");
870 const LoopT *ParentL = L, *OtherParentL = OtherL;
871 do {
872 assert(ParentL->getHeader() == OtherParentL->getHeader() &&
873 "Mismatched parent loop headers!");
874 ParentL = ParentL->getParentLoop();
875 OtherParentL = OtherParentL->getParentLoop();
876 } while (ParentL);
877
878 for (const LoopT *SubL : *L) {
879 BlockT *SubH = SubL->getHeader();
880 const LoopT *OtherSubL = OtherLoopHeaders.lookup(SubH);
881 assert(OtherSubL && "Inner loop is missing in computed loop info!");
882 OtherLoopHeaders.erase(SubH);
883 compareLoops(SubL, OtherSubL, OtherLoopHeaders);
884 }
885
886 std::vector<BlockT *> BBs = L->getBlocks();
887 std::vector<BlockT *> OtherBBs = OtherL->getBlocks();
888 assert(compareVectors(BBs, OtherBBs) &&
889 "Mismatched basic blocks in the loops!");
890}
891#endif
892
893template <class BlockT, class LoopT>
896 for (iterator I = begin(), E = end(); I != E; ++I) {
897 assert((*I)->isOutermost() && "Top-level loop has a parent!");
898 (*I)->verifyLoopNest(&Loops);
899 }
900
901// Verify that blocks are mapped to valid loops.
902#ifndef NDEBUG
903 // Every loop must point back at this LoopInfo (see resetLoopInfoOwners).
904 for (const LoopT *L : Loops)
905 assert(L->LI == this && "Loop has a stale owning-LoopInfo back-pointer");
906
907 // Recompute the innermost loop of each block from the loops' block lists,
908 // which are maintained independently of BBMap. Using contains() here would
909 // derive from BBMap itself and check nothing.
910 SmallVector<const LoopT *> Innermost(BBMap.size());
912 while (!Worklist.empty()) {
913 const LoopT *L = Worklist.pop_back_val();
914 // A loop is visited before its children, so a child's blocks overwrite the
915 // entries written by its ancestors.
916 for (const BlockT *BB : L->getBlocks()) {
918 assert(Number < Innermost.size() && "block missing from BBMap");
919 Innermost[Number] = L;
920 }
921 Worklist.append(L->begin(), L->end());
922 }
923
924 for (auto [Number, L] : enumerate(BBMap)) {
925 assert((!L || Loops.count(L)) && "orphaned loop");
926 assert(L == Innermost[Number] &&
927 "BBMap should point to the innermost loop containing the block");
928 }
929
930 // Recompute LoopInfo to verify loops structure.
931 LoopInfoBase<BlockT, LoopT> OtherLI;
932 OtherLI.analyze(ParentPtr);
933
934 // Build a map we can use to move from our LI to the computed one. This
935 // allows us to ignore the particular order in any layer of the loop forest
936 // while still comparing the structure.
937 DenseMap<BlockT *, const LoopT *> OtherLoopHeaders;
938 for (LoopT *L : OtherLI)
939 addInnerLoopsToHeadersMap(OtherLoopHeaders, OtherLI, *L);
940
941 // Walk the top level loops and ensure there is a corresponding top-level
942 // loop in the computed version and then recursively compare those loop
943 // nests.
944 for (LoopT *L : *this) {
945 BlockT *Header = L->getHeader();
946 const LoopT *OtherL = OtherLoopHeaders.lookup(Header);
947 assert(OtherL && "Top level loop is missing in computed loop info!");
948 // Now that we've matched this loop, erase its header from the map.
949 OtherLoopHeaders.erase(Header);
950 // And recursively compare these loops.
951 compareLoops(L, OtherL, OtherLoopHeaders);
952 }
953
954 // Any remaining entries in the map are loops which were found when computing
955 // a fresh LoopInfo but not present in the current one.
956 if (!OtherLoopHeaders.empty()) {
957 for (const auto &HeaderAndLoop : OtherLoopHeaders)
958 dbgs() << "Found new loop: " << *HeaderAndLoop.second << "\n";
959 llvm_unreachable("Found new loops when recomputing LoopInfo!");
960 }
961#endif
962}
963
964} // namespace llvm
965
966#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
#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.
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void updateDFSNumbers() const
updateDFSNumbers - Assign In and Out numbers to the nodes while walking dominator tree in dfs order.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
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.
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
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.
void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild)
This is used when splitting loops up.
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.
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.
size_type size() const
Definition SmallPtrSet.h:99
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.
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
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)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
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
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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)