-
Notifications
You must be signed in to change notification settings - Fork 49
/
parcel_snoopi_deep.jl
1831 lines (1612 loc) · 77.6 KB
/
parcel_snoopi_deep.jl
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
import FlameGraphs
using Base.StackTraces: StackFrame
using FlameGraphs.LeftChildRightSiblingTrees: Node, addchild
using FlameGraphs.AbstractTrees
using Core.Compiler.Timings: InferenceFrameInfo
using SnoopCompileCore: InferenceTiming, InferenceTimingNode, inclusive, exclusive
using Profile
using Cthulhu
const InferenceNode = Union{InferenceFrameInfo,InferenceTiming,InferenceTimingNode}
const flamegraph = FlameGraphs.flamegraph # For re-export
const rextest = r"Test\.jl$" # for detecting calls from a @testset
Core.MethodInstance(mi_info::InferenceFrameInfo) = mi_info.mi
Core.MethodInstance(t::InferenceTiming) = MethodInstance(t.mi_info)
Core.MethodInstance(t::InferenceTimingNode) = MethodInstance(t.mi_timing)
Core.Method(x::InferenceNode) = MethodInstance(x).def::Method # deliberately throw an error if this is a module
isROOT(mi::MethodInstance) = mi === Core.Compiler.Timings.ROOTmi
isROOT(m::Method) = m === Core.Compiler.Timings.ROOTmi.def
isROOT(mi_info::InferenceNode) = isROOT(MethodInstance(mi_info))
isROOT(node::InferenceTimingNode) = isROOT(node.mi_timing)
# Record instruction pointers we've already looked up (performance optimization)
const lookups = Dict{Union{UInt, Core.Compiler.InterpreterIP}, Vector{StackTraces.StackFrame}}()
lookups_key(ip) = ip
lookups_key(ip::Ptr{Nothing}) = UInt(ip)
# These should be in SnoopCompileCore, except that it promises not to specialize Base methods
Base.show(io::IO, t::InferenceTiming) = (print(io, "InferenceTiming: "); _show(io, t))
function _show(io::IO, t::InferenceTiming)
print(io, @sprintf("%8.6f", exclusive(t)), "/", @sprintf("%8.6f", inclusive(t)), " on ")
print(io, stripifi(t.mi_info))
end
function Base.show(io::IO, node::InferenceTimingNode)
print(io, "InferenceTimingNode: ")
_show(io, node.mi_timing)
print(io, " with ", string(length(node.children)), " direct children")
end
"""
flatten(tinf; tmin = 0.0, sortby=exclusive)
Flatten the execution graph of `InferenceTimingNode`s returned from `@snoopi_deep` into a Vector of `InferenceTiming`
frames, each encoding the time needed for inference of a single `MethodInstance`.
By default, results are sorted by `exclusive` time (the time for inferring the `MethodInstance` itself, not including
any inference of its callees); other options are `sortedby=inclusive` which includes the time needed for the callees,
or `nothing` to obtain them in the order they were inferred (depth-first order).
# Example
We'll use [`SnoopCompile.flatten_demo`](@ref), which runs `@snoopi_deep` on a workload designed to yield reproducible results:
```jldoctest flatten; setup=:(using SnoopCompile), filter=r"([0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?/[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?|WARNING: replacing module FlattenDemo\\.\\n)"
julia> tinf = SnoopCompile.flatten_demo()
InferenceTimingNode: 0.002148974/0.002767166 on InferenceFrameInfo for Core.Compiler.Timings.ROOT() with 1 direct children
julia> using AbstractTrees; print_tree(tinf)
InferenceTimingNode: 0.00242354/0.00303526 on InferenceFrameInfo for Core.Compiler.Timings.ROOT() with 1 direct children
└─ InferenceTimingNode: 0.000150891/0.000611721 on InferenceFrameInfo for SnoopCompile.FlattenDemo.packintype(::$Int) with 2 direct children
├─ InferenceTimingNode: 0.000105318/0.000105318 on InferenceFrameInfo for MyType{$Int}(::$Int) with 0 direct children
└─ InferenceTimingNode: 9.43e-5/0.000355512 on InferenceFrameInfo for SnoopCompile.FlattenDemo.dostuff(::MyType{$Int}) with 2 direct children
├─ InferenceTimingNode: 6.6458e-5/0.000124716 on InferenceFrameInfo for SnoopCompile.FlattenDemo.extract(::MyType{$Int}) with 2 direct children
│ ├─ InferenceTimingNode: 3.401e-5/3.401e-5 on InferenceFrameInfo for getproperty(::MyType{$Int}, ::Symbol) with 0 direct children
│ └─ InferenceTimingNode: 2.4248e-5/2.4248e-5 on InferenceFrameInfo for getproperty(::MyType{$Int}, x::Symbol) with 0 direct children
└─ InferenceTimingNode: 0.000136496/0.000136496 on InferenceFrameInfo for SnoopCompile.FlattenDemo.domath(::$Int) with 0 direct children
```
Note the printing of `getproperty(::SnoopCompile.FlattenDemo.MyType{$Int}, x::Symbol)`: it shows the specific Symbol, here `:x`,
that `getproperty` was inferred with. This reflects constant-propagation in inference.
Then:
```jldoctest flatten; setup=:(using SnoopCompile), filter=r"[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?/[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"
julia> flatten(tinf; sortby=nothing)
8-element Vector{SnoopCompileCore.InferenceTiming}:
InferenceTiming: 0.002423543/0.0030352639999999998 on InferenceFrameInfo for Core.Compiler.Timings.ROOT()
InferenceTiming: 0.000150891/0.0006117210000000001 on InferenceFrameInfo for SnoopCompile.FlattenDemo.packintype(::$Int)
InferenceTiming: 0.000105318/0.000105318 on InferenceFrameInfo for SnoopCompile.FlattenDemo.MyType{$Int}(::$Int)
InferenceTiming: 9.43e-5/0.00035551200000000005 on InferenceFrameInfo for SnoopCompile.FlattenDemo.dostuff(::SnoopCompile.FlattenDemo.MyType{$Int})
InferenceTiming: 6.6458e-5/0.000124716 on InferenceFrameInfo for SnoopCompile.FlattenDemo.extract(::SnoopCompile.FlattenDemo.MyType{$Int})
InferenceTiming: 3.401e-5/3.401e-5 on InferenceFrameInfo for getproperty(::SnoopCompile.FlattenDemo.MyType{$Int}, ::Symbol)
InferenceTiming: 2.4248e-5/2.4248e-5 on InferenceFrameInfo for getproperty(::SnoopCompile.FlattenDemo.MyType{$Int}, x::Symbol)
InferenceTiming: 0.000136496/0.000136496 on InferenceFrameInfo for SnoopCompile.FlattenDemo.domath(::$Int)
```
```
julia> flatten(tinf; tmin=1e-4) # sorts by exclusive time (the time before the '/')
4-element Vector{SnoopCompileCore.InferenceTiming}:
InferenceTiming: 0.000105318/0.000105318 on InferenceFrameInfo for SnoopCompile.FlattenDemo.MyType{$Int}(::$Int)
InferenceTiming: 0.000136496/0.000136496 on InferenceFrameInfo for SnoopCompile.FlattenDemo.domath(::$Int)
InferenceTiming: 0.000150891/0.0006117210000000001 on InferenceFrameInfo for SnoopCompile.FlattenDemo.packintype(::$Int)
InferenceTiming: 0.002423543/0.0030352639999999998 on InferenceFrameInfo for Core.Compiler.Timings.ROOT()
julia> flatten(tinf; sortby=inclusive, tmin=1e-4) # sorts by inclusive time (the time after the '/')
6-element Vector{SnoopCompileCore.InferenceTiming}:
InferenceTiming: 0.000105318/0.000105318 on InferenceFrameInfo for SnoopCompile.FlattenDemo.MyType{$Int}(::$Int)
InferenceTiming: 6.6458e-5/0.000124716 on InferenceFrameInfo for SnoopCompile.FlattenDemo.extract(::SnoopCompile.FlattenDemo.MyType{$Int})
InferenceTiming: 0.000136496/0.000136496 on InferenceFrameInfo for SnoopCompile.FlattenDemo.domath(::$Int)
InferenceTiming: 9.43e-5/0.00035551200000000005 on InferenceFrameInfo for SnoopCompile.FlattenDemo.dostuff(::SnoopCompile.FlattenDemo.MyType{$Int})
InferenceTiming: 0.000150891/0.0006117210000000001 on InferenceFrameInfo for SnoopCompile.FlattenDemo.packintype(::$Int)
InferenceTiming: 0.002423543/0.0030352639999999998 on InferenceFrameInfo for Core.Compiler.Timings.ROOT()
```
As you can see, `sortby` affects not just the order but also the selection of frames; with exclusive times, `dostuff` did
not on its own rise above threshold, but it does when using inclusive times.
See also: [`accumulate_by_source`](@ref).
"""
function flatten(tinf::InferenceTimingNode; tmin = 0.0, sortby::Union{typeof(exclusive),typeof(inclusive),Nothing}=exclusive)
out = InferenceTiming[]
flatten!(sortby === nothing ? exclusive : sortby, out, tinf, tmin)
return sortby===nothing ? out : sort(out; by=sortby)
end
function flatten!(gettime::Union{typeof(exclusive),typeof(inclusive)}, out, node, tmin)
time = gettime(node)
if time >= tmin
push!(out, node.mi_timing)
end
for child in node.children
flatten!(gettime, out, child, tmin)
end
return out
end
"""
accumulate_by_source(flattened; tmin = 0.0, by=exclusive)
Add the inference timings for all `MethodInstance`s of a single `Method` together.
`flattened` is the output of [`flatten`](@ref).
Returns a list of `(t, method)` tuples.
When the accumulated time for a `Method` is large, but each instance is small, it indicates
that it is being inferred for many specializations (which might include specializations with different constants).
# Example
We'll use [`SnoopCompile.flatten_demo`](@ref), which runs `@snoopi_deep` on a workload designed to yield reproducible results:
```jldoctest accum1; setup=:(using SnoopCompile), filter=r"([0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?|at .*/deep_demos.jl:\\d+|at Base\\.jl:\\d+|at compiler/typeinfer\\.jl:\\d+|WARNING: replacing module FlattenDemo\\.\\n)"
julia> tinf = SnoopCompile.flatten_demo()
InferenceTimingNode: 0.002148974/0.002767166 on InferenceFrameInfo for Core.Compiler.Timings.ROOT() with 1 direct children
julia> accumulate_by_source(flatten(tinf))
7-element Vector{Tuple{Float64, Union{Method, Core.MethodInstance}}}:
(6.0012999999999996e-5, getproperty(x, f::Symbol) in Base at Base.jl:33)
(6.7714e-5, extract(y::SnoopCompile.FlattenDemo.MyType) in SnoopCompile.FlattenDemo at /pathto/SnoopCompile/src/deep_demos.jl:35)
(9.421e-5, dostuff(y) in SnoopCompile.FlattenDemo at /pathto/SnoopCompile/src/deep_demos.jl:44)
(0.000112057, SnoopCompile.FlattenDemo.MyType{T}(x) where T in SnoopCompile.FlattenDemo at /pathto/SnoopCompile/src/deep_demos.jl:34)
(0.000133895, domath(x) in SnoopCompile.FlattenDemo at /pathto/SnoopCompile/src/deep_demos.jl:40)
(0.000154382, packintype(x) in SnoopCompile.FlattenDemo at /pathto/SnoopCompile/src/deep_demos.jl:36)
(0.003165266, ROOT() in Core.Compiler.Timings at compiler/typeinfer.jl:75)
```
Compared to the output from [`flatten`](@ref), the two inferences passes on `getproperty` have been consolidated into a single aggregate call.
"""
function accumulate_by_source(::Type{M}, flattened::Vector{InferenceTiming}; tmin = 0.0, by::Union{typeof(exclusive),typeof(inclusive)}=exclusive) where M<:Union{Method,MethodInstance}
tmp = Dict{Union{M,MethodInstance},Float64}()
for frame in flattened
mi = MethodInstance(frame)
m = mi.def
if M === Method && isa(m, Method)
tmp[m] = get(tmp, m, 0.0) + by(frame)
else
tmp[mi] = by(frame) # module-level thunks are stored verbatim
end
end
return sort(Tuple{Float64,Union{M,MethodInstance}}[(t, m) for (m, t) in tmp if t >= tmin]; by=first)
end
accumulate_by_source(flattened::Vector{InferenceTiming}; kwargs...) = accumulate_by_source(Method, flattened; kwargs...)
"""
list = collect_for(m::Method, tinf::InferenceTimingNode)
list = collect_for(m::MethodInstance, tinf::InferenceTimingNode)
Collect all `InferenceTimingNode`s (descendants of `tinf`) that match `m`.
"""
collect_for(target::Union{Method,MethodInstance}, tinf::InferenceTimingNode) = collect_for!(InferenceTimingNode[], target, tinf)
function collect_for!(out, target, tinf)
matches(mi::MethodInstance, node) = MethodInstance(node) == mi
matches(m::Method, node) = (mi = MethodInstance(node); mi.def == m)
matches(target, tinf) && push!(out, tinf)
for child in tinf.children
collect_for!(out, target, child)
end
return out
end
"""
staleinstances(tinf::InferenceTimingNode)
Return a list of `InferenceTimingNode`s corresponding to `MethodInstance`s that have "stale" code
(specifically, `CodeInstance`s with outdated `max_world` world ages).
These may be a hint that invalidation occurred while running the workload provided to `@snoopi_deep`,
and consequently an important origin of (re)inference.
!!! warning
`staleinstances` only looks *retrospectively* for stale code; it does not distinguish whether the code became
stale while running `@snoopi_deep` from whether it was already stale before execution commenced.
While `staleinstances` is recommended as a useful "sanity check" to run before performing a detailed analysis of inference,
any serious examination of invalidation should use [`@snoopr`](@ref).
For more information about world age, see https://docs.julialang.org/en/v1/manual/methods/#Redefining-Methods.
"""
staleinstances(root::InferenceTimingNode; min_world_exclude = UInt(1)) = staleinstances!(InferenceTiming[], root, Base.get_world_counter(), UInt(min_world_exclude)::UInt)
function staleinstances!(out, node::InferenceTimingNode, world::UInt, min_world_exclude::UInt)
if hasstaleinstance(MethodInstance(node), world, min_world_exclude)
push!(out, node.mi_timing)
end
for child in node.children
staleinstances!(out, child, world, min_world_exclude)
end
return out
end
# Tip: the following is useful in conjunction with MethodAnalysis.methodinstances() to discover pre-existing stale code
function hasstaleinstance(mi::MethodInstance, world::UInt = Base.get_world_counter(), min_world_exclude::UInt = UInt(1))
m = mi.def
mod = isa(m, Module) ? m : m.module
if Base.parentmodule(mod) !== Core # Core runs in an old world
if isdefined(mi, :cache)
# Check all CodeInstances
ci = mi.cache
while true
if min_world_exclude <= ci.max_world < world # 0 indicates a CodeInstance loaded from precompile cache
return true
end
if isdefined(ci, :next)
ci = ci.next
else
break
end
end
end
end
return false
end
## parcel and supporting infrastructure
function isprecompilable(mi::MethodInstance; excluded_modules=Set([Main::Module]))
m = mi.def
if isa(m, Method)
mod = m.module
can_eval = excluded_modules === nothing || mod ∉ excluded_modules
if can_eval
params = Base.unwrap_unionall(mi.specTypes)::DataType
for p in params.parameters
if p isa Type
if !known_type(mod, p)
can_eval = false
break
end
end
end
end
return can_eval
end
return false
end
struct Precompiles
mi_info::InferenceFrameInfo # entrance point to inference (the "root")
total_time::Float64 # total time for the root
precompiles::Vector{Tuple{Float64,MethodInstance}} # list of precompilable child MethodInstances with their times
end
Precompiles(node::InferenceTimingNode) = Precompiles(InferenceTiming(node).mi_info, inclusive(node), Tuple{Float64,MethodInstance}[])
Core.MethodInstance(pc::Precompiles) = MethodInstance(pc.mi_info)
SnoopCompileCore.inclusive(pc::Precompiles) = pc.total_time
precompilable_time(precompiles::Vector{Tuple{Float64,MethodInstance}}) where T = sum(first, precompiles; init=0.0)
precompilable_time(precompiles::Dict{MethodInstance,T}) where T = sum(values(precompiles); init=zero(T))
precompilable_time(pc::Precompiles) = precompilable_time(pc.precompiles)
function Base.show(io::IO, pc::Precompiles)
tpc = precompilable_time(pc)
print(io, "Precompiles: ", pc.total_time, " for ", MethodInstance(pc),
" had ", length(pc.precompiles), " precompilable roots reclaiming ", tpc,
" ($(round(Int, 100*tpc/pc.total_time))%)")
end
function precompilable_roots!(pc, node::InferenceTimingNode, tthresh; excluded_modules=Set([Main::Module]))
(t = inclusive(node)) >= tthresh || return pc
mi = MethodInstance(node)
if isprecompilable(mi; excluded_modules)
push!(pc.precompiles, (t, mi))
return pc
end
foreach(node.children) do c
precompilable_roots!(pc, c, tthresh; excluded_modules=excluded_modules)
end
return pc
end
function precompilable_roots(node::InferenceTimingNode, tthresh; kwargs...)
pcs = [precompilable_roots!(Precompiles(child), child, tthresh; kwargs...) for child in node.children if inclusive(node) >= tthresh]
t_grand_total = sum(inclusive, node.children)
tpc = precompilable_time.(pcs)
p = sortperm(tpc)
return (t_grand_total, pcs[p])
end
function parcel((t_grand_total,pcs)::Tuple{Float64,Vector{Precompiles}})
# Because the same MethodInstance can be compiled multiple times for different Const values,
# we just keep the largest time observed per MethodInstance.
pcdict = Dict{Module,Dict{MethodInstance,Float64}}()
for pc in pcs
for (t, mi) in pc.precompiles
m = mi.def
mod = isa(m, Method) ? m.module : m
pcmdict = get!(Dict{MethodInstance,Float64}, pcdict, mod)
pcmdict[mi] = max(t, get(pcmdict, mi, zero(Float64)))
end
end
pclist = [mod => (precompilable_time(pcmdict), sort!([(t, mi) for (mi, t) in pcmdict]; by=first)) for (mod, pcmdict) in pcdict]
sort!(pclist; by = pr -> pr.second[1])
return t_grand_total, pclist
end
"""
ttot, pcs = SnoopCompile.parcel(tinf::InferenceTimingNode)
Parcel the "root-most" precompilable MethodInstances into separate modules.
These can be used to generate `precompile` directives to cache the results of type-inference,
reducing latency on first use.
Loosely speaking, and MethodInstance is precompilable if the module that owns the method also
has access to all the types it need to precompile the instance.
When the root node of an entrance to inference is not itself precompilable, `parcel` examines the
children (and possibly, children's children...) until it finds the first node on each branch that
is precompilable. `MethodInstances` are then assigned to the module that owns the method.
`ttot` is the total inference time; `pcs` is a list of `module => (tmod, pclist)` pairs. For each module,
`tmod` is the amount of inference time affiliated with methods owned by that module; `pclist` is a list
of `(t, mi)` time/MethodInstance tuples.
See also: [`SnoopCompile.write`](@ref).
# Example
We'll use [`SnoopCompile.itrigs_demo`](@ref), which runs `@snoopi_deep` on a workload designed to yield reproducible results:
```jldoctest parceltree; setup=:(using SnoopCompile), filter=r"([0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?|WARNING: replacing module ItrigDemo\\.\\n|UInt8|Float64|SnoopCompile\\.ItrigDemo\\.)"
julia> tinf = SnoopCompile.itrigs_demo()
InferenceTimingNode: 0.004490576/0.004711168 on InferenceFrameInfo for Core.Compiler.Timings.ROOT() with 2 direct children
julia> ttot, pcs = SnoopCompile.parcel(tinf);
julia> ttot
0.000220592
julia> pcs
1-element Vector{Pair{Module, Tuple{Float64, Vector{Tuple{Float64, Core.MethodInstance}}}}}:
SnoopCompile.ItrigDemo => (0.000220592, [(9.8986e-5, MethodInstance for double(::Float64)), (0.000121606, MethodInstance for double(::UInt8))])
```
Since there was only one module, `ttot` is the same as `tmod`. The `ItrigDemo` module had two precomilable MethodInstances,
each listed with its corresponding inclusive time.
"""
parcel(tinf::InferenceTimingNode; tmin=0.0, kwargs...) = parcel(precompilable_roots(tinf, tmin; kwargs...))
### write
function get_reprs(tmi::Vector{Tuple{Float64,MethodInstance}}; tmin=0.001)
strs = OrderedSet{String}()
modgens = Dict{Module, Vector{Method}}()
tmp = String[]
twritten = 0.0
for (t, mi) in reverse(tmi)
if t >= tmin
if add_repr!(tmp, modgens, mi; check_eval=false, time=t)
str = pop!(tmp)
if !any(rex -> occursin(rex, str), default_exclusions)
push!(strs, str)
twritten += t
end
end
end
end
return strs, twritten
end
function write(io::IO, tmi::Vector{Tuple{Float64,MethodInstance}}; indent::AbstractString=" ", kwargs...)
strs, twritten = get_reprs(tmi; kwargs...)
for str in strs
println(io, indent, str)
end
return twritten, length(strs)
end
function write(prefix::AbstractString, pc::Vector{Pair{Module,Tuple{Float64,Vector{Tuple{Float64,MethodInstance}}}}}; ioreport::IO=stdout, header::Bool=true, always::Bool=false, kwargs...)
if !isdir(prefix)
mkpath(prefix)
end
for (mod, ttmi) in pc
tmod, tmi = ttmi
v, twritten = get_reprs(tmi; kwargs...)
if isempty(v)
println(ioreport, "$mod: no precompile statements out of $tmod")
continue
end
open(joinpath(prefix, "precompile_$(mod).jl"), "w") do io
if header
if any(str->occursin("__lookup", str), v)
println(io, lookup_kwbody_str)
end
println(io, "function _precompile_()")
!always && println(io, " ccall(:jl_generating_output, Cint, ()) == 1 || return nothing")
end
for ln in v
println(io, " ", ln)
end
header && println(io, "end")
end
println(ioreport, "$mod: precompiled $twritten out of $tmod")
end
end
## Profile-guided de-optimization
# These tools can help balance the need for specialization (to achieve good runtime performance)
# against the desire to reduce specialization to reduce latency.
struct MethodLoc
func::Symbol
file::Symbol
line::Int
end
MethodLoc(sf::StackTraces.StackFrame) = MethodLoc(sf.func, sf.file, sf.line)
Base.show(io::IO, ml::MethodLoc) = print(io, ml.func, " at ", ml.file, ':', ml.line, " [inlined and pre-inferred]")
struct PGDSData
trun::Float64 # runtime cost
trtd::Float64 # runtime dispatch cost
tinf::Float64 # inference time (either exclusive/inclusive depending on settings)
nspec::Int # number of specializations
end
PGDSData() = PGDSData(0.0, 0.0, 0.0, 0)
"""
ridata = runtime_inferencetime(tinf::InferenceTimingNode; consts=true, by=inclusive)
ridata = runtime_inferencetime(tinf::InferenceTimingNode, profiledata; lidict, consts=true, by=inclusive)
Compare runtime and inference-time on a per-method basis. `ridata[m::Method]` returns `(trun, tinfer, nspecializations)`,
measuring the approximate amount of time spent running `m`, inferring `m`, and the number of type-specializations, respectively.
`trun` is estimated from profiling data, which the user is responsible for capturing before the call.
Typically `tinf` is collected via `@snoopi_deep` on the first call (in a fresh session) to a workload,
and the profiling data collected on a subsequent call. In some cases you may need to repeat the workload
several times to collect enough profiling samples.
`profiledata` and `lidict` are obtained from `Profile.retrieve()`.
"""
function runtime_inferencetime(tinf::InferenceTimingNode; kwargs...)
pdata = Profile.fetch()
lookup_firstip!(lookups, pdata)
return runtime_inferencetime(tinf, pdata; lidict=lookups, kwargs...)
end
function runtime_inferencetime(tinf::InferenceTimingNode, pdata;
lidict, consts::Bool=true,
by::Union{typeof(exclusive),typeof(inclusive)}=inclusive,
delay::Float64=ccall(:jl_profile_delay_nsec, UInt64, ())/10^9)
tf = flatten(tinf)
tm = accumulate_by_source(Method, tf; by=by) # this `by` is actually irrelevant, but less confusing this way
# MethodInstances that get inlined don't have the linfo field. Guess the method from the name/line/file.
# Filenames are complicated because of variations in how paths are encoded, especially for methods in Base & stdlibs.
methodlookup = Dict{Tuple{Symbol,Int},Vector{Pair{String,Method}}}() # (func, line) => [file => method]
for (_, m) in tm
isa(m, Method) || continue
fm = get!(Vector{Pair{String,Method}}, methodlookup, (m.name, Int(m.line)))
push!(fm, string(m.file) => m)
end
function matchloc(loc::MethodLoc)
fm = get(methodlookup, (loc.func, Int(loc.line)), nothing)
fm === nothing && return loc
meths = Set{Method}()
locfile = string(loc.file)
for (f, m) in fm
endswith(locfile, f) && push!(meths, m)
end
length(meths) == 1 && return pop!(meths)
return loc
end
matchloc(sf::StackTraces.StackFrame) = matchloc(MethodLoc(sf))
ridata = Dict{Union{Method,MethodLoc},PGDSData}()
# Insert the profiling data
lilists, nselfs, nrtds = select_firstip(pdata, lidict)
for (sfs, nself, nrtd) in zip(lilists, nselfs, nrtds)
for sf in sfs
mi = sf.linfo
m = isa(mi, MethodInstance) ? mi.def : matchloc(sf)
if isa(m, Method) || isa(m, MethodLoc)
d = get(ridata, m, PGDSData())
ridata[m] = PGDSData(d.trun + nself*delay, d.trtd + nrtd*delay, d.tinf, d.nspec)
else
@show typeof(m) m
error("whoops")
end
end
end
# Now add inference times & specialization counts. To get the counts we go back to tf rather than using tm.
if !consts
for (t, mi) in accumulate_by_source(MethodInstance, tf; by=by)
isROOT(mi) && continue
m = mi.def
if isa(m, Method)
d = get(ridata, m, PGDSData())
ridata[m] = PGDSData(d.trun, d.trtd, d.tinf + t, d.nspec + 1)
end
end
else
for frame in tf
isROOT(frame) && continue
t = by(frame)
m = MethodInstance(frame).def
if isa(m, Method)
d = get(ridata, m, PGDSData())
ridata[m] = PGDSData(d.trun, d.trtd, d.tinf + t, d.nspec + 1)
end
end
end
# Sort the outputs to try to prioritize opportunities for the developer. Because we have multiple objectives (fast runtime
# and fast compile time), there's no unique sorting order, nor can we predict the cost to runtime performance of reducing
# the method specialization. Here we use the following approximation: we naively estimate "what the inference time could be" if
# there were only one specialization of each method, and the answers are sorted by the estimated savings. This does not
# even attempt to account for any risk to the runtime. For any serious analysis, looking at the scatter plot with
# [`specialization_plot`](@ref) is recommended.
savings(d::PGDSData) = d.tinf * (d.nspec - 1)
savings(pr::Pair) = savings(pr.second)
return sort(collect(ridata); by=savings)
end
function lookup_firstip!(lookups, pdata)
isfirst = true
for (i, ip) in enumerate(pdata)
if isfirst
sfs = get!(()->Base.StackTraces.lookup(ip), lookups, ip)
if !all(sf -> sf.from_c, sfs)
isfirst = false
end
end
if ip == 0
isfirst = true
end
end
return lookups
end
function select_firstip(pdata, lidict)
counter = Dict{eltype(pdata),Tuple{Int,Int}}()
isfirst = true
isrtd = false
for ip in pdata
if isfirst
sfs = lidict[ip]
if !all(sf -> sf.from_c, sfs)
n, nrtd = get(counter, ip, (0, 0))
counter[ip] = (n + 1, nrtd + isrtd)
isfirst = isrtd = false
else
for sf in sfs
isrtd |= FlameGraphs.status(sf) & FlameGraphs.runtime_dispatch
end
end
end
if ip == 0
isfirst = true
isrtd = false
end
end
lilists, nselfs, nrtds = valtype(lidict)[], Int[], Int[]
for (ip, (n, nrtd)) in counter
push!(lilists, lidict[ip])
push!(nselfs, n)
push!(nrtds, nrtd)
end
return lilists, nselfs, nrtds
end
## Analysis of inference triggers
"""
InferenceTrigger(callee::MethodInstance, callerframes::Vector{StackFrame}, btidx::Int, bt)
Organize information about the "triggers" of inference. `callee` is the `MethodInstance` requiring inference,
`callerframes`, `btidx` and `bt` contain information about the caller.
`callerframes` are the frame(s) of call site that triggered inference; it's a `Vector{StackFrame}`, rather than a
single `StackFrame`, due to the possibility that the caller was inlined into something else, in which case the first entry
is the direct caller and the last entry corresponds to the MethodInstance into which it was ultimately inlined.
`btidx` is the index in `bt`, the backtrace collected upon entry into inference, corresponding to `callerframes`.
`InferenceTrigger`s are created by calling [`inference_triggers`](@ref).
See also: [`callerinstance`](@ref) and [`callingframe`](@ref).
"""
struct InferenceTrigger
node::InferenceTimingNode
callerframes::Vector{StackTraces.StackFrame}
btidx::Int # callerframes = StackTraces.lookup(bt[btidx])
end
function Base.show(io::IO, itrig::InferenceTrigger)
print(io, "Inference triggered to call ")
printstyled(io, stripmi(MethodInstance(itrig.node)); color=:yellow)
if !isempty(itrig.callerframes)
sf = first(itrig.callerframes)
print(io, " from ")
printstyled(io, sf.func; color=:red, bold=true)
print(io, " (", sf.file, ':', sf.line, ')')
caller = itrig.callerframes[end].linfo
if isa(caller, MethodInstance)
length(itrig.callerframes) == 1 ? print(io, " with specialization ") : print(io, " inlined into ")
printstyled(io, stripmi(caller); color=:blue)
if length(itrig.callerframes) > 1
sf = itrig.callerframes[end]
print(io, " (", sf.file, ':', sf.line, ')')
end
elseif isa(caller, Core.CodeInfo)
print(io, " called from toplevel code ", caller)
end
else
print(io, " called from toplevel")
end
end
"""
mi = callerinstance(itrig::InferenceTrigger)
Return the MethodInstance `mi` of the caller in the selected stackframe in `itrig`.
"""
callerinstance(itrig::InferenceTrigger) = itrig.callerframes[end].linfo
function callerinstances(itrigs::AbstractVector{InferenceTrigger})
callers = Set{MethodInstance}()
for itrig in itrigs
!isempty(itrig.callerframes) && push!(callers, callerinstance(itrig))
end
return callers
end
function callermodule(itrig::InferenceTrigger)
if !isempty(itrig.callerframes)
m = callerinstance(itrig).def
return isa(m, Module) ? m : m.module
end
return nothing
end
# Select the next (caller) frame that's a Julia (as opposed to C) frame; returns the stackframe and its index in bt, or nothing
function next_julia_frame(bt, idx, Δ=1; methodinstanceonly::Bool=true, methodonly::Bool=true)
while 1 <= idx+Δ <= length(bt)
ip = lookups_key(bt[idx+=Δ])
sfs = get!(()->Base.StackTraces.lookup(ip), lookups, ip)
sf = sfs[end]
sf.from_c && continue
mi = sf.linfo
methodinstanceonly && (isa(mi, Core.MethodInstance) || continue)
if isa(mi, MethodInstance)
m = mi.def
methodonly && (isa(m, Method) || continue)
# Exclude frames that are in Core.Compiler
isa(m, Method) && m.module === Core.Compiler && continue
end
return sfs, idx
end
return nothing
end
SnoopCompileCore.exclusive(itrig::InferenceTrigger) = exclusive(itrig.node)
SnoopCompileCore.inclusive(itrig::InferenceTrigger) = inclusive(itrig.node)
StackTraces.stacktrace(itrig::InferenceTrigger) = stacktrace(itrig.node.bt)
isprecompilable(itrig::InferenceTrigger) = isprecompilable(MethodInstance(itrig.node))
"""
itrigs = inference_triggers(tinf::InferenceTimingNode; exclude_toplevel=true)
Collect the "triggers" of inference, each a fresh entry into inference via a call dispatched at runtime.
All the entries in `itrigs` are previously uninferred, or are freshly-inferred for specific constant inputs.
`exclude_toplevel` determines whether calls made from the REPL, `include`, or test suites are excluded.
# Example
We'll use [`SnoopCompile.itrigs_demo`](@ref), which runs `@snoopi_deep` on a workload designed to yield reproducible results:
```jldoctest triggers; setup=:(using SnoopCompile), filter=r"([0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?|.*/deep_demos\\.jl:\\d+|WARNING: replacing module ItrigDemo\\.\\n)"
julia> tinf = SnoopCompile.itrigs_demo()
InferenceTimingNode: 0.004490576/0.004711168 on InferenceFrameInfo for Core.Compiler.Timings.ROOT() with 2 direct children
julia> itrigs = inference_triggers(tinf)
2-element Vector{InferenceTrigger}:
Inference triggered to call MethodInstance for double(::UInt8) from calldouble1 (/pathto/SnoopCompile/src/deep_demos.jl:86) inlined into MethodInstance for calldouble2(::Vector{Vector{Any}}) (/pathto/SnoopCompile/src/deep_demos.jl:87)
Inference triggered to call MethodInstance for double(::Float64) from calldouble1 (/pathto/SnoopCompile/src/deep_demos.jl:86) inlined into MethodInstance for calldouble2(::Vector{Vector{Any}}) (/pathto/SnoopCompile/src/deep_demos.jl:87)
```
```
julia> edit(itrigs[1]) # opens an editor at the spot in the caller
julia> ascend(itrigs[2]) # use Cthulhu to inspect the stacktrace (caller is the second item in the trace)
Choose a call for analysis (q to quit):
> double(::Float64)
calldouble1 at /pathto/SnoopCompile/src/deep_demos.jl:86 => calldouble2(::Vector{Vector{Any}}) at /pathto/SnoopCompile/src/deep_demos.jl:87
calleach(::Vector{Vector{Vector{Any}}}) at /pathto/SnoopCompile/src/deep_demos.jl:88
...
```
"""
function inference_triggers(tinf::InferenceTimingNode; exclude_toplevel::Bool=true)
function first_julia_frame(bt)
ret = next_julia_frame(bt, 1)
if ret === nothing
return StackTraces.StackFrame[], 0
end
return ret
end
itrigs = map(tinf.children) do child
bt = child.bt
bt === nothing && throw(ArgumentError("it seems you've supplied a child node, but backtraces are collected only at the entrance to inference"))
InferenceTrigger(child, first_julia_frame(bt)...)
end
if exclude_toplevel
filter!(maybe_internal, itrigs)
end
return itrigs
end
function maybe_internal(itrig::InferenceTrigger)
for sf in itrig.callerframes
linfo = sf.linfo
if isa(linfo, MethodInstance)
m = linfo.def
if isa(m, Method)
if m.module === Base
m.name === :include_string && return false
m.name === :_include_from_serialized && return false
m.name === :return_types && return false # from `@inferred`
end
m.name === :eval && return false
end
end
match(rextest, string(sf.file)) !== nothing && return false
end
return true
end
"""
itrigcaller = callingframe(itrig::InferenceTrigger)
"Step out" one layer of the stacktrace, referencing the caller of the current frame of `itrig`.
You can retrieve the proximal trigger of inference with `InferenceTrigger(itrigcaller)`.
# Example
We collect data using the [`SnoopCompile.itrigs_demo`](@ref):
```julia
julia> itrig = inference_triggers(SnoopCompile.itrigs_demo())[1]
Inference triggered to call MethodInstance for double(::UInt8) from calldouble1 (/pathto/SnoopCompile/src/parcel_snoopi_deep.jl:762) inlined into MethodInstance for calldouble2(::Vector{Vector{Any}}) (/pathto/SnoopCompile/src/parcel_snoopi_deep.jl:763)
julia> itrigcaller = callingframe(itrig)
Inference triggered to call MethodInstance for double(::UInt8) from calleach (/pathto/SnoopCompile/src/parcel_snoopi_deep.jl:764) with specialization MethodInstance for calleach(::Vector{Vector{Vector{Any}}})
```
"""
function callingframe(itrig::InferenceTrigger)
idx = itrig.btidx
if idx < length(itrig.node.bt)
ret = next_julia_frame(itrig.node.bt, idx)
if ret !== nothing
return InferenceTrigger(itrig.node, ret...)
end
end
return InferenceTrigger(itrig.node, StackTraces.StackFrame[], length(itrig.node.bt)+1)
end
"""
itrig0 = InferenceTrigger(itrig::InferenceTrigger)
Reset an inference trigger to point to the stackframe that triggered inference.
This can be useful to undo the actions of [`callingframe`](@ref) and [`skiphigherorder`](@ref).
"""
InferenceTrigger(itrig::InferenceTrigger) = InferenceTrigger(itrig.node, next_julia_frame(itrig.node.bt, 1)...)
"""
itrignew = skiphigherorder(itrig; exact::Bool=false)
Attempt to skip over frames of higher-order functions that take the callee as a function-argument.
This can be useful if you're analyzing inference triggers for an entire package and would prefer to assign
triggers to package-code rather than Base functions like `map!`, `broadcast`, etc.
# Example
We collect data using the [`SnoopCompile.itrigs_higherorder_demo`](@ref):
```julia
julia> itrig = inference_triggers(SnoopCompile.itrigs_higherorder_demo())[1]
Inference triggered to call MethodInstance for double(::Float64) from mymap! (/pathto/SnoopCompile/src/parcel_snoopi_deep.jl:706) with specialization MethodInstance for mymap!(::typeof(SnoopCompile.ItrigHigherOrderDemo.double), ::Vector{Any}, ::Vector{Any})
julia> callingframe(itrig) # step out one (non-inlined) frame
Inference triggered to call MethodInstance for double(::Float64) from mymap (/pathto/SnoopCompile/src/parcel_snoopi_deep.jl:710) with specialization MethodInstance for mymap(::typeof(SnoopCompile.ItrigHigherOrderDemo.double), ::Vector{Any})
julia> skiphigherorder(itrig) # step out to frame that doesn't have `double` as a function-argument
Inference triggered to call MethodInstance for double(::Float64) from callmymap (/pathto/SnoopCompile/src/parcel_snoopi_deep.jl:711) with specialization MethodInstance for callmymap(::Vector{Any})
```
!!! warn
By default `skiphigherorder` is conservative, and insists on being sure that it's the callee being passed to the higher-order function.
Higher-order functions that do not get specialized (e.g., with `::Function` argument types) will not be skipped over.
You can pass `exact=false` to allow `::Function` to also be passed over, but keep in mind that this may falsely skip some frames.
"""
function skiphigherorder(itrig::InferenceTrigger; exact::Bool=true)
ft = Base.unwrap_unionall(Base.unwrap_unionall(MethodInstance(itrig.node).specTypes).parameters[1])
sfs, idx = itrig.callerframes, itrig.btidx
while idx < length(itrig.node.bt)
if !isempty(sfs)
callermi = sfs[end].linfo
if !hasparameter(callermi.specTypes, ft, exact)
return InferenceTrigger(itrig.node, sfs, idx)
end
end
ret = next_julia_frame(itrig.node.bt, idx)
ret === nothing && return InferenceTrigger(itrig.node, sfs, idx)
sfs, idx = ret
end
return itrig
end
function hasparameter(@nospecialize(typ), @nospecialize(ft), exact::Bool)
isa(typ, Type) || return false
typ = Base.unwrap_unionall(typ)
typ === ft && return true
exact || (typ === Function && return true)
typ === Union{} && return false
if isa(typ, Union)
hasparameter(typ.a, ft, exact) && return true
hasparameter(typ.b, ft, exact) && return true
return false
end
for p in typ.parameters
hasparameter(p, ft, exact) && return true
end
return false
end
"""
ncallees, ncallers = diversity(itrigs::AbstractVector{InferenceTrigger})
Count the number of distinct MethodInstances among the callees and callers, respectively, among the triggers in `itrigs`.
"""
function diversity(itrigs)
# Analyze caller => callee argument type diversity
callees, callers, ncextra = Set{MethodInstance}(), Set{MethodInstance}(), 0
for itrig in itrigs
push!(callees, MethodInstance(itrig.node))
caller = itrig.callerframes[end].linfo
if isa(caller, MethodInstance)
push!(callers, caller)
else
ncextra += 1
end
end
return length(callees), length(callers) + ncextra
end
# Integrations
AbstractTrees.children(tinf::InferenceTimingNode) = tinf.children
InteractiveUtils.edit(itrig::InferenceTrigger) = edit(Location(itrig.callerframes[end]))
Cthulhu.descend(itrig::InferenceTrigger; kwargs...) = descend(callerinstance(itrig); kwargs...)
Cthulhu.instance(itrig::InferenceTrigger) = MethodInstance(itrig.node)
Cthulhu.method(itrig::InferenceTrigger) = Method(itrig.node)
Cthulhu.specTypes(itrig::InferenceTrigger) = Cthulhu.specTypes(Cthulhu.instance(itrig))
Cthulhu.backedges(itrig::InferenceTrigger) = (itrig.callerframes,)
Cthulhu.nextnode(itrig::InferenceTrigger, edge) = (ret = callingframe(itrig); return isempty(ret.callerframes) ? nothing : ret)
filtermod(mod::Module, itrigs::AbstractVector{InferenceTrigger}) = filter(==(mod) ∘ callermodule, itrigs)
### inference trigger trees
# good for organizing into "events"
struct TriggerNode
itrig::Union{Nothing,InferenceTrigger}
children::Vector{TriggerNode}
parent::TriggerNode
TriggerNode() = new(nothing, TriggerNode[])
TriggerNode(parent::TriggerNode, itrig::InferenceTrigger) = new(itrig, TriggerNode[], parent)
end
function Base.show(io::IO, node::TriggerNode)
print(io, "TriggerNode for ")
AbstractTrees.printnode(io, node)
print(io, " with ", length(node.children), " direct children")
end
AbstractTrees.children(node::TriggerNode) = node.children
function AbstractTrees.printnode(io::IO, node::TriggerNode)
if node.itrig === nothing
print(io, "root")
else
print(io, stripmi(MethodInstance(node.itrig.node)))
end
end
function addchild!(node, itrig)
newnode = TriggerNode(node, itrig)
push!(node.children, newnode)
return newnode
end
truncbt(itrig::InferenceTrigger) = itrig.node.bt[max(1, itrig.btidx):end]
function findparent(node::TriggerNode, bt)
node.itrig === nothing && return node # this is the root
btnode = truncbt(node.itrig)
lbt, lbtnode = length(bt), length(btnode)
if lbt > lbtnode && view(bt, lbt - lbtnode + 1 : lbt) == btnode
return node
end
return findparent(node.parent, bt)
end
"""
root = trigger_tree(itrigs)
Organize inference triggers `itrigs` in tree format, grouping items via the call tree.
It is a tree rather than a more general graph due to the fact that caching inference results means that each node gets
visited only once.
"""
function trigger_tree(itrigs::AbstractVector{InferenceTrigger})
root = node = TriggerNode()
for itrig in itrigs
thisbt = truncbt(itrig)
node = findparent(node, thisbt)
node = addchild!(node, itrig)
end
return root
end
flatten(node::TriggerNode) = flatten!(InferenceTrigger[], node)
function flatten!(itrigs, node::TriggerNode)
if node.itrig !== nothing
push!(itrigs, node.itrig)
end
for child in node.children
flatten!(itrigs, child)
end
return itrigs
end
InteractiveUtils.edit(node::TriggerNode) = edit(node.itrig)
Base.stacktrace(node::TriggerNode) = stacktrace(node.itrig)
Cthulhu.ascend(node::TriggerNode) = ascend(node.itrig)
### tagged trigger lists
# good for organizing a collection of related triggers
struct TaggedTriggers{TT}
tag::TT
itrigs::Vector{InferenceTrigger}
end
const MethodTriggers = TaggedTriggers{Method}
"""
mtrigs = accumulate_by_source(Method, itrigs::AbstractVector{InferenceTrigger})
Consolidate inference triggers via their caller method. `mtrigs` is a vector of `Method=>list`
pairs, where `list` is a list of `InferenceTrigger`s.
"""
function accumulate_by_source(::Type{Method}, itrigs::AbstractVector{InferenceTrigger})
cs = Dict{Method,Vector{InferenceTrigger}}()
for itrig in itrigs
isempty(itrig.callerframes) && continue
mi = callerinstance(itrig)
m = mi.def
if isa(m, Method)
list = get!(Vector{InferenceTrigger}, cs, m)
push!(list, itrig)
end
end
return sort!([MethodTriggers(m, list) for (m, list) in cs]; by=methtrig->length(methtrig.itrigs))
end
function Base.show(io::IO, methtrigs::MethodTriggers)