-
Notifications
You must be signed in to change notification settings - Fork 18k
/
Copy pathrulegen.go
1887 lines (1755 loc) · 48.8 KB
/
rulegen.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 2015 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.
// This program generates Go code that applies rewrite rules to a Value.
// The generated code implements a function of type func (v *Value) bool
// which reports whether if did something.
// Ideas stolen from the Swift Java compiler:
// https://bitsavers.org/pdf/dec/tech_reports/WRL-2000-2.pdf
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/printer"
"go/token"
"io"
"log"
"os"
"path"
"regexp"
"sort"
"strconv"
"strings"
"golang.org/x/tools/go/ast/astutil"
)
// rule syntax:
// sexpr [&& extra conditions] => [@block] sexpr
//
// sexpr are s-expressions (lisp-like parenthesized groupings)
// sexpr ::= [variable:](opcode sexpr*)
// | variable
// | <type>
// | [auxint]
// | {aux}
//
// aux ::= variable | {code}
// type ::= variable | {code}
// variable ::= some token
// opcode ::= one of the opcodes from the *Ops.go files
// special rules: trailing ellipsis "..." (in the outermost sexpr?) must match on both sides of a rule.
// trailing three underscore "___" in the outermost match sexpr indicate the presence of
// extra ignored args that need not appear in the replacement
// extra conditions is just a chunk of Go that evaluates to a boolean. It may use
// variables declared in the matching tsexpr. The variable "v" is predefined to be
// the value matched by the entire rule.
// If multiple rules match, the first one in file order is selected.
var (
genLog = flag.Bool("log", false, "generate code that logs; for debugging only")
addLine = flag.Bool("line", false, "add line number comment to generated rules; for debugging only")
)
type Rule struct {
Rule string
Loc string // file name & line number
}
func (r Rule) String() string {
return fmt.Sprintf("rule %q at %s", r.Rule, r.Loc)
}
func normalizeSpaces(s string) string {
return strings.Join(strings.Fields(strings.TrimSpace(s)), " ")
}
// parse returns the matching part of the rule, additional conditions, and the result.
func (r Rule) parse() (match, cond, result string) {
s := strings.Split(r.Rule, "=>")
match = normalizeSpaces(s[0])
result = normalizeSpaces(s[1])
cond = ""
if i := strings.Index(match, "&&"); i >= 0 {
cond = normalizeSpaces(match[i+2:])
match = normalizeSpaces(match[:i])
}
return match, cond, result
}
func genRules(arch arch) { genRulesSuffix(arch, "") }
func genSplitLoadRules(arch arch) { genRulesSuffix(arch, "splitload") }
func genLateLowerRules(arch arch) { genRulesSuffix(arch, "latelower") }
func genRulesSuffix(arch arch, suff string) {
// Open input file.
text, err := os.Open(arch.name + suff + ".rules")
if err != nil {
if suff == "" {
// All architectures must have a plain rules file.
log.Fatalf("can't read rule file: %v", err)
}
// Some architectures have bonus rules files that others don't share. That's fine.
return
}
// oprules contains a list of rules for each block and opcode
blockrules := map[string][]Rule{}
oprules := map[string][]Rule{}
// read rule file
scanner := bufio.NewScanner(text)
rule := ""
var lineno int
var ruleLineno int // line number of "=>"
for scanner.Scan() {
lineno++
line := scanner.Text()
if i := strings.Index(line, "//"); i >= 0 {
// Remove comments. Note that this isn't string safe, so
// it will truncate lines with // inside strings. Oh well.
line = line[:i]
}
rule += " " + line
rule = strings.TrimSpace(rule)
if rule == "" {
continue
}
if !strings.Contains(rule, "=>") {
continue
}
if ruleLineno == 0 {
ruleLineno = lineno
}
if strings.HasSuffix(rule, "=>") {
continue // continue on the next line
}
if n := balance(rule); n > 0 {
continue // open parentheses remain, continue on the next line
} else if n < 0 {
break // continuing the line can't help, and it will only make errors worse
}
loc := fmt.Sprintf("%s%s.rules:%d", arch.name, suff, ruleLineno)
for _, rule2 := range expandOr(rule) {
r := Rule{Rule: rule2, Loc: loc}
if rawop := strings.Split(rule2, " ")[0][1:]; isBlock(rawop, arch) {
blockrules[rawop] = append(blockrules[rawop], r)
continue
}
// Do fancier value op matching.
match, _, _ := r.parse()
op, oparch, _, _, _, _ := parseValue(match, arch, loc)
opname := fmt.Sprintf("Op%s%s", oparch, op.name)
oprules[opname] = append(oprules[opname], r)
}
rule = ""
ruleLineno = 0
}
if err := scanner.Err(); err != nil {
log.Fatalf("scanner failed: %v\n", err)
}
if balance(rule) != 0 {
log.Fatalf("%s.rules:%d: unbalanced rule: %v\n", arch.name, lineno, rule)
}
// Order all the ops.
var ops []string
for op := range oprules {
ops = append(ops, op)
}
sort.Strings(ops)
genFile := &File{Arch: arch, Suffix: suff}
// Main rewrite routine is a switch on v.Op.
fn := &Func{Kind: "Value", ArgLen: -1}
sw := &Switch{Expr: exprf("v.Op")}
for _, op := range ops {
eop, ok := parseEllipsisRules(oprules[op], arch)
if ok {
if strings.Contains(oprules[op][0].Rule, "=>") && opByName(arch, op).aux != opByName(arch, eop).aux {
panic(fmt.Sprintf("can't use ... for ops that have different aux types: %s and %s", op, eop))
}
swc := &Case{Expr: exprf("%s", op)}
swc.add(stmtf("v.Op = %s", eop))
swc.add(stmtf("return true"))
sw.add(swc)
continue
}
swc := &Case{Expr: exprf("%s", op)}
swc.add(stmtf("return rewriteValue%s%s_%s(v)", arch.name, suff, op))
sw.add(swc)
}
if len(sw.List) > 0 { // skip if empty
fn.add(sw)
}
fn.add(stmtf("return false"))
genFile.add(fn)
// Generate a routine per op. Note that we don't make one giant routine
// because it is too big for some compilers.
for _, op := range ops {
rules := oprules[op]
_, ok := parseEllipsisRules(oprules[op], arch)
if ok {
continue
}
// rr is kept between iterations, so that each rule can check
// that the previous rule wasn't unconditional.
var rr *RuleRewrite
fn := &Func{
Kind: "Value",
Suffix: fmt.Sprintf("_%s", op),
ArgLen: opByName(arch, op).argLength,
}
fn.add(declReserved("b", "v.Block"))
fn.add(declReserved("config", "b.Func.Config"))
fn.add(declReserved("fe", "b.Func.fe"))
fn.add(declReserved("typ", "&b.Func.Config.Types"))
for _, rule := range rules {
if rr != nil && !rr.CanFail {
log.Fatalf("unconditional rule %s is followed by other rules", rr.Match)
}
rr = &RuleRewrite{Loc: rule.Loc}
rr.Match, rr.Cond, rr.Result = rule.parse()
pos, _ := genMatch(rr, arch, rr.Match, fn.ArgLen >= 0)
if pos == "" {
pos = "v.Pos"
}
if rr.Cond != "" {
rr.add(breakf("!(%s)", rr.Cond))
}
genResult(rr, arch, rr.Result, pos)
if *genLog {
rr.add(stmtf("logRule(%q)", rule.Loc))
}
fn.add(rr)
}
if rr.CanFail {
fn.add(stmtf("return false"))
}
genFile.add(fn)
}
// Generate block rewrite function. There are only a few block types
// so we can make this one function with a switch.
fn = &Func{Kind: "Block"}
fn.add(declReserved("config", "b.Func.Config"))
fn.add(declReserved("typ", "&b.Func.Config.Types"))
sw = &Switch{Expr: exprf("b.Kind")}
ops = ops[:0]
for op := range blockrules {
ops = append(ops, op)
}
sort.Strings(ops)
for _, op := range ops {
name, data := getBlockInfo(op, arch)
swc := &Case{Expr: exprf("%s", name)}
for _, rule := range blockrules[op] {
swc.add(genBlockRewrite(rule, arch, data))
}
sw.add(swc)
}
if len(sw.List) > 0 { // skip if empty
fn.add(sw)
}
fn.add(stmtf("return false"))
genFile.add(fn)
// Remove unused imports and variables.
buf := new(bytes.Buffer)
fprint(buf, genFile)
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "", buf, parser.ParseComments)
if err != nil {
filename := fmt.Sprintf("%s_broken.go", arch.name)
if err := os.WriteFile(filename, buf.Bytes(), 0644); err != nil {
log.Printf("failed to dump broken code to %s: %v", filename, err)
} else {
log.Printf("dumped broken code to %s", filename)
}
log.Fatalf("failed to parse generated code for arch %s: %v", arch.name, err)
}
tfile := fset.File(file.Pos())
// First, use unusedInspector to find the unused declarations by their
// start position.
u := unusedInspector{unused: make(map[token.Pos]bool)}
u.node(file)
// Then, delete said nodes via astutil.Apply.
pre := func(c *astutil.Cursor) bool {
node := c.Node()
if node == nil {
return true
}
if u.unused[node.Pos()] {
c.Delete()
// Unused imports and declarations use exactly
// one line. Prevent leaving an empty line.
tfile.MergeLine(tfile.Position(node.Pos()).Line)
return false
}
return true
}
post := func(c *astutil.Cursor) bool {
switch node := c.Node().(type) {
case *ast.GenDecl:
if len(node.Specs) == 0 {
// Don't leave a broken or empty GenDecl behind,
// such as "import ()".
c.Delete()
}
}
return true
}
file = astutil.Apply(file, pre, post).(*ast.File)
// Write the well-formatted source to file
f, err := os.Create("../rewrite" + arch.name + suff + ".go")
if err != nil {
log.Fatalf("can't write output: %v", err)
}
defer f.Close()
// gofmt result; use a buffered writer, as otherwise go/format spends
// far too much time in syscalls.
bw := bufio.NewWriter(f)
if err := format.Node(bw, fset, file); err != nil {
log.Fatalf("can't format output: %v", err)
}
if err := bw.Flush(); err != nil {
log.Fatalf("can't write output: %v", err)
}
if err := f.Close(); err != nil {
log.Fatalf("can't write output: %v", err)
}
}
// unusedInspector can be used to detect unused variables and imports in an
// ast.Node via its node method. The result is available in the "unused" map.
//
// note that unusedInspector is lazy and best-effort; it only supports the node
// types and patterns used by the rulegen program.
type unusedInspector struct {
// scope is the current scope, which can never be nil when a declaration
// is encountered. That is, the unusedInspector.node entrypoint should
// generally be an entire file or block.
scope *scope
// unused is the resulting set of unused declared names, indexed by the
// starting position of the node that declared the name.
unused map[token.Pos]bool
// defining is the object currently being defined; this is useful so
// that if "foo := bar" is unused and removed, we can then detect if
// "bar" becomes unused as well.
defining *object
}
// scoped opens a new scope when called, and returns a function which closes
// that same scope. When a scope is closed, unused variables are recorded.
func (u *unusedInspector) scoped() func() {
outer := u.scope
u.scope = &scope{outer: outer, objects: map[string]*object{}}
return func() {
for anyUnused := true; anyUnused; {
anyUnused = false
for _, obj := range u.scope.objects {
if obj.numUses > 0 {
continue
}
u.unused[obj.pos] = true
for _, used := range obj.used {
if used.numUses--; used.numUses == 0 {
anyUnused = true
}
}
// We've decremented numUses for each of the
// objects in used. Zero this slice too, to keep
// everything consistent.
obj.used = nil
}
}
u.scope = outer
}
}
func (u *unusedInspector) exprs(list []ast.Expr) {
for _, x := range list {
u.node(x)
}
}
func (u *unusedInspector) node(node ast.Node) {
switch node := node.(type) {
case *ast.File:
defer u.scoped()()
for _, decl := range node.Decls {
u.node(decl)
}
case *ast.GenDecl:
for _, spec := range node.Specs {
u.node(spec)
}
case *ast.ImportSpec:
impPath, _ := strconv.Unquote(node.Path.Value)
name := path.Base(impPath)
u.scope.objects[name] = &object{
name: name,
pos: node.Pos(),
}
case *ast.FuncDecl:
u.node(node.Type)
if node.Body != nil {
u.node(node.Body)
}
case *ast.FuncType:
if node.Params != nil {
u.node(node.Params)
}
if node.Results != nil {
u.node(node.Results)
}
case *ast.FieldList:
for _, field := range node.List {
u.node(field)
}
case *ast.Field:
u.node(node.Type)
// statements
case *ast.BlockStmt:
defer u.scoped()()
for _, stmt := range node.List {
u.node(stmt)
}
case *ast.DeclStmt:
u.node(node.Decl)
case *ast.IfStmt:
if node.Init != nil {
u.node(node.Init)
}
u.node(node.Cond)
u.node(node.Body)
if node.Else != nil {
u.node(node.Else)
}
case *ast.ForStmt:
if node.Init != nil {
u.node(node.Init)
}
if node.Cond != nil {
u.node(node.Cond)
}
if node.Post != nil {
u.node(node.Post)
}
u.node(node.Body)
case *ast.SwitchStmt:
if node.Init != nil {
u.node(node.Init)
}
if node.Tag != nil {
u.node(node.Tag)
}
u.node(node.Body)
case *ast.CaseClause:
u.exprs(node.List)
defer u.scoped()()
for _, stmt := range node.Body {
u.node(stmt)
}
case *ast.BranchStmt:
case *ast.ExprStmt:
u.node(node.X)
case *ast.AssignStmt:
if node.Tok != token.DEFINE {
u.exprs(node.Rhs)
u.exprs(node.Lhs)
break
}
lhs := node.Lhs
if len(lhs) == 2 && lhs[1].(*ast.Ident).Name == "_" {
lhs = lhs[:1]
}
if len(lhs) != 1 {
panic("no support for := with multiple names")
}
name := lhs[0].(*ast.Ident)
obj := &object{
name: name.Name,
pos: name.NamePos,
}
old := u.defining
u.defining = obj
u.exprs(node.Rhs)
u.defining = old
u.scope.objects[name.Name] = obj
case *ast.ReturnStmt:
u.exprs(node.Results)
case *ast.IncDecStmt:
u.node(node.X)
// expressions
case *ast.CallExpr:
u.node(node.Fun)
u.exprs(node.Args)
case *ast.SelectorExpr:
u.node(node.X)
case *ast.UnaryExpr:
u.node(node.X)
case *ast.BinaryExpr:
u.node(node.X)
u.node(node.Y)
case *ast.StarExpr:
u.node(node.X)
case *ast.ParenExpr:
u.node(node.X)
case *ast.IndexExpr:
u.node(node.X)
u.node(node.Index)
case *ast.TypeAssertExpr:
u.node(node.X)
u.node(node.Type)
case *ast.Ident:
if obj := u.scope.Lookup(node.Name); obj != nil {
obj.numUses++
if u.defining != nil {
u.defining.used = append(u.defining.used, obj)
}
}
case *ast.BasicLit:
case *ast.ValueSpec:
u.exprs(node.Values)
default:
panic(fmt.Sprintf("unhandled node: %T", node))
}
}
// scope keeps track of a certain scope and its declared names, as well as the
// outer (parent) scope.
type scope struct {
outer *scope // can be nil, if this is the top-level scope
objects map[string]*object // indexed by each declared name
}
func (s *scope) Lookup(name string) *object {
if obj := s.objects[name]; obj != nil {
return obj
}
if s.outer == nil {
return nil
}
return s.outer.Lookup(name)
}
// object keeps track of a declared name, such as a variable or import.
type object struct {
name string
pos token.Pos // start position of the node declaring the object
numUses int // number of times this object is used
used []*object // objects that its declaration makes use of
}
func fprint(w io.Writer, n Node) {
switch n := n.(type) {
case *File:
file := n
seenRewrite := make(map[[3]string]string)
fmt.Fprintf(w, "// Code generated from _gen/%s%s.rules using 'go generate'; DO NOT EDIT.\n", n.Arch.name, n.Suffix)
fmt.Fprintf(w, "\npackage ssa\n")
for _, path := range append([]string{
"fmt",
"internal/buildcfg",
"math",
"math/bits",
"cmd/internal/obj",
"cmd/compile/internal/base",
"cmd/compile/internal/types",
"cmd/compile/internal/ir",
}, n.Arch.imports...) {
fmt.Fprintf(w, "import %q\n", path)
}
for _, f := range n.List {
f := f.(*Func)
fmt.Fprintf(w, "func rewrite%s%s%s%s(", f.Kind, n.Arch.name, n.Suffix, f.Suffix)
fmt.Fprintf(w, "%c *%s) bool {\n", strings.ToLower(f.Kind)[0], f.Kind)
if f.Kind == "Value" && f.ArgLen > 0 {
for i := f.ArgLen - 1; i >= 0; i-- {
fmt.Fprintf(w, "v_%d := v.Args[%d]\n", i, i)
}
}
for _, n := range f.List {
fprint(w, n)
if rr, ok := n.(*RuleRewrite); ok {
k := [3]string{
normalizeMatch(rr.Match, file.Arch),
normalizeWhitespace(rr.Cond),
normalizeWhitespace(rr.Result),
}
if prev, ok := seenRewrite[k]; ok {
log.Fatalf("duplicate rule %s, previously seen at %s\n", rr.Loc, prev)
}
seenRewrite[k] = rr.Loc
}
}
fmt.Fprintf(w, "}\n")
}
case *Switch:
fmt.Fprintf(w, "switch ")
fprint(w, n.Expr)
fmt.Fprintf(w, " {\n")
for _, n := range n.List {
fprint(w, n)
}
fmt.Fprintf(w, "}\n")
case *Case:
fmt.Fprintf(w, "case ")
fprint(w, n.Expr)
fmt.Fprintf(w, ":\n")
for _, n := range n.List {
fprint(w, n)
}
case *RuleRewrite:
if *addLine {
fmt.Fprintf(w, "// %s\n", n.Loc)
}
fmt.Fprintf(w, "// match: %s\n", n.Match)
if n.Cond != "" {
fmt.Fprintf(w, "// cond: %s\n", n.Cond)
}
fmt.Fprintf(w, "// result: %s\n", n.Result)
fmt.Fprintf(w, "for %s {\n", n.Check)
nCommutative := 0
for _, n := range n.List {
if b, ok := n.(*CondBreak); ok {
b.InsideCommuteLoop = nCommutative > 0
}
fprint(w, n)
if loop, ok := n.(StartCommuteLoop); ok {
if nCommutative != loop.Depth {
panic("mismatch commute loop depth")
}
nCommutative++
}
}
fmt.Fprintf(w, "return true\n")
for i := 0; i < nCommutative; i++ {
fmt.Fprintln(w, "}")
}
if n.CommuteDepth > 0 && n.CanFail {
fmt.Fprint(w, "break\n")
}
fmt.Fprintf(w, "}\n")
case *Declare:
fmt.Fprintf(w, "%s := ", n.Name)
fprint(w, n.Value)
fmt.Fprintln(w)
case *CondBreak:
fmt.Fprintf(w, "if ")
fprint(w, n.Cond)
fmt.Fprintf(w, " {\n")
if n.InsideCommuteLoop {
fmt.Fprintf(w, "continue")
} else {
fmt.Fprintf(w, "break")
}
fmt.Fprintf(w, "\n}\n")
case ast.Node:
printConfig.Fprint(w, emptyFset, n)
if _, ok := n.(ast.Stmt); ok {
fmt.Fprintln(w)
}
case StartCommuteLoop:
fmt.Fprintf(w, "for _i%[1]d := 0; _i%[1]d <= 1; _i%[1]d, %[2]s_0, %[2]s_1 = _i%[1]d + 1, %[2]s_1, %[2]s_0 {\n", n.Depth, n.V)
default:
log.Fatalf("cannot print %T", n)
}
}
var printConfig = printer.Config{
Mode: printer.RawFormat, // we use go/format later, so skip work here
}
var emptyFset = token.NewFileSet()
// Node can be a Statement or an ast.Expr.
type Node interface{}
// Statement can be one of our high-level statement struct types, or an
// ast.Stmt under some limited circumstances.
type Statement interface{}
// BodyBase is shared by all of our statement pseudo-node types which can
// contain other statements.
type BodyBase struct {
List []Statement
CanFail bool
}
func (w *BodyBase) add(node Statement) {
var last Statement
if len(w.List) > 0 {
last = w.List[len(w.List)-1]
}
if node, ok := node.(*CondBreak); ok {
w.CanFail = true
if last, ok := last.(*CondBreak); ok {
// Add to the previous "if <cond> { break }" via a
// logical OR, which will save verbosity.
last.Cond = &ast.BinaryExpr{
Op: token.LOR,
X: last.Cond,
Y: node.Cond,
}
return
}
}
w.List = append(w.List, node)
}
// predeclared contains globally known tokens that should not be redefined.
var predeclared = map[string]bool{
"nil": true,
"false": true,
"true": true,
}
// declared reports if the body contains a Declare with the given name.
func (w *BodyBase) declared(name string) bool {
if predeclared[name] {
// Treat predeclared names as having already been declared.
// This lets us use nil to match an aux field or
// true and false to match an auxint field.
return true
}
for _, s := range w.List {
if decl, ok := s.(*Declare); ok && decl.Name == name {
return true
}
}
return false
}
// These types define some high-level statement struct types, which can be used
// as a Statement. This allows us to keep some node structs simpler, and have
// higher-level nodes such as an entire rule rewrite.
//
// Note that ast.Expr is always used as-is; we don't declare our own expression
// nodes.
type (
File struct {
BodyBase // []*Func
Arch arch
Suffix string
}
Func struct {
BodyBase
Kind string // "Value" or "Block"
Suffix string
ArgLen int32 // if kind == "Value", number of args for this op
}
Switch struct {
BodyBase // []*Case
Expr ast.Expr
}
Case struct {
BodyBase
Expr ast.Expr
}
RuleRewrite struct {
BodyBase
Match, Cond, Result string // top comments
Check string // top-level boolean expression
Alloc int // for unique var names
Loc string // file name & line number of the original rule
CommuteDepth int // used to track depth of commute loops
}
Declare struct {
Name string
Value ast.Expr
}
CondBreak struct {
Cond ast.Expr
InsideCommuteLoop bool
}
StartCommuteLoop struct {
Depth int
V string
}
)
// exprf parses a Go expression generated from fmt.Sprintf, panicking if an
// error occurs.
func exprf(format string, a ...interface{}) ast.Expr {
src := fmt.Sprintf(format, a...)
expr, err := parser.ParseExpr(src)
if err != nil {
log.Fatalf("expr parse error on %q: %v", src, err)
}
return expr
}
// stmtf parses a Go statement generated from fmt.Sprintf. This function is only
// meant for simple statements that don't have a custom Statement node declared
// in this package, such as ast.ReturnStmt or ast.ExprStmt.
func stmtf(format string, a ...interface{}) Statement {
src := fmt.Sprintf(format, a...)
fsrc := "package p\nfunc _() {\n" + src + "\n}\n"
file, err := parser.ParseFile(token.NewFileSet(), "", fsrc, 0)
if err != nil {
log.Fatalf("stmt parse error on %q: %v", src, err)
}
return file.Decls[0].(*ast.FuncDecl).Body.List[0]
}
var reservedNames = map[string]bool{
"v": true, // Values[i], etc
"b": true, // v.Block
"config": true, // b.Func.Config
"fe": true, // b.Func.fe
"typ": true, // &b.Func.Config.Types
}
// declf constructs a simple "name := value" declaration,
// using exprf for its value.
//
// name must not be one of reservedNames.
// This helps prevent unintended shadowing and name clashes.
// To declare a reserved name, use declReserved.
func declf(loc, name, format string, a ...interface{}) *Declare {
if reservedNames[name] {
log.Fatalf("rule %s uses the reserved name %s", loc, name)
}
return &Declare{name, exprf(format, a...)}
}
// declReserved is like declf, but the name must be one of reservedNames.
// Calls to declReserved should generally be static and top-level.
func declReserved(name, value string) *Declare {
if !reservedNames[name] {
panic(fmt.Sprintf("declReserved call does not use a reserved name: %q", name))
}
return &Declare{name, exprf(value)}
}
// breakf constructs a simple "if cond { break }" statement, using exprf for its
// condition.
func breakf(format string, a ...interface{}) *CondBreak {
return &CondBreak{Cond: exprf(format, a...)}
}
func genBlockRewrite(rule Rule, arch arch, data blockData) *RuleRewrite {
rr := &RuleRewrite{Loc: rule.Loc}
rr.Match, rr.Cond, rr.Result = rule.parse()
_, _, auxint, aux, s := extract(rr.Match) // remove parens, then split
// check match of control values
if len(s) < data.controls {
log.Fatalf("incorrect number of arguments in %s, got %v wanted at least %v", rule, len(s), data.controls)
}
controls := s[:data.controls]
pos := make([]string, data.controls)
for i, arg := range controls {
cname := fmt.Sprintf("b.Controls[%v]", i)
if strings.Contains(arg, "(") {
vname, expr := splitNameExpr(arg)
if vname == "" {
vname = fmt.Sprintf("v_%v", i)
}
rr.add(declf(rr.Loc, vname, cname))
p, op := genMatch0(rr, arch, expr, vname, nil, false) // TODO: pass non-nil cnt?
if op != "" {
check := fmt.Sprintf("%s.Op == %s", cname, op)
if rr.Check == "" {
rr.Check = check
} else {
rr.Check += " && " + check
}
}
if p == "" {
p = vname + ".Pos"
}
pos[i] = p
} else {
rr.add(declf(rr.Loc, arg, cname))
pos[i] = arg + ".Pos"
}
}
for _, e := range []struct {
name, field, dclType string
}{
{auxint, "AuxInt", data.auxIntType()},
{aux, "Aux", data.auxType()},
} {
if e.name == "" {
continue
}
if e.dclType == "" {
log.Fatalf("op %s has no declared type for %s", data.name, e.field)
}
if !token.IsIdentifier(e.name) || rr.declared(e.name) {
rr.add(breakf("%sTo%s(b.%s) != %s", unTitle(e.field), title(e.dclType), e.field, e.name))
} else {
rr.add(declf(rr.Loc, e.name, "%sTo%s(b.%s)", unTitle(e.field), title(e.dclType), e.field))
}
}
if rr.Cond != "" {
rr.add(breakf("!(%s)", rr.Cond))
}
// Rule matches. Generate result.
outop, _, auxint, aux, t := extract(rr.Result) // remove parens, then split
blockName, outdata := getBlockInfo(outop, arch)
if len(t) < outdata.controls {
log.Fatalf("incorrect number of output arguments in %s, got %v wanted at least %v", rule, len(s), outdata.controls)
}
// Check if newsuccs is the same set as succs.
succs := s[data.controls:]
newsuccs := t[outdata.controls:]
m := map[string]bool{}
for _, succ := range succs {
if m[succ] {
log.Fatalf("can't have a repeat successor name %s in %s", succ, rule)
}
m[succ] = true
}
for _, succ := range newsuccs {
if !m[succ] {
log.Fatalf("unknown successor %s in %s", succ, rule)
}
delete(m, succ)
}
if len(m) != 0 {
log.Fatalf("unmatched successors %v in %s", m, rule)
}
var genControls [2]string
for i, control := range t[:outdata.controls] {
// Select a source position for any new control values.
// TODO: does it always make sense to use the source position
// of the original control values or should we be using the
// block's source position in some cases?
newpos := "b.Pos" // default to block's source position
if i < len(pos) && pos[i] != "" {
// Use the previous control value's source position.
newpos = pos[i]
}
// Generate a new control value (or copy an existing value).
genControls[i] = genResult0(rr, arch, control, false, false, newpos, nil)
}
switch outdata.controls {
case 0:
rr.add(stmtf("b.Reset(%s)", blockName))
case 1:
rr.add(stmtf("b.resetWithControl(%s, %s)", blockName, genControls[0]))
case 2:
rr.add(stmtf("b.resetWithControl2(%s, %s, %s)", blockName, genControls[0], genControls[1]))
default:
log.Fatalf("too many controls: %d", outdata.controls)
}
if auxint != "" {
// Make sure auxint value has the right type.
rr.add(stmtf("b.AuxInt = %sToAuxInt(%s)", unTitle(outdata.auxIntType()), auxint))
}
if aux != "" {
// Make sure aux value has the right type.
rr.add(stmtf("b.Aux = %sToAux(%s)", unTitle(outdata.auxType()), aux))
}
succChanged := false
for i := 0; i < len(succs); i++ {
if succs[i] != newsuccs[i] {
succChanged = true
}
}
if succChanged {
if len(succs) != 2 {
log.Fatalf("changed successors, len!=2 in %s", rule)
}
if succs[0] != newsuccs[1] || succs[1] != newsuccs[0] {
log.Fatalf("can only handle swapped successors in %s", rule)
}