forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCallGraph.cpp
1175 lines (952 loc) · 37.1 KB
/
CallGraph.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===------ CallGraph.cpp - The Call Graph Data Structure ----*- C++ -*----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SILAnalysis/CallGraph.h"
#include "swift/SILPasses/Utils/Local.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/Basic/DemangleWrappers.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILWitnessTable.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <utility>
using namespace swift;
#define DEBUG_TYPE "call-graph"
STATISTIC(NumCallGraphNodes, "# of call graph nodes created");
STATISTIC(NumAppliesWithEdges, "# of call sites with edges");
STATISTIC(NumCallGraphsBuilt, "# of times the call graph is built");
llvm::cl::opt<bool> DumpCallGraph("sil-dump-call-graph",
llvm::cl::init(false), llvm::cl::Hidden);
llvm::cl::opt<bool> DumpCallGraphStats("sil-dump-call-graph-stats",
llvm::cl::init(false), llvm::cl::Hidden);
CallGraph::CallGraph(SILModule *Mod, bool completeModule)
: M(*Mod), NodeOrdinal(0), EdgeOrdinal(0) {
++NumCallGraphsBuilt;
// Create a call graph node for each function in the module and add
// each to a worklist of functions to process.
std::vector<SILFunction *> Workitems;
for (auto &F : M) {
addCallGraphNode(&F);
if (F.isDefinition())
Workitems.push_back(&F);
}
// Now compute the sets of call graph nodes any given class method
// decl could target.
computeMethodCallees();
// Add edges for each function in the worklist. We capture the
// initial functions in the module up-front into this worklist
// because the process of adding edges can deseralize new functions,
// at which point we process those functions (adding edges), and it
// would be an error to process those functions again when we come
// across them in the module.
for (auto I = Workitems.begin(), E = Workitems.end(); I != E; ++I)
addEdges(*I);
if (DumpCallGraph)
dump();
if (DumpCallGraphStats)
dumpStats();
}
CallGraph::~CallGraph() {
// Clean up all call graph nodes.
for (auto &P : FunctionToNodeMap) {
P.second->~CallGraphNode();
}
// Clean up all call graph edges.
for (auto &P : InstToEdgeMap) {
P.second->~CallGraphEdge();
}
// Clean up all SCCs.
for (CallGraphSCC *SCC : BottomUpSCCOrder) {
SCC->~CallGraphSCC();
}
}
/// Update the callee set for each method of a given class, along with
/// all the overridden methods from superclasses.
void CallGraph::computeClassMethodCalleesForClass(ClassDecl *CD) {
for (auto *Member : CD->getMembers()) {
auto *AFD = dyn_cast<AbstractFunctionDecl>(Member);
if (!AFD)
continue;
auto Method = SILDeclRef(AFD);
auto *CalledFn = M.lookUpFunctionInVTable(CD, Method);
if (!CalledFn)
continue;
// FIXME: Link in external declarations, at least for complete call sets.
auto *Node = getOrAddCallGraphNode(CalledFn);
bool canCallUnknown = !calleesAreStaticallyKnowable(M, Method);
// Update the callee sets for this method and all the methods it
// overrides by inserting the call graph node for the function
// that this method invokes.
do {
auto &TheCalleeSet = getOrCreateCalleeSetForMethod(Method);
assert(TheCalleeSet.getPointer() && "Unexpected null callee set!");
TheCalleeSet.getPointer()->insert(Node);
if (canCallUnknown)
TheCalleeSet.setInt(true);
Method = Method.getOverriddenVTableEntry();
} while (Method);
}
}
void
CallGraph::computeWitnessMethodCalleesForWitnessTable(SILWitnessTable &WTable) {
for (const SILWitnessTable::Entry &Entry : WTable.getEntries()) {
if (Entry.getKind() != SILWitnessTable::Method)
continue;
auto &WitnessEntry = Entry.getMethodWitness();
auto Requirement = WitnessEntry.Requirement;
auto *WitnessFn = WitnessEntry.Witness;
// Dead function elimination nulls out entries for functions it removes.
if (!WitnessFn)
continue;
auto *Node = getOrAddCallGraphNode(WitnessFn);
auto &TheCalleeSet = getOrCreateCalleeSetForMethod(Requirement);
assert(TheCalleeSet.getPointer() && "Unexpected null callee set!");
TheCalleeSet.getPointer()->insert(Node);
// FIXME: For now, conservatively assume that unknown functions
// can be called from any witness_method call site.
TheCalleeSet.setInt(true);
}
}
/// Remove a function from all the callee sets. This should be called
/// on any function that we'll eventually remove.
// FIXME: Consider adding a reverse mapping from call graph node to
// the sets it appears in.
void CallGraph::removeFunctionFromCalleeSets(SILFunction *F) {
auto *Node = getCallGraphNode(F);
for (auto I = CalleeSetCache.begin(), E = CalleeSetCache.end();
I != E; ++I) {
auto *Callees = I->second.getPointer();
Callees->remove(Node);
}
}
/// Compute the callees for each method that appears in a VTable or
/// Witness Table.
void CallGraph::computeMethodCallees() {
// Remove contents of old callee sets - in case we are updating the sets.
for (auto Iter : CalleeSetCache) {
auto *TheCalleeSet = Iter.second.getPointer();
Iter.second.setInt(false);
TheCalleeSet->clear();
}
for (auto &VTable : M.getVTableList())
computeClassMethodCalleesForClass(VTable.getClass());
for (auto &WTable : M.getWitnessTableList())
computeWitnessMethodCalleesForWitnessTable(WTable);
}
CallGraphNode *CallGraph::addCallGraphNode(SILFunction *F) {
// TODO: Compute this from the call graph itself after stripping
// unreachable nodes from graph.
++NumCallGraphNodes;
auto *Node = new (Allocator) CallGraphNode(F, ++NodeOrdinal);
assert(!FunctionToNodeMap.count(F) &&
"Added function already has a call graph node!");
FunctionToNodeMap[F] = Node;
return Node;
}
CallGraphEdge::CalleeSet &
CallGraph::getOrCreateCalleeSetForMethod(SILDeclRef Decl) {
auto *AFD = cast<AbstractFunctionDecl>(Decl.getDecl());
auto Found = CalleeSetCache.find(AFD);
if (Found != CalleeSetCache.end())
return Found->second;
auto *NodeSet = new (Allocator) CallGraphEdge::CallGraphNodeSet;
bool canCallUnknown = !calleesAreStaticallyKnowable(M, Decl);
// Allocate a new callee set, and for now just assume it can call
// unknown functions.
CallGraphEdge::CalleeSet TheCalleeSet(NodeSet, canCallUnknown);
bool Inserted;
CalleeSetMap::iterator It;
std::tie(It, Inserted) =
CalleeSetCache.insert(std::make_pair(AFD, TheCalleeSet));
assert(Inserted && "Expected new entry to be inserted!");
return It->second;
}
SILFunction *
CallGraphEdge::Callees::getFunctionFromNode(CallGraphNode *const &Node) {
return Node->getFunction();
}
CallGraphEdge *CallGraph::makeCallGraphEdgeForCallee(FullApplySite Apply,
SILValue Callee) {
switch (Callee->getKind()) {
case ValueKind::ThinToThickFunctionInst:
Callee = cast<ThinToThickFunctionInst>(Callee)->getOperand();
SWIFT_FALLTHROUGH;
case ValueKind::FunctionRefInst: {
auto *CalleeFn = cast<FunctionRefInst>(Callee)->getReferencedFunction();
if (CalleeFn->isExternalDeclaration())
M.linkFunction(CalleeFn, SILModule::LinkingMode::LinkAll,
CallGraphLinkerEditor(this).getCallback());
auto *CalleeNode = getOrAddCallGraphNode(CalleeFn);
return new (Allocator) CallGraphEdge(Apply.getInstruction(), CalleeNode,
EdgeOrdinal++);
}
case ValueKind::PartialApplyInst: {
Callee = cast<PartialApplyInst>(Callee)->getCallee();
return makeCallGraphEdgeForCallee(Apply, Callee);
}
case ValueKind::DynamicMethodInst:
// TODO: Decide how to handle these in graph construction and
// analysis passes. We might just leave them out of the
// graph.
return new (Allocator) CallGraphEdge(Apply.getInstruction(), EdgeOrdinal++);
case ValueKind::SILArgument:
// First-pass call-graph construction will not do anything with
// these, but a second pass can potentially statically determine
// the called function in some cases.
return new (Allocator) CallGraphEdge(Apply.getInstruction(), EdgeOrdinal++);
case ValueKind::ApplyInst:
case ValueKind::TryApplyInst:
// TODO: Probably not worth iterating invocation- then
// reverse-invocation order to catch this.
return new (Allocator) CallGraphEdge(Apply.getInstruction(), EdgeOrdinal++);
case ValueKind::TupleExtractInst:
// TODO: It would be good to tunnel through extracts so that we
// can build a more accurate call graph prior to any
// optimizations.
return new (Allocator) CallGraphEdge(Apply.getInstruction(), EdgeOrdinal++);
case ValueKind::StructExtractInst:
// TODO: It would be good to tunnel through extracts so that we
// can build a more accurate call graph prior to any
// optimizations.
return new (Allocator) CallGraphEdge(Apply.getInstruction(), EdgeOrdinal++);
case ValueKind::WitnessMethodInst: {
auto *WMI = cast<WitnessMethodInst>(Callee);
SILFunction *CalleeFn;
ArrayRef<Substitution> Subs;
SILWitnessTable *WT;
// Attempt to find a specific callee for the given conformance and member.
std::tie(CalleeFn, WT, Subs) =
WMI->getModule().lookUpFunctionInWitnessTable(WMI->getConformance(),
WMI->getMember());
if (CalleeFn) {
if (CalleeFn->isExternalDeclaration())
M.linkFunction(CalleeFn, SILModule::LinkingMode::LinkAll,
CallGraphLinkerEditor(this).getCallback());
auto *CalleeNode = getOrAddCallGraphNode(CalleeFn);
return new (Allocator) CallGraphEdge(Apply.getInstruction(), CalleeNode,
EdgeOrdinal++);
}
// Lookup the previously computed callee set if we didn't find a
// specific callee.
auto *AFD = cast<AbstractFunctionDecl>(WMI->getMember().getDecl());
auto Found = CalleeSetCache.find(AFD);
if (Found != CalleeSetCache.end())
return new (Allocator) CallGraphEdge(Apply.getInstruction(),
Found->second, EdgeOrdinal++);
// Otherwise default to an edge with unknown callees.
return new (Allocator) CallGraphEdge(Apply.getInstruction(), EdgeOrdinal++);
}
case ValueKind::ClassMethodInst: {
auto *CMI = cast<ClassMethodInst>(Callee);
auto *AFD = cast<AbstractFunctionDecl>(CMI->getMember().getDecl());
auto Found = CalleeSetCache.find(AFD);
if (Found != CalleeSetCache.end())
return new (Allocator) CallGraphEdge(Apply.getInstruction(),
Found->second, EdgeOrdinal++);
// We don't know the callees in cases where the method isn't
// present in a vtable, so create a call graph edge with no known
// callees, assumed to be able to call unknown functions.
return new (Allocator) CallGraphEdge(Apply.getInstruction(), EdgeOrdinal++);
}
case ValueKind::SuperMethodInst:
return new (Allocator) CallGraphEdge(Apply.getInstruction(), EdgeOrdinal++);
default:
assert(!isa<MethodInst>(Callee) &&
"Unhandled method instruction in call graph construction!");
return new (Allocator) CallGraphEdge(Apply.getInstruction(), EdgeOrdinal++);
}
}
static void orderEdges(const llvm::SmallPtrSetImpl<CallGraphEdge *> &Edges,
llvm::SmallVectorImpl<CallGraphEdge *> &OrderedEdges) {
for (auto *Edge : Edges)
OrderedEdges.push_back(Edge);
std::sort(OrderedEdges.begin(), OrderedEdges.end(),
[](CallGraphEdge *left, CallGraphEdge *right) {
return left->getOrdinal() < right->getOrdinal();
});
}
void CallGraph::addEdgesForInstruction(SILInstruction *I,
CallGraphNode *CallerNode) {
auto Apply = FullApplySite::isa(I);
// TODO: Support non-apply instructions.
if (!Apply)
return;
auto *Edge = makeCallGraphEdgeForCallee(Apply, Apply.getCallee());
assert(Edge && "Expected to be able to make call graph edge for callee!");
assert(!InstToEdgeMap.count(Apply.getInstruction()) &&
"Added apply that already has an edge node!\n");
InstToEdgeMap[Apply.getInstruction()] = Edge;
CallerNode->addCalleeEdge(Edge);
for (auto *CalleeNode : Edge->getCalleeSet())
CalleeNode->addCallerEdge(Edge);
// TODO: Compute this from the call graph itself after stripping
// unreachable nodes from graph.
++NumAppliesWithEdges;
}
void CallGraph::removeEdgeFromFunction(CallGraphEdge *Edge, SILFunction *F) {
// Remove the edge from all the potential callee call graph nodes.
auto CalleeSet = Edge->getCalleeSet();
for (auto *CalleeNode : CalleeSet)
CalleeNode->removeCallerEdge(Edge);
// Remove the edge from the caller's call graph node.
auto *CallerNode = getCallGraphNode(F);
CallerNode->removeCalleeEdge(Edge);
// Remove the mapping from the apply to this edge.
auto Apply = Edge->getInstruction();
InstToEdgeMap.erase(Apply);
// Call the destructor for the edge. The memory will be reclaimed
// when the call graph is deleted by virtue of the bump pointer
// allocator.
Edge->~CallGraphEdge();
}
void CallGraph::removeNode(CallGraphNode *Node) {
assert(Node->getCallerEdges().size() == 0 &&
"Node to delete must not have any caller edges");
assert(Node->getCalleeEdges().size() == 0 &&
"Node to delete must not have any callee edges");
// Avoid keeping a dangling node pointers in the vectors.
// Next time they will be computed from scratch.
BottomUpFunctionOrder.clear();
clearBottomUpSCCOrder();
FunctionToNodeMap.erase(Node->getFunction());
// Call the destructor for the node. The memory will be reclaimed
// when the call graph is deleted by virtue of the bump pointer
// allocator.
Node->~CallGraphNode();
}
// Remove the call graph edges associated with an apply, where the
// apply is known to the call graph.
void CallGraph::removeEdgesForInstruction(SILInstruction *I) {
assert(InstToEdgeMap.count(I) && "Expected apply to be in edge map!");
removeEdgeFromFunction(InstToEdgeMap[I], I->getFunction());
}
void CallGraph::addEdges(SILFunction *F) {
auto *CallerNode = getOrAddCallGraphNode(F);
for (auto &BB : *F) {
for (auto &I : BB) {
if (FullApplySite::isa(&I))
addEdgesForInstruction(&I, CallerNode);
auto *FRI = dyn_cast<FunctionRefInst>(&I);
if (!FRI)
continue;
auto *CalleeFn = FRI->getReferencedFunction();
if (CalleeFn->isExternalDeclaration())
M.linkFunction(CalleeFn, SILModule::LinkingMode::LinkAll,
CallGraphLinkerEditor(this).getCallback());
if (CalleeFn->isPossiblyUsedExternally()) {
auto *CalleeNode = tryGetCallGraphNode(CalleeFn);
assert((!CalleeNode || !CalleeNode->isCallerEdgesComplete()) &&
"Expected function to have incomplete set of caller edges!");
(void) CalleeNode;
continue;
}
bool hasAllApplyUsers =
std::none_of(FRI->use_begin(), FRI->use_end(),
[](Operand *Op) {
return !FullApplySite::isa(Op->getUser());
});
// If we have a non-apply user of this function, mark its caller set
// as being incomplete.
if (!hasAllApplyUsers) {
auto *CalleeNode = getOrAddCallGraphNode(CalleeFn);
CalleeNode->markCallerEdgesIncomplete();
}
}
}
}
// Print check lines prior to call graph output, and also print the
// function bodies. This can be used to minimize the effort in
// creating new call graph test cases.
static llvm::cl::opt<std::string>
CallGraphFileCheckPrefix("call-graph-file-check-prefix", llvm::cl::init(""),
llvm::cl::desc("Print a FileCheck prefix before each line"));
static void indent(llvm::raw_ostream &OS, int Indent) {
if (!CallGraphFileCheckPrefix.empty()) return;
std::string Blanks(Indent, ' ');
OS << Blanks;
}
static void printFlag(llvm::raw_ostream &OS,
const char *Description, bool Value, int Indent =0) {
indent(OS, Indent);
OS << CallGraphFileCheckPrefix << Description << ": " <<
(Value ? "yes\n" : "no\n");
}
void CallGraphEdge::print(llvm::raw_ostream &OS, int Indent) const {
indent(OS, Indent);
OS << CallGraphFileCheckPrefix << "Call site #" << Ordinal << ": ";
OS << *getInstruction();
printFlag(OS, "Unknown callees", canCallUnknownFunction(), Indent);
if (getCalleeSet().empty())
return;
bool First = true;
indent(OS, Indent);
OS << CallGraphFileCheckPrefix << "Known callees:\n";
for (auto *Callee : getCalleeSet()) {
if (!First)
OS << "\n";
First = false;
auto Name = Callee->getFunction()->getName();
indent(OS, Indent + 2);
OS << CallGraphFileCheckPrefix << "Name: " << Name << "\n";
indent(OS, Indent + 2);
OS << CallGraphFileCheckPrefix << "Demangled: " <<
demangle_wrappers::demangleSymbolAsString(Name) << "\n";
}
}
void CallGraphEdge::dump(int Indent) const {
#ifndef NDEBUG
print(llvm::errs(), Indent);
#endif
}
void CallGraphEdge::dump() const {
#ifndef NDEBUG
dump(0);
#endif
}
void CallGraphNode::print(llvm::raw_ostream &OS) const {
OS << CallGraphFileCheckPrefix << "Function #" << Ordinal << ": " <<
getFunction()->getName() << "\n";
OS << CallGraphFileCheckPrefix << "Demangled: " <<
demangle_wrappers::demangleSymbolAsString(getFunction()->getName()) << "\n";
printFlag(OS, "Trivially dead", isTriviallyDead());
printFlag(OS, "All callers known", isCallerEdgesComplete());
auto &CalleeEdges = getCalleeEdges();
if (!CalleeEdges.empty()) {
OS << CallGraphFileCheckPrefix << "Call sites:\n";
llvm::SmallVector<CallGraphEdge *, 8> OrderedCalleeEdges;
orderEdges(CalleeEdges, OrderedCalleeEdges);
for (auto *Edge : OrderedCalleeEdges) {
OS << "\n";
Edge->print(OS, /* Indent= */ 2);
}
OS << "\n";
}
auto &CallerEdges = getCallerEdges();
if (!CallerEdges.empty()) {
OS << CallGraphFileCheckPrefix <<
(!isCallerEdgesComplete() ? "Known " : "");
OS << "Callers:\n";
llvm::SmallVector<CallGraphEdge *, 8> OrderedCallerEdges;
orderEdges(CallerEdges, OrderedCallerEdges);
llvm::SetVector<SILFunction *> Callers;
for (auto *Edge : OrderedCallerEdges)
Callers.insert(Edge->getInstruction()->getFunction());
for (auto *Caller : Callers) {
OS << "\n";
indent(OS, 2);
OS << CallGraphFileCheckPrefix << "Name: " << Caller->getName() << "\n";
indent(OS, 2);
OS << CallGraphFileCheckPrefix << "Demangled: " <<
demangle_wrappers::demangleSymbolAsString(Caller->getName()) << "\n";
}
OS << "\n";
}
if (!CallGraphFileCheckPrefix.empty())
getFunction()->print(OS);
}
void CallGraphNode::dump() const {
#ifndef NDEBUG
print(llvm::errs());
#endif
}
void CallGraph::print(llvm::raw_ostream &OS) {
OS << CallGraphFileCheckPrefix << "*** Call Graph ***\n";
auto const &Funcs = getBottomUpFunctionOrder();
for (auto *F : Funcs) {
auto *Node = getCallGraphNode(F);
if (Node)
Node->print(OS);
else
OS << "!!! Missing node for " << F->getName() << "!!!";
OS << "\n";
}
}
void CallGraph::dump() {
#ifndef NDEBUG
print(llvm::errs());
#endif
}
namespace {
template<int NumBuckets>
struct Histogram {
unsigned Data[NumBuckets];
Histogram() {
for (auto i = 0; i < NumBuckets; ++i) {
Data[i] = 0;
}
}
void increment(unsigned Bucket) {
Bucket = Bucket < NumBuckets ? Bucket : NumBuckets - 1;
Data[Bucket]++;
}
void print(llvm::raw_ostream &OS) {
auto Last = NumBuckets - 1;
for (auto i = 0; i < NumBuckets; ++i) {
auto *Separator = Last == i ? "+: " : ": ";
if (Data[i])
OS << CallGraphFileCheckPrefix << i << Separator << Data[i] << "\n";
}
OS << "\n";
}
};
} // end anonymous namespace
void CallGraph::printStats(llvm::raw_ostream &OS) {
Histogram<256> CallSitesPerFunction;
Histogram<256> CallersPerFunction;
Histogram<256> CalleesPerCallSite;
unsigned CountNodes = 0;
unsigned CountCallSites = 0;
auto const &Funcs = getBottomUpFunctionOrder();
for (auto *F : Funcs) {
++CountNodes;
auto *Node = getCallGraphNode(F);
if (Node) {
CallSitesPerFunction.increment(Node->getCalleeEdges().size());
CallersPerFunction.increment(Node->getCallerEdges().size());
CountCallSites += Node->getCalleeEdges().size();
for (auto *Edge : Node->getCalleeEdges())
CalleesPerCallSite.increment(Edge->getCalleeSet().size());
} else {
OS << "!!! Missing node for " << F->getName() << "!!!";
}
}
OS << CallGraphFileCheckPrefix << "*** Call Graph Statistics ***\n";
OS << CallGraphFileCheckPrefix << "Number of call graph nodes: " <<
CountNodes << "\n";
OS << CallGraphFileCheckPrefix << "Number of call graph edges: " <<
CountCallSites << "\n";
OS << CallGraphFileCheckPrefix <<
"Histogram of number of call sites per function:\n";
CallSitesPerFunction.print(OS);
OS << CallGraphFileCheckPrefix <<
"Histogram of number of callees per call site:\n";
CalleesPerCallSite.print(OS);
OS << CallGraphFileCheckPrefix <<
"Histogram of number of callers per function:\n";
CallersPerFunction.print(OS);
OS << CallGraphFileCheckPrefix << "Bump pointer allocated memory (bytes): " <<
Allocator.getTotalMemory() << "\n";
OS << CallGraphFileCheckPrefix << "Number of callee sets allocated: " <<
CalleeSetCache.size() << "\n";
}
void CallGraph::dumpStats() {
#ifndef NDEBUG
printStats(llvm::errs());
#endif
}
namespace {
/// Finds SCCs in the call graph. Our call graph has an unconventional
/// form where each edge of the graph is really a multi-edge that can
/// point to multiple call graph nodes in the case where we can call
/// one of several different functions.
class CallGraphSCCFinder {
unsigned NextDFSNum;
llvm::SmallVectorImpl<CallGraphSCC *> &TheSCCs;
llvm::DenseMap<CallGraphNode *, unsigned> DFSNum;
llvm::DenseMap<CallGraphNode *, unsigned> MinDFSNum;
llvm::SetVector<CallGraphNode *> DFSStack;
/// The CallGraphSCCFinder does not own this bump ptr allocator, so does not
/// call the destructor of objects allocated from it.
llvm::BumpPtrAllocator &BPA;
public:
CallGraphSCCFinder(llvm::SmallVectorImpl<CallGraphSCC *> &TheSCCs,
llvm::BumpPtrAllocator &BPA)
: NextDFSNum(0), TheSCCs(TheSCCs), BPA(BPA) {}
void DFS(CallGraphNode *Node) {
// Set the DFSNum for this node if we haven't already, and if we
// have, which indicates it's already been visited, return.
if (!DFSNum.insert(std::make_pair(Node, NextDFSNum)).second)
return;
assert(MinDFSNum.find(Node) == MinDFSNum.end() &&
"Node should not already have a minimum DFS number!");
MinDFSNum[Node] = NextDFSNum;
++NextDFSNum;
DFSStack.insert(Node);
llvm::SmallVector<CallGraphEdge *, 4> OrderedEdges;
orderEdges(Node->getCalleeEdges(), OrderedEdges);
for (auto *ApplyEdge : OrderedEdges) {
for (auto *CalleeNode : ApplyEdge->getCalleeSet()) {
if (DFSNum.find(CalleeNode) == DFSNum.end()) {
DFS(CalleeNode);
MinDFSNum[Node] = std::min(MinDFSNum[Node], MinDFSNum[CalleeNode]);
} else if (DFSStack.count(CalleeNode)) {
MinDFSNum[Node] = std::min(MinDFSNum[Node], DFSNum[CalleeNode]);
}
}
}
// If this node is the root of an SCC (including SCCs with a
// single node), pop the SCC and push it on our SCC stack.
if (DFSNum[Node] == MinDFSNum[Node]) {
auto *SCC = new (BPA) CallGraphSCC();
CallGraphNode *Popped;
do {
Popped = DFSStack.pop_back_val();
SCC->SCCNodes.push_back(Popped->getFunction());
} while (Popped != Node);
TheSCCs.push_back(SCC);
}
}
};
} // end anonymous namespace
void CallGraph::clearBottomUpSCCOrder() {
for (auto *SCC : BottomUpSCCOrder)
SCC->~CallGraphSCC();
BottomUpSCCOrder.clear();
}
void CallGraph::computeBottomUpSCCOrder() {
if (!BottomUpSCCOrder.empty()) {
clearBottomUpSCCOrder();
}
CallGraphSCCFinder SCCFinder(BottomUpSCCOrder, Allocator);
for (auto &F : M) {
if (F.isDefinition()) {
auto *Node = getCallGraphNode(&F);
SCCFinder.DFS(Node);
}
}
}
void CallGraph::computeBottomUpFunctionOrder() {
// We do not need to call any destructors here.
BottomUpFunctionOrder.clear();
computeBottomUpSCCOrder();
for (auto *SCC : BottomUpSCCOrder)
for (auto *Fn : SCC->SCCNodes)
BottomUpFunctionOrder.push_back(Fn);
}
//===----------------------------------------------------------------------===//
// CallGraphEditor
//===----------------------------------------------------------------------===//
void CallGraphEditor::replaceApplyWithNew(FullApplySite Old,
FullApplySite New) {
if (!CG)
return;
if (auto *Edge = CG->tryGetCallGraphEdge(Old.getInstruction()))
CG->removeEdgeFromFunction(Edge, Old.getInstruction()->getFunction());
CG->addEdgesForInstruction(New.getInstruction());
}
void CallGraphEditor::replaceApplyWithCallSites(FullApplySite Old,
llvm::SmallVectorImpl<SILInstruction *> &NewCallSites) {
if (!CG)
return;
if (auto *Edge = CG->tryGetCallGraphEdge(Old.getInstruction()))
CG->removeEdgeFromFunction(Edge, Old.getInstruction()->getFunction());
for (auto NewApply : NewCallSites)
CG->addEdgesForInstruction(NewApply);
}
void CallGraphEditor::moveNodeToNewFunction(SILFunction *Old,
SILFunction *New) {
if (!CG)
return;
auto Iter = CG->FunctionToNodeMap.find(Old);
assert(Iter != CG->FunctionToNodeMap.end());
auto *Node = Iter->second;
CG->FunctionToNodeMap.erase(Iter);
CG->FunctionToNodeMap[New] = Node;
}
void CallGraphEditor::removeAllCalleeEdgesFrom(SILFunction *F) {
if (!CG)
return;
auto &CalleeEdges = CG->getCallGraphNode(F)->getCalleeEdges();
while (!CalleeEdges.empty()) {
auto *Edge = *CalleeEdges.begin();
CG->removeEdgeFromFunction(Edge, F);
}
}
void CallGraphEditor::removeAllCallerEdgesFrom(SILFunction *F) {
if (!CG)
return;
auto &CallerEdges = CG->getCallGraphNode(F)->getCallerEdges();
while (!CallerEdges.empty()) {
auto *Edge = *CallerEdges.begin();
auto Apply = Edge->getInstruction();
CG->removeEdgeFromFunction(Edge, Apply->getFunction());
}
}
void CallGraphEditor::updatePartialApplyUses(swift::ApplySite AI) {
if (!CG)
return;
for (auto *Use : AI.getInstruction()->getUses()) {
if (auto FAS = FullApplySite::isa(Use->getUser()))
replaceApplyWithNew(FAS, FAS);
}
}
void CallGraphEditor::eraseFunction(SILFunction *F) {
auto &M = F->getModule();
M.eraseFunction(F);
if (CG)
removeCallGraphNode(F);
}
//===----------------------------------------------------------------------===//
// CallGraph Verification
//===----------------------------------------------------------------------===//
void CallGraph::verify() const {
#ifndef NDEBUG
// For every function in the module, add it to our SILFunction set.
llvm::DenseSet<SILFunction *> Functions;
for (auto &F : M)
Functions.insert(&F);
// For every pair (SILFunction, CallGraphNode) in the
// function-to-node map, verify:
//
// a. The function is in the current module.
// b. The call graph node is for that same function.
//
// In addition, call the verify method for the function.
unsigned numEdges = 0;
for (auto &P : FunctionToNodeMap) {
SILFunction *F = P.first;
CallGraphNode *Node = P.second;
assert(Functions.count(F) &&
"Function in call graph but not in module!?");
assert(Node->getFunction() == F &&
"Func mapped to node, but node has different Function inside?!");
verify(F);
numEdges += Node->getCalleeEdges().size();
}
assert(InstToEdgeMap.size() == numEdges &&
"Some edges in InstToEdgeMap are not contained in any node");
// Verify the callee sets.
for (auto Iter : CalleeSetCache) {
auto *CalleeSet = Iter.second.getPointer();
for (CallGraphNode *Node : *CalleeSet) {
SILFunction *F = Node->getFunction();
assert(tryGetCallGraphNode(F) &&
"Callee set contains dangling node poiners");
}
}
#endif
}
void CallGraph::verify(SILFunction *F) const {
#ifndef NDEBUG
// Collect all full apply sites of the function.
auto *Node = getCallGraphNode(F);
unsigned numEdges = 0;
for (auto &BB : *F) {
for (auto &I : BB) {
auto FAS = FullApplySite::isa(&I);
if (!FAS)
continue;
auto *Edge = getCallGraphEdge(FAS.getInstruction());
numEdges++;
assert(Edge->getInstruction() == &I &&
"Edge is not linked to the correct apply site");
assert(InstToEdgeMap.lookup(FAS.getInstruction()) == Edge &&
"Edge is not in InstToEdgeMap");
if (!Edge->canCallUnknownFunction()) {
// In the trivial case that we call a known function, check if we have
// exactly one callee in the edge.
SILValue Callee = FAS.getCallee();
if (auto *PAI = dyn_cast<PartialApplyInst>(Callee))
Callee = PAI->getCallee();
if (auto *FRI = dyn_cast<FunctionRefInst>(Callee)) {
auto *CalleeNode = Edge->getSingleCalleeOrNull();
assert(CalleeNode &&
CalleeNode->getFunction() == FRI->getReferencedFunction() &&
"Direct apply is not represented by a single-callee edge");
}
}
}
}
// Check if we have an exact 1-to-1 mapping from full apply sites to edges.
auto &CalleeEdges = Node->getCalleeEdges();
assert(numEdges == CalleeEdges.size() && "More edges than full apply sites");
// Make structural graph checks:
// 1.) Check that the callee edges are part of the callee node's caller set.
for (auto *Edge : CalleeEdges) {
assert(Edge->getInstruction()->getFunction() == F &&
"Apply in callee set that is not in the callee function?!");
for (auto *CalleeNode : Edge->getCalleeSet()) {
auto &CallerEdges = CalleeNode->getCallerEdges();
assert(std::find(CallerEdges.begin(), CallerEdges.end(), Edge) !=
CallerEdges.end() &&
"Edge not in caller set of callee");
}
}
// 2.) Check that the caller edges have this node in their callee sets.
for (auto *Edge : Node->getCallerEdges()) {
auto CalleeSet = Edge->getCalleeSet();
assert(std::find(CalleeSet.begin(), CalleeSet.end(), Node) !=
CalleeSet.end() &&
"Node not in callee set of caller edge");
}
#endif
}
//===----------------------------------------------------------------------===//
// View CG Implementation
//===----------------------------------------------------------------------===//
#ifndef NDEBUG
namespace swift {
/// Another representation of the call graph using sorted vectors instead of
/// sets. Used for viewing the callgraph as dot file with llvm::ViewGraph.
struct OrderedCallGraph {
struct Node;
struct Edge {
Edge(CallGraphEdge *CGEdge, Node *Child) : CGEdge(CGEdge), Child(Child) { }
CallGraphEdge *CGEdge;
Node *Child;
};