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;
54template <class N, class M> class PopulateLoopsDFS;
55
56//===----------------------------------------------------------------------===//
57/// Instances of this class are used to represent loops that are detected in the
58/// flow graph.
59///
60template <class BlockT, class LoopT> class LoopBase {
61 LoopT *ParentLoop;
62 // Loops contained entirely within this one.
63 std::vector<LoopT *> SubLoops;
64
65 // The list of blocks in this loop. First entry is the header node.
66 std::vector<BlockT *> Blocks;
67
69
70#if LLVM_ENABLE_ABI_BREAKING_CHECKS
71 /// Indicator that this loop is no longer a valid loop.
72 bool IsInvalid = false;
73#endif
74
75 LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
76 const LoopBase<BlockT, LoopT> &
77 operator=(const LoopBase<BlockT, LoopT> &) = delete;
78
79public:
80 /// Return the nesting level of this loop. An outer-most loop has depth 1,
81 /// for consistency with loop depth values used for basic blocks, where depth
82 /// 0 is used for blocks not inside any loops.
83 unsigned getLoopDepth() const {
84 assert(!isInvalid() && "Loop not in a valid state!");
85 unsigned D = 1;
86 for (const LoopT *CurLoop = ParentLoop; CurLoop;
87 CurLoop = CurLoop->ParentLoop)
88 ++D;
89 return D;
90 }
91 BlockT *getHeader() const { return getBlocks().front(); }
92 /// Return the parent loop if it exists or nullptr for top
93 /// level loops.
94
95 /// A loop is either top-level in a function (that is, it is not
96 /// contained in any other loop) or it is entirely enclosed in
97 /// some other loop.
98 /// If a loop is top-level, it has no parent, otherwise its
99 /// parent is the innermost loop in which it is enclosed.
100 LoopT *getParentLoop() const { return ParentLoop; }
101
102 /// Get the outermost loop in which this loop is contained.
103 /// This may be the loop itself, if it already is the outermost loop.
104 const LoopT *getOutermostLoop() const {
105 const LoopT *L = static_cast<const LoopT *>(this);
106 while (L->ParentLoop)
107 L = L->ParentLoop;
108 return L;
109 }
110
112 LoopT *L = static_cast<LoopT *>(this);
113 while (L->ParentLoop)
114 L = L->ParentLoop;
115 return L;
116 }
117
118 /// This is a raw interface for bypassing addChildLoop.
119 void setParentLoop(LoopT *L) {
120 assert(!isInvalid() && "Loop not in a valid state!");
121 ParentLoop = L;
122 }
123
124 /// Return true if the specified loop is contained within in this loop.
125 bool contains(const LoopT *L) const {
126 assert(!isInvalid() && "Loop not in a valid state!");
127 if (L == this)
128 return true;
129 if (!L)
130 return false;
131 return contains(L->getParentLoop());
132 }
133
134 /// Return true if the specified basic block is in this loop.
135 bool contains(const BlockT *BB) const {
136 assert(!isInvalid() && "Loop not in a valid state!");
137 return DenseBlockSet.count(BB);
138 }
139
140 /// Return true if the specified instruction is in this loop.
141 template <class InstT> bool contains(const InstT *Inst) const {
142 return contains(Inst->getParent());
143 }
144
145 /// Return the loops contained entirely within this loop.
146 const std::vector<LoopT *> &getSubLoops() const {
147 assert(!isInvalid() && "Loop not in a valid state!");
148 return SubLoops;
149 }
150 using iterator = typename std::vector<LoopT *>::const_iterator;
152 typename std::vector<LoopT *>::const_reverse_iterator;
153 iterator begin() const { return getSubLoops().begin(); }
154 iterator end() const { return getSubLoops().end(); }
155 reverse_iterator rbegin() const { return getSubLoops().rbegin(); }
156 reverse_iterator rend() const { return getSubLoops().rend(); }
157
158 // LoopInfo does not detect irreducible control flow, just natural
159 // loops. That is, it is possible that there is cyclic control
160 // flow within the "innermost loop" or around the "outermost
161 // loop".
162
163 /// Return true if the loop does not contain any (natural) loops.
164 bool isInnermost() const { return getSubLoops().empty(); }
165 /// Return true if the loop does not have a parent (natural) loop
166 // (i.e. it is outermost, which is the same as top-level).
167 bool isOutermost() const { return getParentLoop() == nullptr; }
168
169 /// Get a list of the basic blocks which make up this loop.
171 assert(!isInvalid() && "Loop not in a valid state!");
172 return Blocks;
173 }
175 block_iterator block_begin() const { return getBlocks().begin(); }
176 block_iterator block_end() const { return getBlocks().end(); }
178 assert(!isInvalid() && "Loop not in a valid state!");
179 return make_range(block_begin(), block_end());
180 }
181
182 /// Get the number of blocks in this loop in constant time.
183 /// Invalidate the loop, indicating that it is no longer a loop.
184 unsigned getNumBlocks() const {
185 assert(!isInvalid() && "Loop not in a valid state!");
186 return Blocks.size();
187 }
188
189 /// Return a direct, immutable handle to the blocks set.
191 assert(!isInvalid() && "Loop not in a valid state!");
192 return DenseBlockSet;
193 }
194
195 /// Return true if this loop is no longer valid. The only valid use of this
196 /// helper is "assert(L.isInvalid())" or equivalent, since IsInvalid is set to
197 /// true by the destructor. In other words, if this accessor returns true,
198 /// the caller has already triggered UB by calling this accessor; and so it
199 /// can only be called in a context where a return value of true indicates a
200 /// programmer error.
201 bool isInvalid() const {
202#if LLVM_ENABLE_ABI_BREAKING_CHECKS
203 return IsInvalid;
204#else
205 return false;
206#endif
207 }
208
209 /// True if terminator in the block can branch to another block that is
210 /// outside of the current loop. \p BB must be inside the loop.
211 bool isLoopExiting(const BlockT *BB) const {
212 assert(!isInvalid() && "Loop not in a valid state!");
213 assert(contains(BB) && "Exiting block must be part of the loop");
214 for (const auto *Succ : children<const BlockT *>(BB)) {
215 if (!contains(Succ))
216 return true;
217 }
218 return false;
219 }
220
221 /// Returns true if \p BB is a loop-latch.
222 /// A latch block is a block that contains a branch back to the header.
223 /// This function is useful when there are multiple latches in a loop
224 /// because \fn getLoopLatch will return nullptr in that case.
225 bool isLoopLatch(const BlockT *BB) const {
226 assert(!isInvalid() && "Loop not in a valid state!");
227 assert(contains(BB) && "block does not belong to the loop");
229 }
230
231 /// Calculate the number of back edges to the loop header.
232 unsigned getNumBackEdges() const {
233 assert(!isInvalid() && "Loop not in a valid state!");
235 [&](BlockT *Pred) { return contains(Pred); });
236 }
237
238 //===--------------------------------------------------------------------===//
239 // APIs for simple analysis of the loop.
240 //
241 // Note that all of these methods can fail on general loops (ie, there may not
242 // be a preheader, etc). For best success, the loop simplification and
243 // induction variable canonicalization pass should be used to normalize loops
244 // for easy analysis. These methods assume canonical loops.
245
246 /// Return all blocks inside the loop that have successors outside of the
247 /// loop. These are the blocks _inside of the current loop_ which branch out.
248 /// The returned list is always unique.
249 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
250
251 /// If getExitingBlocks would return exactly one block, return that block.
252 /// Otherwise return null.
253 BlockT *getExitingBlock() const;
254
255 /// Return all of the successor blocks of this loop. These are the blocks
256 /// _outside of the current loop_ which are branched to.
257 void getExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
258
259 /// If getExitBlocks would return exactly one block, return that block.
260 /// Otherwise return null.
261 BlockT *getExitBlock() const;
262
263 /// Return true if no exit block for the loop has a predecessor that is
264 /// outside the loop.
265 bool hasDedicatedExits() const;
266
267 /// Return all unique successor blocks of this loop.
268 /// These are the blocks _outside of the current loop_ which are branched to.
269 void getUniqueExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
270
271 /// Return all unique successor blocks of this loop except successors from
272 /// Latch block are not considered. If the exit comes from Latch has also
273 /// non Latch predecessor in a loop it will be added to ExitBlocks.
274 /// These are the blocks _outside of the current loop_ which are branched to.
276
277 /// If getUniqueExitBlocks would return exactly one block, return that block.
278 /// Otherwise return null.
279 BlockT *getUniqueExitBlock() const;
280
281 /// If there is a preheader for this loop, return it. A loop has a preheader
282 /// if there is only one edge to the header of the loop from outside of the
283 /// loop. If this is the case, the block branching to the header of the loop
284 /// is the preheader node.
285 ///
286 /// This method returns null if there is no preheader for the loop.
287 BlockT *getLoopPreheader() const;
288
289 /// If the given loop's header has exactly one unique predecessor outside the
290 /// loop, return it. Otherwise return null.
291 /// This is less strict that the loop "preheader" concept, which requires
292 /// the predecessor to have exactly one successor.
293 BlockT *getLoopPredecessor() const;
294
295 /// If there is a single latch block for this loop, return it.
296 /// A latch block is a block that contains a branch back to the header.
297 BlockT *getLoopLatch() const;
298
299 /// Return all loop latch blocks of this loop. A latch block is a block that
300 /// contains a branch back to the header.
301 void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
302 assert(!isInvalid() && "Loop not in a valid state!");
303 BlockT *H = getHeader();
304 for (const auto Pred : inverse_children<BlockT *>(H))
305 if (contains(Pred))
306 LoopLatches.push_back(Pred);
307 }
308
309 /// Return all inner loops in the loop nest rooted by the loop in preorder,
310 /// with siblings in forward program order.
311 template <class Type>
312 static void getInnerLoopsInPreorder(const LoopT &L,
313 SmallVectorImpl<Type> &PreOrderLoops) {
314 SmallVector<LoopT *, 4> PreOrderWorklist;
315 PreOrderWorklist.append(L.rbegin(), L.rend());
316
317 while (!PreOrderWorklist.empty()) {
318 LoopT *L = PreOrderWorklist.pop_back_val();
319 // Sub-loops are stored in forward program order, but will process the
320 // worklist backwards so append them in reverse order.
321 PreOrderWorklist.append(L->rbegin(), L->rend());
322 PreOrderLoops.push_back(L);
323 }
324 }
325
326 /// Return all loops in the loop nest rooted by the loop in preorder, with
327 /// siblings in forward program order.
329 SmallVector<const LoopT *, 4> PreOrderLoops;
330 const LoopT *CurLoop = static_cast<const LoopT *>(this);
331 PreOrderLoops.push_back(CurLoop);
332 getInnerLoopsInPreorder(*CurLoop, PreOrderLoops);
333 return PreOrderLoops;
334 }
336 SmallVector<LoopT *, 4> PreOrderLoops;
337 LoopT *CurLoop = static_cast<LoopT *>(this);
338 PreOrderLoops.push_back(CurLoop);
339 getInnerLoopsInPreorder(*CurLoop, PreOrderLoops);
340 return PreOrderLoops;
341 }
342
343 //===--------------------------------------------------------------------===//
344 // APIs for updating loop information after changing the CFG
345 //
346
347 /// This method is used by other analyses to update loop information.
348 /// NewBB is set to be a new member of the current loop.
349 /// Because of this, it is added as a member of all parent loops, and is added
350 /// to the specified LoopInfo object as being in the current basic block. It
351 /// is not valid to replace the loop header with this method.
352 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
353
354 /// This is used when splitting loops up. It replaces the OldChild entry in
355 /// our children list with NewChild, and updates the parent pointer of
356 /// OldChild to be null and the NewChild to be this loop.
357 /// This updates the loop depth of the new child.
358 void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
359
360 /// Add the specified loop to be a child of this loop.
361 /// This updates the loop depth of the new child.
362 void addChildLoop(LoopT *NewChild) {
363 assert(!isInvalid() && "Loop not in a valid state!");
364 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
365 NewChild->ParentLoop = static_cast<LoopT *>(this);
366 SubLoops.push_back(NewChild);
367 }
368
369 /// This removes the specified child from being a subloop of this loop. The
370 /// loop is not deleted, as it will presumably be inserted into another loop.
372 assert(!isInvalid() && "Loop not in a valid state!");
373 assert(I != SubLoops.end() && "Cannot remove end iterator!");
374 LoopT *Child = *I;
375 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
376 SubLoops.erase(SubLoops.begin() + (I - begin()));
377 Child->ParentLoop = nullptr;
378 return Child;
379 }
380
381 /// This removes the specified child from being a subloop of this loop. The
382 /// loop is not deleted, as it will presumably be inserted into another loop.
383 LoopT *removeChildLoop(LoopT *Child) {
384 return removeChildLoop(llvm::find(*this, Child));
385 }
386
387 /// This adds a basic block directly to the basic block list.
388 /// This should only be used by transformations that create new loops. Other
389 /// transformations should use addBasicBlockToLoop.
390 void addBlockEntry(BlockT *BB) {
391 assert(!isInvalid() && "Loop not in a valid state!");
392 Blocks.push_back(BB);
393 DenseBlockSet.insert(BB);
394 }
395
396 /// interface to reverse Blocks[from, end of loop] in this loop
397 void reverseBlock(unsigned from) {
398 assert(!isInvalid() && "Loop not in a valid state!");
399 std::reverse(Blocks.begin() + from, Blocks.end());
400 }
401
402 /// interface to do reserve() for Blocks
403 void reserveBlocks(unsigned size) {
404 assert(!isInvalid() && "Loop not in a valid state!");
405 Blocks.reserve(size);
406 }
407
408 /// interface to do reserve() for SubLoops
409 void reserveSubLoops(unsigned Size) {
410 assert(!isInvalid() && "Loop not in a valid state!");
411 SubLoops.reserve(Size);
412 }
413
414 /// Capacity of the block list; input to an enclosing loop's reserveBlocks()
415 /// during construction, when this loop's list is not yet fully populated.
416 unsigned getBlocksCapacity() const { return Blocks.capacity(); }
417
418 /// This method is used to move BB (which must be part of this loop) to be the
419 /// loop header of the loop (the block that dominates all others).
420 void moveToHeader(BlockT *BB) {
421 assert(!isInvalid() && "Loop not in a valid state!");
422 if (Blocks[0] == BB)
423 return;
424 for (unsigned i = 0;; ++i) {
425 assert(i != Blocks.size() && "Loop does not contain BB!");
426 if (Blocks[i] == BB) {
427 Blocks[i] = Blocks[0];
428 Blocks[0] = BB;
429 return;
430 }
431 }
432 }
433
434 /// This removes the specified basic block from the current loop, updating the
435 /// Blocks as appropriate. This does not update the mapping in the LoopInfo
436 /// class.
437 void removeBlockFromLoop(BlockT *BB) {
438 assert(!isInvalid() && "Loop not in a valid state!");
439 auto I = find(Blocks, BB);
440 assert(I != Blocks.end() && "N is not in this list!");
441 Blocks.erase(I);
442
443 DenseBlockSet.erase(BB);
444 }
445
446 /// Verify loop structure
447 void verifyLoop() const;
448
449 /// Verify loop structure of this loop and all nested loops.
451
452 /// Returns true if the loop is annotated parallel.
453 ///
454 /// Derived classes can override this method using static template
455 /// polymorphism.
456 bool isAnnotatedParallel() const { return false; }
457
458 /// Print loop with all the BBs inside it.
459 void print(raw_ostream &OS, bool Verbose = false, bool PrintNested = true,
460 unsigned Depth = 0) const;
461
462protected:
463 friend class LoopInfoBase<BlockT, LoopT>;
464 friend class PopulateLoopsDFS<BlockT, LoopT>;
465
466 /// This creates an empty loop.
467 LoopBase() : ParentLoop(nullptr) {}
468
469 explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
470 Blocks.push_back(BB);
471 DenseBlockSet.insert(BB);
472 }
473
474 // Since loop passes like SCEV are allowed to key analysis results off of
475 // `Loop` pointers, we cannot re-use pointers within a loop pass manager.
476 // This means loop passes should not be `delete` ing `Loop` objects directly
477 // (and risk a later `Loop` allocation re-using the address of a previous one)
478 // but should be using LoopInfo::markAsRemoved, which keeps around the `Loop`
479 // pointer till the end of the lifetime of the `LoopInfo` object.
480 //
481 // To make it easier to follow this rule, we mark the destructor as
482 // non-public.
484 for (auto *SubLoop : SubLoops)
485 SubLoop->~LoopT();
486
487#if LLVM_ENABLE_ABI_BREAKING_CHECKS
488 IsInvalid = true;
489#endif
490 SubLoops.clear();
491 Blocks.clear();
492 DenseBlockSet.clear();
493 ParentLoop = nullptr;
494 }
495};
496
497template <class BlockT, class LoopT>
499 Loop.print(OS);
500 return OS;
501}
502
503//===----------------------------------------------------------------------===//
504/// This class builds and contains all of the top-level loop
505/// structures in the specified function.
506///
507
508template <class BlockT, class LoopT> class LoopInfoBase {
510 "LoopInfo requires GraphTraits<BlockT *>::getNumber (see "
511 "GraphHasNodeNumbers)");
512
513 // Mapping of each block, indexed by its number, to the innermost loop it
514 // occurs in (or null).
516
517 using ParentT = decltype(std::declval<const BlockT *>()->getParent());
518 ParentT ParentPtr = nullptr;
519 unsigned BlockNumberEpoch;
520
521 std::vector<LoopT *> TopLevelLoops;
522 BumpPtrAllocator LoopAllocator;
523
524 friend class LoopBase<BlockT, LoopT>;
525 friend class LoopInfo;
526
527 void operator=(const LoopInfoBase &) = delete;
528 LoopInfoBase(const LoopInfoBase &) = delete;
529
530public:
531 LoopInfoBase() = default;
533
534 LoopInfoBase(LoopInfoBase &&Arg)
535 : BBMap(std::move(Arg.BBMap)),
536 TopLevelLoops(std::move(Arg.TopLevelLoops)),
537 LoopAllocator(std::move(Arg.LoopAllocator)) {
538 ParentPtr = Arg.ParentPtr;
539 BlockNumberEpoch = Arg.BlockNumberEpoch;
540 // We have to clear the arguments top level loops as we've taken ownership.
541 Arg.TopLevelLoops.clear();
542 }
543 LoopInfoBase &operator=(LoopInfoBase &&RHS) {
544 BBMap = std::move(RHS.BBMap);
545 ParentPtr = RHS.ParentPtr;
546 BlockNumberEpoch = RHS.BlockNumberEpoch;
547
548 for (auto *L : TopLevelLoops)
549 L->~LoopT();
550
551 TopLevelLoops = std::move(RHS.TopLevelLoops);
552 LoopAllocator = std::move(RHS.LoopAllocator);
553 RHS.TopLevelLoops.clear();
554 return *this;
555 }
556
558 BBMap.clear();
559
560 for (auto *L : TopLevelLoops)
561 L->~LoopT();
562 TopLevelLoops.clear();
563 LoopAllocator.Reset();
564 }
565
566 template <typename... ArgsTy> LoopT *AllocateLoop(ArgsTy &&...Args) {
567 LoopT *Storage = LoopAllocator.Allocate<LoopT>();
568 return new (Storage) LoopT(std::forward<ArgsTy>(Args)...);
569 }
570
571 /// iterator/begin/end - The interface to the top-level loops in the current
572 /// function.
573 ///
574 using iterator = typename std::vector<LoopT *>::const_iterator;
576 typename std::vector<LoopT *>::const_reverse_iterator;
577 iterator begin() const { return TopLevelLoops.begin(); }
578 iterator end() const { return TopLevelLoops.end(); }
579 reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
580 reverse_iterator rend() const { return TopLevelLoops.rend(); }
581 bool empty() const { return TopLevelLoops.empty(); }
582
583 /// Return all of the loops in the function in preorder across the loop
584 /// nests, with siblings in forward program order.
585 ///
586 /// Note that because loops form a forest of trees, preorder is equivalent to
587 /// reverse postorder.
589
590 /// Return all of the loops in the function in preorder across the loop
591 /// nests, with siblings in *reverse* program order.
592 ///
593 /// Note that because loops form a forest of trees, preorder is equivalent to
594 /// reverse postorder.
595 ///
596 /// Also note that this is *not* a reverse preorder. Only the siblings are in
597 /// reverse program order.
599
600private:
601 /// Verify that used block numbers are still valid.
602 void verifyBlockNumberEpoch(ParentT BBParent) const {
603 assert(ParentPtr == BBParent &&
604 "loop info queried with block of other function");
605 assert(BlockNumberEpoch ==
607 "loop info used with outdated block numbers");
608 }
609
610public:
611 /// Return the inner most loop that BB lives in. If a basic block is in no
612 /// loop (for example the entry node), null is returned.
613 LoopT *getLoopFor(const BlockT *BB) const {
614 verifyBlockNumberEpoch(BB->getParent());
616 return Number < BBMap.size() ? BBMap[Number] : nullptr;
617 }
618
619 /// Same as getLoopFor.
620 const LoopT *operator[](const BlockT *BB) const { return getLoopFor(BB); }
621
622 /// Return the loop nesting level of the specified block. A depth of 0 means
623 /// the block is not inside any loop.
624 unsigned getLoopDepth(const BlockT *BB) const {
625 const LoopT *L = getLoopFor(BB);
626 return L ? L->getLoopDepth() : 0;
627 }
628
629 /// Edge type.
630 using Edge = std::pair<BlockT *, BlockT *>;
631
632 /// Return true if \p L does not have any exit blocks.
633 bool hasNoExitBlocks(const LoopT &L) const;
634
635 /// Return all pairs of (_inside_block_,_outside_block_).
636 void getExitEdges(const LoopT &L, SmallVectorImpl<Edge> &ExitEdges) const;
637
638 /// Return the unique exit block for the latch of \p L, or null if there are
639 /// multiple different exit blocks or the latch is not exiting.
640 BlockT *getUniqueLatchExitBlock(const LoopT &L) const;
641
642 /// Remove every block satisfying \p Pred from \p L's block list, preserving
643 /// the order of the remaining blocks. Only \p L itself is updated, not its
644 /// ancestors or descendants, and not the block-to-loop mapping.
645 template <typename PredicateT>
646 void removeBlocksIf(LoopT &L, PredicateT Pred) {
647 llvm::erase_if(L.Blocks, [&](BlockT *BB) {
648 if (!Pred(BB))
649 return false;
650 L.DenseBlockSet.erase(BB);
651 return true;
652 });
653 }
654
655 /// Remove every block satisfying \p Pred from \p Start and each of its
656 /// ancestors up to but not including \p Stop, which must be null or an
657 /// ancestor of \p Start; a null \p Stop walks to the top level.
658 template <typename PredicateT>
659 void removeBlocksFromLoopAndAncestors(LoopT *Start, LoopT *Stop,
660 PredicateT Pred) {
661 for (LoopT *Cur = Start; Cur != Stop; Cur = Cur->getParentLoop())
662 removeBlocksIf(*Cur, Pred);
663 }
664
665 /// Detach and return the children of \p Parent (the top-level loops if
666 /// \p Parent is null) that satisfy \p Pred, clearing their parent pointers.
667 /// Both the remaining and the returned children keep their relative order.
668 template <typename PredicateT>
670 std::vector<LoopT *> &List = Parent ? Parent->SubLoops : TopLevelLoops;
672 llvm::erase_if(List, [&](LoopT *Child) {
673 if (!Pred(Child))
674 return false;
675 Child->ParentLoop = nullptr;
676 Taken.push_back(Child);
677 return true;
678 });
679 return Taken;
680 }
681
682 /// \brief Find the innermost loop containing both given loops.
683 ///
684 /// \returns the innermost loop containing both \p A and \p B
685 /// or nullptr if there is no such loop.
686 LoopT *getSmallestCommonLoop(LoopT *A, LoopT *B) const;
687 /// \brief Find the innermost loop containing both given blocks.
688 ///
689 /// \returns the innermost loop containing both \p A and \p B
690 /// or nullptr if there is no such loop.
691 LoopT *getSmallestCommonLoop(BlockT *A, BlockT *B) const;
692
693 // True if the block is a loop header node
694 bool isLoopHeader(const BlockT *BB) const {
695 const LoopT *L = getLoopFor(BB);
696 return L && L->getHeader() == BB;
697 }
698
699 /// Return the top-level loops.
700 const std::vector<LoopT *> &getTopLevelLoops() const { return TopLevelLoops; }
701
702 /// This removes the specified top-level loop from this loop info object.
703 /// The loop is not deleted, as it will presumably be inserted into
704 /// another loop.
706 assert(I != end() && "Cannot remove end iterator!");
707 LoopT *L = *I;
708 assert(L->isOutermost() && "Not a top-level loop!");
709 TopLevelLoops.erase(TopLevelLoops.begin() + (I - begin()));
710 return L;
711 }
712
713 /// Change the top-level loop that contains BB to the specified loop.
714 /// This should be used by transformations that restructure the loop hierarchy
715 /// tree.
716 void changeLoopFor(const BlockT *BB, LoopT *L) {
717 verifyBlockNumberEpoch(BB->getParent());
719 if (Number >= BBMap.size()) {
720 unsigned Max =
721 GraphTraits<decltype(BB->getParent())>::getMaxNumber(BB->getParent());
722 assert(Number < Max);
723 BBMap.resize(Max);
724 }
725 BBMap[Number] = L;
726 }
727
728 /// Replace the specified loop in the top-level loops list with the indicated
729 /// loop.
730 void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop) {
731 auto I = find(TopLevelLoops, OldLoop);
732 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
733 *I = NewLoop;
734 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
735 "Loops already embedded into a subloop!");
736 }
737
738 /// This adds the specified loop to the collection of top-level loops.
739 void addTopLevelLoop(LoopT *New) {
740 assert(New->isOutermost() && "Loop already in subloop!");
741 TopLevelLoops.push_back(New);
742 }
743
744 /// This method completely removes BB from all data structures,
745 /// including all of the Loop objects it is nested in and our mapping from
746 /// BasicBlocks to loops.
747 void removeBlock(BlockT *BB) {
748 verifyBlockNumberEpoch(BB->getParent());
750 if (Number >= BBMap.size())
751 return;
752
753 for (LoopT *L = BBMap[Number]; L; L = L->getParentLoop())
754 L->removeBlockFromLoop(BB);
755 BBMap[Number] = nullptr;
756 }
757
758 // Internals
759
760 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
761 const LoopT *ParentLoop) {
762 if (!SubLoop)
763 return true;
764 if (SubLoop == ParentLoop)
765 return false;
766 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
767 }
768
769 /// Create the loop forest using a stable algorithm.
771
772 // Debugging
773 void print(raw_ostream &OS) const;
774
775 void verify(const DominatorTreeBase<BlockT, false> &DomTree) const;
776
777 /// Destroy a loop that has been removed from the `LoopInfo` nest.
778 ///
779 /// This runs the destructor of the loop object making it invalid to
780 /// reference afterward. The memory is retained so that the *pointer* to the
781 /// loop remains valid.
782 ///
783 /// The caller is responsible for removing this loop from the loop nest and
784 /// otherwise disconnecting it from the broader `LoopInfo` data structures.
785 /// Callers that don't naturally handle this themselves should probably call
786 /// `erase' instead.
787 void destroy(LoopT *L) {
788 L->~LoopT();
789
790 // Since LoopAllocator is a BumpPtrAllocator, this Deallocate only poisons
791 // \c L, but the pointer remains valid for non-dereferencing uses.
792 LoopAllocator.Deallocate(L);
793 }
794};
795
796} // namespace llvm
797
798#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 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 in 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.
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.
void reverseBlock(unsigned from)
interface to reverse Blocks[from, end of loop] in this loop
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.
LoopBase(BlockT *BB)
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.
void reserveBlocks(unsigned size)
interface to do reserve() for Blocks
unsigned getBlocksCapacity() const
Capacity of the block list; input to an enclosing loop's reserveBlocks() during construction,...
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.
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 reserveSubLoops(unsigned Size)
interface to do reserve() for SubLoops
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 * 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
const SmallPtrSetImpl< const BlockT * > & getBlocksSet() const
Return a direct, immutable handle to the blocks set.
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 verify(const DominatorTreeBase< BlockT, false > &DomTree) const
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
void analyze(const DominatorTreeBase< BlockT, false > &DomTree)
Create the loop forest using a stable algorithm.
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)
LoopT * AllocateLoop(ArgsTy &&...Args)
const LoopT * operator[](const BlockT *BB) const
Same as getLoopFor.
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.
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
Populate all loop data in a stable order during a single forward DFS.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
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...
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.
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
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
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.
iterator_range< typename GraphTraits< Inverse< GraphType > >::ChildIteratorType > inverse_children(const typename GraphTraits< GraphType >::NodeRef &G)
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
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