LLVM 24.0.0git
GenericLoopInfo.h
Go to the documentation of this file.
1//===- GenericLoopInfo - Generic Loop Info for graphs -----------*- 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 file defines the LoopInfoBase class that is used to identify natural
10// loops and determine the loop depth of various nodes in a generic graph of
11// blocks. A natural loop has exactly one entry-point, which is called the
12// header. Note that natural loops may actually be several loops that share the
13// same header node.
14//
15// This analysis calculates the nesting structure of loops in a function. For
16// each natural loop identified, this analysis identifies natural loops
17// contained entirely within the loop and the basic blocks that make up the
18// loop.
19//
20// It can calculate on the fly various bits of information, for example:
21//
22// * whether there is a preheader for the loop
23// * the number of back edges to the header
24// * whether or not a particular block branches out of the loop
25// * the successor blocks of the loop
26// * the loop depth
27// * etc...
28//
29// Note that this analysis specifically identifies *Loops* not cycles or SCCs
30// in the graph. There can be strongly connected components in the graph which
31// this analysis will not recognize and that will not be represented by a Loop
32// instance. In particular, a Loop might be inside such a non-loop SCC, or a
33// non-loop SCC might contain a sub-SCC which is a Loop.
34//
35// For an overview of terminology used in this API (and thus all of our loop
36// analyses or transforms), see docs/LoopTerminology.md.
37//
38//===----------------------------------------------------------------------===//
39
40#ifndef LLVM_SUPPORT_GENERICLOOPINFO_H
41#define LLVM_SUPPORT_GENERICLOOPINFO_H
42
43#include "llvm/ADT/DenseSet.h"
45#include "llvm/ADT/STLExtras.h"
49
50namespace llvm {
51
52template <class N, class M> class LoopInfoBase;
53template <class N, class M> class LoopBase;
54
55//===----------------------------------------------------------------------===//
56/// Instances of this class are used to represent loops that are detected in the
57/// flow graph.
58///
59template <class BlockT, class LoopT> class LoopBase {
60 LoopT *ParentLoop;
61 // Loops contained entirely within this one.
62 std::vector<LoopT *> SubLoops;
63
64 // The list of blocks in this loop; first entry is the header. Either borrows
65 // a slice of the owning LoopInfo's BlockLayout, marked by the
66 // BorrowedCapacity sentinel, or is a private allocation of BlockCapacity
67 // slots from its allocator.
68 //
69 // Until analyze()'s layout carve runs, PendingHeader stashes the loop header
70 // (see pendingHeader()).
71 union {
73 BlockT **BlockData = nullptr;
74 };
75 unsigned BlockLen = 0;
76 unsigned BlockCapacity = 0;
77
78 static constexpr unsigned BorrowedCapacity = -1u;
79
80 // The LoopInfo that owns this loop. Used to answer contains(BlockT *) from
81 // the central block-to-loop map.
82 LoopInfoBase<BlockT, LoopT> *LI = nullptr;
83
84#if LLVM_ENABLE_ABI_BREAKING_CHECKS
85 /// Indicator that this loop is no longer a valid loop.
86 bool IsInvalid = false;
87#endif
88
89 LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
91 operator=(const LoopBase<BlockT, LoopT> &) = delete;
92
93public:
94 /// Return the nesting level of this loop. An outer-most loop has depth 1,
95 /// for consistency with loop depth values used for basic blocks, where depth
96 /// 0 is used for blocks not inside any loops.
97 unsigned getLoopDepth() const {
98 assert(!isInvalid() && "Loop not in a valid state!");
99 unsigned D = 1;
100 for (const LoopT *CurLoop = ParentLoop; CurLoop;
101 CurLoop = CurLoop->ParentLoop)
102 ++D;
103 return D;
104 }
105 BlockT *getHeader() const { return getBlocks().front(); }
106 /// Return the parent loop if it exists or nullptr for top
107 /// level loops.
108
109 /// A loop is either top-level in a function (that is, it is not
110 /// contained in any other loop) or it is entirely enclosed in
111 /// some other loop.
112 /// If a loop is top-level, it has no parent, otherwise its
113 /// parent is the innermost loop in which it is enclosed.
114 LoopT *getParentLoop() const { return ParentLoop; }
115
116 /// Get the outermost loop in which this loop is contained.
117 /// This may be the loop itself, if it already is the outermost loop.
118 const LoopT *getOutermostLoop() const {
119 const LoopT *L = static_cast<const LoopT *>(this);
120 while (L->ParentLoop)
121 L = L->ParentLoop;
122 return L;
123 }
124
126 LoopT *L = static_cast<LoopT *>(this);
127 while (L->ParentLoop)
128 L = L->ParentLoop;
129 return L;
130 }
131
132 /// This is a raw interface for bypassing addChildLoop.
133 void setParentLoop(LoopT *L) {
134 assert(!isInvalid() && "Loop not in a valid state!");
135 ParentLoop = L;
136 }
137
138 /// Return true if the specified loop is contained within this loop.
139 ///
140 /// This walks the parent chain and is O(depth). Deep nesting is not a
141 /// performance target (yet).
142 bool contains(const LoopT *L) const {
143 assert(!isInvalid() && "Loop not in a valid state!");
144 for (;;) {
145 if (L == this)
146 return true;
147 if (!L)
148 return false;
149 L = L->getParentLoop();
150 }
151 }
152
153 /// Return true if the specified basic block is in this loop, using LoopInfo's
154 /// block-to-loop map.
155 ///
156 /// This is only valid when that map agrees with the block lists. Avoid when
157 /// the loop nest is being restructured, when a block may appear in a loop's
158 /// block list before it is mapped to that loop. Code in such a transient
159 /// state must scan getBlocks() directly instead.
160 bool contains(const BlockT *BB) const {
161 assert(!isInvalid() && "Loop not in a valid state!");
162 // A block from another function is never contained, and its number would
163 // otherwise index this function's map.
164 if (BB->getParent() != LI->ParentPtr)
165 return false;
166 return contains(LI->lookupLoopFor(BB));
167 }
168
169 /// Return true if the specified instruction is in this loop.
170 template <class InstT> bool contains(const InstT *Inst) const {
171 return contains(Inst->getParent());
172 }
173
174 /// Return the loops contained entirely within this loop.
175 const std::vector<LoopT *> &getSubLoops() const {
176 assert(!isInvalid() && "Loop not in a valid state!");
177 return SubLoops;
178 }
179 using iterator = typename std::vector<LoopT *>::const_iterator;
181 typename std::vector<LoopT *>::const_reverse_iterator;
182 iterator begin() const { return getSubLoops().begin(); }
183 iterator end() const { return getSubLoops().end(); }
184 reverse_iterator rbegin() const { return getSubLoops().rbegin(); }
185 reverse_iterator rend() const { return getSubLoops().rend(); }
186
187 // LoopInfo does not detect irreducible control flow, just natural
188 // loops. That is, it is possible that there is cyclic control
189 // flow within the "innermost loop" or around the "outermost
190 // loop".
191
192 /// Return true if the loop does not contain any (natural) loops.
193 bool isInnermost() const { return getSubLoops().empty(); }
194 /// Return true if the loop does not have a parent (natural) loop
195 // (i.e. it is outermost, which is the same as top-level).
196 bool isOutermost() const { return getParentLoop() == nullptr; }
197
198 /// Get a list of the basic blocks which make up this loop.
200 assert(!isInvalid() && "Loop not in a valid state!");
201 return ArrayRef<BlockT *>(BlockData, BlockLen);
202 }
204 block_iterator block_begin() const { return getBlocks().begin(); }
205 block_iterator block_end() const { return getBlocks().end(); }
207 assert(!isInvalid() && "Loop not in a valid state!");
208 return make_range(block_begin(), block_end());
209 }
210
211 /// Get the number of blocks in this loop in constant time.
212 /// Invalidate the loop, indicating that it is no longer a loop.
213 unsigned getNumBlocks() const {
214 assert(!isInvalid() && "Loop not in a valid state!");
215 return BlockLen;
216 }
217
218 /// Return true if this loop is no longer valid. The only valid use of this
219 /// helper is "assert(L.isInvalid())" or equivalent, since IsInvalid is set to
220 /// true by the destructor. In other words, if this accessor returns true,
221 /// the caller has already triggered UB by calling this accessor; and so it
222 /// can only be called in a context where a return value of true indicates a
223 /// programmer error.
224 bool isInvalid() const {
225#if LLVM_ENABLE_ABI_BREAKING_CHECKS
226 return IsInvalid;
227#else
228 return false;
229#endif
230 }
231
232 /// True if terminator in the block can branch to another block that is
233 /// outside of the current loop. \p BB must be inside the loop.
234 bool isLoopExiting(const BlockT *BB) const {
235 assert(!isInvalid() && "Loop not in a valid state!");
236 assert(contains(BB) && "Exiting block must be part of the loop");
237 for (const auto *Succ : children<const BlockT *>(BB)) {
238 if (!contains(Succ))
239 return true;
240 }
241 return false;
242 }
243
244 /// Returns true if \p BB is a loop-latch.
245 /// A latch block is a block that contains a branch back to the header.
246 /// This function is useful when there are multiple latches in a loop
247 /// because \fn getLoopLatch will return nullptr in that case.
248 bool isLoopLatch(const BlockT *BB) const {
249 assert(!isInvalid() && "Loop not in a valid state!");
250 assert(contains(BB) && "block does not belong to the loop");
252 }
253
254 /// Calculate the number of back edges to the loop header.
255 unsigned getNumBackEdges() const {
256 assert(!isInvalid() && "Loop not in a valid state!");
258 [&](BlockT *Pred) { return contains(Pred); });
259 }
260
261 //===--------------------------------------------------------------------===//
262 // APIs for simple analysis of the loop.
263 //
264 // Note that all of these methods can fail on general loops (ie, there may not
265 // be a preheader, etc). For best success, the loop simplification and
266 // induction variable canonicalization pass should be used to normalize loops
267 // for easy analysis. These methods assume canonical loops.
268
269 /// Return all blocks inside the loop that have successors outside of the
270 /// loop. These are the blocks _inside of the current loop_ which branch out.
271 /// The returned list is always unique.
272 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
273
274 /// If getExitingBlocks would return exactly one block, return that block.
275 /// Otherwise return null.
276 BlockT *getExitingBlock() const;
277
278 /// Return all of the successor blocks of this loop. These are the blocks
279 /// _outside of the current loop_ which are branched to.
280 void getExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
281
282 /// If getExitBlocks would return exactly one block, return that block.
283 /// Otherwise return null.
284 BlockT *getExitBlock() const;
285
286 /// Return true if no exit block for the loop has a predecessor that is
287 /// outside the loop.
288 bool hasDedicatedExits() const;
289
290 /// Return all unique successor blocks of this loop.
291 /// These are the blocks _outside of the current loop_ which are branched to.
292 void getUniqueExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
293
294 /// Return all unique successor blocks of this loop except successors from
295 /// Latch block are not considered. If the exit comes from Latch has also
296 /// non Latch predecessor in a loop it will be added to ExitBlocks.
297 /// These are the blocks _outside of the current loop_ which are branched to.
299
300 /// If getUniqueExitBlocks would return exactly one block, return that block.
301 /// Otherwise return null.
302 BlockT *getUniqueExitBlock() const;
303
304 /// If there is a preheader for this loop, return it. A loop has a preheader
305 /// if there is only one edge to the header of the loop from outside of the
306 /// loop. If this is the case, the block branching to the header of the loop
307 /// is the preheader node.
308 ///
309 /// This method returns null if there is no preheader for the loop.
310 BlockT *getLoopPreheader() const;
311
312 /// If the given loop's header has exactly one unique predecessor outside the
313 /// loop, return it. Otherwise return null.
314 /// This is less strict that the loop "preheader" concept, which requires
315 /// the predecessor to have exactly one successor.
316 BlockT *getLoopPredecessor() const;
317
318 /// If there is a single latch block for this loop, return it.
319 /// A latch block is a block that contains a branch back to the header.
320 BlockT *getLoopLatch() const;
321
322 /// Return all loop latch blocks of this loop. A latch block is a block that
323 /// contains a branch back to the header.
324 void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
325 assert(!isInvalid() && "Loop not in a valid state!");
326 BlockT *H = getHeader();
327 for (const auto Pred : inverse_children<BlockT *>(H))
328 if (contains(Pred))
329 LoopLatches.push_back(Pred);
330 }
331
332 /// Return all inner loops in the loop nest rooted by the loop in preorder,
333 /// with siblings in forward program order.
334 template <class Type>
335 static void getInnerLoopsInPreorder(const LoopT &L,
336 SmallVectorImpl<Type> &PreOrderLoops) {
337 SmallVector<LoopT *, 4> PreOrderWorklist;
338 PreOrderWorklist.append(L.rbegin(), L.rend());
339
340 while (!PreOrderWorklist.empty()) {
341 LoopT *L = PreOrderWorklist.pop_back_val();
342 // Sub-loops are stored in forward program order, but will process the
343 // worklist backwards so append them in reverse order.
344 PreOrderWorklist.append(L->rbegin(), L->rend());
345 PreOrderLoops.push_back(L);
346 }
347 }
348
349 /// Return all loops in the loop nest rooted by the loop in preorder, with
350 /// siblings in forward program order.
352 SmallVector<const LoopT *, 4> PreOrderLoops;
353 const LoopT *CurLoop = static_cast<const LoopT *>(this);
354 PreOrderLoops.push_back(CurLoop);
355 getInnerLoopsInPreorder(*CurLoop, PreOrderLoops);
356 return PreOrderLoops;
357 }
359 SmallVector<LoopT *, 4> PreOrderLoops;
360 LoopT *CurLoop = static_cast<LoopT *>(this);
361 PreOrderLoops.push_back(CurLoop);
362 getInnerLoopsInPreorder(*CurLoop, PreOrderLoops);
363 return PreOrderLoops;
364 }
365
366 //===--------------------------------------------------------------------===//
367 // APIs for updating loop information after changing the CFG
368 //
369
370 /// This method is used by other analyses to update loop information.
371 /// NewBB is set to be a new member of the current loop.
372 /// Because of this, it is added as a member of all parent loops, and is added
373 /// to the specified LoopInfo object as being in the current basic block. It
374 /// is not valid to replace the loop header with this method.
375 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
376
377 /// This is used when splitting loops up. It replaces the OldChild entry in
378 /// our children list with NewChild, and updates the parent pointer of
379 /// OldChild to be null and the NewChild to be this loop.
380 /// This updates the loop depth of the new child.
381 void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
382
383 /// Add the specified loop to be a child of this loop.
384 /// This updates the loop depth of the new child.
385 void addChildLoop(LoopT *NewChild) {
386 assert(!isInvalid() && "Loop not in a valid state!");
387 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
388 NewChild->ParentLoop = static_cast<LoopT *>(this);
389 SubLoops.push_back(NewChild);
390 }
391
392 /// This removes the specified child from being a subloop of this loop. The
393 /// loop is not deleted, as it will presumably be inserted into another loop.
395 assert(!isInvalid() && "Loop not in a valid state!");
396 assert(I != SubLoops.end() && "Cannot remove end iterator!");
397 LoopT *Child = *I;
398 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
399 SubLoops.erase(SubLoops.begin() + (I - begin()));
400 Child->ParentLoop = nullptr;
401 return Child;
402 }
403
404 /// This removes the specified child from being a subloop of this loop. The
405 /// loop is not deleted, as it will presumably be inserted into another loop.
406 LoopT *removeChildLoop(LoopT *Child) {
407 return removeChildLoop(llvm::find(*this, Child));
408 }
409
410 /// This adds a basic block directly to the basic block list.
411 /// This should only be used by transformations that create new loops. Other
412 /// transformations should use addBasicBlockToLoop.
413 void addBlockEntry(BlockT *BB) {
414 assert(!isInvalid() && "Loop not in a valid state!");
415 // A borrowed slice or a full private allocation grows into fresh private
416 // storage before appending.
417 if (BlockCapacity == BorrowedCapacity || BlockLen == BlockCapacity)
418 LI->reallocBlocks(*static_cast<LoopT *>(this),
419 std::max(2 * BlockLen, 4u));
420 BlockData[BlockLen++] = BB;
421 }
422
423 /// interface to do reserve() for Blocks
424 void reserveBlocks(unsigned Size) {
425 assert(!isInvalid() && "Loop not in a valid state!");
426 if (BlockCapacity < Size)
427 LI->reallocBlocks(*static_cast<LoopT *>(this), Size);
428 }
429
430 /// This method is used to move BB (which must be part of this loop) to be the
431 /// loop header of the loop (the block that dominates all others).
432 void moveToHeader(BlockT *BB) {
433 assert(!isInvalid() && "Loop not in a valid state!");
434 if (BlockData[0] == BB)
435 return;
436 LI->materializeBlocks(*static_cast<LoopT *>(this));
437 for (unsigned i = 0;; ++i) {
438 assert(i != BlockLen && "Loop does not contain BB!");
439 if (BlockData[i] == BB) {
440 BlockData[i] = BlockData[0];
441 BlockData[0] = BB;
442 return;
443 }
444 }
445 }
446
447 /// This removes the specified basic block from the current loop, updating the
448 /// Blocks as appropriate. This does not update the mapping in the LoopInfo
449 /// class.
450 void removeBlockFromLoop(BlockT *BB) {
451 assert(!isInvalid() && "Loop not in a valid state!");
452 LI->materializeBlocks(*static_cast<LoopT *>(this));
453 MutableArrayRef<BlockT *> Blocks(BlockData, BlockLen);
454 auto *I = llvm::find(Blocks, BB);
455 assert(I != Blocks.end() && "N is not in this list!");
456 std::move(I + 1, Blocks.end(), I);
457 --BlockLen;
458 }
459
460 /// Verify loop structure
461 void verifyLoop() const;
462
463 /// Verify loop structure of this loop and all nested loops.
465
466 /// Returns true if the loop is annotated parallel.
467 ///
468 /// Derived classes can override this method using static template
469 /// polymorphism.
470 bool isAnnotatedParallel() const { return false; }
471
472 /// Print loop with all the BBs inside it.
473 void print(raw_ostream &OS, bool Verbose = false, bool PrintNested = true,
474 unsigned Depth = 0) const;
475
476protected:
477 friend class LoopInfoBase<BlockT, LoopT>;
478
479 /// This creates an empty loop.
480 LoopBase() : ParentLoop(nullptr) {}
481
482 // Since loop passes like SCEV are allowed to key analysis results off of
483 // `Loop` pointers, we cannot re-use pointers within a loop pass manager.
484 // This means loop passes should not be `delete` ing `Loop` objects directly
485 // (and risk a later `Loop` allocation re-using the address of a previous one)
486 // but should be using LoopInfo::markAsRemoved, which keeps around the `Loop`
487 // pointer till the end of the lifetime of the `LoopInfo` object.
488 //
489 // To make it easier to follow this rule, we mark the destructor as
490 // non-public.
492 for (auto *SubLoop : SubLoops)
493 SubLoop->~LoopT();
494
495#if LLVM_ENABLE_ABI_BREAKING_CHECKS
496 IsInvalid = true;
497#endif
498 SubLoops.clear();
499 // The block storage is reclaimed by the owning LoopInfo.
500 BlockData = nullptr;
501 BlockLen = 0;
502 BlockCapacity = 0;
503 ParentLoop = nullptr;
504 }
505};
506
507template <class BlockT, class LoopT>
509 Loop.print(OS);
510 return OS;
511}
512
513//===----------------------------------------------------------------------===//
514/// This class builds and contains all of the top-level loop
515/// structures in the specified function.
516///
517
518template <class BlockT, class LoopT> class LoopInfoBase {
520 "LoopInfo requires GraphTraits<BlockT *>::getNumber (see "
521 "GraphHasNodeNumbers)");
522
523 // Mapping of each block, indexed by its number, to the innermost loop it
524 // occurs in (or null).
526
527 using ParentT = decltype(std::declval<BlockT *>()->getParent());
528 ParentT ParentPtr = nullptr;
529 unsigned BlockNumberEpoch;
530
531 std::vector<LoopT *> TopLevelLoops;
532
533 // Shared reverse postorder layout of the in-loop blocks. Each initial loop is
534 // a slice of this array, subloop slices nested inside their parent's.
535 std::unique_ptr<BlockT *[]> BlockLayout;
536
537 BumpPtrAllocator LoopAllocator;
538
539 friend class LoopBase<BlockT, LoopT>;
540 friend class LoopInfo;
541
542 void operator=(const LoopInfoBase &) = delete;
543 LoopInfoBase(const LoopInfoBase &) = delete;
544
545public:
546 LoopInfoBase() = default;
548
549 LoopInfoBase(LoopInfoBase &&Arg)
550 : BBMap(std::move(Arg.BBMap)),
551 TopLevelLoops(std::move(Arg.TopLevelLoops)),
552 BlockLayout(std::move(Arg.BlockLayout)),
553 LoopAllocator(std::move(Arg.LoopAllocator)) {
554 ParentPtr = Arg.ParentPtr;
555 BlockNumberEpoch = Arg.BlockNumberEpoch;
556 resetLoopInfoOwners();
557 // We have to clear the arguments top level loops as we've taken ownership.
558 Arg.TopLevelLoops.clear();
559 }
560 LoopInfoBase &operator=(LoopInfoBase &&RHS) {
561 BBMap = std::move(RHS.BBMap);
562 ParentPtr = RHS.ParentPtr;
563 BlockNumberEpoch = RHS.BlockNumberEpoch;
564
565 for (auto *L : TopLevelLoops)
566 L->~LoopT();
567
568 TopLevelLoops = std::move(RHS.TopLevelLoops);
569 BlockLayout = std::move(RHS.BlockLayout);
570 LoopAllocator = std::move(RHS.LoopAllocator);
571 resetLoopInfoOwners();
572 RHS.TopLevelLoops.clear();
573 return *this;
574 }
575
577 BBMap.clear();
578
579 for (auto *L : TopLevelLoops)
580 L->~LoopT();
581 TopLevelLoops.clear();
582 BlockLayout.reset();
583 LoopAllocator.Reset();
584 }
585
586 LoopT *AllocateLoop() {
587 LoopT *Storage = LoopAllocator.Allocate<LoopT>();
588 LoopT *L = new (Storage) LoopT();
589 L->LI = this;
590 return L;
591 }
592
593 /// iterator/begin/end - The interface to the top-level loops in the current
594 /// function.
595 ///
596 using iterator = typename std::vector<LoopT *>::const_iterator;
598 typename std::vector<LoopT *>::const_reverse_iterator;
599 iterator begin() const { return TopLevelLoops.begin(); }
600 iterator end() const { return TopLevelLoops.end(); }
601 reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
602 reverse_iterator rend() const { return TopLevelLoops.rend(); }
603 bool empty() const { return TopLevelLoops.empty(); }
604
605 /// Return all of the loops in the function in preorder across the loop
606 /// nests, with siblings in forward program order.
607 ///
608 /// Note that because loops form a forest of trees, preorder is equivalent to
609 /// reverse postorder.
611
612 /// Return all of the loops in the function in preorder across the loop
613 /// nests, with siblings in *reverse* program order.
614 ///
615 /// Note that because loops form a forest of trees, preorder is equivalent to
616 /// reverse postorder.
617 ///
618 /// Also note that this is *not* a reverse preorder. Only the siblings are in
619 /// reverse program order.
621
622private:
623 // Point every loop's owning-LoopInfo back-pointer at this object. Called
624 // after a move.
625 void resetLoopInfoOwners() {
626 SmallVector<LoopT *, 8> Worklist(TopLevelLoops.begin(),
627 TopLevelLoops.end());
628 while (!Worklist.empty()) {
629 LoopT *L = Worklist.pop_back_val();
630 L->LI = this;
631 Worklist.append(L->begin(), L->end());
632 }
633 }
634
635 /// Verify that used block numbers are still valid.
636 void
637 verifyBlockNumberEpoch(const std::remove_pointer_t<ParentT> *BBParent) const {
638 assert(ParentPtr == BBParent &&
639 "loop info queried with block of other function");
640 assert(BlockNumberEpoch ==
641 GraphTraits<ParentT>::getNumberEpoch(ParentPtr) &&
642 "loop info used with outdated block numbers");
643 }
644
645 // Look up BB's innermost loop in the block-to-loop map; BB must belong to
646 // this function.
647 LoopT *lookupLoopFor(const BlockT *BB) const {
648 unsigned Number = GraphTraits<const BlockT *>::getNumber(BB);
649 return Number < BBMap.size() ? BBMap[Number] : nullptr;
650 }
651
652 /// AllocateLoop for analyze(): stash \p Header (see pendingHeader).
653 /// getHeader() only works once the layout carve has replaced the stash with
654 /// the loop's block list.
655 LoopT *allocateLoop(BlockT *Header) {
656 LoopT *L = AllocateLoop();
657 L->PendingHeader = Header;
658 return L;
659 }
660
661 /// The header of a loop under construction, stashed until the layout carve
662 /// builds the block list.
663 static BlockT *pendingHeader(const LoopT *L) { return L->PendingHeader; }
664
665 /// True if \p L borrows its block list from BlockLayout.
666 static bool hasBorrowedBlocks(const LoopT &L) {
667 return L.BlockCapacity == LoopT::BorrowedCapacity;
668 }
669
670 /// Replace \p L's block list with a private allocation of NewCapacity
671 /// slots. The old storage is abandoned in place so slices sharing it stay
672 /// intact; it is reclaimed when this LoopInfo is cleared.
673 void reallocBlocks(LoopT &L, unsigned NewCapacity) {
674 assert(NewCapacity >= L.BlockLen && "capacity below size");
675 BlockT **New = LoopAllocator.Allocate<BlockT *>(NewCapacity);
676 llvm::copy(L.getBlocks(), New);
677 L.BlockData = New;
678 L.BlockCapacity = NewCapacity;
679 }
680
681 /// Copy \p L's borrowed block list into private storage before a mutation.
682 void materializeBlocks(LoopT &L) {
683 if (hasBorrowedBlocks(L))
684 reallocBlocks(L, L.BlockLen);
685 }
686
687public:
688 /// Return the inner most loop that BB lives in. If a basic block is in no
689 /// loop (for example the entry node), null is returned.
690 LoopT *getLoopFor(const BlockT *BB) const {
691 verifyBlockNumberEpoch(BB->getParent());
692 return lookupLoopFor(BB);
693 }
694
695 /// Same as getLoopFor.
696 const LoopT *operator[](const BlockT *BB) const { return getLoopFor(BB); }
697
698 /// Return the loop nesting level of the specified block. A depth of 0 means
699 /// the block is not inside any loop.
700 unsigned getLoopDepth(const BlockT *BB) const {
701 const LoopT *L = getLoopFor(BB);
702 return L ? L->getLoopDepth() : 0;
703 }
704
705 /// Edge type.
706 using Edge = std::pair<BlockT *, BlockT *>;
707
708 /// Return true if \p L does not have any exit blocks.
709 bool hasNoExitBlocks(const LoopT &L) const;
710
711 /// Return all pairs of (_inside_block_,_outside_block_).
712 void getExitEdges(const LoopT &L, SmallVectorImpl<Edge> &ExitEdges) const;
713
714 /// Return the unique exit block for the latch of \p L, or null if there are
715 /// multiple different exit blocks or the latch is not exiting.
716 BlockT *getUniqueLatchExitBlock(const LoopT &L) const;
717
718 /// Remove every block satisfying \p Pred from \p L's block list, preserving
719 /// the order of the remaining blocks. Only \p L itself is updated, not its
720 /// ancestors or descendants, and not the block-to-loop mapping.
721 template <typename PredicateT>
722 void removeBlocksIf(LoopT &L, PredicateT Pred) {
723 materializeBlocks(L);
724 L.BlockLen = llvm::remove_if(
725 MutableArrayRef<BlockT *>(L.BlockData, L.BlockLen), Pred) -
726 L.BlockData;
727 }
728
729 /// Remove every block satisfying \p Pred from \p Start and each of its
730 /// ancestors up to but not including \p Stop, which must be null or an
731 /// ancestor of \p Start; a null \p Stop walks to the top level.
732 template <typename PredicateT>
733 void removeBlocksFromLoopAndAncestors(LoopT *Start, LoopT *Stop,
734 PredicateT Pred) {
735 for (LoopT *Cur = Start; Cur != Stop; Cur = Cur->getParentLoop())
736 removeBlocksIf(*Cur, Pred);
737 }
738
739 /// Detach and return the children of \p Parent (the top-level loops if
740 /// \p Parent is null) that satisfy \p Pred, clearing their parent pointers.
741 /// Both the remaining and the returned children keep their relative order.
742 template <typename PredicateT>
744 std::vector<LoopT *> &List = Parent ? Parent->SubLoops : TopLevelLoops;
746 llvm::erase_if(List, [&](LoopT *Child) {
747 if (!Pred(Child))
748 return false;
749 Child->ParentLoop = nullptr;
750 Taken.push_back(Child);
751 return true;
752 });
753 return Taken;
754 }
755
756 /// \brief Find the innermost loop containing both given loops.
757 ///
758 /// \returns the innermost loop containing both \p A and \p B
759 /// or nullptr if there is no such loop.
760 LoopT *getSmallestCommonLoop(LoopT *A, LoopT *B) const;
761 /// \brief Find the innermost loop containing both given blocks.
762 ///
763 /// \returns the innermost loop containing both \p A and \p B
764 /// or nullptr if there is no such loop.
765 LoopT *getSmallestCommonLoop(BlockT *A, BlockT *B) const;
766
767 // True if the block is a loop header node
768 bool isLoopHeader(const BlockT *BB) const {
769 const LoopT *L = getLoopFor(BB);
770 return L && L->getHeader() == BB;
771 }
772
773 /// Return the top-level loops.
774 const std::vector<LoopT *> &getTopLevelLoops() const { return TopLevelLoops; }
775
776 /// This removes the specified top-level loop from this loop info object.
777 /// The loop is not deleted, as it will presumably be inserted into
778 /// another loop.
780 assert(I != end() && "Cannot remove end iterator!");
781 LoopT *L = *I;
782 assert(L->isOutermost() && "Not a top-level loop!");
783 TopLevelLoops.erase(TopLevelLoops.begin() + (I - begin()));
784 return L;
785 }
786
787 /// Change the top-level loop that contains BB to the specified loop.
788 /// This should be used by transformations that restructure the loop hierarchy
789 /// tree.
790 void changeLoopFor(const BlockT *BB, LoopT *L) {
791 verifyBlockNumberEpoch(BB->getParent());
793 if (Number >= BBMap.size()) {
794 unsigned Max =
795 GraphTraits<decltype(BB->getParent())>::getMaxNumber(BB->getParent());
796 assert(Number < Max);
797 BBMap.resize(Max);
798 }
799 BBMap[Number] = L;
800 }
801
802 /// Replace the specified loop in the top-level loops list with the indicated
803 /// loop.
804 void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop) {
805 auto I = find(TopLevelLoops, OldLoop);
806 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
807 *I = NewLoop;
808 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
809 "Loops already embedded into a subloop!");
810 }
811
812 /// This adds the specified loop to the collection of top-level loops.
813 void addTopLevelLoop(LoopT *New) {
814 assert(New->isOutermost() && "Loop already in subloop!");
815 TopLevelLoops.push_back(New);
816 }
817
818 /// This method completely removes BB from all data structures,
819 /// including all of the Loop objects it is nested in and our mapping from
820 /// BasicBlocks to loops.
821 void removeBlock(BlockT *BB) {
822 verifyBlockNumberEpoch(BB->getParent());
824 if (Number >= BBMap.size())
825 return;
826
827 for (LoopT *L = BBMap[Number]; L; L = L->getParentLoop())
828 L->removeBlockFromLoop(BB);
829 BBMap[Number] = nullptr;
830 }
831
832 // Internals
833
834 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
835 const LoopT *ParentLoop) {
836 if (!SubLoop)
837 return true;
838 if (SubLoop == ParentLoop)
839 return false;
840 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
841 }
842
843 /// Create the loop forest for a function. A dominator tree is needed only for
844 /// an irreducible CFG, where dominance reduces a loop that an edge re-enters
845 /// to the natural loop of its header's backedges.
846 ///@{
847 /// Build a dominator tree if one is needed.
848 void analyze(ParentT F);
849 /// Call \p GetDomTree if a dominator tree is needed.
850 void
851 analyze(ParentT F,
852 function_ref<const DominatorTreeBase<BlockT, false> &()> GetDomTree);
853 /// Analyze the function \p DomTree describes.
855 ///@}
856
857 // Debugging
858 void print(raw_ostream &OS) const;
859
860 void verify() const;
861
862 /// Destroy a loop that has been removed from the `LoopInfo` nest.
863 ///
864 /// This runs the destructor of the loop object making it invalid to
865 /// reference afterward. The memory is retained so that the *pointer* to the
866 /// loop remains valid.
867 ///
868 /// The caller is responsible for removing this loop from the loop nest and
869 /// otherwise disconnecting it from the broader `LoopInfo` data structures.
870 /// Callers that don't naturally handle this themselves should probably call
871 /// `erase' instead.
872 void destroy(LoopT *L) {
873 L->~LoopT();
874
875 // Since LoopAllocator is a BumpPtrAllocator, this Deallocate only poisons
876 // \c L, but the pointer remains valid for non-dereferencing uses.
877 LoopAllocator.Deallocate(L);
878 }
879};
880
881} // namespace llvm
882
883#endif // LLVM_SUPPORT_GENERICLOOPINFO_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
This file defines a set of templates that efficiently compute a dominator tree over a generic graph.
Hexagon Hardware Loops
#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 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.
This file defines generic set operations that may be used on set's of different types,...
Value * RHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const_pointer const_iterator
Definition ArrayRef.h:48
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Core dominator tree base class.
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.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
static void getInnerLoopsInPreorder(const LoopT &L, SmallVectorImpl< Type > &PreOrderLoops)
Return all inner loops in the loop nest rooted by the loop in preorder, with siblings in forward prog...
typename std::vector< LoopT * >::const_iterator iterator
bool isOutermost() const
Return true if the loop does not have a parent (natural) loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
void reserveBlocks(unsigned Size)
interface to do reserve() for Blocks
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate.
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
bool contains(const InstT *Inst) const
Return true if the specified instruction is in 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.
SmallVector< LoopT *, 4 > getLoopsInPreorder()
typename std::vector< LoopT * >::const_reverse_iterator reverse_iterator
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
SmallVector< const LoopT *, 4 > getLoopsInPreorder() const
Return all loops in the loop nest rooted by the loop in preorder, with siblings in forward program or...
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
BlockT * getHeader() const
const LoopT * getOutermostLoop() const
Get the outermost loop in which this loop is contained.
void getLoopLatches(SmallVectorImpl< BlockT * > &LoopLatches) const
Return all loop latch blocks of this loop.
unsigned getLoopDepth() const
Return the nesting level of this loop.
LoopBase()
This creates an empty 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.
LoopT * removeChildLoop(LoopT *Child)
This removes the specified child from being a subloop of this loop.
iterator_range< block_iterator > blocks() const
block_iterator block_end() const
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 contains(const BlockT *BB) const
Return true if the specified basic block is in this loop, using LoopInfo's block-to-loop map.
bool isLoopLatch(const BlockT *BB) const
iterator end() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
reverse_iterator rbegin() 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< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
reverse_iterator rend() const
BlockT ** BlockData
BlockT * PendingHeader
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
LoopT * getOutermostLoop()
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
void setParentLoop(LoopT *L)
This is a raw interface for bypassing addChildLoop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
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.
block_iterator block_begin() const
void moveToHeader(BlockT *BB)
This method is used to move BB (which must be part of this loop) to be the loop header of the loop (t...
typename ArrayRef< BlockT * >::const_iterator block_iterator
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
This class builds and contains all of the top-level loop structures in the specified function.
const std::vector< LoopT * > & getTopLevelLoops() const
Return the top-level loops.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
void analyze(const DominatorTreeBase< BlockT, false > &DomTree)
Analyze the function DomTree describes.
bool hasNoExitBlocks(const LoopT &L) const
Return true if L does not have any exit blocks.
void removeBlocksFromLoopAndAncestors(LoopT *Start, LoopT *Stop, PredicateT Pred)
Remove every block satisfying Pred from Start and each of its ancestors up to but not including Stop,...
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
reverse_iterator rend() const
void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop)
Replace the specified loop in the top-level loops list with the indicated loop.
iterator end() const
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
LoopInfoBase(LoopInfoBase &&Arg)
const LoopT * operator[](const BlockT *BB) const
Same as getLoopFor.
void analyze(ParentT F, function_ref< const DominatorTreeBase< BlockT, false > &()> GetDomTree)
Call GetDomTree if a dominator tree is needed.
bool isLoopHeader(const BlockT *BB) const
LoopT * removeLoop(iterator I)
This removes the specified top-level loop from this loop info object.
LoopT * getSmallestCommonLoop(BlockT *A, BlockT *B) const
Find the innermost loop containing both given blocks.
LoopInfoBase()=default
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< Loop * >::const_iterator iterator
typename std::vector< Loop * >::const_reverse_iterator reverse_iterator
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
void analyze(ParentT F)
Create the loop forest for a function.
SmallVector< LoopT *, 4 > takeChildrenIf(LoopT *Parent, PredicateT Pred)
Detach and return the children of Parent (the top-level loops if Parent is null) that satisfy Pred,...
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).
static bool isNotAlreadyContainedIn(const LoopT *SubLoop, const LoopT *ParentLoop)
void removeBlocksIf(LoopT &L, PredicateT Pred)
Remove every block satisfying Pred from L's block list, preserving the order of the remaining blocks.
reverse_iterator rbegin() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
std::pair< BasicBlock *, BasicBlock * > Edge
LoopInfoBase & operator=(LoopInfoBase &&RHS)
void destroy(LoopT *L)
Destroy a loop that has been removed from the LoopInfo nest.
void changeLoopFor(const BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
iterator end() const
Definition ArrayRef.h:339
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
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
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr bool GraphHasNodeNumbers
Indicate whether a GraphTraits<NodeT>::getNumber() is supported.
auto remove_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1784
iterator_range< typename GraphTraits< Inverse< GraphType > >::ChildIteratorType > inverse_children(const typename GraphTraits< GraphType >::NodeRef &G)
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1885
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
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
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878