Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
352 lines (327 loc) · 10.4 KB
/
Copy pathmain.go
File metadata and controls
352 lines (327 loc) · 10.4 KB
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
// Command loopvec analyzes Go source files and rewrites element-wise loops
// to use the simd package for hardware vectorization.
//
// Usage:
//
// loopvec [-split | -w | -d] [-cpuprofile file] [-memprofile file] [packages...]
//
// Without flags, loopvec prints the rewritten source to stdout.
// With -split, loopvec writes the simd variant to file_simd.go and adds
// //go:build !goexperiment.simd to the original file.
// With -w, loopvec writes changes back to the source files in place.
// With -d, loopvec prints a unified diff for each changed file.
// With -cpuprofile or -memprofile, loopvec writes a pprof profile of its own
// run to the named file.
package main
import (
"encoding/json"
"flag"
"fmt"
"go/format"
"go/token"
"os"
"os/exec"
"runtime"
"runtime/pprof"
"strings"
"golang.org/x/tools/go/packages"
"github.com/mauri870/loopvec/internal/analysis"
"github.com/mauri870/loopvec/internal/rewrite"
)
var (
writeBack = flag.Bool("w", false, "write result to source files in place")
splitMode = flag.Bool("split", false, "write simd variant to file_simd.go and add //go:build !goexperiment.simd to original")
diffMode = flag.Bool("d", false, "display unified diff instead of rewritten source")
jsonMode = flag.Bool("json", false, "print one JSON line per candidate loop (file, line, func, vectorized, reason) instead of rewriting")
allowMethods = flag.Bool("methods", false, "rewrite loops inside methods (requires Go 1.28+ / gotip CL 839405 to avoid compiler crash)")
floatReassoc = flag.Bool("fp-reassoc", false, "rewrite floating-point sums and products by regrouping the additions, which can change the result in the last bits")
cpuProfile = flag.String("cpuprofile", "", "write a CPU profile of the run to `file`")
memProfile = flag.String("memprofile", "", "write a heap profile at the end of the run to `file`")
)
func main() {
flag.Parse()
patterns := flag.Args()
if len(patterns) == 0 {
patterns = []string{"."}
}
stopProfiles, err := startProfiles(*cpuProfile, *memProfile)
if err != nil {
fmt.Fprintln(os.Stderr, "loopvec:", err)
os.Exit(1)
}
err = run(patterns)
if perr := stopProfiles(); err == nil {
err = perr
}
if err != nil {
fmt.Fprintln(os.Stderr, "loopvec:", err)
os.Exit(1)
}
}
// startProfiles starts the CPU profile when cpuPath is set and returns a
// function that stops it and writes the heap profile when memPath is set.
func startProfiles(cpuPath, memPath string) (stop func() error, err error) {
var cpuFile *os.File
if cpuPath != "" {
cpuFile, err = os.Create(cpuPath)
if err != nil {
return nil, fmt.Errorf("cpuprofile: %w", err)
}
if err := pprof.StartCPUProfile(cpuFile); err != nil {
_ = cpuFile.Close()
return nil, fmt.Errorf("cpuprofile: %w", err)
}
}
return func() error {
if cpuFile != nil {
pprof.StopCPUProfile()
if err := cpuFile.Close(); err != nil {
return fmt.Errorf("cpuprofile: %w", err)
}
}
if memPath == "" {
return nil
}
f, err := os.Create(memPath)
if err != nil {
return fmt.Errorf("memprofile: %w", err)
}
// Collect first so the profile shows live memory, not garbage.
runtime.GC()
if err := pprof.WriteHeapProfile(f); err != nil {
_ = f.Close()
return fmt.Errorf("memprofile: %w", err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("memprofile: %w", err)
}
return nil
}, nil
}
func run(patterns []string) error {
fset := token.NewFileSet()
cfg := &packages.Config{
Mode: packages.NeedSyntax |
packages.NeedTypesInfo |
packages.NeedTypes |
packages.NeedFiles |
packages.NeedImports,
Fset: fset,
// Strip GOEXPERIMENT=simd so packages.Load always sees the scalar source.
// Without this, files tagged //go:build !goexperiment.simd are excluded
// when the caller runs loopvec under GOEXPERIMENT=simd.
Env: withoutGoExperimentSimd(os.Environ()),
}
pkgs, err := packages.Load(cfg, patterns...)
if err != nil {
return fmt.Errorf("load: %w", err)
}
hasErr := false
for _, pkg := range pkgs {
// Directories with only mage files or files excluded by build tags have
// nothing to analyze; go build ./... skips them silently, so do the same.
// Any other load failure (missing package, no go.mod) is reported below.
if len(pkg.Syntax) == 0 && (len(pkg.Errors) == 0 || hasNoBuildableFilesError(pkg)) {
continue
}
if packages.PrintErrors([]*packages.Package{pkg}) > 0 {
hasErr = true
continue
}
process := processPkg
if *jsonMode {
process = processPkgJSON
}
if err := process(fset, pkg, *allowMethods); err != nil {
fmt.Fprintf(os.Stderr, "loopvec: %s: %v\n", pkg.ID, err)
hasErr = true
}
}
if hasErr {
return fmt.Errorf("errors occurred")
}
return nil
}
// hasNoBuildableFilesError reports whether pkg failed to load because none of
// its Go files apply to the current build configuration.
func hasNoBuildableFilesError(pkg *packages.Package) bool {
for _, e := range pkg.Errors {
if strings.Contains(e.Msg, "build constraints exclude all Go files") ||
strings.Contains(e.Msg, "no Go files in") {
return true
}
}
return false
}
// withoutGoExperimentSimd returns env with "simd" removed from GOEXPERIMENT.
func withoutGoExperimentSimd(env []string) []string {
out := make([]string, 0, len(env))
for _, e := range env {
key, val, ok := strings.Cut(e, "=")
if ok && strings.EqualFold(key, "GOEXPERIMENT") {
filtered := []string{}
for x := range strings.SplitSeq(val, ",") {
if strings.TrimSpace(x) != "simd" {
filtered = append(filtered, x)
}
}
e = key + "=" + strings.Join(filtered, ",")
}
out = append(out, e)
}
return out
}
func processPkg(fset *token.FileSet, pkg *packages.Package, allowMethods bool) error {
info := pkg.TypesInfo
if info == nil {
return fmt.Errorf("no type info available")
}
helperDefined := false
for _, file := range pkg.Syntax {
tf := fset.File(file.Pos())
if tf == nil {
continue
}
path := tf.Name()
src, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("read %s: %w", path, err)
}
result, err := rewrite.File(fset, file, info, src, rewrite.Options{AllowMethods: allowMethods, FloatReassoc: *floatReassoc, HelperDefined: helperDefined})
if err != nil {
return fmt.Errorf("rewrite %s: %w", path, err)
}
helperDefined = helperDefined || result.DefinesHelper
if result.Rewrites == 0 {
continue
}
fmt.Fprintf(os.Stderr, "loopvec: rewrote %d loop(s) in %s\n", result.Rewrites, path)
switch {
case *splitMode:
simdPath := strings.TrimSuffix(path, ".go") + "_simd.go"
simdSrc := stripBuildConstraint(result.Src, "!goexperiment.simd")
if err := os.WriteFile(simdPath, simdSrc, 0o644); err != nil {
return err
}
tagged := addBuildTag(src, "!goexperiment.simd")
if err := os.WriteFile(path, tagged, 0o644); err != nil {
return err
}
case *writeBack:
if err := os.WriteFile(path, result.Src, 0o644); err != nil {
return err
}
case *diffMode:
if err := printDiff(path, src, result.Src); err != nil {
return err
}
default:
if _, err := os.Stdout.Write(result.Src); err != nil {
return err
}
}
}
return nil
}
// jsonCandidate is one line of -json output.
type jsonCandidate struct {
File string `json:"file"`
Line int `json:"line"`
Func string `json:"func"`
Vectorized bool `json:"vectorized"`
Reason string `json:"reason,omitempty"`
// Stage is the part of loopvec that rejected the loop; see
// loopir.Reason.Stage.
Stage string `json:"stage,omitempty"`
}
// processPkgJSON prints one JSON line per candidate loop in pkg to stdout:
// every loop with at least an indexed-assignment body, whether or not it got
// vectorized. Files with a build constraint are skipped, matching rewrite.File.
func processPkgJSON(fset *token.FileSet, pkg *packages.Package, allowMethods bool) error {
info := pkg.TypesInfo
if info == nil {
return fmt.Errorf("no type info available")
}
enc := json.NewEncoder(os.Stdout)
for _, file := range pkg.Syntax {
if rewrite.HasBuildConstraint(file) {
continue
}
for _, c := range analysis.AnalyzeExplain(fset, file, info, analysis.Options{AllowMethods: allowMethods, FloatReassoc: *floatReassoc}) {
line := jsonCandidate{
File: c.File,
Line: c.Line,
Func: c.Func,
Vectorized: c.Vectorized,
Reason: string(c.Reason),
}
if c.Reason != "" {
line.Stage = c.Reason.Stage()
}
if err := enc.Encode(line); err != nil {
return err
}
}
}
return nil
}
// stripBuildConstraint removes the //go:build <tag> line from src, then
// re-formats. Used in split mode to drop the !goexperiment.simd guard that
// the original file already carries, so the simd output has only its own tag.
func stripBuildConstraint(src []byte, tag string) []byte {
s := strings.ReplaceAll(string(src), "//go:build "+tag+"\n", "")
formatted, err := format.Source([]byte(s))
if err != nil {
return []byte(s)
}
return formatted
}
// addBuildTag inserts a //go:build constraint before the package clause if not
// already present. The constraint must appear before the package declaration
// and be separated from it by a blank line for the toolchain to recognize it.
func addBuildTag(src []byte, tag string) []byte {
constraint := "//go:build " + tag
s := string(src)
if strings.Contains(s, constraint) {
return src
}
idx := strings.Index(s, "package ")
if idx < 0 {
return src
}
modified := s[:idx] + constraint + "\n\n" + s[idx:]
formatted, err := format.Source([]byte(modified))
if err != nil {
return []byte(modified)
}
return formatted
}
// printDiff prints a unified diff between orig and rewritten for path,
// using the system diff command. Both sides are labeled with path, so the
// header does not depend on the temporary files or on which diff is installed
// (GNU and BSD diff print their timestamps differently).
func printDiff(path string, orig, rewritten []byte) error {
origFile, err := os.CreateTemp("", "loopvec-orig-*.go")
if err != nil {
return err
}
defer func() { _ = os.Remove(origFile.Name()) }()
if _, err := origFile.Write(orig); err != nil {
_ = origFile.Close()
return err
}
_ = origFile.Close()
newFile, err := os.CreateTemp("", "loopvec-new-*.go")
if err != nil {
return err
}
defer func() { _ = os.Remove(newFile.Name()) }()
if _, err := newFile.Write(rewritten); err != nil {
_ = newFile.Close()
return err
}
_ = newFile.Close()
out, _ := exec.Command("diff", "-u", "-L", path, "-L", path, origFile.Name(), newFile.Name()).Output()
_, err = os.Stdout.Write(out)
return err
}