-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsched.go
1263 lines (1128 loc) · 31.5 KB
/
sched.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 2009 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 staticinit
import (
"fmt"
"go/constant"
"go/token"
"os"
"strings"
"cmd/compile/internal/base"
"cmd/compile/internal/ir"
"cmd/compile/internal/reflectdata"
"cmd/compile/internal/staticdata"
"cmd/compile/internal/typecheck"
"cmd/compile/internal/types"
"cmd/internal/obj"
"cmd/internal/objabi"
"cmd/internal/src"
)
type Entry struct {
Xoffset int64 // struct, array only
Expr ir.Node // bytes of run-time computed expressions
}
type Plan struct {
E []Entry
}
// An Schedule is used to decompose assignment statements into
// static and dynamic initialization parts. Static initializations are
// handled by populating variables' linker symbol data, while dynamic
// initializations are accumulated to be executed in order.
type Schedule struct {
// Out is the ordered list of dynamic initialization
// statements.
Out []ir.Node
Plans map[ir.Node]*Plan
Temps map[ir.Node]*ir.Name
// seenMutation tracks whether we've seen an initialization
// expression that may have modified other package-scope variables
// within this package.
seenMutation bool
}
func (s *Schedule) append(n ir.Node) {
s.Out = append(s.Out, n)
}
// StaticInit adds an initialization statement n to the schedule.
func (s *Schedule) StaticInit(n ir.Node) {
if !s.tryStaticInit(n) {
if base.Flag.Percent != 0 {
ir.Dump("StaticInit failed", n)
}
s.append(n)
}
}
// varToMapInit holds book-keeping state for global map initialization;
// it records the init function created by the compiler to host the
// initialization code for the map in question.
var varToMapInit map[*ir.Name]*ir.Func
// MapInitToVar is the inverse of VarToMapInit; it maintains a mapping
// from a compiler-generated init function to the map the function is
// initializing.
var MapInitToVar map[*ir.Func]*ir.Name
// recordFuncForVar establishes a mapping between global map var "v" and
// outlined init function "fn" (and vice versa); so that we can use
// the mappings later on to update relocations.
func recordFuncForVar(v *ir.Name, fn *ir.Func) {
if varToMapInit == nil {
varToMapInit = make(map[*ir.Name]*ir.Func)
MapInitToVar = make(map[*ir.Func]*ir.Name)
}
varToMapInit[v] = fn
MapInitToVar[fn] = v
}
// allBlank reports whether every node in exprs is blank.
func allBlank(exprs []ir.Node) bool {
for _, expr := range exprs {
if !ir.IsBlank(expr) {
return false
}
}
return true
}
// tryStaticInit attempts to statically execute an initialization
// statement and reports whether it succeeded.
func (s *Schedule) tryStaticInit(n ir.Node) bool {
var lhs []ir.Node
var rhs ir.Node
switch n.Op() {
default:
base.FatalfAt(n.Pos(), "unexpected initialization statement: %v", n)
case ir.OAS:
n := n.(*ir.AssignStmt)
lhs, rhs = []ir.Node{n.X}, n.Y
case ir.OAS2:
// Usually OAS2 has been rewritten to separate OASes by types2.
// What's left here is "var a, b = tmp1, tmp2" as a result from rewriting
// "var a, b = f()" that needs type conversion, which is not static.
n := n.(*ir.AssignListStmt)
for _, rhs := range n.Rhs {
for rhs.Op() == ir.OCONVNOP {
rhs = rhs.(*ir.ConvExpr).X
}
if name, ok := rhs.(*ir.Name); !ok || !name.AutoTemp() {
base.FatalfAt(n.Pos(), "unexpected rhs, not an autotmp: %+v", rhs)
}
}
return false
case ir.OAS2DOTTYPE, ir.OAS2FUNC, ir.OAS2MAPR, ir.OAS2RECV:
n := n.(*ir.AssignListStmt)
if len(n.Lhs) < 2 || len(n.Rhs) != 1 {
base.FatalfAt(n.Pos(), "unexpected shape for %v: %v", n.Op(), n)
}
lhs, rhs = n.Lhs, n.Rhs[0]
case ir.OCALLFUNC:
return false // outlined map init call; no mutations
}
if !s.seenMutation {
s.seenMutation = mayModifyPkgVar(rhs)
}
if allBlank(lhs) && !AnySideEffects(rhs) {
return true // discard
}
// Only worry about simple "l = r" assignments. The OAS2*
// assignments mostly necessitate dynamic execution anyway.
if len(lhs) > 1 {
return false
}
lno := ir.SetPos(n)
defer func() { base.Pos = lno }()
nam := lhs[0].(*ir.Name)
return s.StaticAssign(nam, 0, rhs, nam.Type())
}
// like staticassign but we are copying an already
// initialized value r.
func (s *Schedule) staticcopy(l *ir.Name, loff int64, rn *ir.Name, typ *types.Type) bool {
if rn.Class == ir.PFUNC {
// TODO if roff != 0 { panic }
staticdata.InitAddr(l, loff, staticdata.FuncLinksym(rn))
return true
}
if rn.Class != ir.PEXTERN || rn.Sym().Pkg != types.LocalPkg {
return false
}
if rn.Defn == nil {
// No explicit initialization value. Probably zeroed but perhaps
// supplied externally and of unknown value.
return false
}
if rn.Defn.Op() != ir.OAS {
return false
}
if rn.Type().IsString() { // perhaps overwritten by cmd/link -X (#34675)
return false
}
if rn.Embed != nil {
return false
}
orig := rn
r := rn.Defn.(*ir.AssignStmt).Y
if r == nil {
// types2.InitOrder doesn't include default initializers.
base.Fatalf("unexpected initializer: %v", rn.Defn)
}
// Variable may have been reassigned by a user-written function call
// that was invoked to initialize another global variable (#51913).
if s.seenMutation {
if base.Debug.StaticCopy != 0 {
base.WarnfAt(l.Pos(), "skipping static copy of %v+%v with %v", l, loff, r)
}
return false
}
for r.Op() == ir.OCONVNOP && !types.Identical(r.Type(), typ) {
r = r.(*ir.ConvExpr).X
}
switch r.Op() {
case ir.OMETHEXPR:
r = r.(*ir.SelectorExpr).FuncName()
fallthrough
case ir.ONAME:
r := r.(*ir.Name)
if s.staticcopy(l, loff, r, typ) {
return true
}
// We may have skipped past one or more OCONVNOPs, so
// use conv to ensure r is assignable to l (#13263).
dst := ir.Node(l)
if loff != 0 || !types.Identical(typ, l.Type()) {
dst = ir.NewNameOffsetExpr(base.Pos, l, loff, typ)
}
s.append(ir.NewAssignStmt(base.Pos, dst, typecheck.Conv(r, typ)))
return true
case ir.ONIL:
return true
case ir.OLITERAL:
if ir.IsZero(r) {
return true
}
staticdata.InitConst(l, loff, r, int(typ.Size()))
return true
case ir.OADDR:
r := r.(*ir.AddrExpr)
if a, ok := r.X.(*ir.Name); ok && a.Op() == ir.ONAME {
staticdata.InitAddr(l, loff, staticdata.GlobalLinksym(a))
return true
}
case ir.OPTRLIT:
r := r.(*ir.AddrExpr)
switch r.X.Op() {
case ir.OARRAYLIT, ir.OSLICELIT, ir.OSTRUCTLIT, ir.OMAPLIT:
// copy pointer
staticdata.InitAddr(l, loff, staticdata.GlobalLinksym(s.Temps[r]))
return true
}
case ir.OSLICELIT:
r := r.(*ir.CompLitExpr)
// copy slice
staticdata.InitSlice(l, loff, staticdata.GlobalLinksym(s.Temps[r]), r.Len)
return true
case ir.OARRAYLIT, ir.OSTRUCTLIT:
r := r.(*ir.CompLitExpr)
p := s.Plans[r]
for i := range p.E {
e := &p.E[i]
typ := e.Expr.Type()
if e.Expr.Op() == ir.OLITERAL || e.Expr.Op() == ir.ONIL {
staticdata.InitConst(l, loff+e.Xoffset, e.Expr, int(typ.Size()))
continue
}
x := e.Expr
if x.Op() == ir.OMETHEXPR {
x = x.(*ir.SelectorExpr).FuncName()
}
if x.Op() == ir.ONAME && s.staticcopy(l, loff+e.Xoffset, x.(*ir.Name), typ) {
continue
}
// Requires computation, but we're
// copying someone else's computation.
ll := ir.NewNameOffsetExpr(base.Pos, l, loff+e.Xoffset, typ)
rr := ir.NewNameOffsetExpr(base.Pos, orig, e.Xoffset, typ)
ir.SetPos(rr)
s.append(ir.NewAssignStmt(base.Pos, ll, rr))
}
return true
}
return false
}
func (s *Schedule) StaticAssign(l *ir.Name, loff int64, r ir.Node, typ *types.Type) bool {
// If we're building for FIPS, avoid global data relocations
// by treating all address-of operations as non-static.
// See ../../../internal/obj/fips.go for more context.
// We do this even in non-PIE mode to avoid generating
// static temporaries that would go into SRODATAFIPS
// but need relocations. We can't handle that in the verification.
disableGlobalAddrs := base.Ctxt.IsFIPS()
if r == nil {
// No explicit initialization value. Either zero or supplied
// externally.
return true
}
for r.Op() == ir.OCONVNOP {
r = r.(*ir.ConvExpr).X
}
assign := func(pos src.XPos, a *ir.Name, aoff int64, v ir.Node) {
if s.StaticAssign(a, aoff, v, v.Type()) {
return
}
var lhs ir.Node
if ir.IsBlank(a) {
// Don't use NameOffsetExpr with blank (#43677).
lhs = ir.BlankNode
} else {
lhs = ir.NewNameOffsetExpr(pos, a, aoff, v.Type())
}
s.append(ir.NewAssignStmt(pos, lhs, v))
}
switch r.Op() {
case ir.ONAME:
if disableGlobalAddrs {
return false
}
r := r.(*ir.Name)
return s.staticcopy(l, loff, r, typ)
case ir.OMETHEXPR:
if disableGlobalAddrs {
return false
}
r := r.(*ir.SelectorExpr)
return s.staticcopy(l, loff, r.FuncName(), typ)
case ir.ONIL:
return true
case ir.OLITERAL:
if ir.IsZero(r) {
return true
}
if disableGlobalAddrs && r.Type().IsString() {
return false
}
staticdata.InitConst(l, loff, r, int(typ.Size()))
return true
case ir.OADDR:
if disableGlobalAddrs {
return false
}
r := r.(*ir.AddrExpr)
if name, offset, ok := StaticLoc(r.X); ok && name.Class == ir.PEXTERN {
staticdata.InitAddrOffset(l, loff, name.Linksym(), offset)
return true
}
fallthrough
case ir.OPTRLIT:
if disableGlobalAddrs {
return false
}
r := r.(*ir.AddrExpr)
switch r.X.Op() {
case ir.OARRAYLIT, ir.OSLICELIT, ir.OMAPLIT, ir.OSTRUCTLIT:
// Init pointer.
a := StaticName(r.X.Type())
s.Temps[r] = a
staticdata.InitAddr(l, loff, a.Linksym())
// Init underlying literal.
assign(base.Pos, a, 0, r.X)
return true
}
//dump("not static ptrlit", r);
case ir.OSTR2BYTES:
if disableGlobalAddrs {
return false
}
r := r.(*ir.ConvExpr)
if l.Class == ir.PEXTERN && r.X.Op() == ir.OLITERAL {
sval := ir.StringVal(r.X)
staticdata.InitSliceBytes(l, loff, sval)
return true
}
case ir.OSLICELIT:
if disableGlobalAddrs {
return false
}
r := r.(*ir.CompLitExpr)
s.initplan(r)
// Init slice.
ta := types.NewArray(r.Type().Elem(), r.Len)
ta.SetNoalg(true)
a := StaticName(ta)
s.Temps[r] = a
staticdata.InitSlice(l, loff, a.Linksym(), r.Len)
// Fall through to init underlying array.
l = a
loff = 0
fallthrough
case ir.OARRAYLIT, ir.OSTRUCTLIT:
r := r.(*ir.CompLitExpr)
s.initplan(r)
p := s.Plans[r]
for i := range p.E {
e := &p.E[i]
if e.Expr.Op() == ir.OLITERAL && !disableGlobalAddrs || e.Expr.Op() == ir.ONIL {
staticdata.InitConst(l, loff+e.Xoffset, e.Expr, int(e.Expr.Type().Size()))
continue
}
ir.SetPos(e.Expr)
assign(base.Pos, l, loff+e.Xoffset, e.Expr)
}
return true
case ir.OMAPLIT:
break
case ir.OCLOSURE:
if disableGlobalAddrs {
return false
}
r := r.(*ir.ClosureExpr)
if !r.Func.IsClosure() {
if base.Debug.Closure > 0 {
base.WarnfAt(r.Pos(), "closure converted to global")
}
// Closures with no captured variables are globals,
// so the assignment can be done at link time.
// TODO if roff != 0 { panic }
staticdata.InitAddr(l, loff, staticdata.FuncLinksym(r.Func.Nname))
return true
}
ir.ClosureDebugRuntimeCheck(r)
case ir.OCONVIFACE:
// This logic is mirrored in isStaticCompositeLiteral.
// If you change something here, change it there, and vice versa.
if disableGlobalAddrs {
return false
}
// Determine the underlying concrete type and value we are converting from.
r := r.(*ir.ConvExpr)
val := ir.Node(r)
for val.Op() == ir.OCONVIFACE {
val = val.(*ir.ConvExpr).X
}
if val.Type().IsInterface() {
// val is an interface type.
// If val is nil, we can statically initialize l;
// both words are zero and so there no work to do, so report success.
// If val is non-nil, we have no concrete type to record,
// and we won't be able to statically initialize its value, so report failure.
return val.Op() == ir.ONIL
}
if val.Type().HasShape() {
// See comment in cmd/compile/internal/walk/convert.go:walkConvInterface
return false
}
reflectdata.MarkTypeUsedInInterface(val.Type(), l.Linksym())
var itab *ir.AddrExpr
if typ.IsEmptyInterface() {
itab = reflectdata.TypePtrAt(base.Pos, val.Type())
} else {
itab = reflectdata.ITabAddrAt(base.Pos, val.Type(), typ)
}
// Create a copy of l to modify while we emit data.
// Emit itab, advance offset.
staticdata.InitAddr(l, loff, itab.X.(*ir.LinksymOffsetExpr).Linksym)
// Emit data.
if types.IsDirectIface(val.Type()) {
if val.Op() == ir.ONIL {
// Nil is zero, nothing to do.
return true
}
// Copy val directly into n.
ir.SetPos(val)
assign(base.Pos, l, loff+int64(types.PtrSize), val)
} else {
// Construct temp to hold val, write pointer to temp into n.
a := StaticName(val.Type())
s.Temps[val] = a
assign(base.Pos, a, 0, val)
staticdata.InitAddr(l, loff+int64(types.PtrSize), a.Linksym())
}
return true
case ir.OINLCALL:
if disableGlobalAddrs {
return false
}
r := r.(*ir.InlinedCallExpr)
return s.staticAssignInlinedCall(l, loff, r, typ)
}
if base.Flag.Percent != 0 {
ir.Dump("not static", r)
}
return false
}
func (s *Schedule) initplan(n ir.Node) {
if s.Plans[n] != nil {
return
}
p := new(Plan)
s.Plans[n] = p
switch n.Op() {
default:
base.Fatalf("initplan")
case ir.OARRAYLIT, ir.OSLICELIT:
n := n.(*ir.CompLitExpr)
var k int64
for _, a := range n.List {
if a.Op() == ir.OKEY {
kv := a.(*ir.KeyExpr)
k = typecheck.IndexConst(kv.Key)
a = kv.Value
}
s.addvalue(p, k*n.Type().Elem().Size(), a)
k++
}
case ir.OSTRUCTLIT:
n := n.(*ir.CompLitExpr)
for _, a := range n.List {
if a.Op() != ir.OSTRUCTKEY {
base.Fatalf("initplan structlit")
}
a := a.(*ir.StructKeyExpr)
if a.Sym().IsBlank() {
continue
}
s.addvalue(p, a.Field.Offset, a.Value)
}
case ir.OMAPLIT:
n := n.(*ir.CompLitExpr)
for _, a := range n.List {
if a.Op() != ir.OKEY {
base.Fatalf("initplan maplit")
}
a := a.(*ir.KeyExpr)
s.addvalue(p, -1, a.Value)
}
}
}
func (s *Schedule) addvalue(p *Plan, xoffset int64, n ir.Node) {
// special case: zero can be dropped entirely
if ir.IsZero(n) {
return
}
// special case: inline struct and array (not slice) literals
if isvaluelit(n) {
s.initplan(n)
q := s.Plans[n]
for _, qe := range q.E {
// qe is a copy; we are not modifying entries in q.E
qe.Xoffset += xoffset
p.E = append(p.E, qe)
}
return
}
// add to plan
p.E = append(p.E, Entry{Xoffset: xoffset, Expr: n})
}
func (s *Schedule) staticAssignInlinedCall(l *ir.Name, loff int64, call *ir.InlinedCallExpr, typ *types.Type) bool {
if base.Debug.InlStaticInit == 0 {
return false
}
// Handle the special case of an inlined call of
// a function body with a single return statement,
// which turns into a single assignment plus a goto.
//
// For example code like this:
//
// type T struct{ x int }
// func F(x int) *T { return &T{x} }
// var Global = F(400)
//
// turns into IR like this:
//
// INLCALL-init
// . AS2-init
// . . DCL # x.go:18:13
// . . . NAME-p.x Class:PAUTO Offset:0 InlFormal OnStack Used int tc(1) # x.go:14:9,x.go:18:13
// . AS2 Def tc(1) # x.go:18:13
// . AS2-Lhs
// . . NAME-p.x Class:PAUTO Offset:0 InlFormal OnStack Used int tc(1) # x.go:14:9,x.go:18:13
// . AS2-Rhs
// . . LITERAL-400 int tc(1) # x.go:18:14
// . INLMARK Index:1 # +x.go:18:13
// INLCALL PTR-*T tc(1) # x.go:18:13
// INLCALL-Body
// . BLOCK tc(1) # x.go:18:13
// . BLOCK-List
// . . DCL tc(1) # x.go:18:13
// . . . NAME-p.~R0 Class:PAUTO Offset:0 OnStack Used PTR-*T tc(1) # x.go:18:13
// . . AS2 tc(1) # x.go:18:13
// . . AS2-Lhs
// . . . NAME-p.~R0 Class:PAUTO Offset:0 OnStack Used PTR-*T tc(1) # x.go:18:13
// . . AS2-Rhs
// . . . INLINED RETURN ARGUMENT HERE
// . . GOTO p..i1 tc(1) # x.go:18:13
// . LABEL p..i1 # x.go:18:13
// INLCALL-ReturnVars
// . NAME-p.~R0 Class:PAUTO Offset:0 OnStack Used PTR-*T tc(1) # x.go:18:13
//
// In non-unified IR, the tree is slightly different:
// - if there are no arguments to the inlined function,
// the INLCALL-init omits the AS2.
// - the DCL inside BLOCK is on the AS2's init list,
// not its own statement in the top level of the BLOCK.
//
// If the init values are side-effect-free and each either only
// appears once in the function body or is safely repeatable,
// then we inline the value expressions into the return argument
// and then call StaticAssign to handle that copy.
//
// This handles simple cases like
//
// var myError = errors.New("mine")
//
// where errors.New is
//
// func New(text string) error {
// return &errorString{text}
// }
//
// We could make things more sophisticated but this kind of initializer
// is the most important case for us to get right.
init := call.Init()
var as2init *ir.AssignListStmt
if len(init) == 2 && init[0].Op() == ir.OAS2 && init[1].Op() == ir.OINLMARK {
as2init = init[0].(*ir.AssignListStmt)
} else if len(init) == 1 && init[0].Op() == ir.OINLMARK {
as2init = new(ir.AssignListStmt)
} else {
return false
}
if len(call.Body) != 2 || call.Body[0].Op() != ir.OBLOCK || call.Body[1].Op() != ir.OLABEL {
return false
}
label := call.Body[1].(*ir.LabelStmt).Label
block := call.Body[0].(*ir.BlockStmt)
list := block.List
var dcl *ir.Decl
if len(list) == 3 && list[0].Op() == ir.ODCL {
dcl = list[0].(*ir.Decl)
list = list[1:]
}
if len(list) != 2 ||
list[0].Op() != ir.OAS2 ||
list[1].Op() != ir.OGOTO ||
list[1].(*ir.BranchStmt).Label != label {
return false
}
as2body := list[0].(*ir.AssignListStmt)
if dcl == nil {
ainit := as2body.Init()
if len(ainit) != 1 || ainit[0].Op() != ir.ODCL {
return false
}
dcl = ainit[0].(*ir.Decl)
}
if len(as2body.Lhs) != 1 || as2body.Lhs[0] != dcl.X {
return false
}
// Can't remove the parameter variables if an address is taken.
for _, v := range as2init.Lhs {
if v.(*ir.Name).Addrtaken() {
return false
}
}
// Can't move the computation of the args if they have side effects.
for _, r := range as2init.Rhs {
if AnySideEffects(r) {
return false
}
}
// Can only substitute arg for param if param is used
// at most once or is repeatable.
count := make(map[*ir.Name]int)
for _, x := range as2init.Lhs {
count[x.(*ir.Name)] = 0
}
hasClosure := false
ir.Visit(as2body.Rhs[0], func(n ir.Node) {
if name, ok := n.(*ir.Name); ok {
if c, ok := count[name]; ok {
count[name] = c + 1
}
}
if clo, ok := n.(*ir.ClosureExpr); ok {
hasClosure = hasClosure || clo.Func.IsClosure()
}
})
// If there's a closure, it has captured the param,
// so we can't substitute arg for param.
if hasClosure {
return false
}
for name, c := range count {
if c > 1 {
// Check whether corresponding initializer can be repeated.
// Something like 1 can be; make(chan int) or &T{} cannot,
// because they need to evaluate to the same result in each use.
for i, n := range as2init.Lhs {
if n == name && !canRepeat(as2init.Rhs[i]) {
return false
}
}
}
}
// Possible static init.
// Build tree with args substituted for params and try it.
args := make(map[*ir.Name]ir.Node)
for i, v := range as2init.Lhs {
if ir.IsBlank(v) {
continue
}
args[v.(*ir.Name)] = as2init.Rhs[i]
}
r, ok := subst(as2body.Rhs[0], args)
if !ok {
return false
}
ok = s.StaticAssign(l, loff, r, typ)
if ok && base.Flag.Percent != 0 {
ir.Dump("static inlined-LEFT", l)
ir.Dump("static inlined-ORIG", call)
ir.Dump("static inlined-RIGHT", r)
}
return ok
}
// from here down is the walk analysis
// of composite literals.
// most of the work is to generate
// data statements for the constant
// part of the composite literal.
var statuniqgen int // name generator for static temps
// StaticName returns a name backed by a (writable) static data symbol.
func StaticName(t *types.Type) *ir.Name {
// Don't use LookupNum; it interns the resulting string, but these are all unique.
sym := typecheck.Lookup(fmt.Sprintf("%s%d", obj.StaticNamePrefix, statuniqgen))
statuniqgen++
n := ir.NewNameAt(base.Pos, sym, t)
sym.Def = n
n.Class = ir.PEXTERN
typecheck.Target.Externs = append(typecheck.Target.Externs, n)
n.Linksym().Set(obj.AttrStatic, true)
return n
}
// StaticLoc returns the static address of n, if n has one, or else nil.
func StaticLoc(n ir.Node) (name *ir.Name, offset int64, ok bool) {
if n == nil {
return nil, 0, false
}
switch n.Op() {
case ir.ONAME:
n := n.(*ir.Name)
return n, 0, true
case ir.OMETHEXPR:
n := n.(*ir.SelectorExpr)
return StaticLoc(n.FuncName())
case ir.ODOT:
n := n.(*ir.SelectorExpr)
if name, offset, ok = StaticLoc(n.X); !ok {
break
}
offset += n.Offset()
return name, offset, true
case ir.OINDEX:
n := n.(*ir.IndexExpr)
if n.X.Type().IsSlice() {
break
}
if name, offset, ok = StaticLoc(n.X); !ok {
break
}
l := getlit(n.Index)
if l < 0 {
break
}
// Check for overflow.
if n.Type().Size() != 0 && types.MaxWidth/n.Type().Size() <= int64(l) {
break
}
offset += int64(l) * n.Type().Size()
return name, offset, true
}
return nil, 0, false
}
func isSideEffect(n ir.Node) bool {
switch n.Op() {
// Assume side effects unless we know otherwise.
default:
return true
// No side effects here (arguments are checked separately).
case ir.ONAME,
ir.ONONAME,
ir.OTYPE,
ir.OLITERAL,
ir.ONIL,
ir.OADD,
ir.OSUB,
ir.OOR,
ir.OXOR,
ir.OADDSTR,
ir.OADDR,
ir.OANDAND,
ir.OBYTES2STR,
ir.ORUNES2STR,
ir.OSTR2BYTES,
ir.OSTR2RUNES,
ir.OCAP,
ir.OCOMPLIT,
ir.OMAPLIT,
ir.OSTRUCTLIT,
ir.OARRAYLIT,
ir.OSLICELIT,
ir.OPTRLIT,
ir.OCONV,
ir.OCONVIFACE,
ir.OCONVNOP,
ir.ODOT,
ir.OEQ,
ir.ONE,
ir.OLT,
ir.OLE,
ir.OGT,
ir.OGE,
ir.OKEY,
ir.OSTRUCTKEY,
ir.OLEN,
ir.OMUL,
ir.OLSH,
ir.ORSH,
ir.OAND,
ir.OANDNOT,
ir.ONEW,
ir.ONOT,
ir.OBITNOT,
ir.OPLUS,
ir.ONEG,
ir.OOROR,
ir.OPAREN,
ir.ORUNESTR,
ir.OREAL,
ir.OIMAG,
ir.OCOMPLEX:
return false
// Only possible side effect is division by zero.
case ir.ODIV, ir.OMOD:
n := n.(*ir.BinaryExpr)
if n.Y.Op() != ir.OLITERAL || constant.Sign(n.Y.Val()) == 0 {
return true
}
// Only possible side effect is panic on invalid size,
// but many makechan and makemap use size zero, which is definitely OK.
case ir.OMAKECHAN, ir.OMAKEMAP:
n := n.(*ir.MakeExpr)
if !ir.IsConst(n.Len, constant.Int) || constant.Sign(n.Len.Val()) != 0 {
return true
}
// Only possible side effect is panic on invalid size.
// TODO(rsc): Merge with previous case (probably breaks toolstash -cmp).
case ir.OMAKESLICE, ir.OMAKESLICECOPY:
return true
}
return false
}
// AnySideEffects reports whether n contains any operations that could have observable side effects.
func AnySideEffects(n ir.Node) bool {
return ir.Any(n, isSideEffect)
}
// mayModifyPkgVar reports whether expression n may modify any
// package-scope variables declared within the current package.
func mayModifyPkgVar(n ir.Node) bool {
// safeLHS reports whether the assigned-to variable lhs is either a
// local variable or a global from another package.
safeLHS := func(lhs ir.Node) bool {
outer := ir.OuterValue(lhs)
// "*p = ..." should be safe if p is a local variable.
// TODO: Should ir.OuterValue handle this?
for outer.Op() == ir.ODEREF {
outer = outer.(*ir.StarExpr).X
}
v, ok := outer.(*ir.Name)
return ok && v.Op() == ir.ONAME && !(v.Class == ir.PEXTERN && v.Sym().Pkg == types.LocalPkg)
}
return ir.Any(n, func(n ir.Node) bool {
switch n.Op() {
case ir.OCALLFUNC, ir.OCALLINTER:
return !ir.IsFuncPCIntrinsic(n.(*ir.CallExpr))
case ir.OAPPEND, ir.OCLEAR, ir.OCOPY:
return true // could mutate a global array
case ir.OASOP:
n := n.(*ir.AssignOpStmt)
if !safeLHS(n.X) {
return true
}
case ir.OAS:
n := n.(*ir.AssignStmt)
if !safeLHS(n.X) {
return true
}
case ir.OAS2, ir.OAS2DOTTYPE, ir.OAS2FUNC, ir.OAS2MAPR, ir.OAS2RECV:
n := n.(*ir.AssignListStmt)
for _, lhs := range n.Lhs {
if !safeLHS(lhs) {
return true
}
}
}
return false
})
}
// canRepeat reports whether executing n multiple times has the same effect as
// assigning n to a single variable and using that variable multiple times.
func canRepeat(n ir.Node) bool {
bad := func(n ir.Node) bool {
if isSideEffect(n) {
return true
}
switch n.Op() {
case ir.OMAKECHAN,
ir.OMAKEMAP,
ir.OMAKESLICE,
ir.OMAKESLICECOPY,
ir.OMAPLIT,
ir.ONEW,
ir.OPTRLIT,
ir.OSLICELIT,
ir.OSTR2BYTES,
ir.OSTR2RUNES:
return true
}
return false
}
return !ir.Any(n, bad)
}
func getlit(lit ir.Node) int {
if ir.IsSmallIntConst(lit) {
return int(ir.Int64Val(lit))
}
return -1
}