collab/polyglot-riscv-arm

what if the same machine code was valid riscv and arm asm

git clone https://git.julia.blue/collab/polyglot-riscv-arm

Jonathan Dönszelmannwebsite start885cc4e

main
9.4 KiB467 linesraw
1package mra
2
3import (
4	"bytes"
5	"encoding/xml"
6	"fmt"
7	"log"
8	"regexp"
9	"strings"
10)
11
12const (
13	InstrGeneral   = "general"
14	InstrSystem    = "system"
15	InstrFloat     = "float"
16	InstrFpSimd    = "fpsimd"
17	InstrAdvSimd   = "advsimd"
18	InstrSve       = "sve"
19	InstrSve2      = "sve2"
20	InstrMortlach  = "mortlach"
21	InstrMortlach2 = "mortlach2"
22)
23
24const (
25	InstrGeneralID uint8 = iota
26	InstrSystemID
27	InstrFloatID
28	InstrFpSimdID
29	InstrAdvSimdID
30	InstrSveID
31	InstrSve2ID
32	InstrMortlachID
33	InstrMortlach2ID
34	InstrNumIDs
35)
36
37func IDToClass(class uint8) string {
38	switch class {
39	case InstrGeneralID:
40		return InstrGeneral
41	case InstrSystemID:
42		return InstrSystem
43	case InstrFloatID:
44		return InstrFloat
45	case InstrFpSimdID:
46		return InstrFpSimd
47	case InstrAdvSimdID:
48		return InstrAdvSimd
49	case InstrSveID:
50		return InstrSve
51	case InstrSve2ID:
52		return InstrSve2
53	case InstrMortlachID:
54		return InstrMortlach
55	case InstrMortlach2ID:
56		return InstrMortlach2
57	}
58	return "other"
59}
60
61func ClassToID(class string) uint8 {
62	switch class {
63	case InstrGeneral:
64		return InstrGeneralID
65	case InstrSystem:
66		return InstrSystemID
67	case InstrFloat:
68		return InstrFloatID
69	case InstrFpSimd:
70		return InstrFpSimdID
71	case InstrAdvSimd:
72		return InstrAdvSimdID
73	case InstrSve:
74		return InstrSveID
75	case InstrSve2:
76		return InstrSve2ID
77	case InstrMortlach:
78		return InstrMortlachID
79	case InstrMortlach2:
80		return InstrMortlach2ID
81	}
82	return InstrNumIDs
83}
84
85var InstrBase = strings.Join([]string{
86	InstrGeneral,
87	InstrFloat,
88	InstrFpSimd,
89	InstrAdvSimd,
90}, ",")
91
92type DocVar struct {
93	XMLName xml.Name `xml:"docvar"`
94	Key     string   `xml:"key,attr"`
95	Val     string   `xml:"value,attr"`
96}
97
98type DocVars struct {
99	XMLName xml.Name `xml:"docvars"`
100	Vars    []DocVar `xml:"docvar"`
101}
102
103func (d DocVars) Mnemonic() string {
104	for _, v := range d.Vars {
105		if v.Key == "mnemonic" {
106			return v.Val
107		}
108	}
109	return ""
110}
111
112func (d DocVars) InstrClass() string {
113	for _, v := range d.Vars {
114		if v.Key == "instr-class" {
115			return v.Val
116		}
117	}
118	return ""
119}
120
121type PsText struct {
122	XMLName xml.Name `xml:"pstext"`
123	Content string   `xml:",innerxml"`
124}
125
126type Ps struct {
127	XMLName xml.Name `xml:"ps"`
128	Name    string   `xml:"name,attr"`
129	PsText  PsText   `xml:"pstext"`
130}
131
132type PsSection struct {
133	XMLName xml.Name `xml:"ps_section"`
134	Ps      Ps
135}
136
137type ArchVariant struct {
138	XMLName xml.Name `xml:"arch_variant"`
139	Name    string   `xml:"name,attr"`
140	Feature string   `xml:"feature,attr"`
141}
142
143type ArchVariants struct {
144	XMLName  xml.Name      `xml:"arch_variants"`
145	Variants []ArchVariant `xml:"arch_variant"`
146}
147
148func (a ArchVariants) GetVariants() []string {
149	var vars []string
150	for _, v := range a.Variants {
151		vars = append(vars, v.Name)
152	}
153	return vars
154}
155
156func (a ArchVariants) GetFeatures() []string {
157	var feats []string
158	for _, v := range a.Variants {
159		feats = append(feats, v.Feature)
160	}
161	return feats
162}
163
164type BitC struct {
165	XMLName xml.Name `xml:"c"`
166	Cols    int      `xml:"colspan,attr"`
167	Value   string   `xml:",chardata"`
168}
169
170type Box struct {
171	XMLName    xml.Name `xml:"box"`
172	Bits       []BitC   `xml:"c"`
173	Name       string   `xml:"name,attr"`
174	Constraint string   `xml:"constraint,attr"`
175}
176
177type RegDiagram struct {
178	XMLName xml.Name `xml:"regdiagram"`
179	Name    string   `xml:"psname,attr"`
180	Boxes   []Box    `xml:"box"`
181}
182
183func (r RegDiagram) String() string {
184	b := &bytes.Buffer{}
185	for i, box := range r.Boxes {
186		if box.Name != "" {
187			fmt.Fprint(b, box.Name)
188		}
189		if box.Constraint != "" {
190			fmt.Fprint(b, strings.ReplaceAll(box.Constraint, " ", ""), "|")
191			continue
192		} else if box.Name != "" {
193			fmt.Fprint(b, "=")
194		}
195		for _, bit := range box.Bits {
196			if bit.Value == "" {
197				bit.Value = "x"
198			}
199			if bit.Cols == 0 {
200				bit.Cols = 1
201			}
202			bit.Value = strings.ReplaceAll(bit.Value, "(1)", "x")
203			bit.Value = strings.ReplaceAll(bit.Value, "(0)", "x")
204			fmt.Fprint(b, strings.Repeat(bit.Value, bit.Cols))
205		}
206		if i != len(r.Boxes)-1 {
207			fmt.Fprint(b, "|")
208		}
209	}
210	return b.String()
211}
212
213type Encoding struct {
214	XMLName xml.Name `xml:"encoding"`
215	Name    string   `xml:"name,attr"`
216	Docs    DocVars  `xml:"docvars"`
217}
218
219type IClass struct {
220	XMLName      xml.Name     `xml:"iclass"`
221	Name         string       `xml:"name,attr"`
222	Id           string       `xml:"id,attr"`
223	RegDiagram   RegDiagram   `xml:"regdiagram"`
224	ArchVariants ArchVariants `xml:"arch_variants"`
225	Code         PsSection    `xml:"ps_section"`
226	Encodings    []Encoding   `xml:"encoding"`
227	Docs         DocVars      `xml:"docvars"`
228}
229
230type Classes struct {
231	XMLName xml.Name `xml:"classes"`
232	IClass  []IClass `xml:"iclass"`
233}
234
235type InsnSection struct {
236	XMLName xml.Name  `xml:"instructionsection"`
237	Docs    DocVars   `xml:"docvars"`
238	Type    string    `xml:"type,attr"`
239	Id      string    `xml:"id,attr"`
240	Classes Classes   `xml:"classes"`
241	Code    PsSection `xml:"ps_section"`
242}
243
244type Assign struct {
245	Dest string
246	Src  string
247}
248
249func getAssigns(code string) []Assign {
250	lines := strings.Split(code, "\n")
251	var assigns []Assign
252	for _, l := range lines {
253		before, after, found := strings.Cut(l, " = ")
254		if !found {
255			continue
256		}
257		assigns = append(assigns, Assign{
258			Dest: before,
259			Src:  after,
260		})
261	}
262	return assigns
263}
264
265var linkrx = regexp.MustCompile(`<a.*?>`)
266
267func (is InsnSection) ReadSet() []string {
268	lines := strings.Split(is.Code.Ps.PsText.Content, "\n")
269	var set []string
270	for _, l := range lines {
271		if strings.Contains(l, "impl-aarch64.X.read.2") {
272			l = strings.ReplaceAll(l, "</a>", "")
273			l = linkrx.ReplaceAllLiteralString(l, "")
274			_, after, found := strings.Cut(l, "=")
275			if !found {
276				log.Fatal("no = in ", l)
277			}
278			set = append(set, strings.TrimSpace(after))
279		}
280	}
281	return set
282}
283
284func (is InsnSection) Uses(op string) bool {
285	lines := strings.Split(is.Code.Ps.PsText.Content, "\n")
286	for _, l := range lines {
287		if strings.Contains(l, op) {
288			return true
289		}
290	}
291	return false
292}
293
294func (is InsnSection) UsesPc() bool {
295	return is.Uses("impl-aarch64.PC.read.0")
296}
297
298func (is InsnSection) ReadsMem() bool {
299	return is.Uses("impl-aarch64.Mem.read.3")
300}
301
302func (is InsnSection) WritesMem() bool {
303	return is.Uses("impl-aarch64.Mem.write.3")
304}
305
306func (is InsnSection) MemAtomic() bool {
307	return is.Uses("impl-aarch64.MemAtomic.4")
308}
309
310func (is InsnSection) IsBranch() bool {
311	return is.Uses("impl-shared.BranchTo.3")
312}
313
314func (is InsnSection) BaseVariant() bool {
315	for _, c := range is.Classes.IClass {
316		if len(c.ArchVariants.Variants) != 0 {
317			return false
318		}
319	}
320	return true
321}
322
323func (is InsnSection) Variant(version string) bool {
324	for _, c := range is.Classes.IClass {
325		for _, v := range c.ArchVariants.Variants {
326			if v.Name == version {
327				return true
328			}
329		}
330	}
331	return false
332}
333
334func (is InsnSection) VariantLE(version string) bool {
335	for _, c := range is.Classes.IClass {
336		if len(c.ArchVariants.Variants) == 0 {
337			return true
338		}
339		for _, v := range c.ArchVariants.Variants {
340			if strings.Compare(v.Name, version) <= 0 {
341				return true
342			}
343		}
344	}
345	return false
346}
347
348func (is InsnSection) HasClass(class string) bool {
349	if class == "all" {
350		return true
351	}
352	for _, c := range is.Classes.IClass {
353		if c.Docs.InstrClass() == class {
354			return true
355		}
356	}
357	if is.Docs.InstrClass() != "" && is.Docs.InstrClass() == class {
358		return true
359	}
360	return false
361}
362
363func (is InsnSection) GetClasses() []string {
364	m := make(map[string]bool)
365	for _, c := range is.Classes.IClass {
366		if c.Docs.InstrClass() != "" {
367			m[c.Docs.InstrClass()] = true
368		}
369	}
370	if is.Docs.InstrClass() != "" {
371		m[is.Docs.InstrClass()] = true
372	}
373	var classes []string
374	for k := range m {
375		classes = append(classes, k)
376	}
377	return classes
378}
379
380func (is InsnSection) BaseArch() bool {
381	if !strings.Contains(InstrBase, is.Docs.InstrClass()) {
382		return false
383	}
384	return is.BaseVariant()
385}
386
387func (is InsnSection) MatchesArch(name string, feature string) bool {
388	for _, c := range is.Classes.IClass {
389		for _, v := range c.ArchVariants.Variants {
390			if strings.Contains(v.Name, name) && strings.Contains(v.Feature, feature) {
391				return true
392			}
393		}
394	}
395	return false
396}
397
398func (is InsnSection) WriteSet() []string {
399	lines := strings.Split(is.Code.Ps.PsText.Content, "\n")
400	set := make(map[string]bool)
401	for _, l := range lines {
402		if strings.Contains(l, "impl-aarch64.X.write.2") {
403			l = strings.ReplaceAll(l, "</a>", "")
404			l = linkrx.ReplaceAllLiteralString(l, "")
405			before, _, found := strings.Cut(l, "=")
406			if !found {
407				log.Fatal("no = in ", l)
408			}
409			set[strings.TrimSpace(before)] = true
410		}
411	}
412	var ret []string
413	for k := range set {
414		ret = append(ret, k)
415	}
416	return ret
417}
418
419func (is InsnSection) Names() []string {
420	set := make(map[string]bool)
421	for _, c := range is.Classes.IClass {
422		for _, e := range c.Encodings {
423			set[e.Docs.Mnemonic()] = true
424		}
425	}
426	var names []string
427	for k := range set {
428		names = append(names, k)
429	}
430	return names
431}
432
433type Record struct {
434	File       string
435	Name       string
436	IClass     string
437	Path       string
438	Variants   string
439	Features   string
440	InstrClass string
441	RegDiagram string
442}
443
444func NewRecords(file string, insn InsnSection) []Record {
445	var records []Record
446	for _, c := range insn.Classes.IClass {
447		set := make(map[string]bool)
448		for _, e := range c.Encodings {
449			set[e.Docs.Mnemonic()] = true
450		}
451		var names []string
452		for k := range set {
453			names = append(names, k)
454		}
455		records = append(records, Record{
456			File:       file,
457			Name:       strings.Join(names, ";"),
458			IClass:     c.Id,
459			Path:       c.RegDiagram.Name,
460			Variants:   strings.Join(c.ArchVariants.GetVariants(), ";"),
461			Features:   strings.Join(c.ArchVariants.GetFeatures(), ";"),
462			InstrClass: c.Docs.InstrClass(),
463			RegDiagram: c.RegDiagram.String(),
464		})
465	}
466	return records
467}