37#ifndef LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
38#define LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
49#define DEBUG_TYPE "dom-tree-builder"
52namespace DomTreeBuilder {
55 using NodePtr =
typename DomTreeT::NodePtr;
56 using NodeT =
typename DomTreeT::NodeType;
58 using RootsT =
decltype(DomTreeT::Roots);
59 static constexpr bool IsPostDom = DomTreeT::IsPostDominator;
85 using UpdateT =
typename DomTreeT::UpdateType;
114 template <
bool Inversed>
128 using DirectedNodeT =
129 std::conditional_t<Inversed, Inverse<NodePtr>,
NodePtr>;
134 if constexpr (std::is_same_v<std::decay_t<
decltype(*R.begin())>,
NodePtr>)
146 Max =
GraphTraits<
decltype(BB->getParent())>::getMaxNumber(
149 NodeInfos.resize(Max ? Max + 1 : Idx + 1);
167 assert(IDom || DT.getNode(
nullptr));
172 return DT.createNode(BB, IDomNode);
187 BP.
N->printAsOperand(O,
false);
205 template <
bool IsReverse = false,
typename DescendCondition>
207 unsigned AttachToNum,
213 while (!WorkList.
empty()) {
220 if (BBInfo.DFSNum != 0)
222 BBInfo.Parent = ParentNum;
223 BBInfo.DFSNum = BBInfo.Semi = BBInfo.Label = ++LastNum;
232 if (Condition(BB, Succ))
238 if (SuccOrder && Successors.size() > 1)
241 return SuccOrder->find(A)->second < SuccOrder->find(B)->second;
244 for (
const NodePtr Succ : Successors) {
245 if (!Condition(BB, Succ))
268 unsigned eval(
unsigned V,
unsigned LastLinked,
272 if (VInfo->
Parent < LastLinked)
278 Stack.push_back(VInfo);
279 VInfo = NumToInfo[VInfo->
Parent];
280 }
while (VInfo->
Parent >= LastLinked);
287 VInfo = Stack.pop_back_val();
290 if (PLabelInfo->
Semi < VLabelInfo->
Semi)
293 PLabelInfo = VLabelInfo;
295 }
while (!Stack.empty());
301 const unsigned NextDFSNum(
NumToNode.size());
309 for (
unsigned i = 1; i < NextDFSNum; ++i) {
311 IDoms[i] = VInfo.Parent;
312 NumToInfo[i] = &VInfo;
317 for (
unsigned i = NextDFSNum - 1; i >= 2; --i) {
318 auto &WInfo = *NumToInfo[i];
321 WInfo.Semi = WInfo.Parent;
322 for (
unsigned RCIdx = WInfo.ReverseChildrenStart; RCIdx != 0;) {
324 RCIdx = Entry.second;
326 NumToInfo[
eval(Entry.first, i + 1, EvalStack, NumToInfo)]->Semi;
327 if (SemiU < WInfo.Semi)
335 for (
unsigned i = 2; i < NextDFSNum; ++i) {
336 auto &WInfo = *NumToInfo[i];
338 unsigned WIDom = IDoms[i];
339 while (WIDom > WInfo.Semi)
340 WIDom = IDoms[WIDom];
353 assert(
NumToNode.size() == 1 &&
"SNCAInfo must be freshly constructed");
356 BBInfo.DFSNum = BBInfo.Semi = BBInfo.Label = 1;
365 assert(
N &&
"N must be a valid node");
370 assert(DT.Parent &&
"Parent not set");
378 assert(DT.Parent &&
"Parent pointer is not set");
422 bool HasNonTrivialRoots =
false;
425 if (
Total + 1 != Num) {
426 HasNonTrivialRoots =
true;
433 std::optional<NodeOrderMap> SuccOrder;
434 auto InitSuccOrderOnce = [&]() {
439 SuccOrder->try_emplace(Succ, 0);
442 unsigned NodeNum = 0;
443 for (
const auto Node :
nodes(DT.Parent)) {
445 auto Order = SuccOrder->find(
Node);
446 if (Order != SuccOrder->end()) {
447 assert(Order->second == 0);
448 Order->second = NodeNum;
480 const unsigned NewNum =
484 <<
"(non-trivial root): "
486 Roots.push_back(FurthestAway);
487 LLVM_DEBUG(
dbgs() <<
"\t\t\tPrev DFSNum: " << Num <<
", new DFSNum: "
488 << NewNum <<
"\n\t\t\tRemoving DFS info\n");
489 for (
unsigned i = NewNum; i > Num; --i) {
496 const unsigned PrevNum = Num;
499 for (
unsigned i = PrevNum + 1; i <= Num; ++i)
511 assert((
Total + 1 == Num) &&
"Everything should have been visited");
514 if (HasNonTrivialRoots)
540 for (
unsigned i = 0; i < Roots.size(); ++i) {
541 auto &Root = Roots[i];
546 <<
" remains a root\n");
552 for (
unsigned x = 2; x <= Num; ++x) {
573 template <
typename DescendCondition>
576 assert(DT.Roots.size() == 1 &&
"Dominators should have a singe root");
577 runDFS(DT.Roots[0], 0, DC, 0);
583 for (
const NodePtr Root : DT.Roots)
584 Num =
runDFS(Root, Num, DC, 1);
588 auto *Parent = DT.Parent;
612 dbgs() <<
"DomTree recalculated, skipping future batch updates\n");
615 if (DT.Roots.empty())
623 DT.RootNode = DT.createNode(Root);
642 DT.createNode(W, IDomNode);
660 return LHS->getLevel() <
RHS->getLevel();
666 std::priority_queue<TreeNodePtr, SmallVector<TreeNodePtr, 8>, Compare>
670#if LLVM_ENABLE_ABI_BREAKING_CHECKS
678 "From has to be a valid CFG node or a virtual root");
679 assert(To &&
"Cannot be a nullptr");
691 FromTN = DT.createNode(From, VirtualRoot);
692 DT.Roots.push_back(From);
695 DT.DFSInfoValid =
false;
712 if (!DT.isVirtualRoot(To->
getIDom()))
719 <<
" is no longer a root\n\t\tRebuilding the tree!!!\n");
727 if (
A.size() !=
B.size())
731 if (Set.count(
N) == 0)
744 return HasForwardSuccessors(N, BUI);
757 <<
"The entire tree needs to be rebuilt\n");
778 assert(NCDBlock || DT.isPostDominator());
783 const unsigned NCDLevel = NCD->
getLevel();
801 II.Visited.insert(To);
803 while (!
II.Bucket.empty()) {
806 II.Affected.push_back(TN);
808 const unsigned CurrentLevel = TN->
getLevel();
810 <<
"as affected, CurrentLevel " << CurrentLevel
827 "Unreachable successor found at reachable insertion");
828 const unsigned SuccLevel = SuccTN->
getLevel();
831 <<
", level = " << SuccLevel <<
"\n");
840 if (SuccLevel <= NCDLevel + 1 || !
II.Visited.insert(SuccTN).second)
843 if (SuccLevel > CurrentLevel) {
848 UnaffectedOnCurrentLevel.
push_back(SuccTN);
849#if LLVM_ENABLE_ABI_BREAKING_CHECKS
850 II.VisitedUnaffected.push_back(SuccTN);
856 <<
" to a Bucket\n");
857 II.Bucket.push(SuccTN);
861 if (UnaffectedOnCurrentLevel.
empty())
883#if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
886 "TN should have been updated by an affected ancestor");
910 for (
const auto &Edge : DiscoveredEdgesToReachable) {
923 &DiscoveredConnectingEdges) {
924 assert(!DT.getNode(Root) &&
"Root must not be reachable");
927 auto UnreachableDescender = [&DT, &DiscoveredConnectingEdges](
NodePtr From,
933 DiscoveredConnectingEdges.push_back({From, ToTN});
938 SNCA.
runDFS(Root, 0, UnreachableDescender, 0);
947 assert(From && To &&
"Cannot disconnect nullptrs");
951#if LLVM_ENABLE_ABI_BREAKING_CHECKS
955 auto IsSuccessor = [BUI](
const NodePtr SuccCandidate,
const NodePtr Of) {
960 assert(!IsSuccessor(To, From) &&
"Deleted edge still exists in the CFG!");
972 <<
") already unreachable -- there is no edge to delete\n");
976 const NodePtr NCDBlock = DT.findNearestCommonDominator(From, To);
981 DT.DFSInfoValid =
false;
1011 assert(ToIDom || DT.isPostDominator());
1017 if (!PrevIDomSubTree) {
1024 const unsigned Level = ToIDomTN->
getLevel();
1026 return DT.getNode(To)->getLevel() > Level;
1033 SNCA.
runDFS(ToIDom, 0, DescendBelow, 0);
1048 if (!DT.getNode(Pred))
1051 const NodePtr Support = DT.findNearestCommonDominator(TNB, Pred);
1053 if (Support != TNB) {
1055 <<
" is reachable from support "
1077 LLVM_DEBUG(
dbgs() <<
"\tDeletion made a region reverse-unreachable\n");
1080 DT.Roots.push_back(ToTN->
getBlock());
1086 const unsigned Level = ToTN->
getLevel();
1090 auto DescendAndCollect = [Level, &AffectedQueue, &DT](
NodePtr,
NodePtr To) {
1102 unsigned LastDFSNum =
1109 for (
const NodePtr N : AffectedQueue) {
1113 assert(NCDBlock || DT.isPostDominator());
1133 for (
unsigned i = LastDFSNum; i > 0; --i) {
1141 if (MinNode == ToTN)
1144 LLVM_DEBUG(
dbgs() <<
"DeleteUnreachable: running DFS with MinNode = "
1146 const unsigned MinLevel = MinNode->
getLevel();
1155 return ToTN->
getLevel() > MinLevel;
1156 DT.createNode(To, DT.getNode(R));
1178 if (NumUpdates == 0)
1183 if (NumUpdates == 1) {
1186 if (Update.getKind() == UpdateKind::Insert)
1187 InsertEdge(DT,
nullptr, Update.getFrom(), Update.getTo());
1189 DeleteEdge(DT,
nullptr, Update.getFrom(), Update.getTo());
1192 if (Update.getKind() == UpdateKind::Insert)
1193 InsertEdge(DT, &BUI, Update.getFrom(), Update.getTo());
1195 DeleteEdge(DT, &BUI, Update.getFrom(), Update.getTo());
1209 if (DT.DomTreeNodes.size() <= 100) {
1212 }
else if (BUI.
NumLegalized > DT.DomTreeNodes.size() / 40)
1233 if (CurrentUpdate.getKind() == UpdateKind::Insert)
1234 InsertEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
1236 DeleteEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
1249 if (!DT.Parent && !DT.Roots.empty()) {
1250 errs() <<
"Tree has no parent but has roots!\n";
1256 if (DT.Roots.empty()) {
1257 errs() <<
"Tree doesn't have a root!\n";
1263 errs() <<
"Tree's root is not its parent's entry node!\n";
1271 errs() <<
"Tree has different roots than freshly computed ones!\n";
1272 errs() <<
"\tPDT roots: ";
1275 errs() <<
"\n\tComputed roots: ";
1276 for (
const NodePtr N : ComputedRoots)
1292 for (
auto *TN : DT.DomTreeNodes) {
1295 const NodePtr BB = TN->getBlock();
1298 if (DT.isVirtualRoot(TN))
1303 <<
" not found by DFS walk!\n";
1311 if (
N && !DT.getNode(
N)) {
1313 <<
" not found in the DomTree!\n";
1327 for (
auto *TN : DT.DomTreeNodes) {
1330 const NodePtr BB = TN->getBlock();
1335 if (!IDom && TN->
getLevel() != 0) {
1337 <<
" has a nonzero level " << TN->getLevel() <<
"!\n";
1345 << TN->getLevel() <<
" while its IDom "
1361 if (!DT.DFSInfoValid || !DT.Parent)
1367 auto PrintNodeAndDFSNums = [](
const TreeNodePtr TN) {
1369 << TN->getDFSNumOut() <<
'}';
1375 errs() <<
"DFSIn number for the tree root is not:\n\t";
1376 PrintNodeAndDFSNums(Root);
1384 for (
auto *
Node : DT.DomTreeNodes) {
1389 if (
Node->isLeaf()) {
1390 if (
Node->getDFSNumIn() + 1 !=
Node->getDFSNumOut()) {
1391 errs() <<
"Tree leaf should have DFSOut = DFSIn + 1:\n\t";
1392 PrintNodeAndDFSNums(
Node);
1408 auto PrintChildrenError =
1413 errs() <<
"Incorrect DFS numbers for:\n\tParent ";
1414 PrintNodeAndDFSNums(
Node);
1416 errs() <<
"\n\tChild ";
1417 PrintNodeAndDFSNums(FirstCh);
1420 errs() <<
"\n\tSecond child ";
1421 PrintNodeAndDFSNums(SecondCh);
1424 errs() <<
"\nAll children: ";
1426 PrintNodeAndDFSNums(Ch);
1434 if (Children.front()->getDFSNumIn() !=
Node->getDFSNumIn() + 1) {
1435 PrintChildrenError(Children.front(),
nullptr);
1439 if (Children.back()->getDFSNumOut() + 1 !=
Node->getDFSNumOut()) {
1440 PrintChildrenError(Children.back(),
nullptr);
1444 for (
size_t i = 0, e = Children.size() - 1; i != e; ++i) {
1445 if (Children[i]->getDFSNumOut() + 1 != Children[i + 1]->getDFSNumIn()) {
1446 PrintChildrenError(Children[i], Children[i + 1]);
1499 for (
auto *TN : DT.DomTreeNodes) {
1502 const NodePtr BB = TN->getBlock();
1503 if (!BB || TN->isLeaf())
1510 return From != BB && To != BB;
1517 <<
" is removed!\n";
1534 for (
auto *TN : DT.DomTreeNodes) {
1537 const NodePtr BB = TN->getBlock();
1538 if (!BB || TN->isLeaf())
1545 return From != BBN && To != BBN;
1555 <<
" is removed!\n";
1576 FreshTree.recalculate(*DT.Parent);
1577 const bool Different = DT.compare(FreshTree);
1580 errs() << (DT.isPostDominator() ?
"Post" :
"")
1581 <<
"DominatorTree is different than a freshly computed one!\n"
1584 errs() <<
"\n\tFreshly computed tree:\n";
1585 FreshTree.print(
errs());
1597template <
typename DomTreeT>
1608template <
class DomTreeT>
1610 typename DomTreeT::NodePtr To) {
1611 if (DT.isPostDominator())
1616template <
class DomTreeT>
1618 typename DomTreeT::NodePtr To) {
1619 if (DT.isPostDominator())
1624template <
class DomTreeT>
1627 DomTreeT::IsPostDominator> &PreViewCFG,
1629 DomTreeT::IsPostDominator> *PostViewCFG) {
1633template <
class DomTreeT>
1634bool Verify(
const DomTreeT &DT,
typename DomTreeT::VerificationLevel VL) {
1648 if (VL == DomTreeT::VerificationLevel::Basic ||
1649 VL == DomTreeT::VerificationLevel::Full)
1652 if (VL == DomTreeT::VerificationLevel::Full)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
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.
This file defines a set of templates that efficiently compute a dominator tree over a generic graph.
Loop::LoopBounds::Direction Direction
uint64_t IntrinsicInst * II
ppc ctr loops PowerPC CTR Loops Verify
This file defines the SmallPtrSet class.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Base class for the actual dominator tree node.
void setIDom(DomTreeNodeBase *NewIDom)
DomTreeNodeBase * getIDom() const
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree.
unsigned getLevel() const
cfg::Update< NodePtr > popUpdateForIncrementalUpdates()
unsigned getNumLegalizedUpdates() const
Implements a dense probed hash-table based set with some number of buckets stored inline.
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 resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
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.
@ C
The default llvm calling convention, compatible with C.
void CalculateWithUpdates(DomTreeT &DT, ArrayRef< typename DomTreeT::UpdateType > Updates)
void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From, typename DomTreeT::NodePtr To)
void Calculate(DomTreeT &DT)
void ApplyUpdates(DomTreeT &DT, GraphDiff< typename DomTreeT::NodePtr, DomTreeT::IsPostDominator > &PreViewCFG, GraphDiff< typename DomTreeT::NodePtr, DomTreeT::IsPostDominator > *PostViewCFG)
void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From, typename DomTreeT::NodePtr To)
auto reverse_if(Range &&R)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
constexpr from_range_t from_range
constexpr bool GraphHasNodeNumbers
Indicate whether a GraphTraits<NodeT>::getNumber() is supported.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
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...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
BatchUpdateInfo(GraphDiffT &PreViewCFG, GraphDiffT *PostViewCFG=nullptr)
const size_t NumLegalized
friend raw_ostream & operator<<(raw_ostream &O, const BlockNamePrinter &BP)
BlockNamePrinter(NodePtr Block)
BlockNamePrinter(TreeNodePtr TN)
unsigned ReverseChildrenStart
Index in ReverseChildren vector.
bool operator()(TreeNodePtr LHS, TreeNodePtr RHS) const
std::priority_queue< TreeNodePtr, SmallVector< TreeNodePtr, 8 >, Compare > Bucket
SmallVector< TreeNodePtr, 8 > Affected
SmallDenseSet< TreeNodePtr, 8 > Visited
SemiNCAInfo(BatchUpdatePtr BUI)
static void UpdateInsertion(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr NCD, InsertionInfo &II)
static void DeleteEdge(DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr From, const NodePtr To)
NodePtr getIDom(NodePtr BB)
InfoRec & getNodeInfo(NodePtr BB)
void doFullDFSWalk(const DomTreeT &DT, DescendCondition DC)
DenseMap< NodePtr, unsigned > NodeOrderMap
static RootsT FindRoots(const DomTreeT &DT, BatchUpdatePtr BUI)
static SmallVector< NodePtr, 8 > getChildren(NodePtr N, BatchUpdatePtr BUI)
static void ComputeUnreachableDominators(DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr Root, const TreeNodePtr Incoming, SmallVectorImpl< std::pair< NodePtr, TreeNodePtr > > &DiscoveredConnectingEdges)
BatchUpdateInfo * BatchUpdatePtr
static bool VerifyLevels(const DomTreeT &DT)
decltype(DomTreeT::Roots) RootsT
bool verifyReachability(const DomTreeT &DT)
unsigned eval(unsigned V, unsigned LastLinked, SmallVectorImpl< InfoRec * > &Stack, ArrayRef< InfoRec * > NumToInfo)
static bool IsSameAsFreshTree(const DomTreeT &DT)
GraphDiff< NodePtr, IsPostDom > GraphDiffT
static constexpr bool IsPostDom
typename DomTreeT::NodePtr NodePtr
static void ApplyUpdates(DomTreeT &DT, GraphDiffT &PreViewCFG, GraphDiffT *PostViewCFG)
typename DomTreeT::UpdateKind UpdateKind
static bool UpdateRootsBeforeInsertion(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr From, const TreeNodePtr To)
bool verifySiblingProperty(const DomTreeT &DT)
typename DomTreeT::NodeType NodeT
void reattachExistingSubtree(DomTreeT &DT, const TreeNodePtr AttachTo)
static NodePtr GetEntryNode(const DomTreeT &DT)
static bool AlwaysDescend(NodePtr, NodePtr)
static void UpdateRootsAfterUpdate(DomTreeT &DT, const BatchUpdatePtr BUI)
SmallVector< NodePtr, 64 > NumToNode
unsigned runDFS(NodePtr V, unsigned LastNum, DescendCondition Condition, unsigned AttachToNum, const NodeOrderMap *SuccOrder=nullptr)
static void DeleteReachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr FromTN, const TreeNodePtr ToTN)
static void RemoveRedundantRoots(const DomTreeT &DT, BatchUpdatePtr BUI, RootsT &Roots)
static bool HasProperSupport(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr TN)
static bool isPermutation(const SmallVectorImpl< NodePtr > &A, const SmallVectorImpl< NodePtr > &B)
static void CalculateFromScratch(DomTreeT &DT, BatchUpdatePtr BUI)
TreeNodePtr getNodeForBlock(NodePtr BB, DomTreeT &DT)
typename DomTreeT::UpdateType UpdateT
static void InsertReachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr From, const TreeNodePtr To)
static bool HasForwardSuccessors(const NodePtr N, BatchUpdatePtr BUI)
static void InsertUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr From, const NodePtr To)
static void ApplyNextUpdate(DomTreeT &DT, BatchUpdateInfo &BUI)
DomTreeNodeBase< NodeT > * TreeNodePtr
static bool VerifyDFSNumbers(const DomTreeT &DT)
static void DeleteUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI, const TreeNodePtr ToTN)
void attachNewSubtree(DomTreeT &DT, const TreeNodePtr AttachTo)
static auto getChildren(NodePtr N)
static void InsertEdge(DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr From, const NodePtr To)
BatchUpdateInfo * BatchUpdates
SmallVector< std::pair< unsigned, unsigned >, 32 > ReverseChildren
Reverse children of nodes; pairs of (DFSNum (predecessor), next-or-zero); forms a linked list in this...
bool verifyParentProperty(const DomTreeT &DT)
bool verifyRoots(const DomTreeT &DT)
std::conditional_t< GraphHasNodeNumbers< NodePtr >, SmallVector< InfoRec, 64 >, DenseMap< NodePtr, InfoRec > > NodeInfos