blob: b6a9436cc1ec3f8079d47e544f961536200ff1e4 [file] [log] [blame]
Chandler Carruthbf71a342014-02-06 04:37:03 +00001//===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Analysis/LazyCallGraph.h"
Chandler Carruth18eadd922014-04-18 10:50:32 +000011#include "llvm/ADT/STLExtras.h"
Chandler Carruth86f0bdf2016-12-09 00:46:44 +000012#include "llvm/ADT/ScopeExit.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000013#include "llvm/ADT/Sequence.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000014#include "llvm/IR/CallSite.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000015#include "llvm/IR/InstVisitor.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000016#include "llvm/IR/Instructions.h"
17#include "llvm/IR/PassManager.h"
Chandler Carruth99b756d2014-04-21 05:04:24 +000018#include "llvm/Support/Debug.h"
Sean Silva7cb30662016-06-18 09:17:32 +000019#include "llvm/Support/GraphWriter.h"
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +000020#include <utility>
Chandler Carruthbf71a342014-02-06 04:37:03 +000021
22using namespace llvm;
23
Chandler Carruthf1221bd2014-04-22 02:48:03 +000024#define DEBUG_TYPE "lcg"
25
Chandler Carruthaaad9f82017-02-09 23:24:13 +000026void LazyCallGraph::EdgeSequence::insertEdgeInternal(Node &TargetN,
27 Edge::Kind EK) {
28 EdgeIndexMap.insert({&TargetN, Edges.size()});
29 Edges.emplace_back(TargetN, EK);
Chandler Carrutha4499e92016-02-02 03:57:13 +000030}
31
Chandler Carruthaaad9f82017-02-09 23:24:13 +000032void LazyCallGraph::EdgeSequence::setEdgeKind(Node &TargetN, Edge::Kind EK) {
33 Edges[EdgeIndexMap.find(&TargetN)->second].setKind(EK);
34}
35
36bool LazyCallGraph::EdgeSequence::removeEdgeInternal(Node &TargetN) {
37 auto IndexMapI = EdgeIndexMap.find(&TargetN);
38 if (IndexMapI == EdgeIndexMap.end())
39 return false;
40
41 Edges[IndexMapI->second] = Edge();
42 EdgeIndexMap.erase(IndexMapI);
43 return true;
44}
45
46static void addEdge(SmallVectorImpl<LazyCallGraph::Edge> &Edges,
47 DenseMap<LazyCallGraph::Node *, int> &EdgeIndexMap,
48 LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK) {
49 if (!EdgeIndexMap.insert({&N, Edges.size()}).second)
50 return;
51
52 DEBUG(dbgs() << " Added callable function: " << N.getName() << "\n");
53 Edges.emplace_back(LazyCallGraph::Edge(N, EK));
54}
55
56LazyCallGraph::EdgeSequence &LazyCallGraph::Node::populateSlow() {
57 assert(!Edges && "Must not have already populated the edges for this node!");
58
59 DEBUG(dbgs() << " Adding functions called by '" << getName()
Chandler Carruth99b756d2014-04-21 05:04:24 +000060 << "' to the graph.\n");
61
Chandler Carruthaaad9f82017-02-09 23:24:13 +000062 Edges = EdgeSequence();
63
Chandler Carruthbf71a342014-02-06 04:37:03 +000064 SmallVector<Constant *, 16> Worklist;
Chandler Carrutha4499e92016-02-02 03:57:13 +000065 SmallPtrSet<Function *, 4> Callees;
Chandler Carruthbf71a342014-02-06 04:37:03 +000066 SmallPtrSet<Constant *, 16> Visited;
Chandler Carrutha4499e92016-02-02 03:57:13 +000067
68 // Find all the potential call graph edges in this function. We track both
69 // actual call edges and indirect references to functions. The direct calls
70 // are trivially added, but to accumulate the latter we walk the instructions
71 // and add every operand which is a constant to the worklist to process
72 // afterward.
Chandler Carruth86f0bdf2016-12-09 00:46:44 +000073 //
74 // Note that we consider *any* function with a definition to be a viable
75 // edge. Even if the function's definition is subject to replacement by
76 // some other module (say, a weak definition) there may still be
77 // optimizations which essentially speculate based on the definition and
78 // a way to check that the specific definition is in fact the one being
79 // used. For example, this could be done by moving the weak definition to
80 // a strong (internal) definition and making the weak definition be an
81 // alias. Then a test of the address of the weak function against the new
82 // strong definition's address would be an effective way to determine the
83 // safety of optimizing a direct call edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +000084 for (BasicBlock &BB : *F)
Chandler Carrutha4499e92016-02-02 03:57:13 +000085 for (Instruction &I : BB) {
86 if (auto CS = CallSite(&I))
87 if (Function *Callee = CS.getCalledFunction())
Chandler Carruth86f0bdf2016-12-09 00:46:44 +000088 if (!Callee->isDeclaration())
89 if (Callees.insert(Callee).second) {
90 Visited.insert(Callee);
Chandler Carruthaaad9f82017-02-09 23:24:13 +000091 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*Callee),
92 LazyCallGraph::Edge::Call);
Chandler Carruth86f0bdf2016-12-09 00:46:44 +000093 }
Chandler Carrutha4499e92016-02-02 03:57:13 +000094
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000095 for (Value *Op : I.operand_values())
Chandler Carruth1583e992014-03-03 10:42:58 +000096 if (Constant *C = dyn_cast<Constant>(Op))
David Blaikie70573dc2014-11-19 07:49:26 +000097 if (Visited.insert(C).second)
Chandler Carruthbf71a342014-02-06 04:37:03 +000098 Worklist.push_back(C);
Chandler Carrutha4499e92016-02-02 03:57:13 +000099 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000100
101 // We've collected all the constant (and thus potentially function or
102 // function containing) operands to all of the instructions in the function.
103 // Process them (recursively) collecting every function found.
Chandler Carruth88823462016-08-24 09:37:14 +0000104 visitReferences(Worklist, Visited, [&](Function &F) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000105 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(F),
106 LazyCallGraph::Edge::Ref);
Chandler Carruth88823462016-08-24 09:37:14 +0000107 });
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000108
109 return *Edges;
Chandler Carruthbf71a342014-02-06 04:37:03 +0000110}
111
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000112void LazyCallGraph::Node::replaceFunction(Function &NewF) {
113 assert(F != &NewF && "Must not replace a function with itself!");
114 F = &NewF;
Chandler Carruthaa839b22014-04-27 01:59:50 +0000115}
116
Matthias Braun8c209aa2017-01-28 02:02:38 +0000117#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
118LLVM_DUMP_METHOD void LazyCallGraph::Node::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000119 dbgs() << *this << '\n';
120}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000121#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000122
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000123LazyCallGraph::LazyCallGraph(Module &M) {
Chandler Carruth99b756d2014-04-21 05:04:24 +0000124 DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
125 << "\n");
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000126 for (Function &F : M)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000127 if (!F.isDeclaration() && !F.hasLocalLinkage()) {
128 DEBUG(dbgs() << " Adding '" << F.getName()
129 << "' to entry set of the graph.\n");
130 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F), Edge::Ref);
131 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000132
133 // Now add entry nodes for functions reachable via initializers to globals.
134 SmallVector<Constant *, 16> Worklist;
135 SmallPtrSet<Constant *, 16> Visited;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000136 for (GlobalVariable &GV : M.globals())
137 if (GV.hasInitializer())
David Blaikie70573dc2014-11-19 07:49:26 +0000138 if (Visited.insert(GV.getInitializer()).second)
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000139 Worklist.push_back(GV.getInitializer());
Chandler Carruthbf71a342014-02-06 04:37:03 +0000140
Chandler Carruth99b756d2014-04-21 05:04:24 +0000141 DEBUG(dbgs() << " Adding functions referenced by global initializers to the "
142 "entry set.\n");
Chandler Carruth88823462016-08-24 09:37:14 +0000143 visitReferences(Worklist, Visited, [&](Function &F) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000144 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F),
145 LazyCallGraph::Edge::Ref);
Chandler Carruth88823462016-08-24 09:37:14 +0000146 });
Chandler Carruthbf71a342014-02-06 04:37:03 +0000147}
148
Chandler Carruthbf71a342014-02-06 04:37:03 +0000149LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
Chandler Carruth2174f442014-04-18 20:44:16 +0000150 : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000151 EntryEdges(std::move(G.EntryEdges)), SCCBPA(std::move(G.SCCBPA)),
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000152 SCCMap(std::move(G.SCCMap)), LeafRefSCCs(std::move(G.LeafRefSCCs)) {
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000153 updateGraphPtrs();
154}
155
156LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
157 BPA = std::move(G.BPA);
Chandler Carruth2174f442014-04-18 20:44:16 +0000158 NodeMap = std::move(G.NodeMap);
Chandler Carrutha4499e92016-02-02 03:57:13 +0000159 EntryEdges = std::move(G.EntryEdges);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000160 SCCBPA = std::move(G.SCCBPA);
161 SCCMap = std::move(G.SCCMap);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000162 LeafRefSCCs = std::move(G.LeafRefSCCs);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000163 updateGraphPtrs();
164 return *this;
165}
166
Matthias Braun8c209aa2017-01-28 02:02:38 +0000167#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
168LLVM_DUMP_METHOD void LazyCallGraph::SCC::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000169 dbgs() << *this << '\n';
170}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000171#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000172
Chandler Carruthe5944d92016-02-17 00:18:16 +0000173#ifndef NDEBUG
174void LazyCallGraph::SCC::verify() {
175 assert(OuterRefSCC && "Can't have a null RefSCC!");
176 assert(!Nodes.empty() && "Can't have an empty SCC!");
Chandler Carruth8f92d6d2014-04-26 01:03:46 +0000177
Chandler Carruthe5944d92016-02-17 00:18:16 +0000178 for (Node *N : Nodes) {
179 assert(N && "Can't have a null node!");
180 assert(OuterRefSCC->G->lookupSCC(*N) == this &&
181 "Node does not map to this SCC!");
182 assert(N->DFSNumber == -1 &&
183 "Must set DFS numbers to -1 when adding a node to an SCC!");
184 assert(N->LowLink == -1 &&
185 "Must set low link to -1 when adding a node to an SCC!");
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000186 for (Edge &E : **N)
187 assert(E.getNode() && "Can't have an unpopulated node!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000188 }
189}
190#endif
191
Chandler Carruthbae595b2016-11-22 19:23:31 +0000192bool LazyCallGraph::SCC::isParentOf(const SCC &C) const {
193 if (this == &C)
194 return false;
195
196 for (Node &N : *this)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000197 for (Edge &E : N->calls())
198 if (OuterRefSCC->G->lookupSCC(E.getNode()) == &C)
199 return true;
Chandler Carruthbae595b2016-11-22 19:23:31 +0000200
201 // No edges found.
202 return false;
203}
204
205bool LazyCallGraph::SCC::isAncestorOf(const SCC &TargetC) const {
206 if (this == &TargetC)
207 return false;
208
209 LazyCallGraph &G = *OuterRefSCC->G;
210
211 // Start with this SCC.
212 SmallPtrSet<const SCC *, 16> Visited = {this};
213 SmallVector<const SCC *, 16> Worklist = {this};
214
215 // Walk down the graph until we run out of edges or find a path to TargetC.
216 do {
217 const SCC &C = *Worklist.pop_back_val();
218 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000219 for (Edge &E : N->calls()) {
220 SCC *CalleeC = G.lookupSCC(E.getNode());
Chandler Carruthbae595b2016-11-22 19:23:31 +0000221 if (!CalleeC)
222 continue;
223
224 // If the callee's SCC is the TargetC, we're done.
225 if (CalleeC == &TargetC)
226 return true;
227
228 // If this is the first time we've reached this SCC, put it on the
229 // worklist to recurse through.
230 if (Visited.insert(CalleeC).second)
231 Worklist.push_back(CalleeC);
232 }
233 } while (!Worklist.empty());
234
235 // No paths found.
236 return false;
237}
238
Chandler Carruthe5944d92016-02-17 00:18:16 +0000239LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {}
240
Matthias Braun8c209aa2017-01-28 02:02:38 +0000241#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
242LLVM_DUMP_METHOD void LazyCallGraph::RefSCC::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000243 dbgs() << *this << '\n';
244}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000245#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000246
Chandler Carruthe5944d92016-02-17 00:18:16 +0000247#ifndef NDEBUG
248void LazyCallGraph::RefSCC::verify() {
249 assert(G && "Can't have a null graph!");
250 assert(!SCCs.empty() && "Can't have an empty SCC!");
251
252 // Verify basic properties of the SCCs.
Chandler Carruth88823462016-08-24 09:37:14 +0000253 SmallPtrSet<SCC *, 4> SCCSet;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000254 for (SCC *C : SCCs) {
255 assert(C && "Can't have a null SCC!");
256 C->verify();
257 assert(&C->getOuterRefSCC() == this &&
258 "SCC doesn't think it is inside this RefSCC!");
Chandler Carruth88823462016-08-24 09:37:14 +0000259 bool Inserted = SCCSet.insert(C).second;
260 assert(Inserted && "Found a duplicate SCC!");
Chandler Carruth23a6c3f2016-12-06 10:29:23 +0000261 auto IndexIt = SCCIndices.find(C);
262 assert(IndexIt != SCCIndices.end() &&
263 "Found an SCC that doesn't have an index!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000264 }
265
266 // Check that our indices map correctly.
267 for (auto &SCCIndexPair : SCCIndices) {
268 SCC *C = SCCIndexPair.first;
269 int i = SCCIndexPair.second;
270 assert(C && "Can't have a null SCC in the indices!");
Chandler Carruth88823462016-08-24 09:37:14 +0000271 assert(SCCSet.count(C) && "Found an index for an SCC not in the RefSCC!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000272 assert(SCCs[i] == C && "Index doesn't point to SCC!");
273 }
274
275 // Check that the SCCs are in fact in post-order.
276 for (int i = 0, Size = SCCs.size(); i < Size; ++i) {
277 SCC &SourceSCC = *SCCs[i];
278 for (Node &N : SourceSCC)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000279 for (Edge &E : *N) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000280 if (!E.isCall())
281 continue;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000282 SCC &TargetSCC = *G->lookupSCC(E.getNode());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000283 if (&TargetSCC.getOuterRefSCC() == this) {
284 assert(SCCIndices.find(&TargetSCC)->second <= i &&
285 "Edge between SCCs violates post-order relationship.");
286 continue;
287 }
288 assert(TargetSCC.getOuterRefSCC().Parents.count(this) &&
289 "Edge to a RefSCC missing us in its parent set.");
290 }
291 }
Chandler Carruth5205c352016-12-07 01:42:40 +0000292
293 // Check that our parents are actually parents.
294 for (RefSCC *ParentRC : Parents) {
295 assert(ParentRC != this && "Cannot be our own parent!");
296 auto HasConnectingEdge = [&] {
297 for (SCC &C : *ParentRC)
298 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000299 for (Edge &E : *N)
300 if (G->lookupRefSCC(E.getNode()) == this)
Chandler Carruth5205c352016-12-07 01:42:40 +0000301 return true;
302 return false;
303 };
304 assert(HasConnectingEdge() && "No edge connects the parent to us!");
305 }
Chandler Carruthe5944d92016-02-17 00:18:16 +0000306}
307#endif
308
309bool LazyCallGraph::RefSCC::isDescendantOf(const RefSCC &C) const {
Chandler Carruth4b096742014-05-01 12:12:42 +0000310 // Walk up the parents of this SCC and verify that we eventually find C.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000311 SmallVector<const RefSCC *, 4> AncestorWorklist;
Chandler Carruth4b096742014-05-01 12:12:42 +0000312 AncestorWorklist.push_back(this);
313 do {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000314 const RefSCC *AncestorC = AncestorWorklist.pop_back_val();
Chandler Carruth4b096742014-05-01 12:12:42 +0000315 if (AncestorC->isChildOf(C))
316 return true;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000317 for (const RefSCC *ParentC : AncestorC->Parents)
Chandler Carruth4b096742014-05-01 12:12:42 +0000318 AncestorWorklist.push_back(ParentC);
319 } while (!AncestorWorklist.empty());
320
321 return false;
322}
323
Chandler Carruth1f621f02016-09-04 08:34:24 +0000324/// Generic helper that updates a postorder sequence of SCCs for a potentially
325/// cycle-introducing edge insertion.
326///
327/// A postorder sequence of SCCs of a directed graph has one fundamental
328/// property: all deges in the DAG of SCCs point "up" the sequence. That is,
329/// all edges in the SCC DAG point to prior SCCs in the sequence.
330///
331/// This routine both updates a postorder sequence and uses that sequence to
332/// compute the set of SCCs connected into a cycle. It should only be called to
333/// insert a "downward" edge which will require changing the sequence to
334/// restore it to a postorder.
335///
336/// When inserting an edge from an earlier SCC to a later SCC in some postorder
337/// sequence, all of the SCCs which may be impacted are in the closed range of
338/// those two within the postorder sequence. The algorithm used here to restore
339/// the state is as follows:
340///
341/// 1) Starting from the source SCC, construct a set of SCCs which reach the
342/// source SCC consisting of just the source SCC. Then scan toward the
343/// target SCC in postorder and for each SCC, if it has an edge to an SCC
344/// in the set, add it to the set. Otherwise, the source SCC is not
345/// a successor, move it in the postorder sequence to immediately before
346/// the source SCC, shifting the source SCC and all SCCs in the set one
347/// position toward the target SCC. Stop scanning after processing the
348/// target SCC.
349/// 2) If the source SCC is now past the target SCC in the postorder sequence,
350/// and thus the new edge will flow toward the start, we are done.
351/// 3) Otherwise, starting from the target SCC, walk all edges which reach an
352/// SCC between the source and the target, and add them to the set of
353/// connected SCCs, then recurse through them. Once a complete set of the
354/// SCCs the target connects to is known, hoist the remaining SCCs between
355/// the source and the target to be above the target. Note that there is no
356/// need to process the source SCC, it is already known to connect.
357/// 4) At this point, all of the SCCs in the closed range between the source
358/// SCC and the target SCC in the postorder sequence are connected,
359/// including the target SCC and the source SCC. Inserting the edge from
360/// the source SCC to the target SCC will form a cycle out of precisely
361/// these SCCs. Thus we can merge all of the SCCs in this closed range into
362/// a single SCC.
363///
364/// This process has various important properties:
365/// - Only mutates the SCCs when adding the edge actually changes the SCC
366/// structure.
367/// - Never mutates SCCs which are unaffected by the change.
368/// - Updates the postorder sequence to correctly satisfy the postorder
369/// constraint after the edge is inserted.
370/// - Only reorders SCCs in the closed postorder sequence from the source to
371/// the target, so easy to bound how much has changed even in the ordering.
372/// - Big-O is the number of edges in the closed postorder range of SCCs from
373/// source to target.
374///
375/// This helper routine, in addition to updating the postorder sequence itself
376/// will also update a map from SCCs to indices within that sequecne.
377///
378/// The sequence and the map must operate on pointers to the SCC type.
379///
380/// Two callbacks must be provided. The first computes the subset of SCCs in
381/// the postorder closed range from the source to the target which connect to
382/// the source SCC via some (transitive) set of edges. The second computes the
383/// subset of the same range which the target SCC connects to via some
384/// (transitive) set of edges. Both callbacks should populate the set argument
385/// provided.
386template <typename SCCT, typename PostorderSequenceT, typename SCCIndexMapT,
387 typename ComputeSourceConnectedSetCallableT,
388 typename ComputeTargetConnectedSetCallableT>
389static iterator_range<typename PostorderSequenceT::iterator>
390updatePostorderSequenceForEdgeInsertion(
391 SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs,
392 SCCIndexMapT &SCCIndices,
393 ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,
394 ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) {
395 int SourceIdx = SCCIndices[&SourceSCC];
396 int TargetIdx = SCCIndices[&TargetSCC];
397 assert(SourceIdx < TargetIdx && "Cannot have equal indices here!");
398
399 SmallPtrSet<SCCT *, 4> ConnectedSet;
400
401 // Compute the SCCs which (transitively) reach the source.
402 ComputeSourceConnectedSet(ConnectedSet);
403
404 // Partition the SCCs in this part of the port-order sequence so only SCCs
405 // connecting to the source remain between it and the target. This is
406 // a benign partition as it preserves postorder.
407 auto SourceI = std::stable_partition(
408 SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
409 [&ConnectedSet](SCCT *C) { return !ConnectedSet.count(C); });
410 for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
411 SCCIndices.find(SCCs[i])->second = i;
412
413 // If the target doesn't connect to the source, then we've corrected the
414 // post-order and there are no cycles formed.
415 if (!ConnectedSet.count(&TargetSCC)) {
416 assert(SourceI > (SCCs.begin() + SourceIdx) &&
417 "Must have moved the source to fix the post-order.");
418 assert(*std::prev(SourceI) == &TargetSCC &&
419 "Last SCC to move should have bene the target.");
420
421 // Return an empty range at the target SCC indicating there is nothing to
422 // merge.
423 return make_range(std::prev(SourceI), std::prev(SourceI));
424 }
425
426 assert(SCCs[TargetIdx] == &TargetSCC &&
427 "Should not have moved target if connected!");
428 SourceIdx = SourceI - SCCs.begin();
429 assert(SCCs[SourceIdx] == &SourceSCC &&
430 "Bad updated index computation for the source SCC!");
431
432
433 // See whether there are any remaining intervening SCCs between the source
434 // and target. If so we need to make sure they all are reachable form the
435 // target.
436 if (SourceIdx + 1 < TargetIdx) {
437 ConnectedSet.clear();
438 ComputeTargetConnectedSet(ConnectedSet);
439
440 // Partition SCCs so that only SCCs reached from the target remain between
441 // the source and the target. This preserves postorder.
442 auto TargetI = std::stable_partition(
443 SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
444 [&ConnectedSet](SCCT *C) { return ConnectedSet.count(C); });
445 for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
446 SCCIndices.find(SCCs[i])->second = i;
447 TargetIdx = std::prev(TargetI) - SCCs.begin();
448 assert(SCCs[TargetIdx] == &TargetSCC &&
449 "Should always end with the target!");
450 }
451
452 // At this point, we know that connecting source to target forms a cycle
453 // because target connects back to source, and we know that all of the SCCs
454 // between the source and target in the postorder sequence participate in that
455 // cycle.
456 return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
457}
458
Chandler Carruthe5944d92016-02-17 00:18:16 +0000459SmallVector<LazyCallGraph::SCC *, 1>
460LazyCallGraph::RefSCC::switchInternalEdgeToCall(Node &SourceN, Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000461 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000462 SmallVector<SCC *, 1> DeletedSCCs;
Chandler Carruth5217c942014-04-30 10:48:36 +0000463
Chandler Carruth11b3f602016-09-04 08:34:31 +0000464#ifndef NDEBUG
465 // In a debug build, verify the RefSCC is valid to start with and when this
466 // routine finishes.
467 verify();
468 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
469#endif
470
Chandler Carruthe5944d92016-02-17 00:18:16 +0000471 SCC &SourceSCC = *G->lookupSCC(SourceN);
472 SCC &TargetSCC = *G->lookupSCC(TargetN);
473
474 // If the two nodes are already part of the same SCC, we're also done as
475 // we've just added more connectivity.
476 if (&SourceSCC == &TargetSCC) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000477 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000478 return DeletedSCCs;
479 }
480
481 // At this point we leverage the postorder list of SCCs to detect when the
482 // insertion of an edge changes the SCC structure in any way.
483 //
484 // First and foremost, we can eliminate the need for any changes when the
485 // edge is toward the beginning of the postorder sequence because all edges
486 // flow in that direction already. Thus adding a new one cannot form a cycle.
487 int SourceIdx = SCCIndices[&SourceSCC];
488 int TargetIdx = SCCIndices[&TargetSCC];
489 if (TargetIdx < SourceIdx) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000490 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000491 return DeletedSCCs;
492 }
493
Chandler Carruthe5944d92016-02-17 00:18:16 +0000494 // Compute the SCCs which (transitively) reach the source.
Chandler Carruth1f621f02016-09-04 08:34:24 +0000495 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000496#ifndef NDEBUG
Chandler Carruth1f621f02016-09-04 08:34:24 +0000497 // Check that the RefSCC is still valid before computing this as the
498 // results will be nonsensical of we've broken its invariants.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000499 verify();
500#endif
Chandler Carruth1f621f02016-09-04 08:34:24 +0000501 ConnectedSet.insert(&SourceSCC);
502 auto IsConnected = [&](SCC &C) {
503 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000504 for (Edge &E : N->calls())
505 if (ConnectedSet.count(G->lookupSCC(E.getNode())))
Chandler Carruth1f621f02016-09-04 08:34:24 +0000506 return true;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000507
Chandler Carruth1f621f02016-09-04 08:34:24 +0000508 return false;
509 };
Chandler Carruthe5944d92016-02-17 00:18:16 +0000510
Chandler Carruth1f621f02016-09-04 08:34:24 +0000511 for (SCC *C :
512 make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
513 if (IsConnected(*C))
514 ConnectedSet.insert(C);
515 };
516
517 // Use a normal worklist to find which SCCs the target connects to. We still
518 // bound the search based on the range in the postorder list we care about,
519 // but because this is forward connectivity we just "recurse" through the
520 // edges.
521 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000522#ifndef NDEBUG
Chandler Carruth1f621f02016-09-04 08:34:24 +0000523 // Check that the RefSCC is still valid before computing this as the
524 // results will be nonsensical of we've broken its invariants.
525 verify();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000526#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000527 ConnectedSet.insert(&TargetSCC);
528 SmallVector<SCC *, 4> Worklist;
529 Worklist.push_back(&TargetSCC);
530 do {
531 SCC &C = *Worklist.pop_back_val();
532 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000533 for (Edge &E : *N) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000534 if (!E.isCall())
535 continue;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000536 SCC &EdgeC = *G->lookupSCC(E.getNode());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000537 if (&EdgeC.getOuterRefSCC() != this)
538 // Not in this RefSCC...
539 continue;
540 if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
541 // Not in the postorder sequence between source and target.
542 continue;
543
544 if (ConnectedSet.insert(&EdgeC).second)
545 Worklist.push_back(&EdgeC);
546 }
547 } while (!Worklist.empty());
Chandler Carruth1f621f02016-09-04 08:34:24 +0000548 };
Chandler Carruthe5944d92016-02-17 00:18:16 +0000549
Chandler Carruth1f621f02016-09-04 08:34:24 +0000550 // Use a generic helper to update the postorder sequence of SCCs and return
551 // a range of any SCCs connected into a cycle by inserting this edge. This
552 // routine will also take care of updating the indices into the postorder
553 // sequence.
554 auto MergeRange = updatePostorderSequenceForEdgeInsertion(
555 SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet,
556 ComputeTargetConnectedSet);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000557
Chandler Carruth1f621f02016-09-04 08:34:24 +0000558 // If the merge range is empty, then adding the edge didn't actually form any
559 // new cycles. We're done.
560 if (MergeRange.begin() == MergeRange.end()) {
561 // Now that the SCC structure is finalized, flip the kind to call.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000562 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruth1f621f02016-09-04 08:34:24 +0000563 return DeletedSCCs;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000564 }
565
Chandler Carruth1f621f02016-09-04 08:34:24 +0000566#ifndef NDEBUG
567 // Before merging, check that the RefSCC remains valid after all the
568 // postorder updates.
569 verify();
570#endif
571
572 // Otherwise we need to merge all of the SCCs in the cycle into a single
Chandler Carruthe5944d92016-02-17 00:18:16 +0000573 // result SCC.
574 //
575 // NB: We merge into the target because all of these functions were already
576 // reachable from the target, meaning any SCC-wide properties deduced about it
577 // other than the set of functions within it will not have changed.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000578 for (SCC *C : MergeRange) {
579 assert(C != &TargetSCC &&
580 "We merge *into* the target and shouldn't process it here!");
581 SCCIndices.erase(C);
582 TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
583 for (Node *N : C->Nodes)
584 G->SCCMap[N] = &TargetSCC;
585 C->clear();
586 DeletedSCCs.push_back(C);
587 }
588
589 // Erase the merged SCCs from the list and update the indices of the
590 // remaining SCCs.
591 int IndexOffset = MergeRange.end() - MergeRange.begin();
592 auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
593 for (SCC *C : make_range(EraseEnd, SCCs.end()))
594 SCCIndices[C] -= IndexOffset;
595
596 // Now that the SCC structure is finalized, flip the kind to call.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000597 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000598
Chandler Carruth11b3f602016-09-04 08:34:31 +0000599 // And we're done!
Chandler Carruthe5944d92016-02-17 00:18:16 +0000600 return DeletedSCCs;
Chandler Carruth5217c942014-04-30 10:48:36 +0000601}
602
Chandler Carruth443e57e2016-12-28 10:34:50 +0000603void LazyCallGraph::RefSCC::switchTrivialInternalEdgeToRef(Node &SourceN,
604 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000605 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruth443e57e2016-12-28 10:34:50 +0000606
607#ifndef NDEBUG
608 // In a debug build, verify the RefSCC is valid to start with and when this
609 // routine finishes.
610 verify();
611 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
612#endif
613
614 assert(G->lookupRefSCC(SourceN) == this &&
615 "Source must be in this RefSCC.");
616 assert(G->lookupRefSCC(TargetN) == this &&
617 "Target must be in this RefSCC.");
618 assert(G->lookupSCC(SourceN) != G->lookupSCC(TargetN) &&
619 "Source and Target must be in separate SCCs for this to be trivial!");
620
621 // Set the edge kind.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000622 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruth443e57e2016-12-28 10:34:50 +0000623}
624
Chandler Carruth88823462016-08-24 09:37:14 +0000625iterator_range<LazyCallGraph::RefSCC::iterator>
626LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN, Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000627 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000628
Chandler Carruth11b3f602016-09-04 08:34:31 +0000629#ifndef NDEBUG
630 // In a debug build, verify the RefSCC is valid to start with and when this
631 // routine finishes.
632 verify();
633 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
634#endif
635
Chandler Carruth443e57e2016-12-28 10:34:50 +0000636 assert(G->lookupRefSCC(SourceN) == this &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000637 "Source must be in this RefSCC.");
Chandler Carruth443e57e2016-12-28 10:34:50 +0000638 assert(G->lookupRefSCC(TargetN) == this &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000639 "Target must be in this RefSCC.");
640
Chandler Carruth443e57e2016-12-28 10:34:50 +0000641 SCC &TargetSCC = *G->lookupSCC(TargetN);
642 assert(G->lookupSCC(SourceN) == &TargetSCC && "Source and Target must be in "
643 "the same SCC to require the "
644 "full CG update.");
645
Chandler Carruthe5944d92016-02-17 00:18:16 +0000646 // Set the edge kind.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000647 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000648
Chandler Carruthe5944d92016-02-17 00:18:16 +0000649 // Otherwise we are removing a call edge from a single SCC. This may break
650 // the cycle. In order to compute the new set of SCCs, we need to do a small
651 // DFS over the nodes within the SCC to form any sub-cycles that remain as
652 // distinct SCCs and compute a postorder over the resulting SCCs.
653 //
654 // However, we specially handle the target node. The target node is known to
655 // reach all other nodes in the original SCC by definition. This means that
656 // we want the old SCC to be replaced with an SCC contaning that node as it
657 // will be the root of whatever SCC DAG results from the DFS. Assumptions
658 // about an SCC such as the set of functions called will continue to hold,
659 // etc.
660
661 SCC &OldSCC = TargetSCC;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000662 SmallVector<std::pair<Node *, EdgeSequence::call_iterator>, 16> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000663 SmallVector<Node *, 16> PendingSCCStack;
664 SmallVector<SCC *, 4> NewSCCs;
665
666 // Prepare the nodes for a fresh DFS.
667 SmallVector<Node *, 16> Worklist;
668 Worklist.swap(OldSCC.Nodes);
669 for (Node *N : Worklist) {
670 N->DFSNumber = N->LowLink = 0;
671 G->SCCMap.erase(N);
672 }
673
674 // Force the target node to be in the old SCC. This also enables us to take
675 // a very significant short-cut in the standard Tarjan walk to re-form SCCs
676 // below: whenever we build an edge that reaches the target node, we know
677 // that the target node eventually connects back to all other nodes in our
678 // walk. As a consequence, we can detect and handle participants in that
679 // cycle without walking all the edges that form this connection, and instead
680 // by relying on the fundamental guarantee coming into this operation (all
681 // nodes are reachable from the target due to previously forming an SCC).
682 TargetN.DFSNumber = TargetN.LowLink = -1;
683 OldSCC.Nodes.push_back(&TargetN);
684 G->SCCMap[&TargetN] = &OldSCC;
685
686 // Scan down the stack and DFS across the call edges.
687 for (Node *RootN : Worklist) {
688 assert(DFSStack.empty() &&
689 "Cannot begin a new root with a non-empty DFS stack!");
690 assert(PendingSCCStack.empty() &&
691 "Cannot begin a new root with pending nodes for an SCC!");
692
693 // Skip any nodes we've already reached in the DFS.
694 if (RootN->DFSNumber != 0) {
695 assert(RootN->DFSNumber == -1 &&
696 "Shouldn't have any mid-DFS root nodes!");
697 continue;
698 }
699
700 RootN->DFSNumber = RootN->LowLink = 1;
701 int NextDFSNumber = 2;
702
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000703 DFSStack.push_back({RootN, (*RootN)->call_begin()});
Chandler Carruthe5944d92016-02-17 00:18:16 +0000704 do {
705 Node *N;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000706 EdgeSequence::call_iterator I;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000707 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000708 auto E = (*N)->call_end();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000709 while (I != E) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000710 Node &ChildN = I->getNode();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000711 if (ChildN.DFSNumber == 0) {
712 // We haven't yet visited this child, so descend, pushing the current
713 // node onto the stack.
714 DFSStack.push_back({N, I});
715
716 assert(!G->SCCMap.count(&ChildN) &&
717 "Found a node with 0 DFS number but already in an SCC!");
718 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
719 N = &ChildN;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000720 I = (*N)->call_begin();
721 E = (*N)->call_end();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000722 continue;
723 }
724
725 // Check for the child already being part of some component.
726 if (ChildN.DFSNumber == -1) {
727 if (G->lookupSCC(ChildN) == &OldSCC) {
728 // If the child is part of the old SCC, we know that it can reach
729 // every other node, so we have formed a cycle. Pull the entire DFS
730 // and pending stacks into it. See the comment above about setting
731 // up the old SCC for why we do this.
732 int OldSize = OldSCC.size();
733 OldSCC.Nodes.push_back(N);
734 OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end());
735 PendingSCCStack.clear();
736 while (!DFSStack.empty())
737 OldSCC.Nodes.push_back(DFSStack.pop_back_val().first);
738 for (Node &N : make_range(OldSCC.begin() + OldSize, OldSCC.end())) {
739 N.DFSNumber = N.LowLink = -1;
740 G->SCCMap[&N] = &OldSCC;
741 }
742 N = nullptr;
743 break;
744 }
745
746 // If the child has already been added to some child component, it
747 // couldn't impact the low-link of this parent because it isn't
748 // connected, and thus its low-link isn't relevant so skip it.
749 ++I;
750 continue;
751 }
752
753 // Track the lowest linked child as the lowest link for this node.
754 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
755 if (ChildN.LowLink < N->LowLink)
756 N->LowLink = ChildN.LowLink;
757
758 // Move to the next edge.
759 ++I;
760 }
761 if (!N)
762 // Cleared the DFS early, start another round.
763 break;
764
765 // We've finished processing N and its descendents, put it on our pending
766 // SCC stack to eventually get merged into an SCC of nodes.
767 PendingSCCStack.push_back(N);
768
769 // If this node is linked to some lower entry, continue walking up the
770 // stack.
771 if (N->LowLink != N->DFSNumber)
772 continue;
773
774 // Otherwise, we've completed an SCC. Append it to our post order list of
775 // SCCs.
776 int RootDFSNumber = N->DFSNumber;
777 // Find the range of the node stack by walking down until we pass the
778 // root DFS number.
779 auto SCCNodes = make_range(
780 PendingSCCStack.rbegin(),
David Majnemer42531262016-08-12 03:55:06 +0000781 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
782 return N->DFSNumber < RootDFSNumber;
783 }));
Chandler Carruthe5944d92016-02-17 00:18:16 +0000784
785 // Form a new SCC out of these nodes and then clear them off our pending
786 // stack.
787 NewSCCs.push_back(G->createSCC(*this, SCCNodes));
788 for (Node &N : *NewSCCs.back()) {
789 N.DFSNumber = N.LowLink = -1;
790 G->SCCMap[&N] = NewSCCs.back();
791 }
792 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
793 } while (!DFSStack.empty());
794 }
795
796 // Insert the remaining SCCs before the old one. The old SCC can reach all
797 // other SCCs we form because it contains the target node of the removed edge
798 // of the old SCC. This means that we will have edges into all of the new
799 // SCCs, which means the old one must come last for postorder.
800 int OldIdx = SCCIndices[&OldSCC];
801 SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end());
802
803 // Update the mapping from SCC* to index to use the new SCC*s, and remove the
804 // old SCC from the mapping.
805 for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx)
806 SCCIndices[SCCs[Idx]] = Idx;
807
Chandler Carruth88823462016-08-24 09:37:14 +0000808 return make_range(SCCs.begin() + OldIdx,
809 SCCs.begin() + OldIdx + NewSCCs.size());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000810}
811
812void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN,
813 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000814 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000815
816 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
817 assert(G->lookupRefSCC(TargetN) != this &&
818 "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000819#ifdef EXPENSIVE_CHECKS
Chandler Carruthe5944d92016-02-17 00:18:16 +0000820 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
821 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000822#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000823
824 // Edges between RefSCCs are the same regardless of call or ref, so we can
825 // just flip the edge here.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000826 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000827
828#ifndef NDEBUG
829 // Check that the RefSCC is still valid.
830 verify();
831#endif
832}
833
834void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN,
835 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000836 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000837
838 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
839 assert(G->lookupRefSCC(TargetN) != this &&
840 "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000841#ifdef EXPENSIVE_CHECKS
Chandler Carruthe5944d92016-02-17 00:18:16 +0000842 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
843 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000844#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000845
846 // Edges between RefSCCs are the same regardless of call or ref, so we can
847 // just flip the edge here.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000848 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000849
850#ifndef NDEBUG
851 // Check that the RefSCC is still valid.
852 verify();
853#endif
854}
855
856void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN,
857 Node &TargetN) {
858 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
859 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
860
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000861 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000862
863#ifndef NDEBUG
864 // Check that the RefSCC is still valid.
865 verify();
866#endif
867}
868
869void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN,
870 Edge::Kind EK) {
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000871 // First insert it into the caller.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000872 SourceN->insertEdgeInternal(TargetN, EK);
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000873
Chandler Carruthe5944d92016-02-17 00:18:16 +0000874 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000875
Chandler Carruthe5944d92016-02-17 00:18:16 +0000876 RefSCC &TargetC = *G->lookupRefSCC(TargetN);
877 assert(&TargetC != this && "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000878#ifdef EXPENSIVE_CHECKS
Chandler Carruthe5944d92016-02-17 00:18:16 +0000879 assert(TargetC.isDescendantOf(*this) &&
880 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000881#endif
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000882
Chandler Carruth91539112015-12-28 01:54:20 +0000883 // The only change required is to add this SCC to the parent set of the
884 // callee.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000885 TargetC.Parents.insert(this);
886
887#ifndef NDEBUG
888 // Check that the RefSCC is still valid.
889 verify();
890#endif
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000891}
892
Chandler Carruthe5944d92016-02-17 00:18:16 +0000893SmallVector<LazyCallGraph::RefSCC *, 1>
894LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) {
Chandler Carruth49d728a2016-09-16 10:20:17 +0000895 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
896 RefSCC &SourceC = *G->lookupRefSCC(SourceN);
897 assert(&SourceC != this && "Source must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000898#ifdef EXPENSIVE_CHECKS
Chandler Carruth49d728a2016-09-16 10:20:17 +0000899 assert(SourceC.isDescendantOf(*this) &&
900 "Source must be a descendant of the Target.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000901#endif
Chandler Carruth49d728a2016-09-16 10:20:17 +0000902
903 SmallVector<RefSCC *, 1> DeletedRefSCCs;
Chandler Carruth312dddf2014-05-04 09:38:32 +0000904
Chandler Carruth11b3f602016-09-04 08:34:31 +0000905#ifndef NDEBUG
906 // In a debug build, verify the RefSCC is valid to start with and when this
907 // routine finishes.
908 verify();
909 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
910#endif
911
Chandler Carruth49d728a2016-09-16 10:20:17 +0000912 int SourceIdx = G->RefSCCIndices[&SourceC];
913 int TargetIdx = G->RefSCCIndices[this];
914 assert(SourceIdx < TargetIdx &&
915 "Postorder list doesn't see edge as incoming!");
Chandler Carruth312dddf2014-05-04 09:38:32 +0000916
Chandler Carruth49d728a2016-09-16 10:20:17 +0000917 // Compute the RefSCCs which (transitively) reach the source. We do this by
918 // working backwards from the source using the parent set in each RefSCC,
919 // skipping any RefSCCs that don't fall in the postorder range. This has the
920 // advantage of walking the sparser parent edge (in high fan-out graphs) but
921 // more importantly this removes examining all forward edges in all RefSCCs
922 // within the postorder range which aren't in fact connected. Only connected
923 // RefSCCs (and their edges) are visited here.
924 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
925 Set.insert(&SourceC);
926 SmallVector<RefSCC *, 4> Worklist;
927 Worklist.push_back(&SourceC);
928 do {
929 RefSCC &RC = *Worklist.pop_back_val();
930 for (RefSCC &ParentRC : RC.parents()) {
931 // Skip any RefSCCs outside the range of source to target in the
932 // postorder sequence.
933 int ParentIdx = G->getRefSCCIndex(ParentRC);
934 assert(ParentIdx > SourceIdx && "Parent cannot precede source in postorder!");
935 if (ParentIdx > TargetIdx)
936 continue;
937 if (Set.insert(&ParentRC).second)
938 // First edge connecting to this parent, add it to our worklist.
939 Worklist.push_back(&ParentRC);
Chandler Carruth312dddf2014-05-04 09:38:32 +0000940 }
Chandler Carruth49d728a2016-09-16 10:20:17 +0000941 } while (!Worklist.empty());
942 };
Chandler Carruth312dddf2014-05-04 09:38:32 +0000943
Chandler Carruth49d728a2016-09-16 10:20:17 +0000944 // Use a normal worklist to find which SCCs the target connects to. We still
945 // bound the search based on the range in the postorder list we care about,
946 // but because this is forward connectivity we just "recurse" through the
947 // edges.
948 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
949 Set.insert(this);
950 SmallVector<RefSCC *, 4> Worklist;
951 Worklist.push_back(this);
952 do {
953 RefSCC &RC = *Worklist.pop_back_val();
954 for (SCC &C : RC)
955 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000956 for (Edge &E : *N) {
957 RefSCC &EdgeRC = *G->lookupRefSCC(E.getNode());
Chandler Carruth49d728a2016-09-16 10:20:17 +0000958 if (G->getRefSCCIndex(EdgeRC) <= SourceIdx)
959 // Not in the postorder sequence between source and target.
960 continue;
Chandler Carruth312dddf2014-05-04 09:38:32 +0000961
Chandler Carruth49d728a2016-09-16 10:20:17 +0000962 if (Set.insert(&EdgeRC).second)
963 Worklist.push_back(&EdgeRC);
964 }
965 } while (!Worklist.empty());
966 };
967
968 // Use a generic helper to update the postorder sequence of RefSCCs and return
969 // a range of any RefSCCs connected into a cycle by inserting this edge. This
970 // routine will also take care of updating the indices into the postorder
971 // sequence.
972 iterator_range<SmallVectorImpl<RefSCC *>::iterator> MergeRange =
973 updatePostorderSequenceForEdgeInsertion(
974 SourceC, *this, G->PostOrderRefSCCs, G->RefSCCIndices,
975 ComputeSourceConnectedSet, ComputeTargetConnectedSet);
976
Chandler Carruth5205c352016-12-07 01:42:40 +0000977 // Build a set so we can do fast tests for whether a RefSCC will end up as
978 // part of the merged RefSCC.
Chandler Carruth49d728a2016-09-16 10:20:17 +0000979 SmallPtrSet<RefSCC *, 16> MergeSet(MergeRange.begin(), MergeRange.end());
Chandler Carruth312dddf2014-05-04 09:38:32 +0000980
Chandler Carruth5205c352016-12-07 01:42:40 +0000981 // This RefSCC will always be part of that set, so just insert it here.
982 MergeSet.insert(this);
983
Chandler Carruth312dddf2014-05-04 09:38:32 +0000984 // Now that we have identified all of the SCCs which need to be merged into
985 // a connected set with the inserted edge, merge all of them into this SCC.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000986 SmallVector<SCC *, 16> MergedSCCs;
987 int SCCIndex = 0;
Chandler Carruth49d728a2016-09-16 10:20:17 +0000988 for (RefSCC *RC : MergeRange) {
989 assert(RC != this && "We're merging into the target RefSCC, so it "
990 "shouldn't be in the range.");
Chandler Carruth312dddf2014-05-04 09:38:32 +0000991
Chandler Carruthe5944d92016-02-17 00:18:16 +0000992 // Merge the parents which aren't part of the merge into the our parents.
Chandler Carruth49d728a2016-09-16 10:20:17 +0000993 for (RefSCC *ParentRC : RC->Parents)
994 if (!MergeSet.count(ParentRC))
995 Parents.insert(ParentRC);
996 RC->Parents.clear();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000997
998 // Walk the inner SCCs to update their up-pointer and walk all the edges to
999 // update any parent sets.
1000 // FIXME: We should try to find a way to avoid this (rather expensive) edge
1001 // walk by updating the parent sets in some other manner.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001002 for (SCC &InnerC : *RC) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001003 InnerC.OuterRefSCC = this;
1004 SCCIndices[&InnerC] = SCCIndex++;
1005 for (Node &N : InnerC) {
1006 G->SCCMap[&N] = &InnerC;
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001007 for (Edge &E : *N) {
1008 RefSCC &ChildRC = *G->lookupRefSCC(E.getNode());
Chandler Carruth49d728a2016-09-16 10:20:17 +00001009 if (MergeSet.count(&ChildRC))
Chandler Carruthe5944d92016-02-17 00:18:16 +00001010 continue;
Chandler Carruth49d728a2016-09-16 10:20:17 +00001011 ChildRC.Parents.erase(RC);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001012 ChildRC.Parents.insert(this);
1013 }
Chandler Carruth312dddf2014-05-04 09:38:32 +00001014 }
Chandler Carruth312dddf2014-05-04 09:38:32 +00001015 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001016
1017 // Now merge in the SCCs. We can actually move here so try to reuse storage
1018 // the first time through.
1019 if (MergedSCCs.empty())
Chandler Carruth49d728a2016-09-16 10:20:17 +00001020 MergedSCCs = std::move(RC->SCCs);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001021 else
Chandler Carruth49d728a2016-09-16 10:20:17 +00001022 MergedSCCs.append(RC->SCCs.begin(), RC->SCCs.end());
1023 RC->SCCs.clear();
1024 DeletedRefSCCs.push_back(RC);
Chandler Carruth312dddf2014-05-04 09:38:32 +00001025 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001026
Chandler Carruth49d728a2016-09-16 10:20:17 +00001027 // Append our original SCCs to the merged list and move it into place.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001028 for (SCC &InnerC : *this)
1029 SCCIndices[&InnerC] = SCCIndex++;
1030 MergedSCCs.append(SCCs.begin(), SCCs.end());
1031 SCCs = std::move(MergedSCCs);
1032
Chandler Carruth49d728a2016-09-16 10:20:17 +00001033 // Remove the merged away RefSCCs from the post order sequence.
1034 for (RefSCC *RC : MergeRange)
1035 G->RefSCCIndices.erase(RC);
1036 int IndexOffset = MergeRange.end() - MergeRange.begin();
1037 auto EraseEnd =
1038 G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end());
1039 for (RefSCC *RC : make_range(EraseEnd, G->PostOrderRefSCCs.end()))
1040 G->RefSCCIndices[RC] -= IndexOffset;
1041
Chandler Carruthe5944d92016-02-17 00:18:16 +00001042 // At this point we have a merged RefSCC with a post-order SCCs list, just
1043 // connect the nodes to form the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001044 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001045
Chandler Carruth312dddf2014-05-04 09:38:32 +00001046 // We return the list of SCCs which were merged so that callers can
1047 // invalidate any data they have associated with those SCCs. Note that these
1048 // SCCs are no longer in an interesting state (they are totally empty) but
1049 // the pointers will remain stable for the life of the graph itself.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001050 return DeletedRefSCCs;
Chandler Carruth312dddf2014-05-04 09:38:32 +00001051}
1052
Chandler Carruthe5944d92016-02-17 00:18:16 +00001053void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) {
1054 assert(G->lookupRefSCC(SourceN) == this &&
1055 "The source must be a member of this RefSCC.");
1056
1057 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1058 assert(&TargetRC != this && "The target must not be a member of this RefSCC");
1059
David Majnemer0d955d02016-08-11 22:21:41 +00001060 assert(!is_contained(G->LeafRefSCCs, this) &&
Chandler Carruthe5944d92016-02-17 00:18:16 +00001061 "Cannot have a leaf RefSCC source.");
1062
Chandler Carruth11b3f602016-09-04 08:34:31 +00001063#ifndef NDEBUG
1064 // In a debug build, verify the RefSCC is valid to start with and when this
1065 // routine finishes.
1066 verify();
1067 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
1068#endif
1069
Chandler Carruthaa839b22014-04-27 01:59:50 +00001070 // First remove it from the node.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001071 bool Removed = SourceN->removeEdgeInternal(TargetN);
1072 (void)Removed;
1073 assert(Removed && "Target not in the edge set for this caller?");
Chandler Carruthaa839b22014-04-27 01:59:50 +00001074
Chandler Carruthe5944d92016-02-17 00:18:16 +00001075 bool HasOtherEdgeToChildRC = false;
1076 bool HasOtherChildRC = false;
1077 for (SCC *InnerC : SCCs) {
1078 for (Node &N : *InnerC) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001079 for (Edge &E : *N) {
1080 RefSCC &OtherChildRC = *G->lookupRefSCC(E.getNode());
Chandler Carruthe5944d92016-02-17 00:18:16 +00001081 if (&OtherChildRC == &TargetRC) {
1082 HasOtherEdgeToChildRC = true;
1083 break;
1084 }
1085 if (&OtherChildRC != this)
1086 HasOtherChildRC = true;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001087 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001088 if (HasOtherEdgeToChildRC)
1089 break;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001090 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001091 if (HasOtherEdgeToChildRC)
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001092 break;
1093 }
1094 // Because the SCCs form a DAG, deleting such an edge cannot change the set
1095 // of SCCs in the graph. However, it may cut an edge of the SCC DAG, making
Chandler Carruthe5944d92016-02-17 00:18:16 +00001096 // the source SCC no longer connected to the target SCC. If so, we need to
1097 // update the target SCC's map of its parents.
1098 if (!HasOtherEdgeToChildRC) {
1099 bool Removed = TargetRC.Parents.erase(this);
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001100 (void)Removed;
1101 assert(Removed &&
Chandler Carruthe5944d92016-02-17 00:18:16 +00001102 "Did not find the source SCC in the target SCC's parent list!");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001103
1104 // It may orphan an SCC if it is the last edge reaching it, but that does
1105 // not violate any invariants of the graph.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001106 if (TargetRC.Parents.empty())
1107 DEBUG(dbgs() << "LCG: Update removing " << SourceN.getFunction().getName()
1108 << " -> " << TargetN.getFunction().getName()
Chandler Carruthaa839b22014-04-27 01:59:50 +00001109 << " edge orphaned the callee's SCC!\n");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001110
Chandler Carruthe5944d92016-02-17 00:18:16 +00001111 // It may make the Source SCC a leaf SCC.
1112 if (!HasOtherChildRC)
1113 G->LeafRefSCCs.push_back(this);
Chandler Carruthaca48d02014-04-26 09:06:53 +00001114 }
1115}
1116
Chandler Carruthe5944d92016-02-17 00:18:16 +00001117SmallVector<LazyCallGraph::RefSCC *, 1>
1118LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN, Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001119 assert(!(*SourceN)[TargetN].isCall() &&
Chandler Carruthe5944d92016-02-17 00:18:16 +00001120 "Cannot remove a call edge, it must first be made a ref edge");
Chandler Carruthaa839b22014-04-27 01:59:50 +00001121
Chandler Carruth11b3f602016-09-04 08:34:31 +00001122#ifndef NDEBUG
1123 // In a debug build, verify the RefSCC is valid to start with and when this
1124 // routine finishes.
1125 verify();
1126 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
1127#endif
1128
Chandler Carruthe5944d92016-02-17 00:18:16 +00001129 // First remove the actual edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001130 bool Removed = SourceN->removeEdgeInternal(TargetN);
1131 (void)Removed;
1132 assert(Removed && "Target not in the edge set for this caller?");
Chandler Carruthe5944d92016-02-17 00:18:16 +00001133
1134 // We return a list of the resulting *new* RefSCCs in post-order.
1135 SmallVector<RefSCC *, 1> Result;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001136
Chandler Carrutha7205b62014-04-26 03:36:37 +00001137 // Direct recursion doesn't impact the SCC graph at all.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001138 if (&SourceN == &TargetN)
1139 return Result;
Chandler Carrutha7205b62014-04-26 03:36:37 +00001140
Chandler Carruthc6334572016-12-28 02:24:58 +00001141 // If this ref edge is within an SCC then there are sufficient other edges to
1142 // form a cycle without this edge so removing it is a no-op.
1143 SCC &SourceC = *G->lookupSCC(SourceN);
1144 SCC &TargetC = *G->lookupSCC(TargetN);
1145 if (&SourceC == &TargetC)
1146 return Result;
1147
Chandler Carruthe5944d92016-02-17 00:18:16 +00001148 // We build somewhat synthetic new RefSCCs by providing a postorder mapping
1149 // for each inner SCC. We also store these associated with *nodes* rather
1150 // than SCCs because this saves a round-trip through the node->SCC map and in
1151 // the common case, SCCs are small. We will verify that we always give the
1152 // same number to every node in the SCC such that these are equivalent.
1153 const int RootPostOrderNumber = 0;
1154 int PostOrderNumber = RootPostOrderNumber + 1;
1155 SmallDenseMap<Node *, int> PostOrderMapping;
1156
1157 // Every node in the target SCC can already reach every node in this RefSCC
1158 // (by definition). It is the only node we know will stay inside this RefSCC.
1159 // Everything which transitively reaches Target will also remain in the
1160 // RefSCC. We handle this by pre-marking that the nodes in the target SCC map
1161 // back to the root post order number.
1162 //
1163 // This also enables us to take a very significant short-cut in the standard
1164 // Tarjan walk to re-form RefSCCs below: whenever we build an edge that
1165 // references the target node, we know that the target node eventually
1166 // references all other nodes in our walk. As a consequence, we can detect
1167 // and handle participants in that cycle without walking all the edges that
1168 // form the connections, and instead by relying on the fundamental guarantee
1169 // coming into this operation.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001170 for (Node &N : TargetC)
1171 PostOrderMapping[&N] = RootPostOrderNumber;
1172
1173 // Reset all the other nodes to prepare for a DFS over them, and add them to
1174 // our worklist.
1175 SmallVector<Node *, 8> Worklist;
1176 for (SCC *C : SCCs) {
1177 if (C == &TargetC)
1178 continue;
1179
1180 for (Node &N : *C)
1181 N.DFSNumber = N.LowLink = 0;
1182
1183 Worklist.append(C->Nodes.begin(), C->Nodes.end());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001184 }
1185
Chandler Carruthe5944d92016-02-17 00:18:16 +00001186 auto MarkNodeForSCCNumber = [&PostOrderMapping](Node &N, int Number) {
1187 N.DFSNumber = N.LowLink = -1;
1188 PostOrderMapping[&N] = Number;
1189 };
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001190
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001191 SmallVector<std::pair<Node *, EdgeSequence::iterator>, 4> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001192 SmallVector<Node *, 4> PendingRefSCCStack;
Chandler Carruthaca48d02014-04-26 09:06:53 +00001193 do {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001194 assert(DFSStack.empty() &&
1195 "Cannot begin a new root with a non-empty DFS stack!");
1196 assert(PendingRefSCCStack.empty() &&
1197 "Cannot begin a new root with pending nodes for an SCC!");
1198
1199 Node *RootN = Worklist.pop_back_val();
1200 // Skip any nodes we've already reached in the DFS.
1201 if (RootN->DFSNumber != 0) {
1202 assert(RootN->DFSNumber == -1 &&
1203 "Shouldn't have any mid-DFS root nodes!");
1204 continue;
1205 }
1206
1207 RootN->DFSNumber = RootN->LowLink = 1;
1208 int NextDFSNumber = 2;
1209
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001210 DFSStack.push_back({RootN, (*RootN)->begin()});
Chandler Carruthe5944d92016-02-17 00:18:16 +00001211 do {
1212 Node *N;
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001213 EdgeSequence::iterator I;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001214 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001215 auto E = (*N)->end();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001216
1217 assert(N->DFSNumber != 0 && "We should always assign a DFS number "
1218 "before processing a node.");
1219
1220 while (I != E) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001221 Node &ChildN = I->getNode();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001222 if (ChildN.DFSNumber == 0) {
1223 // Mark that we should start at this child when next this node is the
1224 // top of the stack. We don't start at the next child to ensure this
1225 // child's lowlink is reflected.
1226 DFSStack.push_back({N, I});
1227
1228 // Continue, resetting to the child node.
1229 ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1230 N = &ChildN;
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001231 I = ChildN->begin();
1232 E = ChildN->end();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001233 continue;
1234 }
1235 if (ChildN.DFSNumber == -1) {
1236 // Check if this edge's target node connects to the deleted edge's
1237 // target node. If so, we know that every node connected will end up
1238 // in this RefSCC, so collapse the entire current stack into the root
1239 // slot in our SCC numbering. See above for the motivation of
1240 // optimizing the target connected nodes in this way.
1241 auto PostOrderI = PostOrderMapping.find(&ChildN);
1242 if (PostOrderI != PostOrderMapping.end() &&
1243 PostOrderI->second == RootPostOrderNumber) {
1244 MarkNodeForSCCNumber(*N, RootPostOrderNumber);
1245 while (!PendingRefSCCStack.empty())
1246 MarkNodeForSCCNumber(*PendingRefSCCStack.pop_back_val(),
1247 RootPostOrderNumber);
1248 while (!DFSStack.empty())
1249 MarkNodeForSCCNumber(*DFSStack.pop_back_val().first,
1250 RootPostOrderNumber);
1251 // Ensure we break all the way out of the enclosing loop.
1252 N = nullptr;
1253 break;
1254 }
1255
1256 // If this child isn't currently in this RefSCC, no need to process
Chandler Carruth23a6c3f2016-12-06 10:29:23 +00001257 // it. However, we do need to remove this RefSCC from its RefSCC's
1258 // parent set.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001259 RefSCC &ChildRC = *G->lookupRefSCC(ChildN);
1260 ChildRC.Parents.erase(this);
1261 ++I;
1262 continue;
1263 }
1264
1265 // Track the lowest link of the children, if any are still in the stack.
1266 // Any child not on the stack will have a LowLink of -1.
1267 assert(ChildN.LowLink != 0 &&
1268 "Low-link must not be zero with a non-zero DFS number.");
1269 if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
1270 N->LowLink = ChildN.LowLink;
1271 ++I;
1272 }
1273 if (!N)
1274 // We short-circuited this node.
1275 break;
1276
1277 // We've finished processing N and its descendents, put it on our pending
1278 // stack to eventually get merged into a RefSCC.
1279 PendingRefSCCStack.push_back(N);
1280
1281 // If this node is linked to some lower entry, continue walking up the
1282 // stack.
1283 if (N->LowLink != N->DFSNumber) {
1284 assert(!DFSStack.empty() &&
1285 "We never found a viable root for a RefSCC to pop off!");
1286 continue;
1287 }
1288
1289 // Otherwise, form a new RefSCC from the top of the pending node stack.
1290 int RootDFSNumber = N->DFSNumber;
1291 // Find the range of the node stack by walking down until we pass the
1292 // root DFS number.
1293 auto RefSCCNodes = make_range(
1294 PendingRefSCCStack.rbegin(),
David Majnemer42531262016-08-12 03:55:06 +00001295 find_if(reverse(PendingRefSCCStack), [RootDFSNumber](const Node *N) {
1296 return N->DFSNumber < RootDFSNumber;
1297 }));
Chandler Carruthe5944d92016-02-17 00:18:16 +00001298
1299 // Mark the postorder number for these nodes and clear them off the
1300 // stack. We'll use the postorder number to pull them into RefSCCs at the
1301 // end. FIXME: Fuse with the loop above.
1302 int RefSCCNumber = PostOrderNumber++;
1303 for (Node *N : RefSCCNodes)
1304 MarkNodeForSCCNumber(*N, RefSCCNumber);
1305
1306 PendingRefSCCStack.erase(RefSCCNodes.end().base(),
1307 PendingRefSCCStack.end());
1308 } while (!DFSStack.empty());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001309
Chandler Carruthaca48d02014-04-26 09:06:53 +00001310 assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
Chandler Carruthe5944d92016-02-17 00:18:16 +00001311 assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!");
Chandler Carruthaca48d02014-04-26 09:06:53 +00001312 } while (!Worklist.empty());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001313
Chandler Carruthe5944d92016-02-17 00:18:16 +00001314 // We now have a post-order numbering for RefSCCs and a mapping from each
1315 // node in this RefSCC to its final RefSCC. We create each new RefSCC node
1316 // (re-using this RefSCC node for the root) and build a radix-sort style map
1317 // from postorder number to the RefSCC. We then append SCCs to each of these
1318 // RefSCCs in the order they occured in the original SCCs container.
1319 for (int i = 1; i < PostOrderNumber; ++i)
1320 Result.push_back(G->createRefSCC(*G));
1321
Chandler Carruth49d728a2016-09-16 10:20:17 +00001322 // Insert the resulting postorder sequence into the global graph postorder
1323 // sequence before the current RefSCC in that sequence. The idea being that
1324 // this RefSCC is the target of the reference edge removed, and thus has
1325 // a direct or indirect edge to every other RefSCC formed and so must be at
1326 // the end of any postorder traversal.
1327 //
1328 // FIXME: It'd be nice to change the APIs so that we returned an iterator
1329 // range over the global postorder sequence and generally use that sequence
1330 // rather than building a separate result vector here.
1331 if (!Result.empty()) {
1332 int Idx = G->getRefSCCIndex(*this);
1333 G->PostOrderRefSCCs.insert(G->PostOrderRefSCCs.begin() + Idx,
1334 Result.begin(), Result.end());
1335 for (int i : seq<int>(Idx, G->PostOrderRefSCCs.size()))
1336 G->RefSCCIndices[G->PostOrderRefSCCs[i]] = i;
1337 assert(G->PostOrderRefSCCs[G->getRefSCCIndex(*this)] == this &&
1338 "Failed to update this RefSCC's index after insertion!");
1339 }
1340
Chandler Carruthe5944d92016-02-17 00:18:16 +00001341 for (SCC *C : SCCs) {
1342 auto PostOrderI = PostOrderMapping.find(&*C->begin());
1343 assert(PostOrderI != PostOrderMapping.end() &&
1344 "Cannot have missing mappings for nodes!");
1345 int SCCNumber = PostOrderI->second;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001346#ifndef NDEBUG
Chandler Carruthe5944d92016-02-17 00:18:16 +00001347 for (Node &N : *C)
1348 assert(PostOrderMapping.find(&N)->second == SCCNumber &&
1349 "Cannot have different numbers for nodes in the same SCC!");
1350#endif
1351 if (SCCNumber == 0)
1352 // The root node is handled separately by removing the SCCs.
1353 continue;
1354
1355 RefSCC &RC = *Result[SCCNumber - 1];
1356 int SCCIndex = RC.SCCs.size();
1357 RC.SCCs.push_back(C);
Chandler Carruth23a6c3f2016-12-06 10:29:23 +00001358 RC.SCCIndices[C] = SCCIndex;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001359 C->OuterRefSCC = &RC;
1360 }
1361
1362 // FIXME: We re-walk the edges in each RefSCC to establish whether it is
1363 // a leaf and connect it to the rest of the graph's parents lists. This is
1364 // really wasteful. We should instead do this during the DFS to avoid yet
1365 // another edge walk.
1366 for (RefSCC *RC : Result)
1367 G->connectRefSCC(*RC);
1368
1369 // Now erase all but the root's SCCs.
David Majnemer42531262016-08-12 03:55:06 +00001370 SCCs.erase(remove_if(SCCs,
1371 [&](SCC *C) {
1372 return PostOrderMapping.lookup(&*C->begin()) !=
1373 RootPostOrderNumber;
1374 }),
Chandler Carruthe5944d92016-02-17 00:18:16 +00001375 SCCs.end());
Chandler Carruth88823462016-08-24 09:37:14 +00001376 SCCIndices.clear();
1377 for (int i = 0, Size = SCCs.size(); i < Size; ++i)
1378 SCCIndices[SCCs[i]] = i;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001379
1380#ifndef NDEBUG
1381 // Now we need to reconnect the current (root) SCC to the graph. We do this
1382 // manually because we can special case our leaf handling and detect errors.
1383 bool IsLeaf = true;
1384#endif
1385 for (SCC *C : SCCs)
1386 for (Node &N : *C) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001387 for (Edge &E : *N) {
1388 RefSCC &ChildRC = *G->lookupRefSCC(E.getNode());
Chandler Carruthe5944d92016-02-17 00:18:16 +00001389 if (&ChildRC == this)
1390 continue;
1391 ChildRC.Parents.insert(this);
1392#ifndef NDEBUG
1393 IsLeaf = false;
1394#endif
1395 }
1396 }
1397#ifndef NDEBUG
1398 if (!Result.empty())
1399 assert(!IsLeaf && "This SCC cannot be a leaf as we have split out new "
1400 "SCCs by removing this edge.");
David Majnemer0a16c222016-08-11 21:15:00 +00001401 if (none_of(G->LeafRefSCCs, [&](RefSCC *C) { return C == this; }))
Chandler Carruthe5944d92016-02-17 00:18:16 +00001402 assert(!IsLeaf && "This SCC cannot be a leaf as it already had child "
1403 "SCCs before we removed this edge.");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001404#endif
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001405 // And connect both this RefSCC and all the new ones to the correct parents.
1406 // The easiest way to do this is just to re-analyze the old parent set.
1407 SmallVector<RefSCC *, 4> OldParents(Parents.begin(), Parents.end());
1408 Parents.clear();
1409 for (RefSCC *ParentRC : OldParents)
Chandler Carruth5205c352016-12-07 01:42:40 +00001410 for (SCC &ParentC : *ParentRC)
1411 for (Node &ParentN : ParentC)
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001412 for (Edge &E : *ParentN) {
1413 RefSCC &RC = *G->lookupRefSCC(E.getNode());
Chandler Carruth5205c352016-12-07 01:42:40 +00001414 if (&RC != ParentRC)
1415 RC.Parents.insert(ParentRC);
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001416 }
1417
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001418 // If this SCC stopped being a leaf through this edge removal, remove it from
Chandler Carruthe5944d92016-02-17 00:18:16 +00001419 // the leaf SCC list. Note that this DTRT in the case where this was never
1420 // a leaf.
1421 // FIXME: As LeafRefSCCs could be very large, we might want to not walk the
1422 // entire list if this RefSCC wasn't a leaf before the edge removal.
1423 if (!Result.empty())
1424 G->LeafRefSCCs.erase(
1425 std::remove(G->LeafRefSCCs.begin(), G->LeafRefSCCs.end(), this),
1426 G->LeafRefSCCs.end());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001427
Chandler Carruth23a6c3f2016-12-06 10:29:23 +00001428#ifndef NDEBUG
1429 // Verify all of the new RefSCCs.
1430 for (RefSCC *RC : Result)
1431 RC->verify();
1432#endif
1433
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001434 // Return the new list of SCCs.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001435 return Result;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001436}
1437
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001438void LazyCallGraph::RefSCC::handleTrivialEdgeInsertion(Node &SourceN,
1439 Node &TargetN) {
1440 // The only trivial case that requires any graph updates is when we add new
1441 // ref edge and may connect different RefSCCs along that path. This is only
1442 // because of the parents set. Every other part of the graph remains constant
1443 // after this edge insertion.
1444 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
1445 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1446 if (&TargetRC == this) {
1447
1448 return;
1449 }
1450
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +00001451#ifdef EXPENSIVE_CHECKS
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001452 assert(TargetRC.isDescendantOf(*this) &&
1453 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001454#endif
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001455 // The only change required is to add this RefSCC to the parent set of the
1456 // target. This is a set and so idempotent if the edge already existed.
1457 TargetRC.Parents.insert(this);
1458}
1459
1460void LazyCallGraph::RefSCC::insertTrivialCallEdge(Node &SourceN,
1461 Node &TargetN) {
1462#ifndef NDEBUG
1463 // Check that the RefSCC is still valid when we finish.
1464 auto ExitVerifier = make_scope_exit([this] { verify(); });
Chandler Carruthbae595b2016-11-22 19:23:31 +00001465
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001466#ifdef EXPENSIVE_CHECKS
1467 // Check that we aren't breaking some invariants of the SCC graph. Note that
1468 // this is quadratic in the number of edges in the call graph!
Chandler Carruthbae595b2016-11-22 19:23:31 +00001469 SCC &SourceC = *G->lookupSCC(SourceN);
1470 SCC &TargetC = *G->lookupSCC(TargetN);
1471 if (&SourceC != &TargetC)
1472 assert(SourceC.isAncestorOf(TargetC) &&
1473 "Call edge is not trivial in the SCC graph!");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001474#endif // EXPENSIVE_CHECKS
1475#endif // NDEBUG
1476
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001477 // First insert it into the source or find the existing edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001478 auto InsertResult =
1479 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001480 if (!InsertResult.second) {
1481 // Already an edge, just update it.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001482 Edge &E = SourceN->Edges[InsertResult.first->second];
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001483 if (E.isCall())
1484 return; // Nothing to do!
1485 E.setKind(Edge::Call);
1486 } else {
1487 // Create the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001488 SourceN->Edges.emplace_back(TargetN, Edge::Call);
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001489 }
1490
1491 // Now that we have the edge, handle the graph fallout.
1492 handleTrivialEdgeInsertion(SourceN, TargetN);
1493}
1494
1495void LazyCallGraph::RefSCC::insertTrivialRefEdge(Node &SourceN, Node &TargetN) {
1496#ifndef NDEBUG
1497 // Check that the RefSCC is still valid when we finish.
1498 auto ExitVerifier = make_scope_exit([this] { verify(); });
Chandler Carruth9eb857c2016-11-22 21:40:10 +00001499
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001500#ifdef EXPENSIVE_CHECKS
Chandler Carruth9eb857c2016-11-22 21:40:10 +00001501 // Check that we aren't breaking some invariants of the RefSCC graph.
1502 RefSCC &SourceRC = *G->lookupRefSCC(SourceN);
1503 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1504 if (&SourceRC != &TargetRC)
1505 assert(SourceRC.isAncestorOf(TargetRC) &&
1506 "Ref edge is not trivial in the RefSCC graph!");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001507#endif // EXPENSIVE_CHECKS
1508#endif // NDEBUG
1509
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001510 // First insert it into the source or find the existing edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001511 auto InsertResult =
1512 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001513 if (!InsertResult.second)
1514 // Already an edge, we're done.
1515 return;
1516
1517 // Create the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001518 SourceN->Edges.emplace_back(TargetN, Edge::Ref);
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001519
1520 // Now that we have the edge, handle the graph fallout.
1521 handleTrivialEdgeInsertion(SourceN, TargetN);
1522}
1523
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001524void LazyCallGraph::RefSCC::replaceNodeFunction(Node &N, Function &NewF) {
1525 Function &OldF = N.getFunction();
Chandler Carruthc00a7ff2014-04-28 11:10:23 +00001526
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001527#ifndef NDEBUG
1528 // Check that the RefSCC is still valid when we finish.
1529 auto ExitVerifier = make_scope_exit([this] { verify(); });
1530
1531 assert(G->lookupRefSCC(N) == this &&
1532 "Cannot replace the function of a node outside this RefSCC.");
1533
1534 assert(G->NodeMap.find(&NewF) == G->NodeMap.end() &&
1535 "Must not have already walked the new function!'");
1536
1537 // It is important that this replacement not introduce graph changes so we
1538 // insist that the caller has already removed every use of the original
1539 // function and that all uses of the new function correspond to existing
1540 // edges in the graph. The common and expected way to use this is when
1541 // replacing the function itself in the IR without changing the call graph
1542 // shape and just updating the analysis based on that.
1543 assert(&OldF != &NewF && "Cannot replace a function with itself!");
1544 assert(OldF.use_empty() &&
1545 "Must have moved all uses from the old function to the new!");
1546#endif
1547
1548 N.replaceFunction(NewF);
1549
1550 // Update various call graph maps.
1551 G->NodeMap.erase(&OldF);
1552 G->NodeMap[&NewF] = &N;
Chandler Carruthc00a7ff2014-04-28 11:10:23 +00001553}
1554
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001555void LazyCallGraph::insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK) {
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001556 assert(SCCMap.empty() &&
Chandler Carruthaa839b22014-04-27 01:59:50 +00001557 "This method cannot be called after SCCs have been formed!");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001558
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001559 return SourceN->insertEdgeInternal(TargetN, EK);
1560}
1561
1562void LazyCallGraph::removeEdge(Node &SourceN, Node &TargetN) {
1563 assert(SCCMap.empty() &&
1564 "This method cannot be called after SCCs have been formed!");
1565
1566 bool Removed = SourceN->removeEdgeInternal(TargetN);
1567 (void)Removed;
1568 assert(Removed && "Target not in the edge set for this caller?");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001569}
1570
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001571void LazyCallGraph::removeDeadFunction(Function &F) {
1572 // FIXME: This is unnecessarily restrictive. We should be able to remove
1573 // functions which recursively call themselves.
1574 assert(F.use_empty() &&
1575 "This routine should only be called on trivially dead functions!");
1576
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001577 auto NI = NodeMap.find(&F);
1578 if (NI == NodeMap.end())
1579 // Not in the graph at all!
1580 return;
1581
1582 Node &N = *NI->second;
1583 NodeMap.erase(NI);
1584
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001585 // Remove this from the entry edges if present.
1586 EntryEdges.removeEdgeInternal(N);
1587
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001588 if (SCCMap.empty()) {
1589 // No SCCs have been formed, so removing this is fine and there is nothing
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001590 // else necessary at this point but clearing out the node.
1591 N.clear();
1592 return;
1593 }
1594
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001595 // Cannot remove a function which has yet to be visited in the DFS walk, so
1596 // if we have a node at all then we must have an SCC and RefSCC.
1597 auto CI = SCCMap.find(&N);
1598 assert(CI != SCCMap.end() &&
1599 "Tried to remove a node without an SCC after DFS walk started!");
1600 SCC &C = *CI->second;
1601 SCCMap.erase(CI);
1602 RefSCC &RC = C.getOuterRefSCC();
1603
1604 // This node must be the only member of its SCC as it has no callers, and
1605 // that SCC must be the only member of a RefSCC as it has no references.
1606 // Validate these properties first.
1607 assert(C.size() == 1 && "Dead functions must be in a singular SCC");
1608 assert(RC.size() == 1 && "Dead functions must be in a singular RefSCC");
Chandler Carruth1f8fcfe2017-02-09 23:30:14 +00001609
1610 // Clean up any remaining reference edges. Note that we walk an unordered set
1611 // here but are just removing and so the order doesn't matter.
1612 for (RefSCC &ParentRC : RC.parents())
1613 for (SCC &ParentC : ParentRC)
1614 for (Node &ParentN : ParentC)
1615 if (ParentN)
1616 ParentN->removeEdgeInternal(N);
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001617
1618 // Now remove this RefSCC from any parents sets and the leaf list.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001619 for (Edge &E : *N)
1620 if (RefSCC *TargetRC = lookupRefSCC(E.getNode()))
1621 TargetRC->Parents.erase(&RC);
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001622 // FIXME: This is a linear operation which could become hot and benefit from
1623 // an index map.
1624 auto LRI = find(LeafRefSCCs, &RC);
1625 if (LRI != LeafRefSCCs.end())
1626 LeafRefSCCs.erase(LRI);
1627
1628 auto RCIndexI = RefSCCIndices.find(&RC);
1629 int RCIndex = RCIndexI->second;
1630 PostOrderRefSCCs.erase(PostOrderRefSCCs.begin() + RCIndex);
1631 RefSCCIndices.erase(RCIndexI);
1632 for (int i = RCIndex, Size = PostOrderRefSCCs.size(); i < Size; ++i)
1633 RefSCCIndices[PostOrderRefSCCs[i]] = i;
1634
1635 // Finally clear out all the data structures from the node down through the
1636 // components.
1637 N.clear();
1638 C.clear();
1639 RC.clear();
1640
1641 // Nothing to delete as all the objects are allocated in stable bump pointer
1642 // allocators.
1643}
1644
Chandler Carruth2a898e02014-04-23 23:20:36 +00001645LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
1646 return *new (MappedN = BPA.Allocate()) Node(*this, F);
Chandler Carruthd8d865e2014-04-18 11:02:33 +00001647}
1648
1649void LazyCallGraph::updateGraphPtrs() {
Chandler Carruthb60cb312014-04-17 07:25:59 +00001650 // Process all nodes updating the graph pointers.
Chandler Carruthaa839b22014-04-27 01:59:50 +00001651 {
1652 SmallVector<Node *, 16> Worklist;
Chandler Carrutha4499e92016-02-02 03:57:13 +00001653 for (Edge &E : EntryEdges)
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001654 Worklist.push_back(&E.getNode());
Chandler Carruthb60cb312014-04-17 07:25:59 +00001655
Chandler Carruthaa839b22014-04-27 01:59:50 +00001656 while (!Worklist.empty()) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001657 Node &N = *Worklist.pop_back_val();
1658 N.G = this;
1659 if (N)
1660 for (Edge &E : *N)
1661 Worklist.push_back(&E.getNode());
Chandler Carruthaa839b22014-04-27 01:59:50 +00001662 }
1663 }
1664
1665 // Process all SCCs updating the graph pointers.
1666 {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001667 SmallVector<RefSCC *, 16> Worklist(LeafRefSCCs.begin(), LeafRefSCCs.end());
Chandler Carruthaa839b22014-04-27 01:59:50 +00001668
1669 while (!Worklist.empty()) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001670 RefSCC &C = *Worklist.pop_back_val();
1671 C.G = this;
1672 for (RefSCC &ParentC : C.parents())
1673 Worklist.push_back(&ParentC);
Chandler Carruthaa839b22014-04-27 01:59:50 +00001674 }
Chandler Carruthb60cb312014-04-17 07:25:59 +00001675 }
Chandler Carruthbf71a342014-02-06 04:37:03 +00001676}
Chandler Carruthbf71a342014-02-06 04:37:03 +00001677
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001678template <typename RootsT, typename GetBeginT, typename GetEndT,
1679 typename GetNodeT, typename FormSCCCallbackT>
1680void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
1681 GetEndT &&GetEnd, GetNodeT &&GetNode,
1682 FormSCCCallbackT &&FormSCC) {
1683 typedef decltype(GetBegin(std::declval<Node &>())) EdgeItT;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001684
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001685 SmallVector<std::pair<Node *, EdgeItT>, 16> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001686 SmallVector<Node *, 16> PendingSCCStack;
1687
1688 // Scan down the stack and DFS across the call edges.
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001689 for (Node *RootN : Roots) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001690 assert(DFSStack.empty() &&
1691 "Cannot begin a new root with a non-empty DFS stack!");
1692 assert(PendingSCCStack.empty() &&
1693 "Cannot begin a new root with pending nodes for an SCC!");
1694
1695 // Skip any nodes we've already reached in the DFS.
1696 if (RootN->DFSNumber != 0) {
1697 assert(RootN->DFSNumber == -1 &&
1698 "Shouldn't have any mid-DFS root nodes!");
1699 continue;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001700 }
1701
Chandler Carruthe5944d92016-02-17 00:18:16 +00001702 RootN->DFSNumber = RootN->LowLink = 1;
1703 int NextDFSNumber = 2;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001704
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001705 DFSStack.push_back({RootN, GetBegin(*RootN)});
Chandler Carruthe5944d92016-02-17 00:18:16 +00001706 do {
1707 Node *N;
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001708 EdgeItT I;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001709 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001710 auto E = GetEnd(*N);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001711 while (I != E) {
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001712 Node &ChildN = GetNode(I);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001713 if (ChildN.DFSNumber == 0) {
1714 // We haven't yet visited this child, so descend, pushing the current
1715 // node onto the stack.
1716 DFSStack.push_back({N, I});
1717
Chandler Carruthe5944d92016-02-17 00:18:16 +00001718 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1719 N = &ChildN;
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001720 I = GetBegin(*N);
1721 E = GetEnd(*N);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001722 continue;
1723 }
1724
1725 // If the child has already been added to some child component, it
1726 // couldn't impact the low-link of this parent because it isn't
1727 // connected, and thus its low-link isn't relevant so skip it.
1728 if (ChildN.DFSNumber == -1) {
1729 ++I;
1730 continue;
1731 }
1732
1733 // Track the lowest linked child as the lowest link for this node.
1734 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1735 if (ChildN.LowLink < N->LowLink)
1736 N->LowLink = ChildN.LowLink;
1737
1738 // Move to the next edge.
1739 ++I;
1740 }
1741
1742 // We've finished processing N and its descendents, put it on our pending
1743 // SCC stack to eventually get merged into an SCC of nodes.
1744 PendingSCCStack.push_back(N);
1745
1746 // If this node is linked to some lower entry, continue walking up the
1747 // stack.
1748 if (N->LowLink != N->DFSNumber)
1749 continue;
1750
1751 // Otherwise, we've completed an SCC. Append it to our post order list of
1752 // SCCs.
1753 int RootDFSNumber = N->DFSNumber;
1754 // Find the range of the node stack by walking down until we pass the
1755 // root DFS number.
1756 auto SCCNodes = make_range(
1757 PendingSCCStack.rbegin(),
David Majnemer42531262016-08-12 03:55:06 +00001758 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
1759 return N->DFSNumber < RootDFSNumber;
1760 }));
Chandler Carruthe5944d92016-02-17 00:18:16 +00001761 // Form a new SCC out of these nodes and then clear them off our pending
1762 // stack.
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001763 FormSCC(SCCNodes);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001764 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
1765 } while (!DFSStack.empty());
1766 }
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001767}
1768
1769/// Build the internal SCCs for a RefSCC from a sequence of nodes.
1770///
1771/// Appends the SCCs to the provided vector and updates the map with their
1772/// indices. Both the vector and map must be empty when passed into this
1773/// routine.
1774void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
1775 assert(RC.SCCs.empty() && "Already built SCCs!");
1776 assert(RC.SCCIndices.empty() && "Already mapped SCC indices!");
1777
1778 for (Node *N : Nodes) {
1779 assert(N->LowLink >= (*Nodes.begin())->LowLink &&
1780 "We cannot have a low link in an SCC lower than its root on the "
1781 "stack!");
1782
1783 // This node will go into the next RefSCC, clear out its DFS and low link
1784 // as we scan.
1785 N->DFSNumber = N->LowLink = 0;
1786 }
1787
1788 // Each RefSCC contains a DAG of the call SCCs. To build these, we do
1789 // a direct walk of the call edges using Tarjan's algorithm. We reuse the
1790 // internal storage as we won't need it for the outer graph's DFS any longer.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001791 buildGenericSCCs(
1792 Nodes, [](Node &N) { return N->call_begin(); },
1793 [](Node &N) { return N->call_end(); },
1794 [](EdgeSequence::call_iterator I) -> Node & { return I->getNode(); },
1795 [this, &RC](node_stack_range Nodes) {
1796 RC.SCCs.push_back(createSCC(RC, Nodes));
1797 for (Node &N : *RC.SCCs.back()) {
1798 N.DFSNumber = N.LowLink = -1;
1799 SCCMap[&N] = RC.SCCs.back();
1800 }
1801 });
Chandler Carruthe5944d92016-02-17 00:18:16 +00001802
1803 // Wire up the SCC indices.
1804 for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i)
1805 RC.SCCIndices[RC.SCCs[i]] = i;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001806}
1807
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001808void LazyCallGraph::buildRefSCCs() {
1809 if (EntryEdges.empty() || !PostOrderRefSCCs.empty())
1810 // RefSCCs are either non-existent or already built!
1811 return;
1812
1813 assert(RefSCCIndices.empty() && "Already mapped RefSCC indices!");
1814
1815 SmallVector<Node *, 16> Roots;
1816 for (Edge &E : *this)
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001817 Roots.push_back(&E.getNode());
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001818
1819 // The roots will be popped of a stack, so use reverse to get a less
1820 // surprising order. This doesn't change any of the semantics anywhere.
1821 std::reverse(Roots.begin(), Roots.end());
1822
1823 buildGenericSCCs(
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001824 Roots,
1825 [](Node &N) {
1826 // We need to populate each node as we begin to walk its edges.
1827 N.populate();
1828 return N->begin();
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001829 },
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001830 [](Node &N) { return N->end(); },
1831 [](EdgeSequence::iterator I) -> Node & { return I->getNode(); },
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001832 [this](node_stack_range Nodes) {
1833 RefSCC *NewRC = createRefSCC(*this);
1834 buildSCCs(*NewRC, Nodes);
1835 connectRefSCC(*NewRC);
1836
1837 // Push the new node into the postorder list and remember its position
1838 // in the index map.
1839 bool Inserted =
1840 RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).second;
1841 (void)Inserted;
1842 assert(Inserted && "Cannot already have this RefSCC in the index map!");
1843 PostOrderRefSCCs.push_back(NewRC);
Chandler Carrutha80cfb32017-02-06 20:59:07 +00001844#ifndef NDEBUG
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001845 NewRC->verify();
Chandler Carrutha80cfb32017-02-06 20:59:07 +00001846#endif
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001847 });
1848}
1849
Chandler Carruthe5944d92016-02-17 00:18:16 +00001850// FIXME: We should move callers of this to embed the parent linking and leaf
1851// tracking into their DFS in order to remove a full walk of all edges.
1852void LazyCallGraph::connectRefSCC(RefSCC &RC) {
1853 // Walk all edges in the RefSCC (this remains linear as we only do this once
1854 // when we build the RefSCC) to connect it to the parent sets of its
1855 // children.
1856 bool IsLeaf = true;
1857 for (SCC &C : RC)
1858 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001859 for (Edge &E : *N) {
1860 RefSCC &ChildRC = *lookupRefSCC(E.getNode());
Chandler Carruthe5944d92016-02-17 00:18:16 +00001861 if (&ChildRC == &RC)
1862 continue;
1863 ChildRC.Parents.insert(&RC);
1864 IsLeaf = false;
1865 }
1866
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001867 // For the SCCs where we find no child SCCs, add them to the leaf list.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001868 if (IsLeaf)
1869 LeafRefSCCs.push_back(&RC);
1870}
1871
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001872AnalysisKey LazyCallGraphAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +00001873
Chandler Carruthbf71a342014-02-06 04:37:03 +00001874LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
1875
Chandler Carruthe5944d92016-02-17 00:18:16 +00001876static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) {
Chandler Carrutha4499e92016-02-02 03:57:13 +00001877 OS << " Edges in function: " << N.getFunction().getName() << "\n";
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001878 for (LazyCallGraph::Edge &E : N.populate())
Chandler Carrutha4499e92016-02-02 03:57:13 +00001879 OS << " " << (E.isCall() ? "call" : "ref ") << " -> "
1880 << E.getFunction().getName() << "\n";
Chandler Carruth11f50322015-01-14 00:27:45 +00001881
1882 OS << "\n";
1883}
1884
Chandler Carruthe5944d92016-02-17 00:18:16 +00001885static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
1886 ptrdiff_t Size = std::distance(C.begin(), C.end());
1887 OS << " SCC with " << Size << " functions:\n";
Chandler Carruth11f50322015-01-14 00:27:45 +00001888
Chandler Carruthe5944d92016-02-17 00:18:16 +00001889 for (LazyCallGraph::Node &N : C)
1890 OS << " " << N.getFunction().getName() << "\n";
1891}
1892
1893static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) {
1894 ptrdiff_t Size = std::distance(C.begin(), C.end());
1895 OS << " RefSCC with " << Size << " call SCCs:\n";
1896
1897 for (LazyCallGraph::SCC &InnerC : C)
1898 printSCC(OS, InnerC);
Chandler Carruth11f50322015-01-14 00:27:45 +00001899
1900 OS << "\n";
1901}
1902
Chandler Carruthd174ce42015-01-05 02:47:05 +00001903PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
Chandler Carruthb47f8012016-03-11 11:05:24 +00001904 ModuleAnalysisManager &AM) {
1905 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
Chandler Carruth11f50322015-01-14 00:27:45 +00001906
1907 OS << "Printing the call graph for module: " << M.getModuleIdentifier()
1908 << "\n\n";
1909
Chandler Carruthe5944d92016-02-17 00:18:16 +00001910 for (Function &F : M)
1911 printNode(OS, G.get(F));
Chandler Carruth11f50322015-01-14 00:27:45 +00001912
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001913 G.buildRefSCCs();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001914 for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs())
1915 printRefSCC(OS, C);
Chandler Carruth18eadd922014-04-18 10:50:32 +00001916
Chandler Carruthbf71a342014-02-06 04:37:03 +00001917 return PreservedAnalyses::all();
Chandler Carruthbf71a342014-02-06 04:37:03 +00001918}
Sean Silva7cb30662016-06-18 09:17:32 +00001919
1920LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS)
1921 : OS(OS) {}
1922
1923static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) {
1924 std::string Name = "\"" + DOT::EscapeString(N.getFunction().getName()) + "\"";
1925
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001926 for (LazyCallGraph::Edge &E : N.populate()) {
Sean Silva7cb30662016-06-18 09:17:32 +00001927 OS << " " << Name << " -> \""
1928 << DOT::EscapeString(E.getFunction().getName()) << "\"";
1929 if (!E.isCall()) // It is a ref edge.
1930 OS << " [style=dashed,label=\"ref\"]";
1931 OS << ";\n";
1932 }
1933
1934 OS << "\n";
1935}
1936
1937PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M,
1938 ModuleAnalysisManager &AM) {
1939 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1940
1941 OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n";
1942
1943 for (Function &F : M)
1944 printNodeDOT(OS, G.get(F));
1945
1946 OS << "}\n";
1947
1948 return PreservedAnalyses::all();
1949}