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;
90 using UpdateT =
typename DomTreeT::UpdateType;
120 template <
bool Inversed>
131 using DirectedNodeT =
132 std::conditional_t<Inversed, Inverse<NodePtr>,
NodePtr>;
142 Max =
GraphTraits<
decltype(BB->getParent())>::getMaxNumber(
145 NodeInfos.resize(Max ? Max + 1 : Idx + 1);
163 assert(IDom || DT.getNode(
nullptr));
168 return DT.createNode(BB, IDomNode);
183 BP.
N->printAsOperand(O,
false);
201 template <
bool IsReverse = false,
typename DescendCondition>
203 unsigned AttachToNum,
209 while (!WorkList.
empty()) {
217 BBInfo.Parent = ParentNum;
218 unsigned Num = LastNum++;
219 BBInfo.Semi = BBInfo.Label = Num;
220 BBInfo.DFSNumPlus1 = Num + 1;
229 if (Condition(BB, Succ))
235 if (SuccOrder && Successors.size() > 1)
238 return SuccOrder->find(A)->second < SuccOrder->find(B)->second;
241 for (
const NodePtr Succ : Successors) {
242 if (!Condition(BB, Succ))
266 unsigned eval(
unsigned V,
unsigned LastLinked,
270 if (VInfo->
Parent < LastLinked)
276 Stack.push_back(VInfo);
277 VInfo = NumToInfo[VInfo->
Parent];
278 }
while (VInfo->
Parent >= LastLinked);
283 unsigned PLabel = PInfo->
Label;
285 VInfo = Stack.pop_back_val();
287 unsigned VLabel = VInfo->
Label;
289 VInfo->
Label = PLabel;
293 }
while (!Stack.empty());
299 const unsigned NextDFSNum(
NumToNode.size());
307 for (
unsigned i = 0; i < NextDFSNum; ++i) {
309 IDoms[i] = VInfo.Parent;
310 NumToInfo[i] = &VInfo;
315 for (
unsigned i = NextDFSNum; --i;) {
316 auto &WInfo = *NumToInfo[i];
319 WInfo.Semi = WInfo.Parent;
320 for (
unsigned RCIdx = WInfo.ReverseChildrenStart; RCIdx != 0;) {
322 RCIdx = Entry.second;
323 unsigned SemiU =
eval(Entry.first, i + 1, EvalStack, NumToInfo);
324 if (SemiU < WInfo.Semi)
328 WInfo.Label = WInfo.Semi;
334 for (
unsigned i = 1; i < NextDFSNum; ++i) {
335 auto &WInfo = *NumToInfo[i];
336 unsigned WIDom = IDoms[i];
337 while (WIDom > WInfo.Semi)
338 WIDom = IDoms[WIDom];
354 BBInfo.Semi = BBInfo.Label = 0;
355 BBInfo.DFSNumPlus1 = 1;
364 assert(
N &&
"N must be a valid node");
369 assert(DT.Parent &&
"Parent not set");
377 assert(DT.Parent &&
"Parent pointer is not set");
421 bool HasNonTrivialRoots =
false;
424 if (
Total + 1 != Num) {
425 HasNonTrivialRoots =
true;
432 std::optional<NodeOrderMap> SuccOrder;
433 auto InitSuccOrderOnce = [&]() {
438 SuccOrder->try_emplace(Succ, 0);
441 unsigned NodeNum = 0;
442 for (
const auto Node :
nodes(DT.Parent)) {
444 auto Order = SuccOrder->find(
Node);
445 if (Order != SuccOrder->end()) {
446 assert(Order->second == 0);
447 Order->second = NodeNum;
479 const unsigned NewNum =
483 <<
"(non-trivial root): "
485 Roots.push_back(FurthestAway);
486 LLVM_DEBUG(
dbgs() <<
"\t\t\tPrev DFSNum: " << Num <<
", new DFSNum: "
487 << NewNum <<
"\n\t\t\tRemoving DFS info\n");
488 for (
unsigned i = NewNum; i-- > Num;) {
495 const unsigned PrevNum = Num;
498 for (
unsigned i = PrevNum; i < Num; ++i)
510 assert((
Total + 1 == Num) &&
"Everything should have been visited");
513 if (HasNonTrivialRoots)
539 for (
unsigned i = 0; i < Roots.size(); ++i) {
540 auto &Root = Roots[i];
545 <<
" remains a root\n");
550 for (
unsigned x = 1; x < Num; ++x) {
571 template <
typename DescendCondition>
574 assert(DT.Roots.size() == 1 &&
"Dominators should have a singe root");
575 runDFS(DT.Roots[0], 0, DC, 0);
581 for (
const NodePtr Root : DT.Roots)
582 Num =
runDFS(Root, Num, DC, 0);
586 auto *Parent = DT.Parent;
610 dbgs() <<
"DomTree recalculated, skipping future batch updates\n");
613 if (DT.Roots.empty())
621 DT.RootNode = DT.createNode(Root);
640 DT.createNode(W, IDomNode);
658 return LHS->getLevel() <
RHS->getLevel();
664 std::priority_queue<TreeNodePtr, SmallVector<TreeNodePtr, 8>, Compare>
668#if LLVM_ENABLE_ABI_BREAKING_CHECKS
676 "From has to be a valid CFG node or a virtual root");
677 assert(To &&
"Cannot be a nullptr");
689 FromTN = DT.createNode(From, VirtualRoot);
690 DT.Roots.push_back(From);
693 DT.DFSInfoValid =
false;
710 if (!DT.isVirtualRoot(To->
getIDom()))
717 <<
" is no longer a root\n\t\tRebuilding the tree!!!\n");
725 if (
A.size() !=
B.size())
729 if (Set.count(
N) == 0)
742 return HasForwardSuccessors(N, BUI);
755 <<
"The entire tree needs to be rebuilt\n");
776 assert(NCDBlock || DT.isPostDominator());
781 const unsigned NCDLevel = NCD->
getLevel();
799 II.Visited.insert(To);
801 while (!
II.Bucket.empty()) {
804 II.Affected.push_back(TN);
806 const unsigned CurrentLevel = TN->
getLevel();
808 <<
"as affected, CurrentLevel " << CurrentLevel
825 "Unreachable successor found at reachable insertion");
826 const unsigned SuccLevel = SuccTN->
getLevel();
829 <<
", level = " << SuccLevel <<
"\n");
838 if (SuccLevel <= NCDLevel + 1 || !
II.Visited.insert(SuccTN).second)
841 if (SuccLevel > CurrentLevel) {
846 UnaffectedOnCurrentLevel.
push_back(SuccTN);
847#if LLVM_ENABLE_ABI_BREAKING_CHECKS
848 II.VisitedUnaffected.push_back(SuccTN);
854 <<
" to a Bucket\n");
855 II.Bucket.push(SuccTN);
859 if (UnaffectedOnCurrentLevel.
empty())
881#if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
884 "TN should have been updated by an affected ancestor");
908 for (
const auto &Edge : DiscoveredEdgesToReachable) {
921 &DiscoveredConnectingEdges) {
922 assert(!DT.getNode(Root) &&
"Root must not be reachable");
925 auto UnreachableDescender = [&DT, &DiscoveredConnectingEdges](
NodePtr From,
931 DiscoveredConnectingEdges.push_back({From, ToTN});
936 SNCA.
runDFS(Root, 0, UnreachableDescender, 0);
945 assert(From && To &&
"Cannot disconnect nullptrs");
949#if LLVM_ENABLE_ABI_BREAKING_CHECKS
953 auto IsSuccessor = [BUI](
const NodePtr SuccCandidate,
const NodePtr Of) {
958 assert(!IsSuccessor(To, From) &&
"Deleted edge still exists in the CFG!");
970 <<
") already unreachable -- there is no edge to delete\n");
974 const NodePtr NCDBlock = DT.findNearestCommonDominator(From, To);
979 DT.DFSInfoValid =
false;
1009 assert(ToIDom || DT.isPostDominator());
1015 if (!PrevIDomSubTree) {
1022 const unsigned Level = ToIDomTN->
getLevel();
1024 return DT.getNode(To)->getLevel() > Level;
1031 SNCA.
runDFS(ToIDom, 0, DescendBelow, 0);
1046 if (!DT.getNode(Pred))
1049 const NodePtr Support = DT.findNearestCommonDominator(TNB, Pred);
1051 if (Support != TNB) {
1053 <<
" is reachable from support "
1075 LLVM_DEBUG(
dbgs() <<
"\tDeletion made a region reverse-unreachable\n");
1078 DT.Roots.push_back(ToTN->
getBlock());
1084 const unsigned Level = ToTN->
getLevel();
1088 auto DescendAndCollect = [Level, &AffectedQueue, &DT](
NodePtr,
NodePtr To) {
1100 unsigned LastDFSNum =
1107 for (
const NodePtr N : AffectedQueue) {
1111 assert(NCDBlock || DT.isPostDominator());
1131 for (
unsigned i = LastDFSNum; i-- > 0;) {
1139 if (MinNode == ToTN)
1142 LLVM_DEBUG(
dbgs() <<
"DeleteUnreachable: running DFS with MinNode = "
1144 const unsigned MinLevel = MinNode->
getLevel();
1153 return ToTN->
getLevel() > MinLevel;
1154 DT.createNode(To, DT.getNode(R));
1176 if (NumUpdates == 0)
1181 if (NumUpdates == 1) {
1184 if (Update.getKind() == UpdateKind::Insert)
1185 InsertEdge(DT,
nullptr, Update.getFrom(), Update.getTo());
1187 DeleteEdge(DT,
nullptr, Update.getFrom(), Update.getTo());
1190 if (Update.getKind() == UpdateKind::Insert)
1191 InsertEdge(DT, &BUI, Update.getFrom(), Update.getTo());
1193 DeleteEdge(DT, &BUI, Update.getFrom(), Update.getTo());
1207 if (DT.DomTreeNodes.size() <= 100) {
1210 }
else if (BUI.
NumLegalized > DT.DomTreeNodes.size() / 40)
1231 if (CurrentUpdate.getKind() == UpdateKind::Insert)
1232 InsertEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
1234 DeleteEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
1247 if (!DT.Parent && !DT.Roots.empty()) {
1248 errs() <<
"Tree has no parent but has roots!\n";
1254 if (DT.Roots.empty()) {
1255 errs() <<
"Tree doesn't have a root!\n";
1261 errs() <<
"Tree's root is not its parent's entry node!\n";
1269 errs() <<
"Tree has different roots than freshly computed ones!\n";
1270 errs() <<
"\tPDT roots: ";
1273 errs() <<
"\n\tComputed roots: ";
1274 for (
const NodePtr N : ComputedRoots)
1290 for (
auto *TN : DT.DomTreeNodes) {
1293 const NodePtr BB = TN->getBlock();
1296 if (DT.isVirtualRoot(TN))
1301 <<
" not found by DFS walk!\n";
1309 if (
N && !DT.getNode(
N)) {
1311 <<
" not found in the DomTree!\n";
1325 for (
auto *TN : DT.DomTreeNodes) {
1328 const NodePtr BB = TN->getBlock();
1333 if (!IDom && TN->
getLevel() != 0) {
1335 <<
" has a nonzero level " << TN->getLevel() <<
"!\n";
1343 << TN->getLevel() <<
" while its IDom "
1359 if (!DT.DFSInfoValid || !DT.Parent)
1365 auto PrintNodeAndDFSNums = [](
const TreeNodePtr TN) {
1367 << TN->getDFSNumOut() <<
'}';
1373 errs() <<
"DFSIn number for the tree root is not:\n\t";
1374 PrintNodeAndDFSNums(Root);
1382 for (
auto *
Node : DT.DomTreeNodes) {
1387 if (
Node->isLeaf()) {
1388 if (
Node->getDFSNumIn() + 1 !=
Node->getDFSNumOut()) {
1389 errs() <<
"Tree leaf should have DFSOut = DFSIn + 1:\n\t";
1390 PrintNodeAndDFSNums(
Node);
1406 auto PrintChildrenError =
1411 errs() <<
"Incorrect DFS numbers for:\n\tParent ";
1412 PrintNodeAndDFSNums(
Node);
1414 errs() <<
"\n\tChild ";
1415 PrintNodeAndDFSNums(FirstCh);
1418 errs() <<
"\n\tSecond child ";
1419 PrintNodeAndDFSNums(SecondCh);
1422 errs() <<
"\nAll children: ";
1424 PrintNodeAndDFSNums(Ch);
1432 if (Children.front()->getDFSNumIn() !=
Node->getDFSNumIn() + 1) {
1433 PrintChildrenError(Children.front(),
nullptr);
1437 if (Children.back()->getDFSNumOut() !=
Node->getDFSNumOut()) {
1438 PrintChildrenError(Children.back(),
nullptr);
1442 for (
size_t i = 0, e = Children.size() - 1; i != e; ++i) {
1443 if (Children[i]->getDFSNumOut() != Children[i + 1]->getDFSNumIn()) {
1444 PrintChildrenError(Children[i], Children[i + 1]);
1497 for (
auto *TN : DT.DomTreeNodes) {
1500 const NodePtr BB = TN->getBlock();
1501 if (!BB || TN->isLeaf())
1508 return From != BB && To != BB;
1515 <<
" is removed!\n";
1532 for (
auto *TN : DT.DomTreeNodes) {
1535 const NodePtr BB = TN->getBlock();
1536 if (!BB || TN->isLeaf())
1543 return From != BBN && To != BBN;
1553 <<
" is removed!\n";
1574 FreshTree.recalculate(*DT.Parent);
1575 const bool Different = DT.compare(FreshTree);
1578 errs() << (DT.isPostDominator() ?
"Post" :
"")
1579 <<
"DominatorTree is different than a freshly computed one!\n"
1582 errs() <<
"\n\tFreshly computed tree:\n";
1583 FreshTree.print(
errs());
1595template <
typename DomTreeT>
1606template <
class DomTreeT>
1608 typename DomTreeT::NodePtr To) {
1609 if (DT.isPostDominator())
1614template <
class DomTreeT>
1616 typename DomTreeT::NodePtr To) {
1617 if (DT.isPostDominator())
1622template <
class DomTreeT>
1625 DomTreeT::IsPostDominator> &PreViewCFG,
1627 DomTreeT::IsPostDominator> *PostViewCFG) {
1631template <
class DomTreeT>
1632bool Verify(
const DomTreeT &DT,
typename DomTreeT::VerificationLevel VL) {
1646 if (VL == DomTreeT::VerificationLevel::Basic ||
1647 VL == DomTreeT::VerificationLevel::Full)
1650 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.
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.
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.
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
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)
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 constexpr unsigned Unvisited
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)
std::conditional_t< GraphHasNodeNumbers< NodePtr >, SmallVector< InfoRec, 32 >, DenseMap< NodePtr, InfoRec > > NodeInfos
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)
SmallVector< NodePtr, 32 > NumToNode
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)