24 #define DEBUG_TYPE "lcg"
26 void LazyCallGraph::EdgeSequence::insertEdgeInternal(Node &TargetN,
28 EdgeIndexMap.insert({&TargetN, Edges.
size()});
32 void LazyCallGraph::EdgeSequence::setEdgeKind(Node &TargetN,
Edge::Kind EK) {
33 Edges[EdgeIndexMap.find(&TargetN)->second].setKind(EK);
36 bool LazyCallGraph::EdgeSequence::removeEdgeInternal(Node &TargetN) {
37 auto IndexMapI = EdgeIndexMap.find(&TargetN);
38 if (IndexMapI == EdgeIndexMap.end())
41 Edges[IndexMapI->second] = Edge();
42 EdgeIndexMap.erase(IndexMapI);
52 DEBUG(
dbgs() <<
" Added callable function: " <<
N.getName() <<
"\n");
57 assert(!Edges &&
"Must not have already populated the edges for this node!");
60 <<
"' to the graph.\n");
62 Edges = EdgeSequence();
88 if (!Callee->isDeclaration())
89 if (Callees.
insert(Callee).second) {
91 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->
get(*Callee),
105 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->
get(F),
111 for (
auto *F : G->LibFunctions)
112 if (!Visited.
count(F))
113 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->
get(*F),
119 void LazyCallGraph::Node::replaceFunction(
Function &NewF) {
120 assert(F != &NewF &&
"Must not replace a function with itself!");
124 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
126 dbgs() << *
this <<
'\n';
147 LibFunctions.insert(&F);
155 <<
"' to entry set of the graph.\n");
163 if (GV.hasInitializer())
167 DEBUG(
dbgs() <<
" Adding functions referenced by global initializers to the "
170 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap,
get(F),
176 : BPA(std::move(
G.BPA)), NodeMap(std::move(
G.NodeMap)),
177 EntryEdges(std::move(
G.EntryEdges)), SCCBPA(std::move(
G.SCCBPA)),
178 SCCMap(std::move(
G.SCCMap)), LeafRefSCCs(std::move(
G.LeafRefSCCs)),
179 LibFunctions(std::move(
G.LibFunctions)) {
184 BPA = std::move(
G.BPA);
185 NodeMap = std::move(
G.NodeMap);
186 EntryEdges = std::move(
G.EntryEdges);
187 SCCBPA = std::move(
G.SCCBPA);
188 SCCMap = std::move(
G.SCCMap);
189 LeafRefSCCs = std::move(
G.LeafRefSCCs);
190 LibFunctions = std::move(
G.LibFunctions);
195 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
197 dbgs() << *
this <<
'\n';
202 void LazyCallGraph::SCC::verify() {
203 assert(OuterRefSCC &&
"Can't have a null RefSCC!");
204 assert(!Nodes.empty() &&
"Can't have an empty SCC!");
206 for (Node *
N : Nodes) {
207 assert(
N &&
"Can't have a null node!");
208 assert(OuterRefSCC->G->lookupSCC(*
N) ==
this &&
209 "Node does not map to this SCC!");
211 "Must set DFS numbers to -1 when adding a node to an SCC!");
213 "Must set low link to -1 when adding a node to an SCC!");
215 assert(
E.getNode() &&
"Can't have an unpopulated node!");
224 for (
Node &
N : *
this)
226 if (OuterRefSCC->G->lookupSCC(
E.getNode()) == &C)
234 if (
this == &TargetC)
247 for (
Edge &
E :
N->calls()) {
253 if (CalleeC == &TargetC)
258 if (Visited.
insert(CalleeC).second)
261 }
while (!Worklist.
empty());
269 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
271 dbgs() << *
this <<
'\n';
276 void LazyCallGraph::RefSCC::verify() {
277 assert(
G &&
"Can't have a null graph!");
278 assert(!SCCs.empty() &&
"Can't have an empty SCC!");
282 for (SCC *
C : SCCs) {
283 assert(
C &&
"Can't have a null SCC!");
285 assert(&
C->getOuterRefSCC() ==
this &&
286 "SCC doesn't think it is inside this RefSCC!");
287 bool Inserted = SCCSet.insert(
C).second;
288 assert(Inserted &&
"Found a duplicate SCC!");
289 auto IndexIt = SCCIndices.find(
C);
290 assert(IndexIt != SCCIndices.end() &&
291 "Found an SCC that doesn't have an index!");
295 for (
auto &SCCIndexPair : SCCIndices) {
296 SCC *
C = SCCIndexPair.first;
297 int i = SCCIndexPair.second;
298 assert(C &&
"Can't have a null SCC in the indices!");
299 assert(SCCSet.count(C) &&
"Found an index for an SCC not in the RefSCC!");
300 assert(SCCs[i] == C &&
"Index doesn't point to SCC!");
304 for (
int i = 0,
Size = SCCs.size(); i <
Size; ++i) {
305 SCC &SourceSCC = *SCCs[i];
306 for (Node &
N : SourceSCC)
310 SCC &TargetSCC = *
G->lookupSCC(
E.getNode());
311 if (&TargetSCC.getOuterRefSCC() ==
this) {
312 assert(SCCIndices.find(&TargetSCC)->second <= i &&
313 "Edge between SCCs violates post-order relationship.");
316 assert(TargetSCC.getOuterRefSCC().Parents.count(
this) &&
317 "Edge to a RefSCC missing us in its parent set.");
322 for (RefSCC *ParentRC : Parents) {
323 assert(ParentRC !=
this &&
"Cannot be our own parent!");
324 auto HasConnectingEdge = [&] {
325 for (SCC &C : *ParentRC)
328 if (
G->lookupRefSCC(
E.getNode()) ==
this)
332 assert(HasConnectingEdge() &&
"No edge connects the parent to us!");
345 for (
const RefSCC *ParentC : AncestorC->Parents)
347 }
while (!AncestorWorklist.
empty());
414 template <
typename SCCT,
typename PostorderSequenceT,
typename SCCIndexMapT,
415 typename ComputeSourceConnectedSetCallableT,
416 typename ComputeTargetConnectedSetCallableT>
419 SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs,
420 SCCIndexMapT &SCCIndices,
421 ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,
422 ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) {
423 int SourceIdx = SCCIndices[&SourceSCC];
424 int TargetIdx = SCCIndices[&TargetSCC];
425 assert(SourceIdx < TargetIdx &&
"Cannot have equal indices here!");
430 ComputeSourceConnectedSet(ConnectedSet);
435 auto SourceI = std::stable_partition(
436 SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
437 [&ConnectedSet](SCCT *
C) {
return !ConnectedSet.
count(C); });
438 for (
int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
439 SCCIndices.find(SCCs[i])->second = i;
443 if (!ConnectedSet.
count(&TargetSCC)) {
444 assert(SourceI > (SCCs.begin() + SourceIdx) &&
445 "Must have moved the source to fix the post-order.");
446 assert(*std::prev(SourceI) == &TargetSCC &&
447 "Last SCC to move should have bene the target.");
451 return make_range(std::prev(SourceI), std::prev(SourceI));
454 assert(SCCs[TargetIdx] == &TargetSCC &&
455 "Should not have moved target if connected!");
456 SourceIdx = SourceI - SCCs.begin();
457 assert(SCCs[SourceIdx] == &SourceSCC &&
458 "Bad updated index computation for the source SCC!");
464 if (SourceIdx + 1 < TargetIdx) {
465 ConnectedSet.
clear();
466 ComputeTargetConnectedSet(ConnectedSet);
470 auto TargetI = std::stable_partition(
471 SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
472 [&ConnectedSet](SCCT *
C) {
return ConnectedSet.
count(C); });
473 for (
int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
474 SCCIndices.find(SCCs[i])->second = i;
475 TargetIdx = std::prev(TargetI) - SCCs.begin();
476 assert(SCCs[TargetIdx] == &TargetSCC &&
477 "Should always end with the target!");
484 return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
491 assert(!(*SourceN)[TargetN].isCall() &&
"Must start with a ref edge!");
501 SCC &SourceSCC = *
G->lookupSCC(SourceN);
502 SCC &TargetSCC = *
G->lookupSCC(TargetN);
506 if (&SourceSCC == &TargetSCC) {
517 int SourceIdx = SCCIndices[&SourceSCC];
518 int TargetIdx = SCCIndices[&TargetSCC];
519 if (TargetIdx < SourceIdx) {
531 ConnectedSet.insert(&SourceSCC);
532 auto IsConnected = [&](
SCC &
C) {
534 for (
Edge &
E : N->calls())
535 if (ConnectedSet.count(
G->lookupSCC(
E.getNode())))
542 make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
544 ConnectedSet.insert(C);
557 ConnectedSet.insert(&TargetSCC);
566 SCC &EdgeC = *
G->lookupSCC(
E.getNode());
570 if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
574 if (ConnectedSet.insert(&EdgeC).second)
577 }
while (!Worklist.
empty());
585 SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet,
586 ComputeTargetConnectedSet);
590 MergeCB(
makeArrayRef(MergeRange.begin(), MergeRange.end()));
594 if (MergeRange.begin() == MergeRange.end()) {
612 for (
SCC *C : MergeRange) {
614 "We merge *into* the target and shouldn't process it here!");
616 TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
617 for (
Node *N : C->Nodes)
618 G->SCCMap[
N] = &TargetSCC;
625 int IndexOffset = MergeRange.end() - MergeRange.begin();
626 auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
628 SCCIndices[
C] -= IndexOffset;
639 assert((*SourceN)[TargetN].isCall() &&
"Must start with a call edge!");
648 assert(
G->lookupRefSCC(SourceN) ==
this &&
649 "Source must be in this RefSCC.");
650 assert(
G->lookupRefSCC(TargetN) ==
this &&
651 "Target must be in this RefSCC.");
652 assert(
G->lookupSCC(SourceN) !=
G->lookupSCC(TargetN) &&
653 "Source and Target must be in separate SCCs for this to be trivial!");
656 SourceN->setEdgeKind(TargetN,
Edge::Ref);
661 assert((*SourceN)[TargetN].isCall() &&
"Must start with a call edge!");
670 assert(
G->lookupRefSCC(SourceN) ==
this &&
671 "Source must be in this RefSCC.");
672 assert(
G->lookupRefSCC(TargetN) ==
this &&
673 "Target must be in this RefSCC.");
675 SCC &TargetSCC = *
G->lookupSCC(TargetN);
676 assert(
G->lookupSCC(SourceN) == &TargetSCC &&
"Source and Target must be in "
677 "the same SCC to require the "
681 SourceN->setEdgeKind(TargetN,
Edge::Ref);
695 SCC &OldSCC = TargetSCC;
702 Worklist.
swap(OldSCC.Nodes);
703 for (
Node *N : Worklist) {
704 N->DFSNumber = N->LowLink = 0;
716 TargetN.DFSNumber = TargetN.LowLink = -1;
717 OldSCC.Nodes.push_back(&TargetN);
718 G->SCCMap[&TargetN] = &OldSCC;
721 for (
Node *RootN : Worklist) {
723 "Cannot begin a new root with a non-empty DFS stack!");
725 "Cannot begin a new root with pending nodes for an SCC!");
728 if (RootN->DFSNumber != 0) {
729 assert(RootN->DFSNumber == -1 &&
730 "Shouldn't have any mid-DFS root nodes!");
734 RootN->DFSNumber = RootN->LowLink = 1;
735 int NextDFSNumber = 2;
737 DFSStack.
push_back({RootN, (*RootN)->call_begin()});
742 auto E = (*N)->call_end();
744 Node &ChildN = I->getNode();
745 if (ChildN.DFSNumber == 0) {
750 assert(!
G->SCCMap.count(&ChildN) &&
751 "Found a node with 0 DFS number but already in an SCC!");
752 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
754 I = (*N)->call_begin();
755 E = (*N)->call_end();
760 if (ChildN.DFSNumber == -1) {
761 if (
G->lookupSCC(ChildN) == &OldSCC) {
766 int OldSize = OldSCC.
size();
767 OldSCC.Nodes.push_back(N);
768 OldSCC.Nodes.append(PendingSCCStack.
begin(), PendingSCCStack.
end());
769 PendingSCCStack.
clear();
770 while (!DFSStack.
empty())
773 N.DFSNumber = N.LowLink = -1;
774 G->SCCMap[&
N] = &OldSCC;
788 assert(ChildN.LowLink > 0 &&
"Must have a positive low-link number!");
789 if (ChildN.LowLink < N->LowLink)
790 N->LowLink = ChildN.LowLink;
805 if (N->LowLink != N->DFSNumber)
810 int RootDFSNumber = N->DFSNumber;
816 return N->DFSNumber < RootDFSNumber;
821 NewSCCs.
push_back(
G->createSCC(*
this, SCCNodes));
823 N.DFSNumber = N.LowLink = -1;
824 G->SCCMap[&
N] = NewSCCs.
back();
826 PendingSCCStack.
erase(SCCNodes.end().base(), PendingSCCStack.
end());
827 }
while (!DFSStack.
empty());
834 int OldIdx = SCCIndices[&OldSCC];
835 SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.
begin(), NewSCCs.
end());
839 for (
int Idx = OldIdx, Size = SCCs.size(); Idx <
Size; ++Idx)
840 SCCIndices[SCCs[Idx]] = Idx;
843 SCCs.begin() + OldIdx + NewSCCs.
size());
848 assert(!(*SourceN)[TargetN].isCall() &&
"Must start with a ref edge!");
850 assert(
G->lookupRefSCC(SourceN) ==
this &&
"Source must be in this RefSCC.");
851 assert(
G->lookupRefSCC(TargetN) !=
this &&
852 "Target must not be in this RefSCC.");
853 #ifdef EXPENSIVE_CHECKS
854 assert(
G->lookupRefSCC(TargetN)->isDescendantOf(*
this) &&
855 "Target must be a descendant of the Source.");
870 assert((*SourceN)[TargetN].isCall() &&
"Must start with a call edge!");
872 assert(
G->lookupRefSCC(SourceN) ==
this &&
"Source must be in this RefSCC.");
873 assert(
G->lookupRefSCC(TargetN) !=
this &&
874 "Target must not be in this RefSCC.");
875 #ifdef EXPENSIVE_CHECKS
876 assert(
G->lookupRefSCC(TargetN)->isDescendantOf(*
this) &&
877 "Target must be a descendant of the Source.");
882 SourceN->setEdgeKind(TargetN,
Edge::Ref);
892 assert(
G->lookupRefSCC(SourceN) ==
this &&
"Source must be in this RefSCC.");
893 assert(
G->lookupRefSCC(TargetN) ==
this &&
"Target must be in this RefSCC.");
895 SourceN->insertEdgeInternal(TargetN,
Edge::Ref);
906 SourceN->insertEdgeInternal(TargetN, EK);
908 assert(
G->lookupRefSCC(SourceN) ==
this &&
"Source must be in this RefSCC.");
910 RefSCC &TargetC = *
G->lookupRefSCC(TargetN);
911 assert(&TargetC !=
this &&
"Target must not be in this RefSCC.");
912 #ifdef EXPENSIVE_CHECKS
913 assert(TargetC.isDescendantOf(*
this) &&
914 "Target must be a descendant of the Source.");
919 TargetC.Parents.insert(
this);
929 assert(
G->lookupRefSCC(TargetN) ==
this &&
"Target must be in this RefSCC.");
930 RefSCC &SourceC = *
G->lookupRefSCC(SourceN);
931 assert(&SourceC !=
this &&
"Source must not be in this RefSCC.");
932 #ifdef EXPENSIVE_CHECKS
933 assert(SourceC.isDescendantOf(*
this) &&
934 "Source must be a descendant of the Target.");
946 int SourceIdx =
G->RefSCCIndices[&SourceC];
947 int TargetIdx =
G->RefSCCIndices[
this];
948 assert(SourceIdx < TargetIdx &&
949 "Postorder list doesn't see edge as incoming!");
959 Set.insert(&SourceC);
967 int ParentIdx =
G->getRefSCCIndex(ParentRC);
968 assert(ParentIdx > SourceIdx &&
"Parent cannot precede source in postorder!");
969 if (ParentIdx > TargetIdx)
971 if (Set.insert(&ParentRC).second)
975 }
while (!Worklist.
empty());
991 RefSCC &EdgeRC = *
G->lookupRefSCC(
E.getNode());
992 if (
G->getRefSCCIndex(EdgeRC) <= SourceIdx)
996 if (Set.insert(&EdgeRC).second)
999 }
while (!Worklist.
empty());
1008 SourceC, *
this,
G->PostOrderRefSCCs,
G->RefSCCIndices,
1009 ComputeSourceConnectedSet, ComputeTargetConnectedSet);
1022 for (
RefSCC *RC : MergeRange) {
1023 assert(RC !=
this &&
"We're merging into the target RefSCC, so it "
1024 "shouldn't be in the range.");
1027 for (
RefSCC *ParentRC : RC->Parents)
1028 if (!MergeSet.count(ParentRC))
1029 Parents.insert(ParentRC);
1030 RC->Parents.clear();
1036 for (
SCC &InnerC : *RC) {
1037 InnerC.OuterRefSCC =
this;
1038 SCCIndices[&InnerC] = SCCIndex++;
1039 for (
Node &N : InnerC) {
1040 G->SCCMap[&
N] = &InnerC;
1041 for (
Edge &
E : *N) {
1042 RefSCC &ChildRC = *
G->lookupRefSCC(
E.getNode());
1043 if (MergeSet.count(&ChildRC))
1045 ChildRC.Parents.erase(RC);
1046 ChildRC.Parents.insert(
this);
1053 if (MergedSCCs.
empty())
1054 MergedSCCs = std::move(RC->SCCs);
1056 MergedSCCs.
append(RC->SCCs.begin(), RC->SCCs.end());
1058 DeletedRefSCCs.push_back(RC);
1062 for (
SCC &InnerC : *
this)
1063 SCCIndices[&InnerC] = SCCIndex++;
1064 MergedSCCs.
append(SCCs.begin(), SCCs.end());
1065 SCCs = std::move(MergedSCCs);
1068 for (
RefSCC *RC : MergeRange)
1069 G->RefSCCIndices.erase(RC);
1070 int IndexOffset = MergeRange.end() - MergeRange.begin();
1072 G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end());
1074 G->RefSCCIndices[RC] -= IndexOffset;
1078 SourceN->insertEdgeInternal(TargetN,
Edge::Ref);
1084 return DeletedRefSCCs;
1088 assert(
G->lookupRefSCC(SourceN) ==
this &&
1089 "The source must be a member of this RefSCC.");
1091 RefSCC &TargetRC = *
G->lookupRefSCC(TargetN);
1092 assert(&TargetRC !=
this &&
"The target must not be a member of this RefSCC");
1095 "Cannot have a leaf RefSCC source.");
1105 bool Removed = SourceN->removeEdgeInternal(TargetN);
1107 assert(Removed &&
"Target not in the edge set for this caller?");
1109 bool HasOtherEdgeToChildRC =
false;
1110 bool HasOtherChildRC =
false;
1111 for (
SCC *InnerC : SCCs) {
1112 for (
Node &N : *InnerC) {
1113 for (
Edge &
E : *N) {
1114 RefSCC &OtherChildRC = *
G->lookupRefSCC(
E.getNode());
1115 if (&OtherChildRC == &TargetRC) {
1116 HasOtherEdgeToChildRC =
true;
1119 if (&OtherChildRC !=
this)
1120 HasOtherChildRC =
true;
1122 if (HasOtherEdgeToChildRC)
1125 if (HasOtherEdgeToChildRC)
1132 if (!HasOtherEdgeToChildRC) {
1133 bool Removed = TargetRC.Parents.erase(
this);
1136 "Did not find the source SCC in the target SCC's parent list!");
1140 if (TargetRC.Parents.empty())
1143 <<
" edge orphaned the callee's SCC!\n");
1146 if (!HasOtherChildRC)
1147 G->LeafRefSCCs.push_back(
this);
1153 assert(!(*SourceN)[TargetN].isCall() &&
1154 "Cannot remove a call edge, it must first be made a ref edge");
1164 bool Removed = SourceN->removeEdgeInternal(TargetN);
1166 assert(Removed &&
"Target not in the edge set for this caller?");
1172 if (&SourceN == &TargetN)
1177 SCC &SourceC = *
G->lookupSCC(SourceN);
1178 SCC &TargetC = *
G->lookupSCC(TargetN);
1179 if (&SourceC == &TargetC)
1187 const int RootPostOrderNumber = 0;
1188 int PostOrderNumber = RootPostOrderNumber + 1;
1204 for (
Node &N : TargetC)
1205 PostOrderMapping[&
N] = RootPostOrderNumber;
1210 for (
SCC *C : SCCs) {
1215 N.DFSNumber = N.LowLink = 0;
1217 Worklist.
append(C->Nodes.begin(), C->Nodes.end());
1220 auto MarkNodeForSCCNumber = [&PostOrderMapping](
Node &
N,
int Number) {
1221 N.DFSNumber = N.LowLink = -1;
1222 PostOrderMapping[&
N] =
Number;
1229 "Cannot begin a new root with a non-empty DFS stack!");
1231 "Cannot begin a new root with pending nodes for an SCC!");
1235 if (RootN->DFSNumber != 0) {
1236 assert(RootN->DFSNumber == -1 &&
1237 "Shouldn't have any mid-DFS root nodes!");
1241 RootN->DFSNumber = RootN->LowLink = 1;
1242 int NextDFSNumber = 2;
1244 DFSStack.
push_back({RootN, (*RootN)->begin()});
1249 auto E = (*N)->end();
1251 assert(N->DFSNumber != 0 &&
"We should always assign a DFS number "
1252 "before processing a node.");
1255 Node &ChildN = I->getNode();
1256 if (ChildN.DFSNumber == 0) {
1263 ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1265 I = ChildN->
begin();
1269 if (ChildN.DFSNumber == -1) {
1275 auto PostOrderI = PostOrderMapping.
find(&ChildN);
1276 if (PostOrderI != PostOrderMapping.
end() &&
1277 PostOrderI->second == RootPostOrderNumber) {
1278 MarkNodeForSCCNumber(*N, RootPostOrderNumber);
1279 while (!PendingRefSCCStack.
empty())
1280 MarkNodeForSCCNumber(*PendingRefSCCStack.
pop_back_val(),
1281 RootPostOrderNumber);
1282 while (!DFSStack.
empty())
1284 RootPostOrderNumber);
1293 RefSCC &ChildRC = *
G->lookupRefSCC(ChildN);
1294 ChildRC.Parents.erase(
this);
1301 assert(ChildN.LowLink != 0 &&
1302 "Low-link must not be zero with a non-zero DFS number.");
1303 if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
1304 N->LowLink = ChildN.LowLink;
1317 if (N->LowLink != N->DFSNumber) {
1319 "We never found a viable root for a RefSCC to pop off!");
1324 int RootDFSNumber = N->DFSNumber;
1328 PendingRefSCCStack.
rbegin(),
1330 return N->DFSNumber < RootDFSNumber;
1336 int RefSCCNumber = PostOrderNumber++;
1337 for (
Node *N : RefSCCNodes)
1338 MarkNodeForSCCNumber(*N, RefSCCNumber);
1340 PendingRefSCCStack.
erase(RefSCCNodes.end().base(),
1341 PendingRefSCCStack.
end());
1342 }
while (!DFSStack.
empty());
1344 assert(DFSStack.
empty() &&
"Didn't flush the entire DFS stack!");
1345 assert(PendingRefSCCStack.
empty() &&
"Didn't flush all pending nodes!");
1346 }
while (!Worklist.
empty());
1353 for (
int i = 1; i < PostOrderNumber; ++i)
1365 if (!Result.
empty()) {
1366 int Idx =
G->getRefSCCIndex(*
this);
1367 G->PostOrderRefSCCs.insert(
G->PostOrderRefSCCs.begin() + Idx,
1369 for (
int i : seq<int>(Idx,
G->PostOrderRefSCCs.size()))
1370 G->RefSCCIndices[
G->PostOrderRefSCCs[i]] = i;
1371 assert(
G->PostOrderRefSCCs[
G->getRefSCCIndex(*
this)] ==
this &&
1372 "Failed to update this RefSCC's index after insertion!");
1375 for (
SCC *C : SCCs) {
1376 auto PostOrderI = PostOrderMapping.
find(&*C->begin());
1377 assert(PostOrderI != PostOrderMapping.
end() &&
1378 "Cannot have missing mappings for nodes!");
1379 int SCCNumber = PostOrderI->second;
1382 assert(PostOrderMapping.
find(&N)->second == SCCNumber &&
1383 "Cannot have different numbers for nodes in the same SCC!");
1389 RefSCC &RC = *Result[SCCNumber - 1];
1390 int SCCIndex = RC.SCCs.size();
1391 RC.SCCs.push_back(C);
1392 RC.SCCIndices[
C] = SCCIndex;
1393 C->OuterRefSCC = &RC;
1400 for (
RefSCC *RC : Result)
1401 G->connectRefSCC(*RC);
1407 RootPostOrderNumber;
1411 for (
int i = 0, Size = SCCs.size(); i <
Size; ++i)
1412 SCCIndices[SCCs[i]] = i;
1420 for (
Node &N : *C) {
1421 for (
Edge &
E : *N) {
1422 RefSCC &ChildRC = *
G->lookupRefSCC(
E.getNode());
1423 if (&ChildRC ==
this)
1425 ChildRC.Parents.insert(
this);
1432 if (!Result.empty())
1433 assert(!IsLeaf &&
"This SCC cannot be a leaf as we have split out new "
1434 "SCCs by removing this edge.");
1435 if (
none_of(
G->LeafRefSCCs, [&](
RefSCC *C) {
return C ==
this; }))
1436 assert(!IsLeaf &&
"This SCC cannot be a leaf as it already had child "
1437 "SCCs before we removed this edge.");
1443 for (
RefSCC *ParentRC : OldParents)
1444 for (
SCC &ParentC : *ParentRC)
1445 for (
Node &ParentN : ParentC)
1446 for (
Edge &
E : *ParentN) {
1447 RefSCC &RC = *
G->lookupRefSCC(
E.getNode());
1448 if (&RC != ParentRC)
1449 RC.Parents.insert(ParentRC);
1457 if (!Result.empty())
1458 G->LeafRefSCCs.erase(
1459 std::remove(
G->LeafRefSCCs.begin(),
G->LeafRefSCCs.end(),
this),
1460 G->LeafRefSCCs.end());
1464 for (RefSCC *RC : Result)
1472 void LazyCallGraph::RefSCC::handleTrivialEdgeInsertion(Node &SourceN,
1478 assert(
G->lookupRefSCC(SourceN) ==
this &&
"Source must be in this RefSCC.");
1479 RefSCC &TargetRC = *
G->lookupRefSCC(TargetN);
1480 if (&TargetRC ==
this) {
1485 #ifdef EXPENSIVE_CHECKS
1486 assert(TargetRC.isDescendantOf(*
this) &&
1487 "Target must be a descendant of the Source.");
1491 TargetRC.Parents.insert(
this);
1500 #ifdef EXPENSIVE_CHECKS
1503 SCC &SourceC = *
G->lookupSCC(SourceN);
1504 SCC &TargetC = *
G->lookupSCC(TargetN);
1505 if (&SourceC != &TargetC)
1506 assert(SourceC.isAncestorOf(TargetC) &&
1507 "Call edge is not trivial in the SCC graph!");
1508 #endif // EXPENSIVE_CHECKS
1513 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.
size()});
1514 if (!InsertResult.second) {
1516 Edge &
E = SourceN->Edges[InsertResult.first->second];
1526 handleTrivialEdgeInsertion(SourceN, TargetN);
1534 #ifdef EXPENSIVE_CHECKS
1536 RefSCC &SourceRC = *
G->lookupRefSCC(SourceN);
1537 RefSCC &TargetRC = *
G->lookupRefSCC(TargetN);
1538 if (&SourceRC != &TargetRC)
1539 assert(SourceRC.isAncestorOf(TargetRC) &&
1540 "Ref edge is not trivial in the RefSCC graph!");
1541 #endif // EXPENSIVE_CHECKS
1546 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.
size()});
1547 if (!InsertResult.second)
1555 handleTrivialEdgeInsertion(SourceN, TargetN);
1565 assert(
G->lookupRefSCC(N) ==
this &&
1566 "Cannot replace the function of a node outside this RefSCC.");
1568 assert(
G->NodeMap.find(&NewF) ==
G->NodeMap.end() &&
1569 "Must not have already walked the new function!'");
1577 assert(&OldF != &NewF &&
"Cannot replace a function with itself!");
1579 "Must have moved all uses from the old function to the new!");
1582 N.replaceFunction(NewF);
1585 G->NodeMap.erase(&OldF);
1586 G->NodeMap[&NewF] = &
N;
1591 "This method cannot be called after SCCs have been formed!");
1593 return SourceN->insertEdgeInternal(TargetN, EK);
1598 "This method cannot be called after SCCs have been formed!");
1600 bool Removed = SourceN->removeEdgeInternal(TargetN);
1602 assert(Removed &&
"Target not in the edge set for this caller?");
1609 "This routine should only be called on trivially dead functions!");
1614 "Must not remove lib functions from the call graph!");
1616 auto NI = NodeMap.find(&F);
1617 if (NI == NodeMap.end())
1621 Node &N = *NI->second;
1625 EntryEdges.removeEdgeInternal(N);
1627 if (SCCMap.empty()) {
1636 auto CI = SCCMap.find(&N);
1637 assert(CI != SCCMap.end() &&
1638 "Tried to remove a node without an SCC after DFS walk started!");
1639 SCC &C = *CI->second;
1641 RefSCC &RC = C.getOuterRefSCC();
1646 assert(C.size() == 1 &&
"Dead functions must be in a singular SCC");
1647 assert(RC.
size() == 1 &&
"Dead functions must be in a singular RefSCC");
1652 for (
SCC &ParentC : ParentRC)
1653 for (
Node &ParentN : ParentC)
1655 ParentN->removeEdgeInternal(N);
1660 TargetRC->Parents.erase(&RC);
1663 auto LRI =
find(LeafRefSCCs, &RC);
1664 if (LRI != LeafRefSCCs.end())
1665 LeafRefSCCs.erase(LRI);
1667 auto RCIndexI = RefSCCIndices.find(&RC);
1668 int RCIndex = RCIndexI->second;
1669 PostOrderRefSCCs.erase(PostOrderRefSCCs.begin() + RCIndex);
1670 RefSCCIndices.erase(RCIndexI);
1671 for (
int i = RCIndex, Size = PostOrderRefSCCs.size(); i <
Size; ++i)
1672 RefSCCIndices[PostOrderRefSCCs[i]] = i;
1685 return *
new (MappedN = BPA.Allocate()) Node(*
this, F);
1688 void LazyCallGraph::updateGraphPtrs() {
1692 for (Edge &
E : EntryEdges)
1695 while (!Worklist.
empty()) {
1708 while (!Worklist.
empty()) {
1711 for (RefSCC &ParentC : C.parents())
1717 template <
typename RootsT,
typename GetBeginT,
typename GetEndT,
1718 typename GetNodeT,
typename FormSCCCallbackT>
1719 void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
1720 GetEndT &&GetEnd, GetNodeT &&GetNode,
1721 FormSCCCallbackT &&FormSCC) {
1722 typedef decltype(GetBegin(std::declval<Node &>())) EdgeItT;
1724 SmallVector<std::pair<Node *, EdgeItT>, 16> DFSStack;
1728 for (Node *RootN : Roots) {
1729 assert(DFSStack.empty() &&
1730 "Cannot begin a new root with a non-empty DFS stack!");
1732 "Cannot begin a new root with pending nodes for an SCC!");
1735 if (RootN->DFSNumber != 0) {
1736 assert(RootN->DFSNumber == -1 &&
1737 "Shouldn't have any mid-DFS root nodes!");
1741 RootN->DFSNumber = RootN->LowLink = 1;
1742 int NextDFSNumber = 2;
1744 DFSStack.push_back({RootN, GetBegin(*RootN)});
1748 std::tie(N, I) = DFSStack.pop_back_val();
1749 auto E = GetEnd(*N);
1751 Node &ChildN = GetNode(I);
1752 if (ChildN.DFSNumber == 0) {
1755 DFSStack.push_back({
N, I});
1757 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1767 if (ChildN.DFSNumber == -1) {
1773 assert(ChildN.LowLink > 0 &&
"Must have a positive low-link number!");
1774 if (ChildN.LowLink < N->LowLink)
1775 N->LowLink = ChildN.LowLink;
1787 if (N->LowLink != N->DFSNumber)
1792 int RootDFSNumber = N->DFSNumber;
1796 PendingSCCStack.
rbegin(),
1797 find_if(
reverse(PendingSCCStack), [RootDFSNumber](
const Node *N) {
1798 return N->DFSNumber < RootDFSNumber;
1803 PendingSCCStack.
erase(SCCNodes.end().base(), PendingSCCStack.
end());
1804 }
while (!DFSStack.empty());
1813 void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
1814 assert(RC.SCCs.empty() &&
"Already built SCCs!");
1815 assert(RC.SCCIndices.empty() &&
"Already mapped SCC indices!");
1817 for (Node *N : Nodes) {
1818 assert(N->LowLink >= (*Nodes.begin())->LowLink &&
1819 "We cannot have a low link in an SCC lower than its root on the "
1824 N->DFSNumber = N->LowLink = 0;
1831 Nodes, [](Node &N) {
return N->call_begin(); },
1832 [](Node &
N) {
return N->call_end(); },
1833 [](EdgeSequence::call_iterator
I) -> Node & {
return I->getNode(); },
1834 [
this, &RC](node_stack_range Nodes) {
1835 RC.SCCs.
push_back(createSCC(RC, Nodes));
1836 for (Node &N : *RC.SCCs.
back()) {
1837 N.DFSNumber = N.LowLink = -1;
1838 SCCMap[&
N] = RC.SCCs.back();
1843 for (
int i = 0, Size = RC.SCCs.size(); i <
Size; ++i)
1844 RC.SCCIndices[RC.SCCs[i]] = i;
1848 if (EntryEdges.empty() || !PostOrderRefSCCs.empty())
1852 assert(RefSCCIndices.empty() &&
"Already mapped RefSCC indices!");
1855 for (
Edge &
E : *
this)
1869 [](Node &
N) {
return N->
end(); },
1872 RefSCC *NewRC = createRefSCC(*
this);
1873 buildSCCs(*NewRC, Nodes);
1874 connectRefSCC(*NewRC);
1879 RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).
second;
1881 assert(Inserted &&
"Cannot already have this RefSCC in the index map!");
1882 PostOrderRefSCCs.push_back(NewRC);
1891 void LazyCallGraph::connectRefSCC(RefSCC &RC) {
1898 for (Edge &
E : *N) {
1900 if (&ChildRC == &RC)
1902 ChildRC.Parents.insert(&RC);
1908 LeafRefSCCs.push_back(&RC);
1918 OS <<
" " << (
E.isCall() ?
"call" :
"ref ") <<
" -> "
1919 <<
E.getFunction().getName() <<
"\n";
1926 OS <<
" SCC with " << Size <<
" functions:\n";
1929 OS <<
" " << N.getFunction().getName() <<
"\n";
1934 OS <<
" RefSCC with " << Size <<
" call SCCs:\n";
1966 OS <<
" " << Name <<
" -> \""
1969 OS <<
" [style=dashed,label=\"ref\"]";
SCC * lookupSCC(Node &N) const
Lookup a function's SCC in the graph.
void push_back(const T &Elt)
This routine provides some synthesis utilities to produce sequences of values.
bool isChildOf(const RefSCC &C) const
Test if this RefSCC is a child of C.
void insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK)
Update the call graph after inserting a new edge.
iterator_range< call_iterator > calls()
void removeOutgoingEdge(Node &SourceN, Node &TargetN)
Remove an edge whose source is in this RefSCC and target is not.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
void removeEdge(Node &SourceN, Node &TargetN)
Update the call graph after deleting an edge.
EdgeSequence & populate()
Populate the edges of this node if necessary.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
A Module instance is used to store all the information related to an LLVM module. ...
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
Kind
The kind of edge in the graph.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
The edge sequence object.
Node & getNode() const
Get the call graph node referenced by this edge.
Implements a lazy call graph analysis and related passes for the new pass manager.
An efficient, type-erasing, non-owning reference to a callable.
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
Node & get(Function &F)
Get a graph node for a given function, scanning it to populate the graph data as necessary.
static void printNode(raw_ostream &OS, LazyCallGraph::Node &N)
StringRef getName() const
Return a constant reference to the value's name.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
LazyCallGraph(Module &M, TargetLibraryInfo &TLI)
Construct a graph for the given module.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
bool isAncestorOf(const SCC &C) const
Test if this SCC is an ancestor of C.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
bool isLibFunction(Function &F) const
Test whether a function is a known and defined library function tracked by the call graph...
bool isDescendantOf(const RefSCC &C) const
Test if this RefSCC is a descendant of C.
LLVM_NODISCARD bool empty() const
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
A RefSCC of the call graph.
bool isCall() const
Test whether the edge represents a direct call to a function.
void insertTrivialCallEdge(Node &SourceN, Node &TargetN)
A convenience wrapper around the above to handle trivial cases of inserting a new call edge...
A lazily constructed view of the call graph of a module.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
iterator_range< parent_iterator > parents() const
LazyCallGraph & operator=(LazyCallGraph &&RHS)
void replaceNodeFunction(Node &N, Function &NewF)
Directly replace a node's function with a new function.
static void addEdge(SmallVectorImpl< LazyCallGraph::Edge > &Edges, DenseMap< LazyCallGraph::Node *, int > &EdgeIndexMap, LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK)
void switchOutgoingEdgeToCall(Node &SourceN, Node &TargetN)
Make an existing outgoing ref edge into a call edge.
iterator find(const_arg_type_t< KeyT > Val)
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
static bool isKnownLibFunction(Function &F, TargetLibraryInfo &TLI)
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
An iterator used for the edges to both entry nodes and child nodes.
LazyCallGraphDOTPrinterPass(raw_ostream &OS)
std::string EscapeString(const std::string &Label)
void swap(SmallVectorImpl &RHS)
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
void switchOutgoingEdgeToRef(Node &SourceN, Node &TargetN)
Make an existing outgoing call edge into a ref edge.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void insertInternalRefEdge(Node &SourceN, Node &TargetN)
Insert a ref edge from one node in this RefSCC to another in this RefSCC.
static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N)
SmallVector< RefSCC *, 1 > removeInternalRefEdge(Node &SourceN, Node &TargetN)
Remove a ref edge which is entirely within this RefSCC.
SmallVector< RefSCC *, 1 > insertIncomingRefEdge(Node &SourceN, Node &TargetN)
Insert an edge whose source is in a descendant RefSCC and target is in this RefSCC.
for(unsigned i=0, e=MI->getNumOperands();i!=e;++i)
RefSCC & getOuterRefSCC() const
A node in the call graph.
A class used to represent edges in the call graph.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Function & getFunction() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void removeDeadFunction(Function &F)
Remove a dead function from the call graph (typically to delete it).
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Provides information about what library functions are available for the current target.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
LLVM_NODISCARD T pop_back_val()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
A range adaptor for a pair of iterators.
An iterator over specifically call edges.
void insertOutgoingEdge(Node &SourceN, Node &TargetN, Edge::Kind EK)
Insert an edge whose parent is in this RefSCC and child is in some child RefSCC.
static void visitReferences(SmallVectorImpl< Constant * > &Worklist, SmallPtrSetImpl< Constant * > &Visited, CallbackT Callback)
Recursively visits the defined functions whose address is reachable from every constant in the Workli...
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
void switchTrivialInternalEdgeToRef(Node &SourceN, Node &TargetN)
Make an existing internal call edge between separate SCCs into a ref edge.
iterator_range< iterator > switchInternalEdgeToRef(Node &SourceN, Node &TargetN)
Make an existing internal call edge within a single SCC into a ref edge.
bool switchInternalEdgeToCall(Node &SourceN, Node &TargetN, function_ref< void(ArrayRef< SCC * > MergedSCCs)> MergeCB={})
Make an existing internal ref edge into a call edge.
LazyCallGraphPrinterPass(raw_ostream &OS)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void emplace_back(ArgTypes &&...Args)
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool isFunctionVectorizable(StringRef F, unsigned VF) const
static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
StringRef getName() const
static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C)
An analysis pass which computes the call graph for a module.
bool hasLocalLinkage() const
void insertTrivialRefEdge(Node &SourceN, Node &TargetN)
A convenience wrapper around the above to handle trivial cases of inserting a new ref edge...
reverse_iterator rbegin()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static iterator_range< typename PostorderSequenceT::iterator > updatePostorderSequenceForEdgeInsertion(SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs, SCCIndexMapT &SCCIndices, ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet, ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet)
Generic helper that updates a postorder sequence of SCCs for a potentially cycle-introducing edge ins...
LLVM Value Representation.
An SCC of the call graph.
This class implements an extremely fast bulk output stream that can only output to a stream...
A container for analyses that lazily runs them and caches their results.
bool isParentOf(const SCC &C) const
Test if this SCC is a parent of C.
RefSCC * lookupRefSCC(Node &N) const
Lookup a function's RefSCC in the graph.
This header defines various interfaces for pass management in LLVM.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
iterator_range< postorder_ref_scc_iterator > postorder_ref_sccs()
A special type used by analysis passes to provide an address that identifies that particular analysis...
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.