Debian Codegraph @

x86/x86asm/testdata/genavxtests.go

raw symbols SCIP
1 // Copyright 2026 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // genavxtests generates test cases by running the assembler test
6 // files in reverse: given a binary encoding, expect the Plan 9/Go
7 // assembly input that produces the encoding. For GNU and Intel
8 // syntaxes, it uses objdump to retrieve the disassembly output.
9 package main
10
11 import (
12 "bufio"
13 "bytes"
14 "encoding/hex"
15 "fmt"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "regexp"
20 "runtime"
21 "strconv"
22 "strings"
23 )
24
25 var tmpDir string
26
27 func main() {
28 files := []string{
29 runtime.GOROOT() + "/src/cmd/asm/internal/asm/testdata/amd64enc.s",
30 runtime.GOROOT() + "/src/cmd/asm/internal/asm/testdata/amd64enc_extra.s",
31 }
32
33 // Assembler test is like
34 // " VPGATHERDQ Y2, (BP)(X7*2), Y1 // c4e2ed904c7d00"
35 hexRe := regexp.MustCompile(`^\s*(.*?)\s*//\s*([0-9a-fA-F]+)\s*$`)
36 type testCase struct {
37 hex string
38 plan9 string
39 }
40 var testCases []testCase
41 seen := make(map[string]bool)
42
43 for _, file := range files {
44 f, err := os.Open(file)
45 if err != nil {
46 fmt.Println("Error opening file:", err)
47 return
48 }
49
50 scanner := bufio.NewScanner(f)
51 for scanner.Scan() {
52 line := scanner.Text()
53 m := hexRe.FindStringSubmatch(line)
54 if len(m) == 3 {
55 plan9 := strings.TrimSpace(m[1])
56 if plan9 == "" || strings.HasPrefix(plan9, "//") {
57 continue
58 }
59 if !strings.HasPrefix(plan9, "V") && !strings.HasPrefix(plan9, "K") && !strings.HasPrefix(plan9, "SHA") {
60 // Test only AVX and SHA instructions for now. (There exist tests for
61 // non-AVX ones).
62 continue
63 }
64 h := strings.ToLower(m[2])
65 if !seen[h] {
66 seen[h] = true
67 testCases = append(testCases, testCase{hex: h, plan9: plan9})
68 }
69 }
70 }
71 f.Close()
72 }
73
74 var buf bytes.Buffer
75 var err error
76 tmpDir, err = os.MkdirTemp("", "avxtest")
77 if err != nil {
78 fmt.Println("Error creating temp dir:", err)
79 return
80 }
81 defer os.RemoveAll(tmpDir)
82
83 for _, tc := range testCases {
84 processHex(tc.hex, tc.plan9, &buf)
85 }
86
87 fmt.Println(buf.String())
88 }
89
90 func processHex(h string, plan9Asm string, buf *bytes.Buffer) {
91 b, err := hex.DecodeString(h)
92 if err != nil {
93 fmt.Printf("Error decoding hex %s: %v\n", h, err)
94 return
95 }
96
97 var s bytes.Buffer
98 s.WriteString(".text\n")
99 s.WriteString(".byte ")
100 for i, v := range b {
101 if i > 0 {
102 s.WriteString(",")
103 }
104 fmt.Fprintf(&s, "0x%02x", v)
105 }
106 s.WriteString("\n")
107
108 asmFile := filepath.Join(tmpDir, "testtmp.s")
109 objFile := filepath.Join(tmpDir, "testtmp.o")
110
111 err = os.WriteFile(asmFile, s.Bytes(), 0644)
112 if err != nil {
113 fmt.Println("Error writing testtmp.s:", err)
114 return
115 }
116
117 cmd := exec.Command("cc", "-arch", "x86_64", "-c", asmFile, "-o", objFile)
118 err = cmd.Run()
119 if err != nil {
120 fmt.Printf("Error compiling hex %s: %v\n", h, err)
121 return
122 }
123
124 gnuOut, _ := exec.Command("objdump", "-d", objFile).CombinedOutput()
125 intelOut, _ := exec.Command("objdump", "--x86-asm-syntax=intel", "-d", objFile).CombinedOutput()
126
127 gnuAsm := parseObjdump(string(gnuOut))
128 intelAsm := parseObjdump(string(intelOut))
129
130 // Normalize spaces
131 gnuAsm = strings.ReplaceAll(gnuAsm, "\t", " ")
132 intelAsm = strings.ReplaceAll(intelAsm, "\t", " ")
133 gnuAsm = strings.ReplaceAll(gnuAsm, ", ", ",")
134
135 intelAsm = strings.ReplaceAll(intelAsm, " + ", "+")
136 intelAsm = strings.ReplaceAll(intelAsm, " - ", "-")
137
138 // Normalize Plan 9 decimal offsets to hex since x86asm outputs them as hex.
139 rePlan9Num := regexp.MustCompile(`([\s\$])(-?[0-9]+)([\(,])`)
140 plan9Asm = rePlan9Num.ReplaceAllStringFunc(plan9Asm, func(m string) string {
141 matches := rePlan9Num.FindStringSubmatch(m)
142 prefix := matches[1]
143 numStr := matches[2]
144 suffix := matches[3]
145 n, _ := strconv.ParseInt(numStr, 10, 64)
146 if prefix == "$" && n < 0 && n >= -128 {
147 // Use unsigned immediate.
148 // TODO: check.
149 n = n & 0xff
150 }
151 if prefix != "$" && n == 0 { // 0 offset remains 0, not 0x0
152 return fmt.Sprintf("%s0%s", prefix, suffix)
153 }
154 if n < 0 {
155 return fmt.Sprintf("%s-0x%x%s", prefix, -n, suffix)
156 }
157 return fmt.Sprintf("%s0x%x%s", prefix, n, suffix)
158 })
159
160 rePlan9Mem := regexp.MustCompile(` \(([A-Z0-9]+)\)`)
161 plan9Asm = rePlan9Mem.ReplaceAllString(plan9Asm, " 0(${1})")
162
163 plan9Asm = strings.ReplaceAll(plan9Asm, ",", ", ")
164 plan9Asm = strings.ReplaceAll(plan9Asm, ", ", ", ")
165
166 padSize := 16 - len(b)
167 padding := ""
168 if padSize > 0 {
169 padding = strings.Repeat("5f", padSize)
170 }
171 hexStr := fmt.Sprintf("%s|%s", h, padding)
172
173 buf.WriteString(fmt.Sprintf("%s\t64\tplan9\t%s\n", hexStr, plan9Asm))
174 buf.WriteString(fmt.Sprintf("%s\t64\tgnu\t%s\n", hexStr, gnuAsm))
175 buf.WriteString(fmt.Sprintf("%s\t64\tintel\t%s\n", hexStr, intelAsm))
176 }
177
178 // parseObjdump extracts the assembly string from objdump output.
179 // It expects lines like: " 0: 62 f1 fd 48 2d c2 vaddpd %zmm2,%zmm21,%zmm2"
180 func parseObjdump(output string) string {
181 lines := strings.Split(output, "\n")
182 for _, line := range lines {
183 if strings.Contains(line, ":") && (strings.Contains(line, "\t") || strings.Contains(line, " ")) {
184 parts := strings.SplitN(strings.TrimSpace(line), ":", 2)
185 if len(parts) < 2 {
186 continue
187 }
188 body := strings.TrimSpace(parts[1])
189 var asm string
190 subParts := strings.SplitN(body, "\t", 2)
191 if len(subParts) == 2 {
192 asm = strings.TrimSpace(subParts[1])
193 } else {
194 idx := strings.Index(body, " ")
195 if idx > 0 {
196 asm = strings.TrimSpace(body[idx:])
197 } else {
198 continue
199 }
200 }
201 asm = strings.ReplaceAll(asm, "\t", " ")
202 if idx := strings.Index(asm, " ##"); idx >= 0 {
203 asm = strings.TrimSpace(asm[:idx])
204 }
205 if idx := strings.Index(asm, " #"); idx >= 0 {
206 asm = strings.TrimSpace(asm[:idx])
207 }
208 if idx := strings.Index(asm, " <"); idx >= 0 {
209 asm = strings.TrimSpace(asm[:idx])
210 }
211 return asm
212 }
213 }
214 return ""
215 }