/
alloctool.go
3126 lines (2885 loc) · 72.4 KB
/
alloctool.go
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
/*
* TODO
* - assume anything written via atomic.Store* is a root?
* - Verify that Make{Interface, Closure} do not cause more heap
* allocations besides the ssa.Allocs already present for them.
* - sends on buffered channel accumulate live data too
* - I dumped all channel sends with pointer types and verified that all
* such sends are on unbuffered channels, thus the live data
* accumulation is already accounted for in the allocation of the object
* being sent. This check could be easily automated via more pointer
* analysis.
* - recursive iteration loops
* - (replaced recursion with loops)
* - don't forget that the tool ignores calls to package fmt.
* - consider transient objects written to channels as permanent
*/
/*
* TO USE
* - make sure the looping calls that this tool ignores are actually prevented
* at runtime (this was the case at the time of writing)
*
* 1) mkdir -p ~/go/src/allocstudy && cd ~/go/src/allocstudy
* 2) ~/biscuit/bin/go get -u "golang.org/x/tools/go/callgraph"
* 3) ~/biscuit/bin/go run allocstudy.go
*/
/*
* HOW IT WORKS
*
* XXX
*/
package main
import "bufio"
import "strconv"
import "os"
import "fmt"
import "time"
import "strings"
import "sort"
import "go/constant"
import "go/token"
import "go/types"
import "go/ast"
import "golang.org/x/tools/go/callgraph"
import "golang.org/x/tools/go/loader"
import "golang.org/x/tools/go/pointer"
import "golang.org/x/tools/go/ssa"
import "golang.org/x/tools/go/ssa/ssautil"
// DUMPER
var dumper = false
type halp_t struct {
cg *callgraph.Graph
heads map[*ssa.BasicBlock]*natl_t
funcvisit map[*callgraph.Node]bool
memos map[*callgraph.Node]*calls_t
fakefunc map[string]bool
chanfuncs map[*ssa.Function]bool
// visited loop blocks
lbvisit map[*ssa.BasicBlock]bool
usedbounds map[*ssa.BasicBlock]bool
infloops map[token.Position]bool
recurses map[string][]string
nomemo map[*callgraph.Node]bool
ms struct {
P lstack_t
S lstack_t
nums map[*callgraph.Node]int
added map[*callgraph.Node]bool
num int
comps []map[*callgraph.Node]bool
}
pkgs []*ssa.Package
}
func (h *halp_t) init(pkgs []*ssa.Package, cg *callgraph.Graph) {
h.pkgs = pkgs
h.cg = cg
h.funcvisit = map[*callgraph.Node]bool{}
h.fakefunc = map[string]bool{}
h.infloops = map[token.Position]bool{}
h.chanfuncs = map[*ssa.Function]bool{}
h.recurses = map[string][]string{}
h.nomemo = map[*callgraph.Node]bool{}
h.reset()
}
func (h *halp_t) reset() {
h.memos = map[*callgraph.Node]*calls_t{}
h.heads = map[*ssa.BasicBlock]*natl_t{}
h.lbvisit = map[*ssa.BasicBlock]bool{}
h.usedbounds = map[*ssa.BasicBlock]bool{}
}
// size class code stolen from src/runtime/sizeclasses.go, which is
// automatically generated during build (but was identical between go1.8 and
// go1.10.1, so maybe the sizeclasses don't change)
const (
_MaxSmallSize = 32768
smallSizeDiv = 8
smallSizeMax = 1024
largeSizeDiv = 128
_NumSizeClasses = 67
_PageShift = 13
)
var size_to_class8 = [smallSizeMax/smallSizeDiv + 1]uint8{0, 1, 2, 3, 3, 4, 4,
5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14,
15, 15, 16, 16, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20,
21, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25,
25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31}
var size_to_class128 = [(_MaxSmallSize-smallSizeMax)/largeSizeDiv + 1]uint8{31,
32, 33, 34, 35, 36, 36, 37, 37, 38, 38, 39, 39, 39, 40, 40, 40, 41, 42,
42, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 45, 45, 45, 45, 46, 46,
46, 46, 46, 46, 47, 47, 47, 48, 48, 49, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 53, 53, 53, 53,
54, 54, 54, 54, 54, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 56, 56,
56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 58, 58, 58, 58,
58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 59, 59, 59, 59, 59, 59,
59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 61, 61, 61,
61, 61, 61, 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
63, 63, 63, 63, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66}
func _sizetoclass(sz int) int {
var sizeclass uint8
if sz <= smallSizeMax-8 {
sizeclass = size_to_class8[(sz+smallSizeDiv-1)/smallSizeDiv]
} else {
sizeclass = size_to_class128[(sz-smallSizeMax+largeSizeDiv-1)/largeSizeDiv]
}
return int(sizeclass)
}
var countsc struct {
counts [_NumSizeClasses]int
}
func classadd(bytes int) {
countsc.counts[_sizetoclass(bytes)]++
}
func classdump() {
fmt.Printf("Size class counts over all traversed allocations\n")
for i, c := range countsc.counts {
fmt.Printf("%3v: %9v\n", i, c)
}
}
var _s = types.StdSizes{WordSize: 8, MaxAlign: 8}
func array_align(t types.Type) int {
truesz := _s.Sizeof(t)
align := _s.Alignof(t)
if truesz%align != 0 {
diff := align - (truesz % align)
truesz += diff
}
//classadd(int(truesz))
return int(truesz)
}
func slicesz(v ssa.Value, num int) int {
// the element type could be types.Named...
var typ *types.Slice
if tt, ok := v.Type().(*types.Named); ok {
typ = tt.Underlying().(*types.Slice)
} else {
typ = v.Type().(*types.Slice)
}
elmsz := array_align(typ.Elem())
return num*elmsz + 3*8
}
func chansz(v *ssa.MakeChan) int {
ue := v.Type().(*types.Chan).Elem()
elmsz := array_align(ue)
// all biscuit channel buffer sizes are constant
num, ok := constant.Int64Val(v.Size.(*ssa.Const).Value)
if !ok {
panic("nuts")
}
es := int(num) * elmsz
es = (es + 7) &^ 0x7
return es + 3*8
}
// returns true if there is a successor path from cur to target
func blockpath1(cur, target *ssa.BasicBlock, v map[*ssa.BasicBlock]bool) bool {
v[cur] = true
if cur == target {
return true
}
for _, bp := range cur.Succs {
if v[bp] {
continue
}
if blockpath1(bp, target, v) {
return true
}
}
return false
}
// returns true if cur == target
func blockpath(cur, target *ssa.BasicBlock) bool {
visited := make(map[*ssa.BasicBlock]bool)
return blockpath1(cur, target, visited)
}
// returns true if b has a successor which is also b's predecessor
func blockcycle(b *ssa.BasicBlock) bool {
for _, bp := range b.Succs {
if blockpath(bp, b) {
return true
}
}
return false
}
// remove "bound", "thunk", and anonymous function identifiers from the name.
// see ssa.Function.Relstring() docs.
func realname(f *ssa.Function) string {
ret := f.String()
if i := strings.Index(ret, "$"); i != -1 {
ret = ret[:i]
}
if i := strings.Index(ret, "#"); i != -1 {
ret = ret[:i]
}
return ret
}
type callstack_t struct {
cs []string
}
func (cs *callstack_t) push(f *ssa.Function) {
//cs.cs = append(cs.cs, realname(f))
cs.cs = append(cs.cs, f.String())
}
func (cs *callstack_t) pop() {
l := len(cs.cs)
cs.cs = cs.cs[:l-1]
}
// returns true if the function imp is present in the current call stack.
func (cs *callstack_t) calledfrom(imp string) bool {
for i := range cs.cs {
if cs.cs[i] == imp {
return true
}
}
return false
}
func (cs *callstack_t) csdump(msg string) {
fmt.Println(msg)
for _, cs := range cs.cs {
fmt.Printf("\t%v\n", cs)
}
}
// a type to keep track of which loops may execute an allocation multiple times
type lmult_t struct {
times int
name string
isinf bool
sym string
}
type alloc_t struct {
num int
inf bool
size int
lmults []lmult_t
}
type calls_t struct {
me *ssa.Function
looper bool
calls []*calls_t
allallocs map[ssa.Value]alloc_t
// total live bytes for this function and its callees
totl int
symloops map[string]bool
}
func newcalls(me *ssa.Function) *calls_t {
ret := &calls_t{me: me, calls: make([]*calls_t, 0)}
ret.allallocs = make(map[ssa.Value]alloc_t)
ret.symloops = make(map[string]bool)
ret.totl = -1
return ret
}
func (c *calls_t) givesym(p map[string]bool) {
for s := range c.symloops {
p[s] = true
}
}
func (c *calls_t) addalloc(k ssa.Value, size int) {
if k == nil {
panic("no")
}
// make([]string, 0) results in ssa.Alloc for [0]string
if size == 0 {
return
}
// ignore allocations that the programmer claims are parity-evicted
if _evicted[k] {
return
}
if old, ok := c.allallocs[k]; ok {
old.num += 1
c.allallocs[k] = old
} else {
c.allallocs[k] = alloc_t{num: 1, inf: false, size: size}
}
}
func (c *calls_t) loopmult(times int, name, sym string) {
isinf := times == INF
if isinf {
times = 1000
}
if times < 0 {
panic("no")
}
for k, ac := range c.allallocs {
ac.num *= times
ac.lmults = append(ac.lmults, lmult_t{times: times,
name: name, isinf: isinf, sym: sym})
c.allallocs[k] = ac
}
}
func (c *calls_t) total(parptrs map[ssa.Value]bool) int {
return c._mysum(parptrs)
}
//func (c *calls_t) total(parptrs map[ssa.Value]bool) int {
// ret := c._mysum(parptrs)
// for _, ch := range c.calls {
// if ch.totl == -1 {
// panic("child without total?")
// }
// ret += ch.totl
// }
// c.totl = ret
// return ret
//}
// calculate total reachable bytes from this function only (not callees)
func (c *calls_t) _mysum(myptrs map[ssa.Value]bool) int {
ret := 0
for k, ac := range c.allallocs {
// XXX
if ac.size < 0 || ac.num < 0 {
panic("eh?")
}
if permanent[k] || (myptrs != nil && myptrs[k]) {
ret += ac.size * ac.num
}
}
return ret
}
func (c *calls_t) merge(sib *calls_t) {
for _, tc := range sib.calls {
c._addchild(tc)
}
c._mergeallocs(sib)
sib.givesym(c.symloops)
}
func (c *calls_t) addchild(child *calls_t) {
c._addchild(child)
c._mergeallocs(child)
child.givesym(c.symloops)
}
func (c *calls_t) _addchild(child *calls_t) {
// XXX
if child == nil {
panic("eh?")
}
c.calls = append(c.calls, child)
}
func (c *calls_t) _mergeallocs(child *calls_t) {
for k, ac := range child.allallocs {
if old, ok := c.allallocs[k]; ok {
old.num += ac.num
old.inf = old.inf || ac.inf
if old.size != ac.size {
panic("crud")
}
old.lmults = append(old.lmults, ac.lmults...)
c.allallocs[k] = old
} else {
c.allallocs[k] = ac
}
}
}
func (c *calls_t) dump(verbose bool) {
c.dump1(verbose, 0, nil)
}
func (c *calls_t) dump1(v bool, depth int, parptrs map[ssa.Value]bool) {
if c.me == &dummyfunc {
return
}
//myptrs := ptrsetadd(parptrs, c.me)
myptrs := funcreach[c.me]
prdepth := func() {
for i := 0; i < depth; i++ {
fmt.Printf(" ")
}
}
prdepth()
lop := ""
if c.looper {
lop = "=L"
}
outter:
for k, ac := range c.allallocs {
if !permanent[k] && !myptrs[k] {
continue
}
for _, lm := range ac.lmults {
if lm.isinf {
lop = "=INFL"
break outter
}
}
}
fmt.Printf("%c %s [%v]%s\n", 'A'+depth, c.me.String(),
human(c.total(myptrs)), lop)
if v {
uniq := make(map[types.Type]bool)
sizes := make(map[types.Type]int)
exists := false
for k, ac := range c.allallocs {
uniq[k.Type()] = true
sizes[k.Type()] = ac.size
if permanent[k] || myptrs[k] {
exists = true
}
}
strs := make(map[types.Type]string)
for t := range uniq {
var s string
for k, ac := range c.allallocs {
if k.Type() != t {
continue
}
if !permanent[k] && !myptrs[k] {
continue
}
if s != "" {
s += "+ "
}
if ac.num == 1 {
s += "1 "
} else {
var t string
for _, lm := range ac.lmults {
if t != "" {
t += "* "
}
var ts string
if lm.isinf {
ts = "INF"
} else {
ts = fmt.Sprintf("%v", lm.times)
}
t += fmt.Sprintf("%v(%v) ", lm.name, ts)
}
s += t
}
strs[t] = s
}
}
if exists {
//prdepth()
//fmt.Printf(" |\n")
//prdepth()
//fmt.Printf(" |- LIMIT TYPE SUM----\n")
//for t, s := range strs {
// prdepth()
// fmt.Printf(" | %v(%v): %v\n", t, sizes[t], s)
//}
prdepth()
fmt.Printf(" |\n")
prdepth()
fmt.Printf(" |--- EACH ALLOC\n")
for k, ac := range c.allallocs {
if !permanent[k] && !myptrs[k] {
continue
}
in, ok := k.(ssa.Instruction)
if !ok {
// dumping code doesn't handle
// *ssa.Function values created from
// *ssa.{Defer,Go} (no corresponding
// call instructions for defer? doesn't
// Go have one though?)
panic("fixme")
}
prdepth()
let := ""
if permanent[k] {
let = " P"
}
fmt.Printf(" |-%v (%v*%v)%v\n", k, ac.size, ac.num, let)
prdepth()
fmt.Printf(" | %T %v\n", k, in.Parent())
prdepth()
fmt.Printf(" | %v\n", inpos(in))
if ac.num > 1 {
prdepth()
fmt.Printf(" | loops (%v):\n", len(ac.lmults))
for _, lm := range ac.lmults {
prdepth()
tstr := fmt.Sprintf("%vx", lm.times)
if lm.isinf {
tstr = "INF"
}
fmt.Printf(" | %v: %v\n", lm.name, tstr)
}
}
}
}
}
for i := range c.calls {
c.calls[i].dump1(v, depth+1, myptrs)
}
}
func (c *calls_t) dyump() {
for k, v := range c.allallocs {
fmt.Printf(" s%5v #%3v %T %v %v %v\n", v.size, v.num, k, k,
k.(ssa.Instruction).Parent(), inpos(k.(ssa.Instruction)))
}
}
// a type to create the symbolic limit equation from a calls_t
type summer_t struct {
lastdid map[ssa.Value]bool
// map of allocation size to count
sizes map[int]int
// map of symbolic loop names to map of allocation sizes to counts
symsize map[string]map[int]int
initted bool
}
func (sm *summer_t) _init() {
if sm.initted {
return
}
sm.initted = true
sm.lastdid = make(map[ssa.Value]bool)
sm.sizes = make(map[int]int)
sm.symsize = make(map[string]map[int]int)
}
func (sm *summer_t) accumulate(c *calls_t, ptrs map[ssa.Value]bool) {
sm._init()
newdid := make(map[ssa.Value]bool)
for k, ac := range c.allallocs {
if !permanent[k] && !ptrs[k] {
continue
}
newdid[k] = true
if sm.lastdid[k] {
continue
}
var syms []string
for _, lm := range ac.lmults {
if lm.sym != "" {
syms = append(syms, lm.sym)
}
}
if len(syms) > 0 {
sort.Strings(syms)
k := ""
sep := ""
for _, sym := range syms {
k += sep + sym
sep = " * "
}
oldm, ok := sm.symsize[k]
if !ok {
oldm = make(map[int]int)
}
old := oldm[ac.size]
oldm[ac.size] = old + ac.num
sm.symsize[k] = oldm
} else {
old := sm.sizes[ac.size]
sm.sizes[ac.size] = old + ac.num
}
}
sm.lastdid = newdid
}
func (sm *summer_t) equation() string {
sm._init()
ret := ""
sep := ""
for sym, sizes := range sm.symsize {
ret += sep + sym
sep2 := " "
for size, count := range sizes {
ret += sep2 + fmt.Sprintf("(%v) * %v", count, size)
sep2 = " + "
}
sep = " + "
}
for size, count := range sm.sizes {
ret += sep + fmt.Sprintf("%v * %v", count, size)
sep = " + "
}
return ret
}
func human(_bytes int) string {
bytes := float64(_bytes)
div := float64(1)
order := 0
for bytes/div > 1024 {
div *= 1024
order++
}
sufs := map[int]string{0: "B", 1: "kB", 2: "MB", 3: "GB", 4: "TB",
5: "PB"}
return fmt.Sprintf("%.2f%s", bytes/div, sufs[order])
}
// map of callees to list of impossible callers.
var _impossible = map[string][]string{
//"(*main.pgcache_t).flush" : []string{"(*main.pgcache_t).evict"},
}
func ignore(f *ssa.Function, cs *callstack_t) bool {
me := realname(f)
for _, t := range []string{"fmt.", "strconv."} {
if strings.Contains(me, t) {
return true
}
}
// prevent programmer-supplied impossible executions
if imp, ok := _impossible[me]; ok {
//fmt.Printf("IMPS %v\n", imp)
//for i := range cs.cs {
// fmt.Printf("\t%v\n", cs.cs[i])
//}
for i := range imp {
if cs.calledfrom(imp[i]) {
fmt.Printf("FORBID %v from %v\n", f, imp[i])
return true
}
}
}
return false
}
func callidests(node *callgraph.Node,
in ssa.CallInstruction) []*callgraph.Node {
target := in.Common()
var ret []*callgraph.Node
for _, e := range node.Out {
// XXX how to identify the particular call instruction from
// ssa.CallInstruction provided by callgraph.Edge? is comparing
// their ssa.CallCommons the correct way?
tt := e.Site.Common()
if tt != target {
continue
}
ret = append(ret, e.Callee)
}
return ret
}
// this function finds which callee function allocates most for a single
// callsite. first bool is whether this call may cause recursion, second is
// whether this callgraph node had an unvisited edge that should be visited for
// this call instruction.
func (ha *halp_t) maxcall(callees []*callgraph.Node, parptrs map[ssa.Value]bool,
cs *callstack_t, iscall bool) (*calls_t, bool, bool) {
var calls *calls_t
found := false
rec := false
var max int
syms := make(map[string]bool)
for _, node := range callees {
if ha.funcvisit[node] {
rec = true
// cycles in the call graph are problematic because our
// tool doesn't know an upper bound on the number of
// times the functions in the cycle are executed.
// although this tool (conservatively) considers
// channel sends as function calls, the receiver
// doesn't actually restart the function call, thus it
// isn't really a cycle in the call graph. therefore:
// don't warn about them.
if iscall {
me := cs.cs[len(cs.cs)-1]
k := fmt.Sprintf("%v -> %v\n", me, node.Func)
var strs []string
for _, e := range cs.cs {
strs = append(strs, e)
}
ha.recurses[k] = strs
}
continue
}
if ignore(node.Func, cs) {
//me := node.Func.String()
//fmt.Printf("**** SKIP %s\n", me)
continue
}
found = true
var tc *calls_t
if v, ok := ha.memos[node]; ok {
tc = v
} else {
tc = ha.alloctree(node, parptrs, cs)
if ha.nomemo[node] {
// XXX alloctree() used to run once per
// function, but can calculate recursive
// functions multiple times now.
for _, bb := range node.Func.Blocks {
delete(ha.heads, bb)
delete(ha.usedbounds, bb)
}
} else {
ha.memos[node] = tc
}
}
tc.givesym(syms)
newmax := tc.total(parptrs)
if newmax >= max {
max = newmax
calls = tc
}
}
if found && calls == nil {
panic("wtf")
}
if calls != nil {
for s := range syms {
calls.symloops[s] = true
}
}
return calls, rec, found
}
func revblksrc(blk *ssa.BasicBlock) (token.Position, bool) {
v := make(map[*ssa.BasicBlock]bool)
return revblksrc1(blk, v)
}
func revblksrc1(blk *ssa.BasicBlock,
v map[*ssa.BasicBlock]bool) (token.Position, bool) {
var zt token.Position
if v[blk] {
return zt, false
}
v[blk] = true
for i := len(blk.Instrs) - 1; i >= 0; i-- {
pos := blk.Instrs[i].Pos()
if pos != token.NoPos {
ret := blk.Instrs[0].Parent().Prog.Fset.Position(pos)
return ret, true
}
}
for _, e := range blk.Preds {
if ret, ok := revblksrc1(e, v); ok {
return ret, true
}
}
return zt, false
}
func readnum(msg string) int {
var ret int
again:
fmt.Print(msg)
//fmt.Printf("\n");return 1
dur := bufio.NewReader(os.Stdin)
str, err := dur.ReadString('\n')
if err != nil {
goto again
}
ret, err = strconv.Atoi(str[:len(str)-1])
if err != nil {
goto again
}
return ret
}
func (ha *halp_t) suminstructions(node *callgraph.Node, blk *ssa.BasicBlock,
parptrs map[ssa.Value]bool, calls *calls_t, cs *callstack_t) {
for _, ip := range blk.Instrs {
switch v := ip.(type) {
case *ssa.Go:
// sum of all stack frames in packages main, common,
// and fs
maxstack := 80 << 10
calls.addalloc(v.Common().Value, maxstack)
case *ssa.Defer:
comm := v.Common()
defsz := 64 + len(comm.Args) * 8
// ssa.Defer.Value is an uninitialized *ssa.Call?
calls.addalloc(comm.Value, defsz)
case *ssa.Send, *ssa.Select:
callees := chandests(ha.cg, v)
for _, ce := range callees {
ha.chanfuncs[ce.Func] = true
}
maxc, _, found := ha.maxcall(callees, parptrs, cs, false)
if found {
// ignore sends that don't allocate
if maxc.total(parptrs) > 0 {
calls.addchild(maxc)
}
}
case ssa.CallInstruction:
// find which function for this call site allocates
// most
callees := callidests(node, v)
maxc, rec, found := ha.maxcall(callees, parptrs, cs, true)
if found {
// ignore calls that don't allocate
if maxc.total(parptrs) > 0 {
calls.addchild(maxc)
}
} else if !rec {
//fmt.Printf("failed for: %v\n", v)
var str string
switch tt := v.Common().Value.(type) {
case *ssa.Builtin:
str = tt.Name()
if strings.Contains(str, "append") {
if str != "append" {
panic("nein")
}
val := v.Value()
num := slicebound(val, cs)
sz := slicesz(val, num)
calls.addalloc(val, sz)
}
case *ssa.Function:
str = tt.String()
default:
//if strings.Contains(node.Func.String(),
// "brefcache_t") {
// continue
//}
sl := node.Func.Prog.Fset.Position(v.Pos())
fmt.Printf("%v %T %v %v\n", v, v.Common().Value, v.Common().Method, sl)
fmt.Printf("callees: %v\n", callees)
fmt.Printf("callees2: %v\n", callgraph.CalleesOf(node))
fmt.Printf("node.Out: %v\n", node.Out)
cs.csdump("CS:")
panic("which call?")
}
ha.fakefunc[str] = true
}
case *ssa.MakeChan:
calls.addalloc(v, chansz(v))
case *ssa.MakeMap:
num := mapbound(v)
elm := v.Type().(*types.Map).Elem()
key := v.Type().(*types.Map).Key()
sz := num * (array_align(elm) + array_align(key))
calls.addalloc(v, sz)
case *ssa.MakeSlice:
num := slicebound(v, cs)
calls.addalloc(v, slicesz(v, num))
case *ssa.Alloc:
if v.Heap {
tp := v.Type().(*types.Pointer)
ut := tp.Elem()
calls.addalloc(v, array_align(ut))
}
}
}
}
func _looppos(nat *natl_t) token.Position {
for _, in := range nat.head.Instrs {
p := inpos(in)
if p.IsValid() {
return p
}
}
for blk := range nat.lblock {
for _, in := range blk.Instrs {
p := inpos(in)
if p.IsValid() {
return p
}
}
}
panic("no valid loop position?")
}
func (ha *halp_t) loopcalc(node *callgraph.Node, parptrs map[ssa.Value]bool,
cs *callstack_t) {
floops := funcloops(node.Func)
// calculate each loop's allocations and iterations in post-order since
// we must calculate the cost of a inner loops before we can calculate
// the cost of the outer loops.
floops.iter(func(nat *natl_t) {
if ha.heads[nat.head] != nil {
panic(">1 loops per head after loop merge")
}
ha.heads[nat.head] = nat
lcalls := newcalls(node.Func)
for bb := range nat.lblock {
ha.suminstructions(node, bb, parptrs, lcalls, cs)
}
// include nested loops in cost
for _, nest := range nat.nests {
lcalls.merge(nest.lcalls)
}
nat.lcalls = lcalls
// don't ask the programmer to provide a bound for loops that
// create no reachable allocations from the containing
// function.
if nat.lcalls._mysum(parptrs) == 0 {
//if nat.lcalls._mysum(funcreach[node.Func]) != 0 {
// panic("oh shit")
//}
// mark BOUND call as used, if it exists, to prevent
// outer loop from getting confused
nat.boundcall(ha.pkgs, ha.usedbounds)
return
}
var iters int
var name string
it, tname, sym, ok := nat.boundcall(ha.pkgs, ha.usedbounds)
if ok {
iters = it
name = tname
} else {
iters = loopbound(node.Func.String(),
_looppos(nat))
name = "MANUAL"
}
if iters == INF {
pos := _looppos(nat)
ha.infloops[pos] = true
}
if sym != "" {
nat.lcalls.symloops[sym] = true
}
// this overestimates allocations since this loopmulti()
// multiplies the number of allocations which aren't in any
// parent's pointer set too, relying on calls_t.total() to
// ignore such allocations.
nat.lcalls.loopmult(iters, name, sym)
})
//floops.dump()
}
var dummyfunc ssa.Function
// XXX don't need to pass parent pointers down since a callee's ptr set must
// include all ptrs of parent that are stored to?
//func ptrsetadd(parptrs map[ssa.Value]bool,
// me *ssa.Function) map[ssa.Value]bool {
// // copy ptrs instead of adding to parptrs set to avoid the trouble of
// // removing this functions pointers from the set once we are done. this
// // function's pointer set may overlap with a parent's and such pointers