blob: fc6b02b7a70726406806b6afa9376db8fec238d4 [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 Carruth219b89b2014-03-04 11:01:28 +000012#include "llvm/IR/CallSite.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000013#include "llvm/IR/InstVisitor.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000014#include "llvm/IR/Instructions.h"
15#include "llvm/IR/PassManager.h"
Chandler Carruth99b756d2014-04-21 05:04:24 +000016#include "llvm/Support/Debug.h"
Sean Silva7cb30662016-06-18 09:17:32 +000017#include "llvm/Support/GraphWriter.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000018
19using namespace llvm;
20
Chandler Carruthf1221bd2014-04-22 02:48:03 +000021#define DEBUG_TYPE "lcg"
22
Chandler Carrutha4499e92016-02-02 03:57:13 +000023static void addEdge(SmallVectorImpl<LazyCallGraph::Edge> &Edges,
Chandler Carruthe5944d92016-02-17 00:18:16 +000024 DenseMap<Function *, int> &EdgeIndexMap, Function &F,
Chandler Carrutha4499e92016-02-02 03:57:13 +000025 LazyCallGraph::Edge::Kind EK) {
26 // Note that we consider *any* function with a definition to be a viable
27 // edge. Even if the function's definition is subject to replacement by
28 // some other module (say, a weak definition) there may still be
29 // optimizations which essentially speculate based on the definition and
30 // a way to check that the specific definition is in fact the one being
31 // used. For example, this could be done by moving the weak definition to
32 // a strong (internal) definition and making the weak definition be an
33 // alias. Then a test of the address of the weak function against the new
34 // strong definition's address would be an effective way to determine the
35 // safety of optimizing a direct call edge.
36 if (!F.isDeclaration() &&
Chandler Carruthe5944d92016-02-17 00:18:16 +000037 EdgeIndexMap.insert({&F, Edges.size()}).second) {
Chandler Carrutha4499e92016-02-02 03:57:13 +000038 DEBUG(dbgs() << " Added callable function: " << F.getName() << "\n");
39 Edges.emplace_back(LazyCallGraph::Edge(F, EK));
40 }
41}
42
Chandler Carruthe5944d92016-02-17 00:18:16 +000043static void findReferences(SmallVectorImpl<Constant *> &Worklist,
44 SmallPtrSetImpl<Constant *> &Visited,
45 SmallVectorImpl<LazyCallGraph::Edge> &Edges,
46 DenseMap<Function *, int> &EdgeIndexMap) {
Chandler Carruthbf71a342014-02-06 04:37:03 +000047 while (!Worklist.empty()) {
48 Constant *C = Worklist.pop_back_val();
49
50 if (Function *F = dyn_cast<Function>(C)) {
Chandler Carrutha4499e92016-02-02 03:57:13 +000051 addEdge(Edges, EdgeIndexMap, *F, LazyCallGraph::Edge::Ref);
Chandler Carruthbf71a342014-02-06 04:37:03 +000052 continue;
53 }
54
Chandler Carruth1583e992014-03-03 10:42:58 +000055 for (Value *Op : C->operand_values())
David Blaikie70573dc2014-11-19 07:49:26 +000056 if (Visited.insert(cast<Constant>(Op)).second)
Chandler Carruth1583e992014-03-03 10:42:58 +000057 Worklist.push_back(cast<Constant>(Op));
Chandler Carruthbf71a342014-02-06 04:37:03 +000058 }
59}
60
Chandler Carruth18eadd922014-04-18 10:50:32 +000061LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
62 : G(&G), F(F), DFSNumber(0), LowLink(0) {
Chandler Carruth99b756d2014-04-21 05:04:24 +000063 DEBUG(dbgs() << " Adding functions called by '" << F.getName()
64 << "' to the graph.\n");
65
Chandler Carruthbf71a342014-02-06 04:37:03 +000066 SmallVector<Constant *, 16> Worklist;
Chandler Carrutha4499e92016-02-02 03:57:13 +000067 SmallPtrSet<Function *, 4> Callees;
Chandler Carruthbf71a342014-02-06 04:37:03 +000068 SmallPtrSet<Constant *, 16> Visited;
Chandler Carrutha4499e92016-02-02 03:57:13 +000069
70 // Find all the potential call graph edges in this function. We track both
71 // actual call edges and indirect references to functions. The direct calls
72 // are trivially added, but to accumulate the latter we walk the instructions
73 // and add every operand which is a constant to the worklist to process
74 // afterward.
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000075 for (BasicBlock &BB : F)
Chandler Carrutha4499e92016-02-02 03:57:13 +000076 for (Instruction &I : BB) {
77 if (auto CS = CallSite(&I))
78 if (Function *Callee = CS.getCalledFunction())
79 if (Callees.insert(Callee).second) {
80 Visited.insert(Callee);
81 addEdge(Edges, EdgeIndexMap, *Callee, LazyCallGraph::Edge::Call);
82 }
83
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000084 for (Value *Op : I.operand_values())
Chandler Carruth1583e992014-03-03 10:42:58 +000085 if (Constant *C = dyn_cast<Constant>(Op))
David Blaikie70573dc2014-11-19 07:49:26 +000086 if (Visited.insert(C).second)
Chandler Carruthbf71a342014-02-06 04:37:03 +000087 Worklist.push_back(C);
Chandler Carrutha4499e92016-02-02 03:57:13 +000088 }
Chandler Carruthbf71a342014-02-06 04:37:03 +000089
90 // We've collected all the constant (and thus potentially function or
91 // function containing) operands to all of the instructions in the function.
92 // Process them (recursively) collecting every function found.
Chandler Carrutha4499e92016-02-02 03:57:13 +000093 findReferences(Worklist, Visited, Edges, EdgeIndexMap);
Chandler Carruthbf71a342014-02-06 04:37:03 +000094}
95
Chandler Carruthe5944d92016-02-17 00:18:16 +000096void LazyCallGraph::Node::insertEdgeInternal(Function &Target, Edge::Kind EK) {
97 if (Node *N = G->lookup(Target))
Chandler Carrutha4499e92016-02-02 03:57:13 +000098 return insertEdgeInternal(*N, EK);
Chandler Carruth5217c942014-04-30 10:48:36 +000099
Chandler Carruthe5944d92016-02-17 00:18:16 +0000100 EdgeIndexMap.insert({&Target, Edges.size()});
101 Edges.emplace_back(Target, EK);
Chandler Carruth5217c942014-04-30 10:48:36 +0000102}
103
Chandler Carruthe5944d92016-02-17 00:18:16 +0000104void LazyCallGraph::Node::insertEdgeInternal(Node &TargetN, Edge::Kind EK) {
105 EdgeIndexMap.insert({&TargetN.getFunction(), Edges.size()});
106 Edges.emplace_back(TargetN, EK);
Chandler Carruthc00a7ff2014-04-28 11:10:23 +0000107}
108
Chandler Carruthe5944d92016-02-17 00:18:16 +0000109void LazyCallGraph::Node::setEdgeKind(Function &TargetF, Edge::Kind EK) {
110 Edges[EdgeIndexMap.find(&TargetF)->second].setKind(EK);
111}
112
113void LazyCallGraph::Node::removeEdgeInternal(Function &Target) {
114 auto IndexMapI = EdgeIndexMap.find(&Target);
Chandler Carrutha4499e92016-02-02 03:57:13 +0000115 assert(IndexMapI != EdgeIndexMap.end() &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000116 "Target not in the edge set for this caller?");
Chandler Carruthaa839b22014-04-27 01:59:50 +0000117
Chandler Carrutha4499e92016-02-02 03:57:13 +0000118 Edges[IndexMapI->second] = Edge();
119 EdgeIndexMap.erase(IndexMapI);
Chandler Carruthaa839b22014-04-27 01:59:50 +0000120}
121
Chandler Carruthdca83402016-06-27 23:26:08 +0000122void LazyCallGraph::Node::dump() const {
123 dbgs() << *this << '\n';
124}
125
Chandler Carruth2174f442014-04-18 20:44:16 +0000126LazyCallGraph::LazyCallGraph(Module &M) : NextDFSNumber(0) {
Chandler Carruth99b756d2014-04-21 05:04:24 +0000127 DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
128 << "\n");
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000129 for (Function &F : M)
130 if (!F.isDeclaration() && !F.hasLocalLinkage())
Chandler Carruthe5944d92016-02-17 00:18:16 +0000131 if (EntryIndexMap.insert({&F, EntryEdges.size()}).second) {
Chandler Carruth99b756d2014-04-21 05:04:24 +0000132 DEBUG(dbgs() << " Adding '" << F.getName()
133 << "' to entry set of the graph.\n");
Chandler Carrutha4499e92016-02-02 03:57:13 +0000134 EntryEdges.emplace_back(F, Edge::Ref);
Chandler Carruth99b756d2014-04-21 05:04:24 +0000135 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000136
137 // Now add entry nodes for functions reachable via initializers to globals.
138 SmallVector<Constant *, 16> Worklist;
139 SmallPtrSet<Constant *, 16> Visited;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000140 for (GlobalVariable &GV : M.globals())
141 if (GV.hasInitializer())
David Blaikie70573dc2014-11-19 07:49:26 +0000142 if (Visited.insert(GV.getInitializer()).second)
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000143 Worklist.push_back(GV.getInitializer());
Chandler Carruthbf71a342014-02-06 04:37:03 +0000144
Chandler Carruth99b756d2014-04-21 05:04:24 +0000145 DEBUG(dbgs() << " Adding functions referenced by global initializers to the "
146 "entry set.\n");
Chandler Carrutha4499e92016-02-02 03:57:13 +0000147 findReferences(Worklist, Visited, EntryEdges, EntryIndexMap);
Chandler Carruth18eadd922014-04-18 10:50:32 +0000148
Chandler Carrutha4499e92016-02-02 03:57:13 +0000149 for (const Edge &E : EntryEdges)
Chandler Carruthe5944d92016-02-17 00:18:16 +0000150 RefSCCEntryNodes.push_back(&E.getFunction());
Chandler Carruthbf71a342014-02-06 04:37:03 +0000151}
152
Chandler Carruthbf71a342014-02-06 04:37:03 +0000153LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
Chandler Carruth2174f442014-04-18 20:44:16 +0000154 : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
Chandler Carrutha4499e92016-02-02 03:57:13 +0000155 EntryEdges(std::move(G.EntryEdges)),
Chandler Carruth0b623ba2014-04-23 04:00:17 +0000156 EntryIndexMap(std::move(G.EntryIndexMap)), SCCBPA(std::move(G.SCCBPA)),
Chandler Carruthe5944d92016-02-17 00:18:16 +0000157 SCCMap(std::move(G.SCCMap)), LeafRefSCCs(std::move(G.LeafRefSCCs)),
Chandler Carruth18eadd922014-04-18 10:50:32 +0000158 DFSStack(std::move(G.DFSStack)),
Chandler Carruthe5944d92016-02-17 00:18:16 +0000159 RefSCCEntryNodes(std::move(G.RefSCCEntryNodes)),
Chandler Carruth2174f442014-04-18 20:44:16 +0000160 NextDFSNumber(G.NextDFSNumber) {
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000161 updateGraphPtrs();
162}
163
164LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
165 BPA = std::move(G.BPA);
Chandler Carruth2174f442014-04-18 20:44:16 +0000166 NodeMap = std::move(G.NodeMap);
Chandler Carrutha4499e92016-02-02 03:57:13 +0000167 EntryEdges = std::move(G.EntryEdges);
Chandler Carruth0b623ba2014-04-23 04:00:17 +0000168 EntryIndexMap = std::move(G.EntryIndexMap);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000169 SCCBPA = std::move(G.SCCBPA);
170 SCCMap = std::move(G.SCCMap);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000171 LeafRefSCCs = std::move(G.LeafRefSCCs);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000172 DFSStack = std::move(G.DFSStack);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000173 RefSCCEntryNodes = std::move(G.RefSCCEntryNodes);
Chandler Carruth2174f442014-04-18 20:44:16 +0000174 NextDFSNumber = G.NextDFSNumber;
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000175 updateGraphPtrs();
176 return *this;
177}
178
Chandler Carruthdca83402016-06-27 23:26:08 +0000179void LazyCallGraph::SCC::dump() const {
180 dbgs() << *this << '\n';
181}
182
Chandler Carruthe5944d92016-02-17 00:18:16 +0000183#ifndef NDEBUG
184void LazyCallGraph::SCC::verify() {
185 assert(OuterRefSCC && "Can't have a null RefSCC!");
186 assert(!Nodes.empty() && "Can't have an empty SCC!");
Chandler Carruth8f92d6d2014-04-26 01:03:46 +0000187
Chandler Carruthe5944d92016-02-17 00:18:16 +0000188 for (Node *N : Nodes) {
189 assert(N && "Can't have a null node!");
190 assert(OuterRefSCC->G->lookupSCC(*N) == this &&
191 "Node does not map to this SCC!");
192 assert(N->DFSNumber == -1 &&
193 "Must set DFS numbers to -1 when adding a node to an SCC!");
194 assert(N->LowLink == -1 &&
195 "Must set low link to -1 when adding a node to an SCC!");
196 for (Edge &E : *N)
197 assert(E.getNode() && "Can't have an edge to a raw function!");
198 }
199}
200#endif
201
202LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {}
203
Chandler Carruthdca83402016-06-27 23:26:08 +0000204void LazyCallGraph::RefSCC::dump() const {
205 dbgs() << *this << '\n';
206}
207
Chandler Carruthe5944d92016-02-17 00:18:16 +0000208#ifndef NDEBUG
209void LazyCallGraph::RefSCC::verify() {
210 assert(G && "Can't have a null graph!");
211 assert(!SCCs.empty() && "Can't have an empty SCC!");
212
213 // Verify basic properties of the SCCs.
214 for (SCC *C : SCCs) {
215 assert(C && "Can't have a null SCC!");
216 C->verify();
217 assert(&C->getOuterRefSCC() == this &&
218 "SCC doesn't think it is inside this RefSCC!");
219 }
220
221 // Check that our indices map correctly.
222 for (auto &SCCIndexPair : SCCIndices) {
223 SCC *C = SCCIndexPair.first;
224 int i = SCCIndexPair.second;
225 assert(C && "Can't have a null SCC in the indices!");
226 assert(SCCs[i] == C && "Index doesn't point to SCC!");
227 }
228
229 // Check that the SCCs are in fact in post-order.
230 for (int i = 0, Size = SCCs.size(); i < Size; ++i) {
231 SCC &SourceSCC = *SCCs[i];
232 for (Node &N : SourceSCC)
233 for (Edge &E : N) {
234 if (!E.isCall())
235 continue;
236 SCC &TargetSCC = *G->lookupSCC(*E.getNode());
237 if (&TargetSCC.getOuterRefSCC() == this) {
238 assert(SCCIndices.find(&TargetSCC)->second <= i &&
239 "Edge between SCCs violates post-order relationship.");
240 continue;
241 }
242 assert(TargetSCC.getOuterRefSCC().Parents.count(this) &&
243 "Edge to a RefSCC missing us in its parent set.");
244 }
245 }
246}
247#endif
248
249bool LazyCallGraph::RefSCC::isDescendantOf(const RefSCC &C) const {
Chandler Carruth4b096742014-05-01 12:12:42 +0000250 // Walk up the parents of this SCC and verify that we eventually find C.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000251 SmallVector<const RefSCC *, 4> AncestorWorklist;
Chandler Carruth4b096742014-05-01 12:12:42 +0000252 AncestorWorklist.push_back(this);
253 do {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000254 const RefSCC *AncestorC = AncestorWorklist.pop_back_val();
Chandler Carruth4b096742014-05-01 12:12:42 +0000255 if (AncestorC->isChildOf(C))
256 return true;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000257 for (const RefSCC *ParentC : AncestorC->Parents)
Chandler Carruth4b096742014-05-01 12:12:42 +0000258 AncestorWorklist.push_back(ParentC);
259 } while (!AncestorWorklist.empty());
260
261 return false;
262}
263
Chandler Carruthe5944d92016-02-17 00:18:16 +0000264SmallVector<LazyCallGraph::SCC *, 1>
265LazyCallGraph::RefSCC::switchInternalEdgeToCall(Node &SourceN, Node &TargetN) {
266 assert(!SourceN[TargetN].isCall() && "Must start with a ref edge!");
Chandler Carruth5217c942014-04-30 10:48:36 +0000267
Chandler Carruthe5944d92016-02-17 00:18:16 +0000268 SmallVector<SCC *, 1> DeletedSCCs;
Chandler Carruth5217c942014-04-30 10:48:36 +0000269
Chandler Carruthe5944d92016-02-17 00:18:16 +0000270 SCC &SourceSCC = *G->lookupSCC(SourceN);
271 SCC &TargetSCC = *G->lookupSCC(TargetN);
272
273 // If the two nodes are already part of the same SCC, we're also done as
274 // we've just added more connectivity.
275 if (&SourceSCC == &TargetSCC) {
276 SourceN.setEdgeKind(TargetN.getFunction(), Edge::Call);
277#ifndef NDEBUG
278 // Check that the RefSCC is still valid.
279 verify();
280#endif
281 return DeletedSCCs;
282 }
283
284 // At this point we leverage the postorder list of SCCs to detect when the
285 // insertion of an edge changes the SCC structure in any way.
286 //
287 // First and foremost, we can eliminate the need for any changes when the
288 // edge is toward the beginning of the postorder sequence because all edges
289 // flow in that direction already. Thus adding a new one cannot form a cycle.
290 int SourceIdx = SCCIndices[&SourceSCC];
291 int TargetIdx = SCCIndices[&TargetSCC];
292 if (TargetIdx < SourceIdx) {
293 SourceN.setEdgeKind(TargetN.getFunction(), Edge::Call);
294#ifndef NDEBUG
295 // Check that the RefSCC is still valid.
296 verify();
297#endif
298 return DeletedSCCs;
299 }
300
301 // When we do have an edge from an earlier SCC to a later SCC in the
302 // postorder sequence, all of the SCCs which may be impacted are in the
303 // closed range of those two within the postorder sequence. The algorithm to
304 // restore the state is as follows:
305 //
306 // 1) Starting from the source SCC, construct a set of SCCs which reach the
307 // source SCC consisting of just the source SCC. Then scan toward the
308 // target SCC in postorder and for each SCC, if it has an edge to an SCC
309 // in the set, add it to the set. Otherwise, the source SCC is not
310 // a successor, move it in the postorder sequence to immediately before
311 // the source SCC, shifting the source SCC and all SCCs in the set one
312 // position toward the target SCC. Stop scanning after processing the
313 // target SCC.
314 // 2) If the source SCC is now past the target SCC in the postorder sequence,
315 // and thus the new edge will flow toward the start, we are done.
316 // 3) Otherwise, starting from the target SCC, walk all edges which reach an
317 // SCC between the source and the target, and add them to the set of
318 // connected SCCs, then recurse through them. Once a complete set of the
319 // SCCs the target connects to is known, hoist the remaining SCCs between
320 // the source and the target to be above the target. Note that there is no
321 // need to process the source SCC, it is already known to connect.
322 // 4) At this point, all of the SCCs in the closed range between the source
323 // SCC and the target SCC in the postorder sequence are connected,
324 // including the target SCC and the source SCC. Inserting the edge from
325 // the source SCC to the target SCC will form a cycle out of precisely
326 // these SCCs. Thus we can merge all of the SCCs in this closed range into
327 // a single SCC.
328 //
329 // This process has various important properties:
330 // - Only mutates the SCCs when adding the edge actually changes the SCC
331 // structure.
332 // - Never mutates SCCs which are unaffected by the change.
333 // - Updates the postorder sequence to correctly satisfy the postorder
334 // constraint after the edge is inserted.
335 // - Only reorders SCCs in the closed postorder sequence from the source to
336 // the target, so easy to bound how much has changed even in the ordering.
337 // - Big-O is the number of edges in the closed postorder range of SCCs from
338 // source to target.
339
340 assert(SourceIdx < TargetIdx && "Cannot have equal indices here!");
341 SmallPtrSet<SCC *, 4> ConnectedSet;
342
343 // Compute the SCCs which (transitively) reach the source.
344 ConnectedSet.insert(&SourceSCC);
345 auto IsConnected = [&](SCC &C) {
346 for (Node &N : C)
347 for (Edge &E : N.calls()) {
348 assert(E.getNode() && "Must have formed a node within an SCC!");
349 if (ConnectedSet.count(G->lookupSCC(*E.getNode())))
350 return true;
351 }
352
353 return false;
354 };
355
356 for (SCC *C :
357 make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
358 if (IsConnected(*C))
359 ConnectedSet.insert(C);
360
361 // Partition the SCCs in this part of the port-order sequence so only SCCs
362 // connecting to the source remain between it and the target. This is
363 // a benign partition as it preserves postorder.
364 auto SourceI = std::stable_partition(
365 SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
366 [&ConnectedSet](SCC *C) { return !ConnectedSet.count(C); });
367 for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
368 SCCIndices.find(SCCs[i])->second = i;
369
370 // If the target doesn't connect to the source, then we've corrected the
371 // post-order and there are no cycles formed.
372 if (!ConnectedSet.count(&TargetSCC)) {
373 assert(SourceI > (SCCs.begin() + SourceIdx) &&
374 "Must have moved the source to fix the post-order.");
375 assert(*std::prev(SourceI) == &TargetSCC &&
376 "Last SCC to move should have bene the target.");
377 SourceN.setEdgeKind(TargetN.getFunction(), Edge::Call);
378#ifndef NDEBUG
379 verify();
380#endif
381 return DeletedSCCs;
382 }
383
384 assert(SCCs[TargetIdx] == &TargetSCC &&
385 "Should not have moved target if connected!");
386 SourceIdx = SourceI - SCCs.begin();
387
388#ifndef NDEBUG
389 // Check that the RefSCC is still valid.
390 verify();
391#endif
392
393 // See whether there are any remaining intervening SCCs between the source
394 // and target. If so we need to make sure they all are reachable form the
395 // target.
396 if (SourceIdx + 1 < TargetIdx) {
397 // Use a normal worklist to find which SCCs the target connects to. We still
398 // bound the search based on the range in the postorder list we care about,
399 // but because this is forward connectivity we just "recurse" through the
400 // edges.
401 ConnectedSet.clear();
402 ConnectedSet.insert(&TargetSCC);
403 SmallVector<SCC *, 4> Worklist;
404 Worklist.push_back(&TargetSCC);
405 do {
406 SCC &C = *Worklist.pop_back_val();
407 for (Node &N : C)
408 for (Edge &E : N) {
409 assert(E.getNode() && "Must have formed a node within an SCC!");
410 if (!E.isCall())
411 continue;
412 SCC &EdgeC = *G->lookupSCC(*E.getNode());
413 if (&EdgeC.getOuterRefSCC() != this)
414 // Not in this RefSCC...
415 continue;
416 if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
417 // Not in the postorder sequence between source and target.
418 continue;
419
420 if (ConnectedSet.insert(&EdgeC).second)
421 Worklist.push_back(&EdgeC);
422 }
423 } while (!Worklist.empty());
424
425 // Partition SCCs so that only SCCs reached from the target remain between
426 // the source and the target. This preserves postorder.
427 auto TargetI = std::stable_partition(
428 SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
429 [&ConnectedSet](SCC *C) { return ConnectedSet.count(C); });
430 for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
431 SCCIndices.find(SCCs[i])->second = i;
432 TargetIdx = std::prev(TargetI) - SCCs.begin();
433 assert(SCCs[TargetIdx] == &TargetSCC &&
434 "Should always end with the target!");
435
436#ifndef NDEBUG
437 // Check that the RefSCC is still valid.
438 verify();
439#endif
440 }
441
442 // At this point, we know that connecting source to target forms a cycle
443 // because target connects back to source, and we know that all of the SCCs
444 // between the source and target in the postorder sequence participate in that
445 // cycle. This means that we need to merge all of these SCCs into a single
446 // result SCC.
447 //
448 // NB: We merge into the target because all of these functions were already
449 // reachable from the target, meaning any SCC-wide properties deduced about it
450 // other than the set of functions within it will not have changed.
451 auto MergeRange =
452 make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
453 for (SCC *C : MergeRange) {
454 assert(C != &TargetSCC &&
455 "We merge *into* the target and shouldn't process it here!");
456 SCCIndices.erase(C);
457 TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
458 for (Node *N : C->Nodes)
459 G->SCCMap[N] = &TargetSCC;
460 C->clear();
461 DeletedSCCs.push_back(C);
462 }
463
464 // Erase the merged SCCs from the list and update the indices of the
465 // remaining SCCs.
466 int IndexOffset = MergeRange.end() - MergeRange.begin();
467 auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
468 for (SCC *C : make_range(EraseEnd, SCCs.end()))
469 SCCIndices[C] -= IndexOffset;
470
471 // Now that the SCC structure is finalized, flip the kind to call.
472 SourceN.setEdgeKind(TargetN.getFunction(), Edge::Call);
473
474#ifndef NDEBUG
475 // And we're done! Verify in debug builds that the RefSCC is coherent.
476 verify();
477#endif
478 return DeletedSCCs;
Chandler Carruth5217c942014-04-30 10:48:36 +0000479}
480
Chandler Carruthe5944d92016-02-17 00:18:16 +0000481void LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN,
482 Node &TargetN) {
483 assert(SourceN[TargetN].isCall() && "Must start with a call edge!");
484
485 SCC &SourceSCC = *G->lookupSCC(SourceN);
486 SCC &TargetSCC = *G->lookupSCC(TargetN);
487
488 assert(&SourceSCC.getOuterRefSCC() == this &&
489 "Source must be in this RefSCC.");
490 assert(&TargetSCC.getOuterRefSCC() == this &&
491 "Target must be in this RefSCC.");
492
493 // Set the edge kind.
494 SourceN.setEdgeKind(TargetN.getFunction(), Edge::Ref);
495
496 // If this call edge is just connecting two separate SCCs within this RefSCC,
497 // there is nothing to do.
498 if (&SourceSCC != &TargetSCC) {
499#ifndef NDEBUG
500 // Check that the RefSCC is still valid.
501 verify();
502#endif
503 return;
504 }
505
506 // Otherwise we are removing a call edge from a single SCC. This may break
507 // the cycle. In order to compute the new set of SCCs, we need to do a small
508 // DFS over the nodes within the SCC to form any sub-cycles that remain as
509 // distinct SCCs and compute a postorder over the resulting SCCs.
510 //
511 // However, we specially handle the target node. The target node is known to
512 // reach all other nodes in the original SCC by definition. This means that
513 // we want the old SCC to be replaced with an SCC contaning that node as it
514 // will be the root of whatever SCC DAG results from the DFS. Assumptions
515 // about an SCC such as the set of functions called will continue to hold,
516 // etc.
517
518 SCC &OldSCC = TargetSCC;
519 SmallVector<std::pair<Node *, call_edge_iterator>, 16> DFSStack;
520 SmallVector<Node *, 16> PendingSCCStack;
521 SmallVector<SCC *, 4> NewSCCs;
522
523 // Prepare the nodes for a fresh DFS.
524 SmallVector<Node *, 16> Worklist;
525 Worklist.swap(OldSCC.Nodes);
526 for (Node *N : Worklist) {
527 N->DFSNumber = N->LowLink = 0;
528 G->SCCMap.erase(N);
529 }
530
531 // Force the target node to be in the old SCC. This also enables us to take
532 // a very significant short-cut in the standard Tarjan walk to re-form SCCs
533 // below: whenever we build an edge that reaches the target node, we know
534 // that the target node eventually connects back to all other nodes in our
535 // walk. As a consequence, we can detect and handle participants in that
536 // cycle without walking all the edges that form this connection, and instead
537 // by relying on the fundamental guarantee coming into this operation (all
538 // nodes are reachable from the target due to previously forming an SCC).
539 TargetN.DFSNumber = TargetN.LowLink = -1;
540 OldSCC.Nodes.push_back(&TargetN);
541 G->SCCMap[&TargetN] = &OldSCC;
542
543 // Scan down the stack and DFS across the call edges.
544 for (Node *RootN : Worklist) {
545 assert(DFSStack.empty() &&
546 "Cannot begin a new root with a non-empty DFS stack!");
547 assert(PendingSCCStack.empty() &&
548 "Cannot begin a new root with pending nodes for an SCC!");
549
550 // Skip any nodes we've already reached in the DFS.
551 if (RootN->DFSNumber != 0) {
552 assert(RootN->DFSNumber == -1 &&
553 "Shouldn't have any mid-DFS root nodes!");
554 continue;
555 }
556
557 RootN->DFSNumber = RootN->LowLink = 1;
558 int NextDFSNumber = 2;
559
560 DFSStack.push_back({RootN, RootN->call_begin()});
561 do {
562 Node *N;
563 call_edge_iterator I;
564 std::tie(N, I) = DFSStack.pop_back_val();
565 auto E = N->call_end();
566 while (I != E) {
567 Node &ChildN = *I->getNode();
568 if (ChildN.DFSNumber == 0) {
569 // We haven't yet visited this child, so descend, pushing the current
570 // node onto the stack.
571 DFSStack.push_back({N, I});
572
573 assert(!G->SCCMap.count(&ChildN) &&
574 "Found a node with 0 DFS number but already in an SCC!");
575 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
576 N = &ChildN;
577 I = N->call_begin();
578 E = N->call_end();
579 continue;
580 }
581
582 // Check for the child already being part of some component.
583 if (ChildN.DFSNumber == -1) {
584 if (G->lookupSCC(ChildN) == &OldSCC) {
585 // If the child is part of the old SCC, we know that it can reach
586 // every other node, so we have formed a cycle. Pull the entire DFS
587 // and pending stacks into it. See the comment above about setting
588 // up the old SCC for why we do this.
589 int OldSize = OldSCC.size();
590 OldSCC.Nodes.push_back(N);
591 OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end());
592 PendingSCCStack.clear();
593 while (!DFSStack.empty())
594 OldSCC.Nodes.push_back(DFSStack.pop_back_val().first);
595 for (Node &N : make_range(OldSCC.begin() + OldSize, OldSCC.end())) {
596 N.DFSNumber = N.LowLink = -1;
597 G->SCCMap[&N] = &OldSCC;
598 }
599 N = nullptr;
600 break;
601 }
602
603 // If the child has already been added to some child component, it
604 // couldn't impact the low-link of this parent because it isn't
605 // connected, and thus its low-link isn't relevant so skip it.
606 ++I;
607 continue;
608 }
609
610 // Track the lowest linked child as the lowest link for this node.
611 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
612 if (ChildN.LowLink < N->LowLink)
613 N->LowLink = ChildN.LowLink;
614
615 // Move to the next edge.
616 ++I;
617 }
618 if (!N)
619 // Cleared the DFS early, start another round.
620 break;
621
622 // We've finished processing N and its descendents, put it on our pending
623 // SCC stack to eventually get merged into an SCC of nodes.
624 PendingSCCStack.push_back(N);
625
626 // If this node is linked to some lower entry, continue walking up the
627 // stack.
628 if (N->LowLink != N->DFSNumber)
629 continue;
630
631 // Otherwise, we've completed an SCC. Append it to our post order list of
632 // SCCs.
633 int RootDFSNumber = N->DFSNumber;
634 // Find the range of the node stack by walking down until we pass the
635 // root DFS number.
636 auto SCCNodes = make_range(
637 PendingSCCStack.rbegin(),
638 std::find_if(PendingSCCStack.rbegin(), PendingSCCStack.rend(),
639 [RootDFSNumber](Node *N) {
640 return N->DFSNumber < RootDFSNumber;
641 }));
642
643 // Form a new SCC out of these nodes and then clear them off our pending
644 // stack.
645 NewSCCs.push_back(G->createSCC(*this, SCCNodes));
646 for (Node &N : *NewSCCs.back()) {
647 N.DFSNumber = N.LowLink = -1;
648 G->SCCMap[&N] = NewSCCs.back();
649 }
650 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
651 } while (!DFSStack.empty());
652 }
653
654 // Insert the remaining SCCs before the old one. The old SCC can reach all
655 // other SCCs we form because it contains the target node of the removed edge
656 // of the old SCC. This means that we will have edges into all of the new
657 // SCCs, which means the old one must come last for postorder.
658 int OldIdx = SCCIndices[&OldSCC];
659 SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end());
660
661 // Update the mapping from SCC* to index to use the new SCC*s, and remove the
662 // old SCC from the mapping.
663 for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx)
664 SCCIndices[SCCs[Idx]] = Idx;
665
666#ifndef NDEBUG
667 // We're done. Check the validity on our way out.
668 verify();
669#endif
670}
671
672void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN,
673 Node &TargetN) {
674 assert(!SourceN[TargetN].isCall() && "Must start with a ref edge!");
675
676 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
677 assert(G->lookupRefSCC(TargetN) != this &&
678 "Target must not be in this RefSCC.");
679 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
680 "Target must be a descendant of the Source.");
681
682 // Edges between RefSCCs are the same regardless of call or ref, so we can
683 // just flip the edge here.
684 SourceN.setEdgeKind(TargetN.getFunction(), Edge::Call);
685
686#ifndef NDEBUG
687 // Check that the RefSCC is still valid.
688 verify();
689#endif
690}
691
692void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN,
693 Node &TargetN) {
694 assert(SourceN[TargetN].isCall() && "Must start with a call edge!");
695
696 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
697 assert(G->lookupRefSCC(TargetN) != this &&
698 "Target must not be in this RefSCC.");
699 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
700 "Target must be a descendant of the Source.");
701
702 // Edges between RefSCCs are the same regardless of call or ref, so we can
703 // just flip the edge here.
704 SourceN.setEdgeKind(TargetN.getFunction(), Edge::Ref);
705
706#ifndef NDEBUG
707 // Check that the RefSCC is still valid.
708 verify();
709#endif
710}
711
712void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN,
713 Node &TargetN) {
714 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
715 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
716
717 SourceN.insertEdgeInternal(TargetN, Edge::Ref);
718
719#ifndef NDEBUG
720 // Check that the RefSCC is still valid.
721 verify();
722#endif
723}
724
725void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN,
726 Edge::Kind EK) {
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000727 // First insert it into the caller.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000728 SourceN.insertEdgeInternal(TargetN, EK);
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000729
Chandler Carruthe5944d92016-02-17 00:18:16 +0000730 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000731
Chandler Carruthe5944d92016-02-17 00:18:16 +0000732 RefSCC &TargetC = *G->lookupRefSCC(TargetN);
733 assert(&TargetC != this && "Target must not be in this RefSCC.");
734 assert(TargetC.isDescendantOf(*this) &&
735 "Target must be a descendant of the Source.");
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000736
Chandler Carruth91539112015-12-28 01:54:20 +0000737 // The only change required is to add this SCC to the parent set of the
738 // callee.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000739 TargetC.Parents.insert(this);
740
741#ifndef NDEBUG
742 // Check that the RefSCC is still valid.
743 verify();
744#endif
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000745}
746
Chandler Carruthe5944d92016-02-17 00:18:16 +0000747SmallVector<LazyCallGraph::RefSCC *, 1>
748LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) {
749 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this SCC.");
Chandler Carruth312dddf2014-05-04 09:38:32 +0000750
Chandler Carruthe5944d92016-02-17 00:18:16 +0000751 // We store the RefSCCs found to be connected in postorder so that we can use
752 // that when merging. We also return this to the caller to allow them to
753 // invalidate information pertaining to these RefSCCs.
754 SmallVector<RefSCC *, 1> Connected;
Chandler Carruth312dddf2014-05-04 09:38:32 +0000755
Chandler Carruthe5944d92016-02-17 00:18:16 +0000756 RefSCC &SourceC = *G->lookupRefSCC(SourceN);
757 assert(&SourceC != this && "Source must not be in this SCC.");
758 assert(SourceC.isDescendantOf(*this) &&
759 "Source must be a descendant of the Target.");
Chandler Carruth312dddf2014-05-04 09:38:32 +0000760
761 // The algorithm we use for merging SCCs based on the cycle introduced here
Chandler Carruthe5944d92016-02-17 00:18:16 +0000762 // is to walk the RefSCC inverted DAG formed by the parent sets. The inverse
763 // graph has the same cycle properties as the actual DAG of the RefSCCs, and
764 // when forming RefSCCs lazily by a DFS, the bottom of the graph won't exist
765 // in many cases which should prune the search space.
Chandler Carruth312dddf2014-05-04 09:38:32 +0000766 //
Chandler Carruthe5944d92016-02-17 00:18:16 +0000767 // FIXME: We can get this pruning behavior even after the incremental RefSCC
Chandler Carruth312dddf2014-05-04 09:38:32 +0000768 // formation by leaving behind (conservative) DFS numberings in the nodes,
769 // and pruning the search with them. These would need to be cleverly updated
770 // during the removal of intra-SCC edges, but could be preserved
771 // conservatively.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000772 //
773 // FIXME: This operation currently creates ordering stability problems
774 // because we don't use stably ordered containers for the parent SCCs.
Chandler Carruth312dddf2014-05-04 09:38:32 +0000775
Chandler Carruthe5944d92016-02-17 00:18:16 +0000776 // The set of RefSCCs that are connected to the parent, and thus will
Chandler Carruth312dddf2014-05-04 09:38:32 +0000777 // participate in the merged connected component.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000778 SmallPtrSet<RefSCC *, 8> ConnectedSet;
779 ConnectedSet.insert(this);
Chandler Carruth312dddf2014-05-04 09:38:32 +0000780
781 // We build up a DFS stack of the parents chains.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000782 SmallVector<std::pair<RefSCC *, parent_iterator>, 8> DFSStack;
783 SmallPtrSet<RefSCC *, 8> Visited;
Chandler Carruth312dddf2014-05-04 09:38:32 +0000784 int ConnectedDepth = -1;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000785 DFSStack.push_back({&SourceC, SourceC.parent_begin()});
786 do {
787 auto DFSPair = DFSStack.pop_back_val();
788 RefSCC *C = DFSPair.first;
789 parent_iterator I = DFSPair.second;
790 auto E = C->parent_end();
791
Chandler Carruth312dddf2014-05-04 09:38:32 +0000792 while (I != E) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000793 RefSCC &Parent = *I++;
Chandler Carruth312dddf2014-05-04 09:38:32 +0000794
795 // If we have already processed this parent SCC, skip it, and remember
796 // whether it was connected so we don't have to check the rest of the
797 // stack. This also handles when we reach a child of the 'this' SCC (the
798 // callee) which terminates the search.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000799 if (ConnectedSet.count(&Parent)) {
800 assert(ConnectedDepth < (int)DFSStack.size() &&
801 "Cannot have a connected depth greater than the DFS depth!");
802 ConnectedDepth = DFSStack.size();
Chandler Carruth312dddf2014-05-04 09:38:32 +0000803 continue;
804 }
Chandler Carruthe5944d92016-02-17 00:18:16 +0000805 if (Visited.count(&Parent))
Chandler Carruth312dddf2014-05-04 09:38:32 +0000806 continue;
807
808 // We fully explore the depth-first space, adding nodes to the connected
809 // set only as we pop them off, so "recurse" by rotating to the parent.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000810 DFSStack.push_back({C, I});
811 C = &Parent;
812 I = C->parent_begin();
813 E = C->parent_end();
Chandler Carruth312dddf2014-05-04 09:38:32 +0000814 }
815
816 // If we've found a connection anywhere below this point on the stack (and
817 // thus up the parent graph from the caller), the current node needs to be
818 // added to the connected set now that we've processed all of its parents.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000819 if ((int)DFSStack.size() == ConnectedDepth) {
Chandler Carruth312dddf2014-05-04 09:38:32 +0000820 --ConnectedDepth; // We're finished with this connection.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000821 bool Inserted = ConnectedSet.insert(C).second;
822 (void)Inserted;
823 assert(Inserted && "Cannot insert a refSCC multiple times!");
824 Connected.push_back(C);
Chandler Carruth312dddf2014-05-04 09:38:32 +0000825 } else {
826 // Otherwise remember that its parents don't ever connect.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000827 assert(ConnectedDepth < (int)DFSStack.size() &&
Chandler Carruth312dddf2014-05-04 09:38:32 +0000828 "Cannot have a connected depth greater than the DFS depth!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000829 Visited.insert(C);
Chandler Carruth312dddf2014-05-04 09:38:32 +0000830 }
Chandler Carruthe5944d92016-02-17 00:18:16 +0000831 } while (!DFSStack.empty());
Chandler Carruth312dddf2014-05-04 09:38:32 +0000832
833 // Now that we have identified all of the SCCs which need to be merged into
834 // a connected set with the inserted edge, merge all of them into this SCC.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000835 // We walk the newly connected RefSCCs in the reverse postorder of the parent
836 // DAG walk above and merge in each of their SCC postorder lists. This
837 // ensures a merged postorder SCC list.
838 SmallVector<SCC *, 16> MergedSCCs;
839 int SCCIndex = 0;
840 for (RefSCC *C : reverse(Connected)) {
841 assert(C != this &&
842 "This RefSCC should terminate the DFS without being reached.");
Chandler Carruth312dddf2014-05-04 09:38:32 +0000843
Chandler Carruthe5944d92016-02-17 00:18:16 +0000844 // Merge the parents which aren't part of the merge into the our parents.
845 for (RefSCC *ParentC : C->Parents)
846 if (!ConnectedSet.count(ParentC))
847 Parents.insert(ParentC);
848 C->Parents.clear();
849
850 // Walk the inner SCCs to update their up-pointer and walk all the edges to
851 // update any parent sets.
852 // FIXME: We should try to find a way to avoid this (rather expensive) edge
853 // walk by updating the parent sets in some other manner.
854 for (SCC &InnerC : *C) {
855 InnerC.OuterRefSCC = this;
856 SCCIndices[&InnerC] = SCCIndex++;
857 for (Node &N : InnerC) {
858 G->SCCMap[&N] = &InnerC;
859 for (Edge &E : N) {
860 assert(E.getNode() &&
861 "Cannot have a null node within a visited SCC!");
862 RefSCC &ChildRC = *G->lookupRefSCC(*E.getNode());
863 if (ConnectedSet.count(&ChildRC))
864 continue;
865 ChildRC.Parents.erase(C);
866 ChildRC.Parents.insert(this);
867 }
Chandler Carruth312dddf2014-05-04 09:38:32 +0000868 }
Chandler Carruth312dddf2014-05-04 09:38:32 +0000869 }
Chandler Carruthe5944d92016-02-17 00:18:16 +0000870
871 // Now merge in the SCCs. We can actually move here so try to reuse storage
872 // the first time through.
873 if (MergedSCCs.empty())
874 MergedSCCs = std::move(C->SCCs);
875 else
876 MergedSCCs.append(C->SCCs.begin(), C->SCCs.end());
877 C->SCCs.clear();
Chandler Carruth312dddf2014-05-04 09:38:32 +0000878 }
Chandler Carruthe5944d92016-02-17 00:18:16 +0000879
880 // Finally append our original SCCs to the merged list and move it into
881 // place.
882 for (SCC &InnerC : *this)
883 SCCIndices[&InnerC] = SCCIndex++;
884 MergedSCCs.append(SCCs.begin(), SCCs.end());
885 SCCs = std::move(MergedSCCs);
886
887 // At this point we have a merged RefSCC with a post-order SCCs list, just
888 // connect the nodes to form the new edge.
889 SourceN.insertEdgeInternal(TargetN, Edge::Ref);
890
891#ifndef NDEBUG
892 // Check that the RefSCC is still valid.
893 verify();
894#endif
Chandler Carruth312dddf2014-05-04 09:38:32 +0000895
896 // We return the list of SCCs which were merged so that callers can
897 // invalidate any data they have associated with those SCCs. Note that these
898 // SCCs are no longer in an interesting state (they are totally empty) but
899 // the pointers will remain stable for the life of the graph itself.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000900 return Connected;
Chandler Carruth312dddf2014-05-04 09:38:32 +0000901}
902
Chandler Carruthe5944d92016-02-17 00:18:16 +0000903void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) {
904 assert(G->lookupRefSCC(SourceN) == this &&
905 "The source must be a member of this RefSCC.");
906
907 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
908 assert(&TargetRC != this && "The target must not be a member of this RefSCC");
909
David Majnemer0d955d02016-08-11 22:21:41 +0000910 assert(!is_contained(G->LeafRefSCCs, this) &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000911 "Cannot have a leaf RefSCC source.");
912
Chandler Carruthaa839b22014-04-27 01:59:50 +0000913 // First remove it from the node.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000914 SourceN.removeEdgeInternal(TargetN.getFunction());
Chandler Carruthaa839b22014-04-27 01:59:50 +0000915
Chandler Carruthe5944d92016-02-17 00:18:16 +0000916 bool HasOtherEdgeToChildRC = false;
917 bool HasOtherChildRC = false;
918 for (SCC *InnerC : SCCs) {
919 for (Node &N : *InnerC) {
920 for (Edge &E : N) {
921 assert(E.getNode() && "Cannot have a missing node in a visited SCC!");
922 RefSCC &OtherChildRC = *G->lookupRefSCC(*E.getNode());
923 if (&OtherChildRC == &TargetRC) {
924 HasOtherEdgeToChildRC = true;
925 break;
926 }
927 if (&OtherChildRC != this)
928 HasOtherChildRC = true;
Chandler Carruth9302fbf2014-04-23 11:03:03 +0000929 }
Chandler Carruthe5944d92016-02-17 00:18:16 +0000930 if (HasOtherEdgeToChildRC)
931 break;
Chandler Carruth9302fbf2014-04-23 11:03:03 +0000932 }
Chandler Carruthe5944d92016-02-17 00:18:16 +0000933 if (HasOtherEdgeToChildRC)
Chandler Carruth9302fbf2014-04-23 11:03:03 +0000934 break;
935 }
936 // Because the SCCs form a DAG, deleting such an edge cannot change the set
937 // of SCCs in the graph. However, it may cut an edge of the SCC DAG, making
Chandler Carruthe5944d92016-02-17 00:18:16 +0000938 // the source SCC no longer connected to the target SCC. If so, we need to
939 // update the target SCC's map of its parents.
940 if (!HasOtherEdgeToChildRC) {
941 bool Removed = TargetRC.Parents.erase(this);
Chandler Carruth9302fbf2014-04-23 11:03:03 +0000942 (void)Removed;
943 assert(Removed &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000944 "Did not find the source SCC in the target SCC's parent list!");
Chandler Carruth9302fbf2014-04-23 11:03:03 +0000945
946 // It may orphan an SCC if it is the last edge reaching it, but that does
947 // not violate any invariants of the graph.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000948 if (TargetRC.Parents.empty())
949 DEBUG(dbgs() << "LCG: Update removing " << SourceN.getFunction().getName()
950 << " -> " << TargetN.getFunction().getName()
Chandler Carruthaa839b22014-04-27 01:59:50 +0000951 << " edge orphaned the callee's SCC!\n");
Chandler Carruth9302fbf2014-04-23 11:03:03 +0000952
Chandler Carruthe5944d92016-02-17 00:18:16 +0000953 // It may make the Source SCC a leaf SCC.
954 if (!HasOtherChildRC)
955 G->LeafRefSCCs.push_back(this);
Chandler Carruthaca48d02014-04-26 09:06:53 +0000956 }
957}
958
Chandler Carruthe5944d92016-02-17 00:18:16 +0000959SmallVector<LazyCallGraph::RefSCC *, 1>
960LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN, Node &TargetN) {
961 assert(!SourceN[TargetN].isCall() &&
962 "Cannot remove a call edge, it must first be made a ref edge");
Chandler Carruthaa839b22014-04-27 01:59:50 +0000963
Chandler Carruthe5944d92016-02-17 00:18:16 +0000964 // First remove the actual edge.
965 SourceN.removeEdgeInternal(TargetN.getFunction());
966
967 // We return a list of the resulting *new* RefSCCs in post-order.
968 SmallVector<RefSCC *, 1> Result;
Chandler Carruth9302fbf2014-04-23 11:03:03 +0000969
Chandler Carrutha7205b62014-04-26 03:36:37 +0000970 // Direct recursion doesn't impact the SCC graph at all.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000971 if (&SourceN == &TargetN)
972 return Result;
Chandler Carrutha7205b62014-04-26 03:36:37 +0000973
Chandler Carruthe5944d92016-02-17 00:18:16 +0000974 // We build somewhat synthetic new RefSCCs by providing a postorder mapping
975 // for each inner SCC. We also store these associated with *nodes* rather
976 // than SCCs because this saves a round-trip through the node->SCC map and in
977 // the common case, SCCs are small. We will verify that we always give the
978 // same number to every node in the SCC such that these are equivalent.
979 const int RootPostOrderNumber = 0;
980 int PostOrderNumber = RootPostOrderNumber + 1;
981 SmallDenseMap<Node *, int> PostOrderMapping;
982
983 // Every node in the target SCC can already reach every node in this RefSCC
984 // (by definition). It is the only node we know will stay inside this RefSCC.
985 // Everything which transitively reaches Target will also remain in the
986 // RefSCC. We handle this by pre-marking that the nodes in the target SCC map
987 // back to the root post order number.
988 //
989 // This also enables us to take a very significant short-cut in the standard
990 // Tarjan walk to re-form RefSCCs below: whenever we build an edge that
991 // references the target node, we know that the target node eventually
992 // references all other nodes in our walk. As a consequence, we can detect
993 // and handle participants in that cycle without walking all the edges that
994 // form the connections, and instead by relying on the fundamental guarantee
995 // coming into this operation.
996 SCC &TargetC = *G->lookupSCC(TargetN);
997 for (Node &N : TargetC)
998 PostOrderMapping[&N] = RootPostOrderNumber;
999
1000 // Reset all the other nodes to prepare for a DFS over them, and add them to
1001 // our worklist.
1002 SmallVector<Node *, 8> Worklist;
1003 for (SCC *C : SCCs) {
1004 if (C == &TargetC)
1005 continue;
1006
1007 for (Node &N : *C)
1008 N.DFSNumber = N.LowLink = 0;
1009
1010 Worklist.append(C->Nodes.begin(), C->Nodes.end());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001011 }
1012
Chandler Carruthe5944d92016-02-17 00:18:16 +00001013 auto MarkNodeForSCCNumber = [&PostOrderMapping](Node &N, int Number) {
1014 N.DFSNumber = N.LowLink = -1;
1015 PostOrderMapping[&N] = Number;
1016 };
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001017
Chandler Carruthe5944d92016-02-17 00:18:16 +00001018 SmallVector<std::pair<Node *, edge_iterator>, 4> DFSStack;
1019 SmallVector<Node *, 4> PendingRefSCCStack;
Chandler Carruthaca48d02014-04-26 09:06:53 +00001020 do {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001021 assert(DFSStack.empty() &&
1022 "Cannot begin a new root with a non-empty DFS stack!");
1023 assert(PendingRefSCCStack.empty() &&
1024 "Cannot begin a new root with pending nodes for an SCC!");
1025
1026 Node *RootN = Worklist.pop_back_val();
1027 // Skip any nodes we've already reached in the DFS.
1028 if (RootN->DFSNumber != 0) {
1029 assert(RootN->DFSNumber == -1 &&
1030 "Shouldn't have any mid-DFS root nodes!");
1031 continue;
1032 }
1033
1034 RootN->DFSNumber = RootN->LowLink = 1;
1035 int NextDFSNumber = 2;
1036
1037 DFSStack.push_back({RootN, RootN->begin()});
1038 do {
1039 Node *N;
1040 edge_iterator I;
1041 std::tie(N, I) = DFSStack.pop_back_val();
1042 auto E = N->end();
1043
1044 assert(N->DFSNumber != 0 && "We should always assign a DFS number "
1045 "before processing a node.");
1046
1047 while (I != E) {
1048 Node &ChildN = I->getNode(*G);
1049 if (ChildN.DFSNumber == 0) {
1050 // Mark that we should start at this child when next this node is the
1051 // top of the stack. We don't start at the next child to ensure this
1052 // child's lowlink is reflected.
1053 DFSStack.push_back({N, I});
1054
1055 // Continue, resetting to the child node.
1056 ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1057 N = &ChildN;
1058 I = ChildN.begin();
1059 E = ChildN.end();
1060 continue;
1061 }
1062 if (ChildN.DFSNumber == -1) {
1063 // Check if this edge's target node connects to the deleted edge's
1064 // target node. If so, we know that every node connected will end up
1065 // in this RefSCC, so collapse the entire current stack into the root
1066 // slot in our SCC numbering. See above for the motivation of
1067 // optimizing the target connected nodes in this way.
1068 auto PostOrderI = PostOrderMapping.find(&ChildN);
1069 if (PostOrderI != PostOrderMapping.end() &&
1070 PostOrderI->second == RootPostOrderNumber) {
1071 MarkNodeForSCCNumber(*N, RootPostOrderNumber);
1072 while (!PendingRefSCCStack.empty())
1073 MarkNodeForSCCNumber(*PendingRefSCCStack.pop_back_val(),
1074 RootPostOrderNumber);
1075 while (!DFSStack.empty())
1076 MarkNodeForSCCNumber(*DFSStack.pop_back_val().first,
1077 RootPostOrderNumber);
1078 // Ensure we break all the way out of the enclosing loop.
1079 N = nullptr;
1080 break;
1081 }
1082
1083 // If this child isn't currently in this RefSCC, no need to process
1084 // it.
1085 // However, we do need to remove this RefSCC from its RefSCC's parent
1086 // set.
1087 RefSCC &ChildRC = *G->lookupRefSCC(ChildN);
1088 ChildRC.Parents.erase(this);
1089 ++I;
1090 continue;
1091 }
1092
1093 // Track the lowest link of the children, if any are still in the stack.
1094 // Any child not on the stack will have a LowLink of -1.
1095 assert(ChildN.LowLink != 0 &&
1096 "Low-link must not be zero with a non-zero DFS number.");
1097 if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
1098 N->LowLink = ChildN.LowLink;
1099 ++I;
1100 }
1101 if (!N)
1102 // We short-circuited this node.
1103 break;
1104
1105 // We've finished processing N and its descendents, put it on our pending
1106 // stack to eventually get merged into a RefSCC.
1107 PendingRefSCCStack.push_back(N);
1108
1109 // If this node is linked to some lower entry, continue walking up the
1110 // stack.
1111 if (N->LowLink != N->DFSNumber) {
1112 assert(!DFSStack.empty() &&
1113 "We never found a viable root for a RefSCC to pop off!");
1114 continue;
1115 }
1116
1117 // Otherwise, form a new RefSCC from the top of the pending node stack.
1118 int RootDFSNumber = N->DFSNumber;
1119 // Find the range of the node stack by walking down until we pass the
1120 // root DFS number.
1121 auto RefSCCNodes = make_range(
1122 PendingRefSCCStack.rbegin(),
1123 std::find_if(PendingRefSCCStack.rbegin(), PendingRefSCCStack.rend(),
1124 [RootDFSNumber](Node *N) {
1125 return N->DFSNumber < RootDFSNumber;
1126 }));
1127
1128 // Mark the postorder number for these nodes and clear them off the
1129 // stack. We'll use the postorder number to pull them into RefSCCs at the
1130 // end. FIXME: Fuse with the loop above.
1131 int RefSCCNumber = PostOrderNumber++;
1132 for (Node *N : RefSCCNodes)
1133 MarkNodeForSCCNumber(*N, RefSCCNumber);
1134
1135 PendingRefSCCStack.erase(RefSCCNodes.end().base(),
1136 PendingRefSCCStack.end());
1137 } while (!DFSStack.empty());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001138
Chandler Carruthaca48d02014-04-26 09:06:53 +00001139 assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
Chandler Carruthe5944d92016-02-17 00:18:16 +00001140 assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!");
Chandler Carruthaca48d02014-04-26 09:06:53 +00001141 } while (!Worklist.empty());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001142
Chandler Carruthe5944d92016-02-17 00:18:16 +00001143 // We now have a post-order numbering for RefSCCs and a mapping from each
1144 // node in this RefSCC to its final RefSCC. We create each new RefSCC node
1145 // (re-using this RefSCC node for the root) and build a radix-sort style map
1146 // from postorder number to the RefSCC. We then append SCCs to each of these
1147 // RefSCCs in the order they occured in the original SCCs container.
1148 for (int i = 1; i < PostOrderNumber; ++i)
1149 Result.push_back(G->createRefSCC(*G));
1150
1151 for (SCC *C : SCCs) {
1152 auto PostOrderI = PostOrderMapping.find(&*C->begin());
1153 assert(PostOrderI != PostOrderMapping.end() &&
1154 "Cannot have missing mappings for nodes!");
1155 int SCCNumber = PostOrderI->second;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001156#ifndef NDEBUG
Chandler Carruthe5944d92016-02-17 00:18:16 +00001157 for (Node &N : *C)
1158 assert(PostOrderMapping.find(&N)->second == SCCNumber &&
1159 "Cannot have different numbers for nodes in the same SCC!");
1160#endif
1161 if (SCCNumber == 0)
1162 // The root node is handled separately by removing the SCCs.
1163 continue;
1164
1165 RefSCC &RC = *Result[SCCNumber - 1];
1166 int SCCIndex = RC.SCCs.size();
1167 RC.SCCs.push_back(C);
1168 SCCIndices[C] = SCCIndex;
1169 C->OuterRefSCC = &RC;
1170 }
1171
1172 // FIXME: We re-walk the edges in each RefSCC to establish whether it is
1173 // a leaf and connect it to the rest of the graph's parents lists. This is
1174 // really wasteful. We should instead do this during the DFS to avoid yet
1175 // another edge walk.
1176 for (RefSCC *RC : Result)
1177 G->connectRefSCC(*RC);
1178
1179 // Now erase all but the root's SCCs.
1180 SCCs.erase(std::remove_if(SCCs.begin(), SCCs.end(),
1181 [&](SCC *C) {
1182 return PostOrderMapping.lookup(&*C->begin()) !=
1183 RootPostOrderNumber;
1184 }),
1185 SCCs.end());
1186
1187#ifndef NDEBUG
1188 // Now we need to reconnect the current (root) SCC to the graph. We do this
1189 // manually because we can special case our leaf handling and detect errors.
1190 bool IsLeaf = true;
1191#endif
1192 for (SCC *C : SCCs)
1193 for (Node &N : *C) {
1194 for (Edge &E : N) {
1195 assert(E.getNode() && "Cannot have a missing node in a visited SCC!");
1196 RefSCC &ChildRC = *G->lookupRefSCC(*E.getNode());
1197 if (&ChildRC == this)
1198 continue;
1199 ChildRC.Parents.insert(this);
1200#ifndef NDEBUG
1201 IsLeaf = false;
1202#endif
1203 }
1204 }
1205#ifndef NDEBUG
1206 if (!Result.empty())
1207 assert(!IsLeaf && "This SCC cannot be a leaf as we have split out new "
1208 "SCCs by removing this edge.");
David Majnemer0a16c222016-08-11 21:15:00 +00001209 if (none_of(G->LeafRefSCCs, [&](RefSCC *C) { return C == this; }))
Chandler Carruthe5944d92016-02-17 00:18:16 +00001210 assert(!IsLeaf && "This SCC cannot be a leaf as it already had child "
1211 "SCCs before we removed this edge.");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001212#endif
1213 // If this SCC stopped being a leaf through this edge removal, remove it from
Chandler Carruthe5944d92016-02-17 00:18:16 +00001214 // the leaf SCC list. Note that this DTRT in the case where this was never
1215 // a leaf.
1216 // FIXME: As LeafRefSCCs could be very large, we might want to not walk the
1217 // entire list if this RefSCC wasn't a leaf before the edge removal.
1218 if (!Result.empty())
1219 G->LeafRefSCCs.erase(
1220 std::remove(G->LeafRefSCCs.begin(), G->LeafRefSCCs.end(), this),
1221 G->LeafRefSCCs.end());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001222
1223 // Return the new list of SCCs.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001224 return Result;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001225}
1226
Chandler Carruthe5944d92016-02-17 00:18:16 +00001227void LazyCallGraph::insertEdge(Node &SourceN, Function &Target, Edge::Kind EK) {
Chandler Carruthc00a7ff2014-04-28 11:10:23 +00001228 assert(SCCMap.empty() && DFSStack.empty() &&
1229 "This method cannot be called after SCCs have been formed!");
1230
Chandler Carruthe5944d92016-02-17 00:18:16 +00001231 return SourceN.insertEdgeInternal(Target, EK);
Chandler Carruthc00a7ff2014-04-28 11:10:23 +00001232}
1233
Chandler Carruthe5944d92016-02-17 00:18:16 +00001234void LazyCallGraph::removeEdge(Node &SourceN, Function &Target) {
Chandler Carruthaa839b22014-04-27 01:59:50 +00001235 assert(SCCMap.empty() && DFSStack.empty() &&
1236 "This method cannot be called after SCCs have been formed!");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001237
Chandler Carruthe5944d92016-02-17 00:18:16 +00001238 return SourceN.removeEdgeInternal(Target);
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001239}
1240
Chandler Carruth2a898e02014-04-23 23:20:36 +00001241LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
1242 return *new (MappedN = BPA.Allocate()) Node(*this, F);
Chandler Carruthd8d865e2014-04-18 11:02:33 +00001243}
1244
1245void LazyCallGraph::updateGraphPtrs() {
Chandler Carruthb60cb312014-04-17 07:25:59 +00001246 // Process all nodes updating the graph pointers.
Chandler Carruthaa839b22014-04-27 01:59:50 +00001247 {
1248 SmallVector<Node *, 16> Worklist;
Chandler Carrutha4499e92016-02-02 03:57:13 +00001249 for (Edge &E : EntryEdges)
1250 if (Node *EntryN = E.getNode())
Chandler Carruthaa839b22014-04-27 01:59:50 +00001251 Worklist.push_back(EntryN);
Chandler Carruthb60cb312014-04-17 07:25:59 +00001252
Chandler Carruthaa839b22014-04-27 01:59:50 +00001253 while (!Worklist.empty()) {
1254 Node *N = Worklist.pop_back_val();
1255 N->G = this;
Chandler Carrutha4499e92016-02-02 03:57:13 +00001256 for (Edge &E : N->Edges)
Chandler Carruthe5944d92016-02-17 00:18:16 +00001257 if (Node *TargetN = E.getNode())
1258 Worklist.push_back(TargetN);
Chandler Carruthaa839b22014-04-27 01:59:50 +00001259 }
1260 }
1261
1262 // Process all SCCs updating the graph pointers.
1263 {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001264 SmallVector<RefSCC *, 16> Worklist(LeafRefSCCs.begin(), LeafRefSCCs.end());
Chandler Carruthaa839b22014-04-27 01:59:50 +00001265
1266 while (!Worklist.empty()) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001267 RefSCC &C = *Worklist.pop_back_val();
1268 C.G = this;
1269 for (RefSCC &ParentC : C.parents())
1270 Worklist.push_back(&ParentC);
Chandler Carruthaa839b22014-04-27 01:59:50 +00001271 }
Chandler Carruthb60cb312014-04-17 07:25:59 +00001272 }
Chandler Carruthbf71a342014-02-06 04:37:03 +00001273}
Chandler Carruthbf71a342014-02-06 04:37:03 +00001274
Chandler Carruthe5944d92016-02-17 00:18:16 +00001275/// Build the internal SCCs for a RefSCC from a sequence of nodes.
1276///
1277/// Appends the SCCs to the provided vector and updates the map with their
1278/// indices. Both the vector and map must be empty when passed into this
1279/// routine.
1280void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
1281 assert(RC.SCCs.empty() && "Already built SCCs!");
1282 assert(RC.SCCIndices.empty() && "Already mapped SCC indices!");
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001283
Chandler Carruthe5944d92016-02-17 00:18:16 +00001284 for (Node *N : Nodes) {
1285 assert(N->LowLink >= (*Nodes.begin())->LowLink &&
Chandler Carruthcace6622014-04-23 10:31:17 +00001286 "We cannot have a low link in an SCC lower than its root on the "
1287 "stack!");
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001288
Chandler Carruthe5944d92016-02-17 00:18:16 +00001289 // This node will go into the next RefSCC, clear out its DFS and low link
1290 // as we scan.
1291 N->DFSNumber = N->LowLink = 0;
1292 }
1293
1294 // Each RefSCC contains a DAG of the call SCCs. To build these, we do
1295 // a direct walk of the call edges using Tarjan's algorithm. We reuse the
1296 // internal storage as we won't need it for the outer graph's DFS any longer.
1297
1298 SmallVector<std::pair<Node *, call_edge_iterator>, 16> DFSStack;
1299 SmallVector<Node *, 16> PendingSCCStack;
1300
1301 // Scan down the stack and DFS across the call edges.
1302 for (Node *RootN : Nodes) {
1303 assert(DFSStack.empty() &&
1304 "Cannot begin a new root with a non-empty DFS stack!");
1305 assert(PendingSCCStack.empty() &&
1306 "Cannot begin a new root with pending nodes for an SCC!");
1307
1308 // Skip any nodes we've already reached in the DFS.
1309 if (RootN->DFSNumber != 0) {
1310 assert(RootN->DFSNumber == -1 &&
1311 "Shouldn't have any mid-DFS root nodes!");
1312 continue;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001313 }
1314
Chandler Carruthe5944d92016-02-17 00:18:16 +00001315 RootN->DFSNumber = RootN->LowLink = 1;
1316 int NextDFSNumber = 2;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001317
Chandler Carruthe5944d92016-02-17 00:18:16 +00001318 DFSStack.push_back({RootN, RootN->call_begin()});
1319 do {
1320 Node *N;
1321 call_edge_iterator I;
1322 std::tie(N, I) = DFSStack.pop_back_val();
1323 auto E = N->call_end();
1324 while (I != E) {
1325 Node &ChildN = *I->getNode();
1326 if (ChildN.DFSNumber == 0) {
1327 // We haven't yet visited this child, so descend, pushing the current
1328 // node onto the stack.
1329 DFSStack.push_back({N, I});
1330
1331 assert(!lookupSCC(ChildN) &&
1332 "Found a node with 0 DFS number but already in an SCC!");
1333 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1334 N = &ChildN;
1335 I = N->call_begin();
1336 E = N->call_end();
1337 continue;
1338 }
1339
1340 // If the child has already been added to some child component, it
1341 // couldn't impact the low-link of this parent because it isn't
1342 // connected, and thus its low-link isn't relevant so skip it.
1343 if (ChildN.DFSNumber == -1) {
1344 ++I;
1345 continue;
1346 }
1347
1348 // Track the lowest linked child as the lowest link for this node.
1349 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1350 if (ChildN.LowLink < N->LowLink)
1351 N->LowLink = ChildN.LowLink;
1352
1353 // Move to the next edge.
1354 ++I;
1355 }
1356
1357 // We've finished processing N and its descendents, put it on our pending
1358 // SCC stack to eventually get merged into an SCC of nodes.
1359 PendingSCCStack.push_back(N);
1360
1361 // If this node is linked to some lower entry, continue walking up the
1362 // stack.
1363 if (N->LowLink != N->DFSNumber)
1364 continue;
1365
1366 // Otherwise, we've completed an SCC. Append it to our post order list of
1367 // SCCs.
1368 int RootDFSNumber = N->DFSNumber;
1369 // Find the range of the node stack by walking down until we pass the
1370 // root DFS number.
1371 auto SCCNodes = make_range(
1372 PendingSCCStack.rbegin(),
1373 std::find_if(PendingSCCStack.rbegin(), PendingSCCStack.rend(),
1374 [RootDFSNumber](Node *N) {
1375 return N->DFSNumber < RootDFSNumber;
1376 }));
1377 // Form a new SCC out of these nodes and then clear them off our pending
1378 // stack.
1379 RC.SCCs.push_back(createSCC(RC, SCCNodes));
1380 for (Node &N : *RC.SCCs.back()) {
1381 N.DFSNumber = N.LowLink = -1;
1382 SCCMap[&N] = RC.SCCs.back();
1383 }
1384 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
1385 } while (!DFSStack.empty());
1386 }
1387
1388 // Wire up the SCC indices.
1389 for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i)
1390 RC.SCCIndices[RC.SCCs[i]] = i;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001391}
1392
Chandler Carruthe5944d92016-02-17 00:18:16 +00001393// FIXME: We should move callers of this to embed the parent linking and leaf
1394// tracking into their DFS in order to remove a full walk of all edges.
1395void LazyCallGraph::connectRefSCC(RefSCC &RC) {
1396 // Walk all edges in the RefSCC (this remains linear as we only do this once
1397 // when we build the RefSCC) to connect it to the parent sets of its
1398 // children.
1399 bool IsLeaf = true;
1400 for (SCC &C : RC)
1401 for (Node &N : C)
1402 for (Edge &E : N) {
1403 assert(E.getNode() &&
1404 "Cannot have a missing node in a visited part of the graph!");
1405 RefSCC &ChildRC = *lookupRefSCC(*E.getNode());
1406 if (&ChildRC == &RC)
1407 continue;
1408 ChildRC.Parents.insert(&RC);
1409 IsLeaf = false;
1410 }
1411
1412 // For the SCCs where we fine no child SCCs, add them to the leaf list.
1413 if (IsLeaf)
1414 LeafRefSCCs.push_back(&RC);
1415}
1416
1417LazyCallGraph::RefSCC *LazyCallGraph::getNextRefSCCInPostOrder() {
1418 if (DFSStack.empty()) {
1419 Node *N;
Chandler Carruth90821c22014-04-26 09:45:55 +00001420 do {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001421 // If we've handled all candidate entry nodes to the SCC forest, we're
1422 // done.
1423 if (RefSCCEntryNodes.empty())
Chandler Carruth90821c22014-04-26 09:45:55 +00001424 return nullptr;
Chandler Carruth18eadd922014-04-18 10:50:32 +00001425
Chandler Carruthe5944d92016-02-17 00:18:16 +00001426 N = &get(*RefSCCEntryNodes.pop_back_val());
Chandler Carruth90821c22014-04-26 09:45:55 +00001427 } while (N->DFSNumber != 0);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001428
1429 // Found a new root, begin the DFS here.
Chandler Carruth5e2d70b2014-04-26 09:28:00 +00001430 N->LowLink = N->DFSNumber = 1;
Chandler Carruth09751bf2014-04-24 09:59:59 +00001431 NextDFSNumber = 2;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001432 DFSStack.push_back({N, N->begin()});
Chandler Carruth18eadd922014-04-18 10:50:32 +00001433 }
1434
Chandler Carruth91dcf0f2014-04-24 21:19:30 +00001435 for (;;) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001436 Node *N;
1437 edge_iterator I;
1438 std::tie(N, I) = DFSStack.pop_back_val();
1439
1440 assert(N->DFSNumber > 0 && "We should always assign a DFS number "
1441 "before placing a node onto the stack.");
Chandler Carruth24553932014-04-24 11:05:20 +00001442
Chandler Carrutha4499e92016-02-02 03:57:13 +00001443 auto E = N->end();
Chandler Carruth5e2d70b2014-04-26 09:28:00 +00001444 while (I != E) {
Chandler Carrutha4499e92016-02-02 03:57:13 +00001445 Node &ChildN = I->getNode(*this);
Chandler Carruthbd5d3082014-04-23 23:34:48 +00001446 if (ChildN.DFSNumber == 0) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001447 // We haven't yet visited this child, so descend, pushing the current
1448 // node onto the stack.
1449 DFSStack.push_back({N, N->begin()});
Chandler Carruth18eadd922014-04-18 10:50:32 +00001450
Chandler Carruth09751bf2014-04-24 09:59:59 +00001451 assert(!SCCMap.count(&ChildN) &&
1452 "Found a node with 0 DFS number but already in an SCC!");
1453 ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
Chandler Carruth5e2d70b2014-04-26 09:28:00 +00001454 N = &ChildN;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001455 I = N->begin();
1456 E = N->end();
Chandler Carruth5e2d70b2014-04-26 09:28:00 +00001457 continue;
Chandler Carruthcace6622014-04-23 10:31:17 +00001458 }
1459
Chandler Carruthe5944d92016-02-17 00:18:16 +00001460 // If the child has already been added to some child component, it
1461 // couldn't impact the low-link of this parent because it isn't
1462 // connected, and thus its low-link isn't relevant so skip it.
1463 if (ChildN.DFSNumber == -1) {
1464 ++I;
1465 continue;
1466 }
1467
1468 // Track the lowest linked child as the lowest link for this node.
1469 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1470 if (ChildN.LowLink < N->LowLink)
Chandler Carruthbd5d3082014-04-23 23:34:48 +00001471 N->LowLink = ChildN.LowLink;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001472
1473 // Move to the next edge.
Chandler Carruth5e2d70b2014-04-26 09:28:00 +00001474 ++I;
Chandler Carruth18eadd922014-04-18 10:50:32 +00001475 }
1476
Chandler Carruthe5944d92016-02-17 00:18:16 +00001477 // We've finished processing N and its descendents, put it on our pending
1478 // SCC stack to eventually get merged into an SCC of nodes.
1479 PendingRefSCCStack.push_back(N);
Chandler Carruth18eadd922014-04-18 10:50:32 +00001480
Chandler Carruthe5944d92016-02-17 00:18:16 +00001481 // If this node is linked to some lower entry, continue walking up the
1482 // stack.
1483 if (N->LowLink != N->DFSNumber) {
1484 assert(!DFSStack.empty() &&
1485 "We never found a viable root for an SCC to pop off!");
1486 continue;
1487 }
Chandler Carruth5e2d70b2014-04-26 09:28:00 +00001488
Chandler Carruthe5944d92016-02-17 00:18:16 +00001489 // Otherwise, form a new RefSCC from the top of the pending node stack.
1490 int RootDFSNumber = N->DFSNumber;
1491 // Find the range of the node stack by walking down until we pass the
1492 // root DFS number.
1493 auto RefSCCNodes = node_stack_range(
1494 PendingRefSCCStack.rbegin(),
1495 std::find_if(
1496 PendingRefSCCStack.rbegin(), PendingRefSCCStack.rend(),
1497 [RootDFSNumber](Node *N) { return N->DFSNumber < RootDFSNumber; }));
1498 // Form a new RefSCC out of these nodes and then clear them off our pending
1499 // stack.
1500 RefSCC *NewRC = createRefSCC(*this);
1501 buildSCCs(*NewRC, RefSCCNodes);
1502 connectRefSCC(*NewRC);
1503 PendingRefSCCStack.erase(RefSCCNodes.end().base(),
1504 PendingRefSCCStack.end());
1505
1506 // We return the new node here. This essentially suspends the DFS walk
1507 // until another RefSCC is requested.
1508 return NewRC;
Chandler Carruth91dcf0f2014-04-24 21:19:30 +00001509 }
Chandler Carruth18eadd922014-04-18 10:50:32 +00001510}
1511
Chandler Carruthb4faf132016-03-11 10:22:49 +00001512char LazyCallGraphAnalysis::PassID;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +00001513
Chandler Carruthbf71a342014-02-06 04:37:03 +00001514LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
1515
Chandler Carruthe5944d92016-02-17 00:18:16 +00001516static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) {
Chandler Carrutha4499e92016-02-02 03:57:13 +00001517 OS << " Edges in function: " << N.getFunction().getName() << "\n";
1518 for (const LazyCallGraph::Edge &E : N)
1519 OS << " " << (E.isCall() ? "call" : "ref ") << " -> "
1520 << E.getFunction().getName() << "\n";
Chandler Carruth11f50322015-01-14 00:27:45 +00001521
1522 OS << "\n";
1523}
1524
Chandler Carruthe5944d92016-02-17 00:18:16 +00001525static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
1526 ptrdiff_t Size = std::distance(C.begin(), C.end());
1527 OS << " SCC with " << Size << " functions:\n";
Chandler Carruth11f50322015-01-14 00:27:45 +00001528
Chandler Carruthe5944d92016-02-17 00:18:16 +00001529 for (LazyCallGraph::Node &N : C)
1530 OS << " " << N.getFunction().getName() << "\n";
1531}
1532
1533static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) {
1534 ptrdiff_t Size = std::distance(C.begin(), C.end());
1535 OS << " RefSCC with " << Size << " call SCCs:\n";
1536
1537 for (LazyCallGraph::SCC &InnerC : C)
1538 printSCC(OS, InnerC);
Chandler Carruth11f50322015-01-14 00:27:45 +00001539
1540 OS << "\n";
1541}
1542
Chandler Carruthd174ce42015-01-05 02:47:05 +00001543PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
Chandler Carruthb47f8012016-03-11 11:05:24 +00001544 ModuleAnalysisManager &AM) {
1545 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
Chandler Carruth11f50322015-01-14 00:27:45 +00001546
1547 OS << "Printing the call graph for module: " << M.getModuleIdentifier()
1548 << "\n\n";
1549
Chandler Carruthe5944d92016-02-17 00:18:16 +00001550 for (Function &F : M)
1551 printNode(OS, G.get(F));
Chandler Carruth11f50322015-01-14 00:27:45 +00001552
Chandler Carruthe5944d92016-02-17 00:18:16 +00001553 for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs())
1554 printRefSCC(OS, C);
Chandler Carruth18eadd922014-04-18 10:50:32 +00001555
Chandler Carruthbf71a342014-02-06 04:37:03 +00001556 return PreservedAnalyses::all();
Chandler Carruthbf71a342014-02-06 04:37:03 +00001557}
Sean Silva7cb30662016-06-18 09:17:32 +00001558
1559LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS)
1560 : OS(OS) {}
1561
1562static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) {
1563 std::string Name = "\"" + DOT::EscapeString(N.getFunction().getName()) + "\"";
1564
1565 for (const LazyCallGraph::Edge &E : N) {
1566 OS << " " << Name << " -> \""
1567 << DOT::EscapeString(E.getFunction().getName()) << "\"";
1568 if (!E.isCall()) // It is a ref edge.
1569 OS << " [style=dashed,label=\"ref\"]";
1570 OS << ";\n";
1571 }
1572
1573 OS << "\n";
1574}
1575
1576PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M,
1577 ModuleAnalysisManager &AM) {
1578 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1579
1580 OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n";
1581
1582 for (Function &F : M)
1583 printNodeDOT(OS, G.get(F));
1584
1585 OS << "}\n";
1586
1587 return PreservedAnalyses::all();
1588}