-
Notifications
You must be signed in to change notification settings - Fork 17.9k
/
Copy pathesc.go
2280 lines (2021 loc) · 64.3 KB
/
esc.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
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gc
import (
"cmd/compile/internal/types"
"fmt"
"strconv"
"strings"
)
// Escape analysis.
// An escape analysis pass for a set of functions. The
// analysis assumes that closures and the functions in which
// they appear are analyzed together, so that the aliasing
// between their variables can be modeled more precisely.
//
// First escfunc, esc and escassign recurse over the ast of
// each function to dig out flow(dst,src) edges between any
// pointer-containing nodes and store those edges in
// e.nodeEscState(dst).Flowsrc. For values assigned to a
// variable in an outer scope or used as a return value,
// they store a flow(theSink, src) edge to a fake node 'the
// Sink'. For variables referenced in closures, an edge
// flow(closure, &var) is recorded and the flow of a closure
// itself to an outer scope is tracked the same way as other
// variables.
//
// Then escflood walks the graph in destination-to-source
// order, starting at theSink, propagating a computed
// "escape level", and tags as escaping values it can
// reach that are either & (address-taken) nodes or new(T),
// and tags pointer-typed or pointer-containing function
// parameters it can reach as leaking.
//
// If a value's address is taken but the address does not escape,
// then the value can stay on the stack. If the value new(T) does
// not escape, then new(T) can be rewritten into a stack allocation.
// The same is true of slice literals.
func escapes(all []*Node) {
visitBottomUp(all, escAnalyze)
}
const (
EscFuncUnknown = 0 + iota
EscFuncPlanned
EscFuncStarted
EscFuncTagged
)
// A Level encodes the reference state and context applied to
// (stack, heap) allocated memory.
//
// value is the overall sum of *(1) and &(-1) operations encountered
// along a path from a destination (sink, return value) to a source
// (allocation, parameter).
//
// suffixValue is the maximum-copy-started-suffix-level on
// a flow path from a sink/destination. That is, a value
// with suffixValue N is guaranteed to be dereferenced at least
// N deep (chained applications of DOTPTR or IND or INDEX)
// before the result is assigned to a sink.
//
// For example, suppose x is a pointer to T, declared type T struct { left, right *T }
// sink = x.left.left --> level(x)=2, x is reached via two dereferences (DOTPTR) and does not escape to sink.
// sink = &T{right:x} --> level(x)=-1, x is accessible from sink via one "address of"
// sink = &T{right:&T{right:x}} --> level(x)=-2, x is accessible from sink via two "address of"
//
// However, in the next example x's level value and suffixValue differ:
// sink = &T{right:&T{right:x.left}} --> level(x).value=-1, level(x).suffixValue=1
// The positive suffixValue indicates that x is NOT accessible
// from sink. Without a separate suffixValue to capture this, x would
// appear to escape because its "value" would be -1. (The copy
// operations are sometimes implicit in the source code; in this case,
// the value of x.left was copied into a field of an newly allocated T).
//
// Each node's level (value and suffixValue) is the maximum for
// all flow paths from (any) sink to that node.
// There's one of these for each Node, and the integer values
// rarely exceed even what can be stored in 4 bits, never mind 8.
type Level struct {
value, suffixValue int8
}
// There are loops in the escape graph,
// causing arbitrary recursion into deeper and deeper
// levels. Cut this off safely by making minLevel sticky:
// once you get that deep, you cannot go down any further
// but you also cannot go up any further. This is a
// conservative fix. Making minLevel smaller (more negative)
// would handle more complex chains of indirections followed
// by address-of operations, at the cost of repeating the
// traversal once for each additional allowed level when a
// loop is encountered. Using -2 suffices to pass all the
// tests we have written so far, which we assume matches the
// level of complexity we want the escape analysis code to
// handle.
const MinLevel = -2
func (l Level) int() int {
return int(l.value)
}
func levelFrom(i int) Level {
if i <= MinLevel {
return Level{value: MinLevel}
}
return Level{value: int8(i)}
}
func satInc8(x int8) int8 {
if x == 127 {
return 127
}
return x + 1
}
func min8(a, b int8) int8 {
if a < b {
return a
}
return b
}
func max8(a, b int8) int8 {
if a > b {
return a
}
return b
}
// inc returns the level l + 1, representing the effect of an indirect (*) operation.
func (l Level) inc() Level {
if l.value <= MinLevel {
return Level{value: MinLevel}
}
return Level{value: satInc8(l.value), suffixValue: satInc8(l.suffixValue)}
}
// dec returns the level l - 1, representing the effect of an address-of (&) operation.
func (l Level) dec() Level {
if l.value <= MinLevel {
return Level{value: MinLevel}
}
return Level{value: l.value - 1, suffixValue: l.suffixValue - 1}
}
// copy returns the level for a copy of a value with level l.
// The resulting suffixValue is at least zero, or larger if it was already larger.
func (l Level) copy() Level {
return Level{value: l.value, suffixValue: max8(l.suffixValue, 0)}
}
func (l1 Level) min(l2 Level) Level {
return Level{
value: min8(l1.value, l2.value),
suffixValue: min8(l1.suffixValue, l2.suffixValue)}
}
// guaranteedDereference returns the number of dereferences
// applied to a pointer before addresses are taken/generated.
// This is the maximum level computed from path suffixes starting
// with copies where paths flow from destination to source.
func (l Level) guaranteedDereference() int {
return int(l.suffixValue)
}
// An EscStep documents one step in the path from memory
// that is heap allocated to the (alleged) reason for the
// heap allocation.
type EscStep struct {
src, dst *Node // the endpoints of this edge in the escape-to-heap chain.
where *Node // sometimes the endpoints don't match source locations; set 'where' to make that right
parent *EscStep // used in flood to record path
why string // explanation for this step in the escape-to-heap chain
busy bool // used in prevent to snip cycles.
}
type NodeEscState struct {
Curfn *Node
Flowsrc []EscStep // flow(this, src)
Retval Nodes // on OCALLxxx, list of dummy return values
Loopdepth int32 // -1: global, 0: return variables, 1:function top level, increased inside function for every loop or label to mark scopes
Level Level
Walkgen uint32
Maxextraloopdepth int32
}
func (e *EscState) nodeEscState(n *Node) *NodeEscState {
if nE, ok := n.Opt().(*NodeEscState); ok {
return nE
}
if n.Opt() != nil {
Fatalf("nodeEscState: opt in use (%T)", n.Opt())
}
nE := &NodeEscState{
Curfn: Curfn,
}
n.SetOpt(nE)
e.opts = append(e.opts, n)
return nE
}
func (e *EscState) track(n *Node) {
if Curfn == nil {
Fatalf("EscState.track: Curfn nil")
}
n.Esc = EscNone // until proven otherwise
nE := e.nodeEscState(n)
nE.Loopdepth = e.loopdepth
e.noesc = append(e.noesc, n)
}
// Escape constants are numbered in order of increasing "escapiness"
// to help make inferences be monotonic. With the exception of
// EscNever which is sticky, eX < eY means that eY is more exposed
// than eX, and hence replaces it in a conservative analysis.
const (
EscUnknown = iota
EscNone // Does not escape to heap, result, or parameters.
EscReturn // Is returned or reachable from returned.
EscHeap // Reachable from the heap
EscNever // By construction will not escape.
EscBits = 3
EscMask = (1 << EscBits) - 1
EscContentEscapes = 1 << EscBits // value obtained by indirect of parameter escapes to heap
EscReturnBits = EscBits + 1
// Node.esc encoding = | escapeReturnEncoding:(width-4) | contentEscapes:1 | escEnum:3
)
// escMax returns the maximum of an existing escape value
// (and its additional parameter flow flags) and a new escape type.
func escMax(e, etype uint16) uint16 {
if e&EscMask >= EscHeap {
// normalize
if e&^EscMask != 0 {
Fatalf("Escape information had unexpected return encoding bits (w/ EscHeap, EscNever), e&EscMask=%v", e&EscMask)
}
}
if e&EscMask > etype {
return e
}
if etype == EscNone || etype == EscReturn {
return (e &^ EscMask) | etype
}
return etype
}
// For each input parameter to a function, the escapeReturnEncoding describes
// how the parameter may leak to the function's outputs. This is currently the
// "level" of the leak where level is 0 or larger (negative level means stored into
// something whose address is returned -- but that implies stored into the heap,
// hence EscHeap, which means that the details are not currently relevant. )
const (
bitsPerOutputInTag = 3 // For each output, the number of bits for a tag
bitsMaskForTag = uint16(1<<bitsPerOutputInTag) - 1 // The bit mask to extract a single tag.
maxEncodedLevel = int(bitsMaskForTag - 1) // The largest level that can be stored in a tag.
)
type EscState struct {
// Fake node that all
// - return values and output variables
// - parameters on imported functions not marked 'safe'
// - assignments to global variables
// flow to.
theSink Node
dsts []*Node // all dst nodes
loopdepth int32 // for detecting nested loop scopes
pdepth int // for debug printing in recursions.
dstcount int // diagnostic
edgecount int // diagnostic
noesc []*Node // list of possible non-escaping nodes, for printing
recursive bool // recursive function or group of mutually recursive functions.
opts []*Node // nodes with .Opt initialized
walkgen uint32
}
func newEscState(recursive bool) *EscState {
e := new(EscState)
e.theSink.Op = ONAME
e.theSink.Orig = &e.theSink
e.theSink.SetClass(PEXTERN)
e.theSink.Sym = lookup(".sink")
e.nodeEscState(&e.theSink).Loopdepth = -1
e.recursive = recursive
return e
}
func (e *EscState) stepWalk(dst, src *Node, why string, parent *EscStep) *EscStep {
// TODO: keep a cache of these, mark entry/exit in escwalk to avoid allocation
// Or perhaps never mind, since it is disabled unless printing is on.
// We may want to revisit this, since the EscStep nodes would make
// an excellent replacement for the poorly-separated graph-build/graph-flood
// stages.
if Debug['m'] == 0 {
return nil
}
return &EscStep{src: src, dst: dst, why: why, parent: parent}
}
func (e *EscState) stepAssign(step *EscStep, dst, src *Node, why string) *EscStep {
if Debug['m'] == 0 {
return nil
}
if step != nil { // Caller may have known better.
if step.why == "" {
step.why = why
}
if step.dst == nil {
step.dst = dst
}
if step.src == nil {
step.src = src
}
return step
}
return &EscStep{src: src, dst: dst, why: why}
}
func (e *EscState) stepAssignWhere(dst, src *Node, why string, where *Node) *EscStep {
if Debug['m'] == 0 {
return nil
}
return &EscStep{src: src, dst: dst, why: why, where: where}
}
// funcSym returns fn.Func.Nname.Sym if no nils are encountered along the way.
func funcSym(fn *Node) *types.Sym {
if fn == nil || fn.Func.Nname == nil {
return nil
}
return fn.Func.Nname.Sym
}
// curfnSym returns n.Curfn.Nname.Sym if no nils are encountered along the way.
func (e *EscState) curfnSym(n *Node) *types.Sym {
nE := e.nodeEscState(n)
return funcSym(nE.Curfn)
}
func escAnalyze(all []*Node, recursive bool) {
e := newEscState(recursive)
for _, n := range all {
if n.Op == ODCLFUNC {
n.Esc = EscFuncPlanned
if Debug['m'] > 3 {
Dump("escAnalyze", n)
}
}
}
// flow-analyze functions
for _, n := range all {
if n.Op == ODCLFUNC {
e.escfunc(n)
}
}
// visit the upstream of each dst, mark address nodes with
// addrescapes, mark parameters unsafe
escapes := make([]uint16, len(e.dsts))
for i, n := range e.dsts {
escapes[i] = n.Esc
}
for _, n := range e.dsts {
e.escflood(n)
}
for {
done := true
for i, n := range e.dsts {
if n.Esc != escapes[i] {
done = false
if Debug['m'] > 2 {
Warnl(n.Pos, "Reflooding %v %S", e.curfnSym(n), n)
}
escapes[i] = n.Esc
e.escflood(n)
}
}
if done {
break
}
}
// for all top level functions, tag the typenodes corresponding to the param nodes
for _, n := range all {
if n.Op == ODCLFUNC {
e.esctag(n)
}
}
if Debug['m'] != 0 {
for _, n := range e.noesc {
if n.Esc == EscNone {
Warnl(n.Pos, "%v %S does not escape", e.curfnSym(n), n)
}
}
}
for _, x := range e.opts {
x.SetOpt(nil)
}
}
func (e *EscState) escfunc(fn *Node) {
if fn.Esc != EscFuncPlanned {
Fatalf("repeat escfunc %v", fn.Func.Nname)
}
fn.Esc = EscFuncStarted
saveld := e.loopdepth
e.loopdepth = 1
savefn := Curfn
Curfn = fn
for _, ln := range Curfn.Func.Dcl {
if ln.Op != ONAME {
continue
}
lnE := e.nodeEscState(ln)
switch ln.Class() {
// out params are in a loopdepth between the sink and all local variables
case PPARAMOUT:
lnE.Loopdepth = 0
case PPARAM:
lnE.Loopdepth = 1
if ln.Type != nil && !types.Haspointers(ln.Type) {
break
}
if Curfn.Nbody.Len() == 0 && !Curfn.Noescape() {
ln.Esc = EscHeap
} else {
ln.Esc = EscNone // prime for escflood later
}
e.noesc = append(e.noesc, ln)
}
}
// in a mutually recursive group we lose track of the return values
if e.recursive {
for _, ln := range Curfn.Func.Dcl {
if ln.Op == ONAME && ln.Class() == PPARAMOUT {
e.escflows(&e.theSink, ln, e.stepAssign(nil, ln, ln, "returned from recursive function"))
}
}
}
e.escloopdepthlist(Curfn.Nbody)
e.esclist(Curfn.Nbody, Curfn)
Curfn = savefn
e.loopdepth = saveld
}
// Mark labels that have no backjumps to them as not increasing e.loopdepth.
// Walk hasn't generated (goto|label).Left.Sym.Label yet, so we'll cheat
// and set it to one of the following two. Then in esc we'll clear it again.
var (
looping Node
nonlooping Node
)
func (e *EscState) escloopdepthlist(l Nodes) {
for _, n := range l.Slice() {
e.escloopdepth(n)
}
}
func (e *EscState) escloopdepth(n *Node) {
if n == nil {
return
}
e.escloopdepthlist(n.Ninit)
switch n.Op {
case OLABEL:
if n.Sym == nil {
Fatalf("esc:label without label: %+v", n)
}
// Walk will complain about this label being already defined, but that's not until
// after escape analysis. in the future, maybe pull label & goto analysis out of walk and put before esc
n.Sym.Label = asTypesNode(&nonlooping)
case OGOTO:
if n.Sym == nil {
Fatalf("esc:goto without label: %+v", n)
}
// If we come past one that's uninitialized, this must be a (harmless) forward jump
// but if it's set to nonlooping the label must have preceded this goto.
if asNode(n.Sym.Label) == &nonlooping {
n.Sym.Label = asTypesNode(&looping)
}
}
e.escloopdepth(n.Left)
e.escloopdepth(n.Right)
e.escloopdepthlist(n.List)
e.escloopdepthlist(n.Nbody)
e.escloopdepthlist(n.Rlist)
}
func (e *EscState) esclist(l Nodes, parent *Node) {
for _, n := range l.Slice() {
e.esc(n, parent)
}
}
func (e *EscState) isSliceSelfAssign(dst, src *Node) bool {
// Detect the following special case.
//
// func (b *Buffer) Foo() {
// n, m := ...
// b.buf = b.buf[n:m]
// }
//
// This assignment is a no-op for escape analysis,
// it does not store any new pointers into b that were not already there.
// However, without this special case b will escape, because we assign to OIND/ODOTPTR.
// Here we assume that the statement will not contain calls,
// that is, that order will move any calls to init.
// Otherwise base ONAME value could change between the moments
// when we evaluate it for dst and for src.
// dst is ONAME dereference.
if dst.Op != ODEREF && dst.Op != ODOTPTR || dst.Left.Op != ONAME {
return false
}
// src is a slice operation.
switch src.Op {
case OSLICE, OSLICE3, OSLICESTR:
// OK.
case OSLICEARR, OSLICE3ARR:
// Since arrays are embedded into containing object,
// slice of non-pointer array will introduce a new pointer into b that was not already there
// (pointer to b itself). After such assignment, if b contents escape,
// b escapes as well. If we ignore such OSLICEARR, we will conclude
// that b does not escape when b contents do.
//
// Pointer to an array is OK since it's not stored inside b directly.
// For slicing an array (not pointer to array), there is an implicit OADDR.
// We check that to determine non-pointer array slicing.
if src.Left.Op == OADDR {
return false
}
default:
return false
}
// slice is applied to ONAME dereference.
if src.Left.Op != ODEREF && src.Left.Op != ODOTPTR || src.Left.Left.Op != ONAME {
return false
}
// dst and src reference the same base ONAME.
return dst.Left == src.Left.Left
}
// isSelfAssign reports whether assignment from src to dst can
// be ignored by the escape analysis as it's effectively a self-assignment.
func (e *EscState) isSelfAssign(dst, src *Node) bool {
if e.isSliceSelfAssign(dst, src) {
return true
}
// Detect trivial assignments that assign back to the same object.
//
// It covers these cases:
// val.x = val.y
// val.x[i] = val.y[j]
// val.x1.x2 = val.x1.y2
// ... etc
//
// These assignments do not change assigned object lifetime.
if dst == nil || src == nil || dst.Op != src.Op {
return false
}
switch dst.Op {
case ODOT, ODOTPTR:
// Safe trailing accessors that are permitted to differ.
case OINDEX:
if e.mayAffectMemory(dst.Right) || e.mayAffectMemory(src.Right) {
return false
}
default:
return false
}
// The expression prefix must be both "safe" and identical.
return samesafeexpr(dst.Left, src.Left)
}
// mayAffectMemory reports whether n evaluation may affect program memory state.
// If expression can't affect it, then it can be safely ignored by the escape analysis.
func (e *EscState) mayAffectMemory(n *Node) bool {
// We may want to use "memory safe" black list instead of general
// "side-effect free", which can include all calls and other ops
// that can affect allocate or change global state.
// It's safer to start from a whitelist for now.
//
// We're ignoring things like division by zero, index out of range,
// and nil pointer dereference here.
switch n.Op {
case ONAME, OCLOSUREVAR, OLITERAL:
return false
// Left+Right group.
case OINDEX, OADD, OSUB, OOR, OXOR, OMUL, OLSH, ORSH, OAND, OANDNOT, ODIV, OMOD:
return e.mayAffectMemory(n.Left) || e.mayAffectMemory(n.Right)
// Left group.
case ODOT, ODOTPTR, ODEREF, OCONVNOP, OCONV, OLEN, OCAP,
ONOT, OBITNOT, OPLUS, ONEG, OALIGNOF, OOFFSETOF, OSIZEOF:
return e.mayAffectMemory(n.Left)
default:
return true
}
}
func (e *EscState) esc(n *Node, parent *Node) {
if n == nil {
return
}
lno := setlineno(n)
// ninit logically runs at a different loopdepth than the rest of the for loop.
e.esclist(n.Ninit, n)
if n.Op == OFOR || n.Op == OFORUNTIL || n.Op == ORANGE {
e.loopdepth++
}
// type switch variables have no ODCL.
// process type switch as declaration.
// must happen before processing of switch body,
// so before recursion.
if n.Op == OSWITCH && n.Left != nil && n.Left.Op == OTYPESW {
for _, cas := range n.List.Slice() { // cases
// it.N().Rlist is the variable per case
if cas.Rlist.Len() != 0 {
e.nodeEscState(cas.Rlist.First()).Loopdepth = e.loopdepth
}
}
}
// Big stuff and non-constant-sized stuff escapes unconditionally.
// "Big" conditions that were scattered around in walk have been
// gathered here.
if n.Esc != EscHeap && n.Type != nil &&
(n.Type.Width > maxStackVarSize ||
(n.Op == ONEW || n.Op == OPTRLIT) && n.Type.Elem().Width >= maxImplicitStackVarSize ||
n.Op == OMAKESLICE && !isSmallMakeSlice(n)) {
// isSmallMakeSlice returns false for non-constant len/cap.
// If that's the case, print a more accurate escape reason.
var msgVerb, escapeMsg string
if n.Op == OMAKESLICE && (!Isconst(n.Left, CTINT) || !Isconst(n.Right, CTINT)) {
msgVerb, escapeMsg = "has ", "non-constant size"
} else {
msgVerb, escapeMsg = "is ", "too large for stack"
}
if Debug['m'] > 2 {
Warnl(n.Pos, "%v "+msgVerb+escapeMsg, n)
}
n.Esc = EscHeap
addrescapes(n)
e.escassignSinkWhy(n, n, escapeMsg) // TODO category: tooLarge
}
e.esc(n.Left, n)
if n.Op == ORANGE {
// ORANGE node's Right is evaluated before the loop
e.loopdepth--
}
e.esc(n.Right, n)
if n.Op == ORANGE {
e.loopdepth++
}
e.esclist(n.Nbody, n)
e.esclist(n.List, n)
e.esclist(n.Rlist, n)
if n.Op == OFOR || n.Op == OFORUNTIL || n.Op == ORANGE {
e.loopdepth--
}
if Debug['m'] > 2 {
fmt.Printf("%v:[%d] %v esc: %v\n", linestr(lineno), e.loopdepth, funcSym(Curfn), n)
}
opSwitch:
switch n.Op {
// Record loop depth at declaration.
case ODCL:
if n.Left != nil {
e.nodeEscState(n.Left).Loopdepth = e.loopdepth
}
case OLABEL:
switch asNode(n.Sym.Label) {
case &nonlooping:
if Debug['m'] > 2 {
fmt.Printf("%v:%v non-looping label\n", linestr(lineno), n)
}
case &looping:
if Debug['m'] > 2 {
fmt.Printf("%v: %v looping label\n", linestr(lineno), n)
}
e.loopdepth++
}
n.Sym.Label = nil
case ORANGE:
if n.List.Len() >= 2 {
// Everything but fixed array is a dereference.
// If fixed array is really the address of fixed array,
// it is also a dereference, because it is implicitly
// dereferenced (see #12588)
if n.Type.IsArray() &&
!(n.Right.Type.IsPtr() && types.Identical(n.Right.Type.Elem(), n.Type)) {
e.escassignWhyWhere(n.List.Second(), n.Right, "range", n)
} else {
e.escassignDereference(n.List.Second(), n.Right, e.stepAssignWhere(n.List.Second(), n.Right, "range-deref", n))
}
}
case OSWITCH:
if n.Left != nil && n.Left.Op == OTYPESW {
for _, cas := range n.List.Slice() {
// cases
// n.Left.Right is the argument of the .(type),
// it.N().Rlist is the variable per case
if cas.Rlist.Len() != 0 {
e.escassignWhyWhere(cas.Rlist.First(), n.Left.Right, "switch case", n)
}
}
}
case OAS, OASOP:
// Filter out some no-op assignments for escape analysis.
if e.isSelfAssign(n.Left, n.Right) {
if Debug['m'] != 0 {
Warnl(n.Pos, "%v ignoring self-assignment in %S", e.curfnSym(n), n)
}
break
}
e.escassign(n.Left, n.Right, e.stepAssignWhere(nil, nil, "", n))
case OAS2: // x,y = a,b
if n.List.Len() == n.Rlist.Len() {
rs := n.Rlist.Slice()
where := n
for i, n := range n.List.Slice() {
e.escassignWhyWhere(n, rs[i], "assign-pair", where)
}
}
case OAS2RECV: // v, ok = <-ch
e.escassignWhyWhere(n.List.First(), n.Rlist.First(), "assign-pair-receive", n)
case OAS2MAPR: // v, ok = m[k]
e.escassignWhyWhere(n.List.First(), n.Rlist.First(), "assign-pair-mapr", n)
case OAS2DOTTYPE: // v, ok = x.(type)
e.escassignWhyWhere(n.List.First(), n.Rlist.First(), "assign-pair-dot-type", n)
case OSEND: // ch <- x
e.escassignSinkWhy(n, n.Right, "send")
case ODEFER:
if e.loopdepth == 1 { // top level
break
}
// arguments leak out of scope
// TODO: leak to a dummy node instead
// defer f(x) - f and x escape
e.escassignSinkWhy(n, n.Left.Left, "defer func")
e.escassignSinkWhy(n, n.Left.Right, "defer func ...") // ODDDARG for call
for _, arg := range n.Left.List.Slice() {
e.escassignSinkWhy(n, arg, "defer func arg")
}
case OGO:
// go f(x) - f and x escape
e.escassignSinkWhy(n, n.Left.Left, "go func")
e.escassignSinkWhy(n, n.Left.Right, "go func ...") // ODDDARG for call
for _, arg := range n.Left.List.Slice() {
e.escassignSinkWhy(n, arg, "go func arg")
}
case OCALLMETH, OCALLFUNC, OCALLINTER:
e.esccall(n, parent)
// esccall already done on n.Rlist.First()
// tie its Retval to n.List
case OAS2FUNC: // x,y = f()
rs := e.nodeEscState(n.Rlist.First()).Retval.Slice()
where := n
for i, n := range n.List.Slice() {
if i >= len(rs) {
break
}
e.escassignWhyWhere(n, rs[i], "assign-pair-func-call", where)
}
if n.List.Len() != len(rs) {
Fatalf("esc oas2func")
}
case ORETURN:
retList := n.List
if retList.Len() == 1 && Curfn.Type.NumResults() > 1 {
// OAS2FUNC in disguise
// esccall already done on n.List.First()
// tie e.nodeEscState(n.List.First()).Retval to Curfn.Func.Dcl PPARAMOUT's
retList = e.nodeEscState(n.List.First()).Retval
}
i := 0
for _, lrn := range Curfn.Func.Dcl {
if i >= retList.Len() {
break
}
if lrn.Op != ONAME || lrn.Class() != PPARAMOUT {
continue
}
e.escassignWhyWhere(lrn, retList.Index(i), "return", n)
i++
}
if i < retList.Len() {
Fatalf("esc return list")
}
// Argument could leak through recover.
case OPANIC:
e.escassignSinkWhy(n, n.Left, "panic")
case OAPPEND:
if !n.IsDDD() {
for _, nn := range n.List.Slice()[1:] {
e.escassignSinkWhy(n, nn, "appended to slice") // lose track of assign to dereference
}
} else {
// append(slice1, slice2...) -- slice2 itself does not escape, but contents do.
slice2 := n.List.Second()
e.escassignDereference(&e.theSink, slice2, e.stepAssignWhere(n, slice2, "appended slice...", n)) // lose track of assign of dereference
if Debug['m'] > 3 {
Warnl(n.Pos, "%v special treatment of append(slice1, slice2...) %S", e.curfnSym(n), n)
}
}
e.escassignDereference(&e.theSink, n.List.First(), e.stepAssignWhere(n, n.List.First(), "appendee slice", n)) // The original elements are now leaked, too
case OCOPY:
e.escassignDereference(&e.theSink, n.Right, e.stepAssignWhere(n, n.Right, "copied slice", n)) // lose track of assign of dereference
case OCONV, OCONVNOP:
e.escassignWhyWhere(n, n.Left, "converted", n)
case OCONVIFACE:
e.track(n)
e.escassignWhyWhere(n, n.Left, "interface-converted", n)
case OARRAYLIT:
// Link values to array
for _, elt := range n.List.Slice() {
if elt.Op == OKEY {
elt = elt.Right
}
e.escassign(n, elt, e.stepAssignWhere(n, elt, "array literal element", n))
}
case OSLICELIT:
// Slice is not leaked until proven otherwise
e.track(n)
// Link values to slice
for _, elt := range n.List.Slice() {
if elt.Op == OKEY {
elt = elt.Right
}
e.escassign(n, elt, e.stepAssignWhere(n, elt, "slice literal element", n))
}
// Link values to struct.
case OSTRUCTLIT:
for _, elt := range n.List.Slice() {
e.escassignWhyWhere(n, elt.Left, "struct literal element", n)
}
case OPTRLIT:
e.track(n)
// Link OSTRUCTLIT to OPTRLIT; if OPTRLIT escapes, OSTRUCTLIT elements do too.
e.escassignWhyWhere(n, n.Left, "pointer literal [assign]", n)
case OCALLPART:
e.track(n)
// Contents make it to memory, lose track.
e.escassignSinkWhy(n, n.Left, "call part")
case OMAPLIT:
e.track(n)
// Keys and values make it to memory, lose track.
for _, elt := range n.List.Slice() {
e.escassignSinkWhy(n, elt.Left, "map literal key")
e.escassignSinkWhy(n, elt.Right, "map literal value")
}
case OCLOSURE:
// Link addresses of captured variables to closure.
for _, v := range n.Func.Closure.Func.Cvars.Slice() {
if v.Op == OXXX { // unnamed out argument; see dcl.go:/^funcargs
continue
}
a := v.Name.Defn
if !v.Name.Byval() {
a = nod(OADDR, a, nil)
a.Pos = v.Pos
e.nodeEscState(a).Loopdepth = e.loopdepth
a = typecheck(a, ctxExpr)
}
e.escassignWhyWhere(n, a, "captured by a closure", n)
}
fallthrough
case OMAKECHAN,
OMAKEMAP,
OMAKESLICE,
ONEW,
ORUNES2STR,
OBYTES2STR,
OSTR2RUNES,
OSTR2BYTES,
ORUNESTR:
e.track(n)
case OADDSTR:
e.track(n)
// Arguments of OADDSTR do not escape.
case OADDR:
// current loop depth is an upper bound on actual loop depth
// of addressed value.
e.track(n)
// for &x, use loop depth of x if known.
// it should always be known, but if not, be conservative
// and keep the current loop depth.
if n.Left.Op == ONAME {
switch n.Left.Class() {
// PPARAM is loop depth 1 always.
// PPARAMOUT is loop depth 0 for writes
// but considered loop depth 1 for address-of,
// so that writing the address of one result
// to another (or the same) result makes the
// first result move to the heap.
case PPARAM, PPARAMOUT:
nE := e.nodeEscState(n)
nE.Loopdepth = 1
break opSwitch
}
}
nE := e.nodeEscState(n)
leftE := e.nodeEscState(n.Left)
if leftE.Loopdepth != 0 {
nE.Loopdepth = leftE.Loopdepth
}
case ODOT,
ODOTPTR,
OINDEX:
// Propagate the loopdepth of t to t.field.
if n.Left.Op != OLITERAL { // OLITERAL node doesn't have esc state
e.nodeEscState(n).Loopdepth = e.nodeEscState(n.Left).Loopdepth
}
}
lineno = lno
}
// escassignWhyWhere bundles a common case of
// escassign(e, dst, src, e.stepAssignWhere(dst, src, reason, where))