Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion .github/workflows/benchmark.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,24 @@ jobs:
LLGO_ROOT: ${{ github.workspace }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0

- name: Determine pull request merge-base
if: github.event_name == 'pull_request'
id: merge-base
run: |
git fetch https://github.com/${{ github.event.pull_request.base.repo.full_name }}.git ${{ github.event.pull_request.base.ref }}
base_sha=$(git merge-base FETCH_HEAD ${{ github.event.pull_request.head.sha }})
echo "sha=$base_sha" >> "$GITHUB_OUTPUT"
echo "Computed pull request merge-base: $base_sha (head: ${{ github.event.pull_request.head.sha }})"
Comment on lines +41 to +44

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Untrusted event fields interpolated into a run step

The Determine pull request merge-base step expands ${{ github.event.pull_request.* }} directly into a shell run: block — the canonical GitHub Actions script-injection shape. Severity is low here: the trigger is pull_request (read-only GITHUB_TOKEN, no secrets), head.sha is a hex SHA, and base.repo.full_name/base.ref are base-side (maintainer-controlled for fork PRs). Recommend passing these through env: and referencing quoted shell variables (e.g. "$BASE_REF", "$HEAD_SHA") so the workflow stays safe against future refactors (e.g. to pull_request_target).


- name: Check out pull request base benchmark source
if: github.event_name == 'pull_request'
uses: actions/checkout@v7
with:
repository: ${{ github.event.pull_request.base.repo.full_name }}
ref: ${{ github.event.pull_request.base.sha }}
ref: ${{ steps.merge-base.outputs.sha }}
path: .benchmark/source
persist-credentials: false

Expand Down
6 changes: 3 additions & 3 deletions benchmark/baseline/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ commit, branch, or pull-request series.

The program workloads reuse:

- `benchmark/binary_size/cprintf`: only `lib/c.Printf`;
- `benchmark/binary_size/println`: only the built-in `println`;
- `benchmark/binary_size/fmtprintf`: `fmt.Printf`.
- `benchmark/binary_size/cprintf`: only `lib/c.Printf` (default and `-lto=full`);
- `benchmark/binary_size/println`: only the built-in `println` (default and `-lto=full`);
- `benchmark/binary_size/fmtprintf`: `fmt.Printf` (default and `-lto=full`).

For each workload, the collector performs an unmeasured warm build, then records
median build time, median process time, file size, executable-code bytes,
Expand Down
10 changes: 8 additions & 2 deletions benchmark/baseline/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,16 @@ type workload struct {
name string
source string
output string
flags []string
}

var workloads = []workload{
{name: "cprintf", source: "benchmark/binary_size/cprintf/main.go", output: "Hello, world\n"},
{name: "cprintf_lto", source: "benchmark/binary_size/cprintf/main.go", output: "Hello, world\n", flags: []string{"-lto=full"}},
{name: "println", source: "benchmark/binary_size/println/main.go", output: "Hello, world\n"},
{name: "println_lto", source: "benchmark/binary_size/println/main.go", output: "Hello, world\n", flags: []string{"-lto=full"}},
{name: "fmtprintf", source: "benchmark/binary_size/fmtprintf/main.go", output: "Hello, world\n"},
{name: "fmtprintf_lto", source: "benchmark/binary_size/fmtprintf/main.go", output: "Hello, world\n", flags: []string{"-lto=full"}},
}

var expectedGoBenchmarks = []string{
Expand Down Expand Up @@ -223,15 +227,17 @@ func collect(ctx context.Context, root, llgo, out string, buildRuns, runRuns int
var sizes, timings []metric
for _, item := range workloads {
binary := filepath.Join(binDir, item.name)
buildArgs := append([]string{"build"}, item.flags...)
buildArgs = append(buildArgs, "-o", binary, filepath.Join(root, item.source))
// Keep first-use toolchain and filesystem caches out of the measured
// median so the first revision is not systematically disadvantaged.
if err := run(ctx, env, io.Discard, llgo, "build", "-o", binary, filepath.Join(root, item.source)); err != nil {
if err := run(ctx, env, io.Discard, llgo, buildArgs...); err != nil {
return fmt.Errorf("warm build %s: %w", item.name, err)
}
buildDurations := make([]time.Duration, 0, buildRuns)
for range buildRuns {
start := time.Now()
if err := run(ctx, env, io.Discard, llgo, "build", "-o", binary, filepath.Join(root, item.source)); err != nil {
if err := run(ctx, env, io.Discard, llgo, buildArgs...); err != nil {
return fmt.Errorf("build %s: %w", item.name, err)
}
buildDurations = append(buildDurations, time.Since(start))
Expand Down
1 change: 1 addition & 0 deletions benchmark/baseline/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ func TestExportBenchmarks(t *testing.T) {
"Unit file-bytes better=lower assume=exact",
"Unit build-ns better=lower",
"BenchmarkProgram/cprintf 1 1 file-bytes 1 text-bytes 1 data-bytes 1 bss-bytes 1 build-ns 1 run-ns",
"BenchmarkProgram/cprintf_lto 1 1 file-bytes 1 text-bytes 1 data-bytes 1 bss-bytes 1 build-ns 1 run-ns",
"BenchmarkRuntimeGetG-1 100 12.5 ns/op",
} {
if !strings.Contains(text, want) {
Expand Down
277 changes: 265 additions & 12 deletions cl/rewrite_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,12 @@ func Use() string {
if strings.Contains(ir, "@staticinit.MethodNames = global %staticinit.Names zeroinitializer") {
t.Fatalf("MethodNames still uses a zero initializer:\n%s", ir)
}
if !strings.Contains(ir, `[%"github.com/xgo-dev/llgo/runtime/internal/runtime.String" { ptr @0, i64 9 }, %"github.com/xgo-dev/llgo/runtime/internal/runtime.String" { ptr @1, i64 12 }]`) {
t.Fatalf("unexpected MethodNames.Value initializer:\n%s", ir)
}
if !strings.Contains(ir, `%staticinit.Nested { [2 x %"github.com/xgo-dev/llgo/runtime/internal/runtime.String"] [%"github.com/xgo-dev/llgo/runtime/internal/runtime.String" { ptr @2, i64 8 }, %"github.com/xgo-dev/llgo/runtime/internal/runtime.String" { ptr @3, i64 11 }] }`) {
t.Fatalf("unexpected MethodNames.Nested initializer:\n%s", ir)
}
for _, want := range []string{`c"KeepValue"`, `c"KeepValueAlt"`, `c"KeepType"`, `c"KeepTypeAlt"`} {
if !strings.Contains(ir, want) {
t.Fatalf("missing %s in IR:\n%s", want, ir)
Expand Down Expand Up @@ -320,9 +326,8 @@ var Value = Outer{
}

var (
blankSliceField *ssa.FieldAddr
sawDirectBlank, sawNestedBlank bool
sawBlankArray, sawNonBlankSibling bool
blankSliceField *ssa.FieldAddr
sawDirectBlank, sawNonBlankSibling bool
)
initFn := pkg.Func("init")
for _, block := range initFn.Blocks {
Expand Down Expand Up @@ -353,21 +358,15 @@ var Value = Outer{
switch {
case len(fields) == 1 && fields[0] == "_":
sawDirectBlank = true
case len(fields) > 1 && want && !indexed:
sawNestedBlank = true
case want && indexed:
sawBlankArray = true
case !want:
case !want && !indexed:
sawNonBlankSibling = true
}
}
}
if !sawDirectBlank || !sawNestedBlank || !sawBlankArray || !sawNonBlankSibling {
if !sawDirectBlank || !sawNonBlankSibling {
t.Fatalf(
"missing SSA classification coverage: direct=%v nested=%v array=%v sibling=%v",
"missing SSA classification coverage: direct=%v sibling=%v",
sawDirectBlank,
sawNestedBlank,
sawBlankArray,
sawNonBlankSibling,
)
}
Expand Down Expand Up @@ -435,6 +434,41 @@ func Use() string { return CallbackTypes[1] }
}
}

func TestStaticGlobalStructSliceLiteralInit(t *testing.T) {
const src = `package staticinit

type Info struct {
Name string
Package string
Changed int
}

var All = []Info{
{"godebug1", "runtime", 1},
{"godebug2", "internal/poll", 2},
}

func Use() Info { return All[0] }
`
ir := compileWithRewrites(t, src, nil)
for _, want := range []string{
`@"staticinit.All$data" = global [2 x %staticinit.Info]`,
`@staticinit.All = global %"github.com/xgo-dev/llgo/runtime/internal/runtime.Slice" { ptr @"staticinit.All$data", i64 2, i64 2 }`,
`c"godebug1"`,
`c"runtime"`,
`c"godebug2"`,
`c"internal/poll"`,
} {
if !strings.Contains(ir, want) {
t.Fatalf("missing static struct slice initializer %q in IR:\n%s", want, ir)
}
}
assertNoStoreToGlobal(t, ir, "@staticinit.All")
if strings.Contains(ir, "runtime.AllocZ") {
t.Fatalf("static struct slice initializer still allocates at runtime:\n%s", ir)
}
}

func TestStaticSliceInitRejectsExecutableReferrers(t *testing.T) {
const src = `package foo

Expand Down Expand Up @@ -1382,3 +1416,222 @@ func f() {}
t.Fatal("compiled owner should be cached")
}
}

func TestCollectAllocStoresFromSSA(t *testing.T) {
const src = `package allocstore

type Point struct {
X, Y int
}

type Nested struct {
P Point
Arr [2]int
Tag string
}

func testConstNested() Nested {
return Nested{
P: Point{10, 20},
Arr: [2]int{30, 40},
Tag: "hello",
}
}

func testConstPoint() Point {
return Point{100, 200}
}

func testDynamic() Point {
return Point{next(), 200}
}

func testCall(p Point) {}

func testEscape() {
var p = Point{1, 2}
testCall(p)
var n = Nested{P: Point{3, 4}}
pRef := &n.P
pRef.X = 99
}

func testArrayInit() [2]int {
var a [2]int
a[0] = 10
a[1] = 20
return a
}

func testDirectStore() int {
var x int
x = 42
return x
}

func testArrayDynamic() [2]int {
var a [2]int
a[0] = next()
return a
}

func next() int { return 1 }
`
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "allocstore.go", src, 0)
if err != nil {
t.Fatal(err)
}
importer := gpackages.NewImporter(fset)
pkg, _, err := ssautil.BuildPackage(
&types.Config{Importer: importer},
fset,
types.NewPackage("allocstore", "allocstore"),
[]*ast.File{file},
ssa.SanityCheckFunctions,
)
if err != nil {
t.Fatal(err)
}

var foundAllocs []*ssa.Alloc
var foundStores []*ssa.Store
var foundFields []*ssa.FieldAddr
var foundIndices []*ssa.IndexAddr

for _, member := range pkg.Members {
fn, ok := member.(*ssa.Function)
if !ok {
continue
}
for _, block := range fn.Blocks {
for _, instr := range block.Instrs {
switch instr := instr.(type) {
case *ssa.Alloc:
if !instr.Heap {
foundAllocs = append(foundAllocs, instr)
}
case *ssa.Store:
foundStores = append(foundStores, instr)
case *ssa.FieldAddr:
foundFields = append(foundFields, instr)
case *ssa.IndexAddr:
foundIndices = append(foundIndices, instr)
}
}
}
}

if len(foundAllocs) == 0 {
t.Fatal("expected to find local allocs in SSA")
}

// Test collectAllocStores on all found allocs
for _, alloc := range foundAllocs {
var stores []staticInitStore
var instrs []ssa.Instruction
collectAllocStores(alloc, nil, &stores, &instrs, make(map[*ssa.Alloc]bool))
collectAllocStores(alloc, []staticInitPathElem{{index: 1}}, &stores, &instrs, make(map[*ssa.Alloc]bool))
}

targetAlloc := foundAllocs[0]

// 1. Cycle detection
var stores []staticInitStore
var instrs []ssa.Instruction
visited := map[*ssa.Alloc]bool{targetAlloc: true}
if collectAllocStores(targetAlloc, nil, &stores, &instrs, visited) {
t.Fatal("expected cycle protection to return false")
}

// 2. appendStaticInitPath
p1 := []staticInitPathElem{{index: 1}, {index: 2}}
p2 := []staticInitPathElem{{index: 3}}
merged := appendStaticInitPath(p1, p2)
if len(merged) != 3 || merged[0].index != 1 || merged[1].index != 2 || merged[2].index != 3 {
t.Fatalf("unexpected appendStaticInitPath result: %+v", merged)
}

// 3. handleStoreVal branches
if len(foundStores) > 0 {
store := foundStores[0]
// Test Const store
cStore := &ssa.Store{Addr: store.Addr, Val: ssa.NewConst(constant.MakeInt64(1), types.Typ[types.Int])}
stores = nil
if !handleStoreVal(cStore, p1, &stores, &instrs, make(map[*ssa.Alloc]bool)) {
t.Fatal("handleStoreVal failed on const")
}
if len(stores) != 1 || len(stores[0].path) != 2 {
t.Fatalf("unexpected handleStoreVal result: %+v", stores)
}

// Test non-const non-unop store
badStore := &ssa.Store{Addr: store.Addr, Val: store.Addr}
if handleStoreVal(badStore, p1, &stores, &instrs, make(map[*ssa.Alloc]bool)) {
t.Fatal("expected handleStoreVal to fail on non-const, non-alloc Val")
}

// Test Heap alloc
heapAlloc := &ssa.Alloc{Heap: true, Comment: "heap"}
heapUnOp := &ssa.UnOp{Op: token.MUL, X: heapAlloc}
heapStore := &ssa.Store{Addr: store.Addr, Val: heapUnOp}
if handleStoreVal(heapStore, p1, &stores, &instrs, make(map[*ssa.Alloc]bool)) {
t.Fatal("expected handleStoreVal to fail on heap alloc")
}
}

// 4. staticInitStorePathToAlloc edge cases
if _, ok := staticInitStorePathToAlloc(nil, targetAlloc); ok {
t.Fatal("expected nil addr to fail")
}
if path, ok := staticInitStorePathToAlloc(targetAlloc, targetAlloc); !ok || len(path) != 0 {
t.Fatalf("expected exact alloc to return empty path, got %+v, %v", path, ok)
}
if len(foundAllocs) > 1 {
if _, ok := staticInitStorePathToAlloc(foundAllocs[1], targetAlloc); ok {
t.Fatal("expected different alloc to fail")
}
}
if len(foundFields) > 0 {
field := foundFields[0]
_, _ = staticInitStorePathToAlloc(field, targetAlloc)
}
if len(foundIndices) > 0 {
index := foundIndices[0]
_, _ = staticInitStorePathToAlloc(index, targetAlloc)
}
}

func TestStaticGlobalPointerIndirectionLiteralInit(t *testing.T) {
const src = `package staticinit

type Inner struct {
A [2]int
B string
}

type Outer struct {
I Inner
Val int
}

var G = Outer{
I: Inner{
A: [2]int{10, 20},
B: "hello",
},
Val: 99,
}

func Use() int {
return G.I.A[0] + G.I.A[1] + len(G.I.B) + G.Val
}
`
ir := compileWithRewrites(t, src, nil)
if strings.Contains(ir, "@staticinit.G = global %staticinit.Outer zeroinitializer") {
t.Fatalf("G still uses a zero initializer:\n%s", ir)
}
if !strings.Contains(ir, `c"hello"`) {
t.Fatalf("missing hello in IR:\n%s", ir)
}
}
Loading
Loading