Debian Codegraph @

internal/gen/optab.go

raw symbols SCIP
1 package gen
2
3 import (
4 "fmt"
5 "sort"
6 "strconv"
7 "strings"
8
9 "github.com/mmcloughlin/avo/internal/api"
10 "github.com/mmcloughlin/avo/internal/inst"
11 "github.com/mmcloughlin/avo/internal/prnt"
12 "github.com/mmcloughlin/avo/printer"
13 )
14
15 type optab struct {
16 prnt.Generator
17
18 cfg printer.Config
19
20 table *Table
21 }
22
23 // NewOptab builds the operator table. This contains a more compact
24 // representation of the instruction database, containing the data needed for
25 // instruction builders to match against provided operands, and build the
26 // selected instruction.
27 func NewOptab(cfg printer.Config) Interface {
28 return GoFmt(&optab{cfg: cfg})
29 }
30
31 func (t *optab) Generate(is []inst.Instruction) ([]byte, error) {
32 t.Printf("// %s\n\n", t.cfg.GeneratedWarning())
33 t.Printf("package x86\n\n")
34 t.Printf("import (\n")
35 t.Printf("\t%q\n", api.ImportPath(api.OperandPackage))
36 t.Printf("\t%q\n", api.ImportPath(api.RegisterPackage))
37 t.Printf(")\n\n")
38
39 // Generate instruction data table.
40 t.table = NewTable(is)
41
42 // Size constants.
43 t.maxOperands(is)
44
45 // Types.
46 t.operandTypeEnum(is)
47 t.implicitRegisterEnum(is)
48 t.enum(t.table.Suffix())
49 t.suffixesType(is)
50 t.suffixesClassEnum(is)
51 t.isasEnum(is)
52 t.opcodeEnum(is)
53
54 // Forms table.
55 t.forms(is)
56
57 return t.Result()
58 }
59
60 func (t *optab) maxOperands(is []inst.Instruction) {
61 max := 0
62 for _, i := range inst.Instructions {
63 for _, f := range i.Forms {
64 a := len(f.Operands) + len(f.ImplicitOperands)
65 if a > max {
66 max = a
67 }
68 }
69 }
70
71 t.Comment("maxoperands is the maximum number of operands in an instruction form, including implicit operands.")
72 t.Printf("const maxoperands = %d\n\n", max)
73 }
74
75 func (t *optab) operandTypeEnum(is []inst.Instruction) {
76 // Operand type enum.
77 e := t.table.OperandType()
78 t.enum(e)
79
80 // Operand match function.
81 types := inst.OperandTypes(is)
82 t.Printf("func (%s %s) Match(op %s) bool {\n", e.Receiver(), e.Name(), api.OperandType)
83 t.Printf("\tswitch %s {\n", e.Receiver())
84 t.Printf("\t\tdefault: return false\n")
85 for _, typ := range types {
86 t.Printf("\t\tcase %s: return %s(op)\n", t.table.OperandTypeConst(typ), api.CheckerName(typ))
87 }
88 t.Printf("\t}\n")
89 t.Printf("}\n\n")
90 }
91
92 func (t *optab) implicitRegisterEnum(is []inst.Instruction) {
93 // Implicit register enum.
94 e := t.table.ImplicitRegister()
95 t.enum(e)
96
97 // Register conversion function.
98 registers := inst.ImplicitRegisters(is)
99 t.Printf("func (%s %s) Register() %s {\n", e.Receiver(), e.Name(), api.RegisterType)
100 t.Printf("\tswitch %s {\n", e.Receiver())
101 t.Printf("\t\tdefault: panic(\"unexpected implicit register type\")\n")
102 for _, r := range registers {
103 t.Printf("\t\tcase %s: return %s\n", t.table.ImplicitRegisterConst(r), api.ImplicitRegister(r))
104 }
105 t.Printf("\t}\n")
106 t.Printf("}\n\n")
107 }
108
109 func (t *optab) suffixesType(is []inst.Instruction) {
110 // Declare the type as an array. This requires us to know the maximum number
111 // of suffixes an instruction can have.
112 max := 0
113 for _, class := range inst.SuffixesClasses(is) {
114 for _, suffixes := range class {
115 if len(suffixes) > max {
116 max = len(suffixes)
117 }
118 }
119 }
120
121 t.Comment("maxsuffixes is the maximum number of suffixes an instruction can have.")
122 t.Printf("const maxsuffixes = %d\n\n", max)
123
124 name := t.table.SuffixesTypeName()
125 t.Printf("type %s [maxsuffixes]%s\n", name, t.table.Suffix().Name())
126
127 // Conversion function to list of strings.
128 mapname := name + "stringsmap"
129
130 t.Printf("func (s %s) Strings() []string {\n", name)
131 t.Printf("return %s[s]", mapname)
132 t.Printf("}\n")
133
134 var entries []string
135 for _, class := range inst.SuffixesClasses(is) {
136 for _, suffixes := range class {
137 entry := fmt.Sprintf("%s: %s", t.table.SuffixesList(suffixes), stringsliteral(suffixes.Strings()))
138 entries = append(entries, entry)
139 }
140 }
141
142 t.Printf("var %s = map[%s][]string{\n", mapname, name)
143 sort.Strings(entries)
144 for _, entry := range entries {
145 t.Printf("%s,\n", entry)
146 }
147 t.Printf("}\n")
148 }
149
150 func (t *optab) suffixesClassEnum(is []inst.Instruction) {
151 // Suffixes class enum.
152 e := t.table.SuffixesClass()
153 t.enum(e)
154
155 // Mapping method to the set of accepted suffixes.
156 sets := map[string]string{}
157 for key, class := range inst.SuffixesClasses(is) {
158 var entries []string
159 for _, suffixes := range class {
160 entry := fmt.Sprintf("%s: true", t.table.SuffixesConst(suffixes))
161 entries = append(entries, entry)
162 }
163
164 sort.Strings(entries)
165 sets[api.SuffixesClassIdentifier(key)] = "{" + strings.Join(entries, ", ") + "}"
166 }
167
168 settype := fmt.Sprintf("map[%s]bool", t.table.SuffixesTypeName())
169 t.mapping(e, "SuffixesSet", settype, "nil", sets)
170 }
171
172 func (t *optab) isasEnum(is []inst.Instruction) {
173 // ISAs enum.
174 e := t.table.ISAs()
175 t.enum(e)
176
177 // Mapping method to produce the list of ISAs.
178 lists := map[string]string{}
179 for _, isas := range inst.ISACombinations(is) {
180 lists[api.ISAsIdentifier(isas)] = stringsliteral(isas)
181 }
182 t.mapping(e, "List", "[]string", "nil", lists)
183 }
184
185 func (t *optab) opcodeEnum(is []inst.Instruction) {
186 e := t.table.Opcode()
187 t.enum(e)
188 t.stringmethod(e)
189 }
190
191 func (t *optab) forms(is []inst.Instruction) {
192 // We require all instructions for a given opcode to be in a contiguous
193 // block. This is likely true already but we'll make a sorted copy to ensure
194 // the optab is robust to changes elsewhere.
195 is = append([]inst.Instruction(nil), is...)
196 sort.Slice(is, func(i, j int) bool {
197 return is[i].Opcode < is[j].Opcode
198 })
199
200 // Output instruction forms table.
201 table := "forms"
202 t.Printf("var %s = []form{\n", table)
203 for _, i := range is {
204 for _, f := range i.Forms {
205 t.Printf("{")
206
207 // Basic properties.
208 t.Printf("%s, ", t.table.OpcodeConst(i.Opcode))
209 t.Printf("%s, ", t.table.SuffixesClassConst(f.SuffixesClass()))
210 t.Printf("%s, ", Features(i, f))
211 t.Printf("%s, ", t.table.ISAsConst(f.ISA))
212
213 // Operands.
214 t.Printf("%d, ", len(f.Operands))
215 t.Printf("oprnds{")
216 for _, op := range f.Operands {
217 t.Printf(
218 "{uint8(%s),false,%s},",
219 t.table.OperandTypeConst(op.Type),
220 Action(op.Action),
221 )
222 }
223 for _, op := range f.ImplicitOperands {
224 t.Printf(
225 "{uint8(%s),true,%s},",
226 t.table.ImplicitRegisterConst(op.Register),
227 Action(op.Action),
228 )
229 }
230 t.Printf("}")
231
232 t.Printf("},\n")
233 }
234 }
235 t.Printf("}\n\n")
236
237 // Build mapping from opcode to corresponding forms.
238 forms := map[string]string{}
239 n := 0
240 for _, i := range is {
241 e := n + len(i.Forms)
242 forms[i.Opcode] = fmt.Sprintf("%s[%d:%d]", table, n, e)
243 n = e
244 }
245
246 t.mapping(t.table.Opcode(), "Forms", "[]form", "nil", forms)
247 }
248
249 func (t *optab) enum(e *Enum) {
250 // Type declaration.
251 t.Comment(e.Doc()...)
252 t.Printf("type %s %s\n\n", e.Name(), e.UnderlyingType())
253
254 // Supported values.
255 t.Printf("const (\n")
256 t.Printf("\t%s %s = iota\n", e.None(), e.name)
257 for _, name := range e.ConstNames() {
258 t.Printf("\t%s\n", name)
259 }
260 t.Printf("\t%s\n", e.MaxName())
261 t.Printf(")\n\n")
262 }
263
264 func (t *optab) mapping(e *Enum, name, ret, zero string, to map[string]string) {
265 table := strings.ToLower(e.Name() + name + "table")
266
267 r := e.Receiver()
268 t.Printf("func (%s %s) %s() %s {\n", r, e.Name(), name, ret)
269 t.Printf("if %s < %s && %s < %s {\n", e.None(), r, r, e.MaxName())
270 t.Printf("return %s[%s-1]\n", table, r)
271 t.Printf("}\n")
272 t.Printf("return %s\n", zero)
273 t.Printf("}\n\n")
274
275 t.Printf("var %s = []%s{\n", table, ret)
276 for _, value := range e.Values() {
277 t.Printf("\t%s,\n", to[value])
278 }
279 t.Printf("}\n\n")
280 }
281
282 func (t *optab) stringmethod(e *Enum) {
283 s := map[string]string{}
284 for _, value := range e.Values() {
285 s[value] = strconv.Quote(value)
286 }
287 t.mapping(e, "String", "string", `""`, s)
288 }
289
290 func stringsliteral(ss []string) string {
291 if ss == nil {
292 return "nil"
293 }
294 var quoted []string
295 for _, s := range ss {
296 quoted = append(quoted, strconv.Quote(s))
297 }
298 return "{" + strings.Join(quoted, ", ") + "}"
299 }