From f6650e68d7664a9eef4f372a50a28bd37fe2026a Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Sat, 25 Jul 2026 01:26:30 +0800 Subject: [PATCH 01/12] build: prepare bounded parallel compilation --- internal/build/build.go | 283 ++++++++++++++++++---------- internal/build/collect.go | 35 ++-- internal/build/dependencies.go | 52 +++++ internal/build/dependencies_test.go | 46 +++++ internal/build/fingerprint_test.go | 7 +- internal/build/module_hook_test.go | 1 + internal/goflags/flagfile.go | 1 + internal/goflags/gobuild.go | 33 +++- internal/goflags/gobuild_test.go | 25 +++ 9 files changed, 363 insertions(+), 120 deletions(-) create mode 100644 internal/build/dependencies.go create mode 100644 internal/build/dependencies_test.go diff --git a/internal/build/build.go b/internal/build/build.go index bc96bd469b..cc1ba01b40 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -183,6 +183,9 @@ type Config struct { // DisableBoundsChecks disables index, slice, and slice-to-array conversion // bounds checks while retaining required integer conversions and nil checks. DisableBoundsChecks bool + // Parallel is the maximum number of LLGo's internally parallel build tasks. + // Zero uses GOMAXPROCS, matching the Go command's default -p behavior. + Parallel int // PthreadStackSize sets a custom stack size, in bytes, for pthread-backed // goroutines. A zero value keeps the platform pthread default. @@ -281,7 +284,19 @@ const ( loadSyntax = loadTypes | packages.NeedSyntax | packages.NeedTypesInfo ) +var llssaInitOnce sync.Once + +func (c *Config) parallelism() int { + if c != nil && c.Parallel > 0 { + return c.Parallel + } + return runtime.GOMAXPROCS(0) +} + func Do(args []string, conf *Config) ([]Package, error) { + if conf.Parallel < 0 { + return nil, fmt.Errorf("parallelism must not be negative: %d", conf.Parallel) + } if conf.Goos == "" { conf.Goos = runtime.GOOS } @@ -372,7 +387,9 @@ func Do(args []string, conf *Config) ([]Package, error) { cl.EnableDebug(emitDebugInfo) cl.EnableDbgSyms(emitDebugInfo) cl.EnableTrace(IsTraceEnabled()) - llssa.Initialize(llssa.InitAll) + llssaInitOnce.Do(func() { + llssa.Initialize(llssa.InitAll) + }) target := &llssa.Target{ GOOS: conf.Goos, @@ -498,7 +515,6 @@ func Do(args []string, conf *Config) ([]Package, error) { } progSSA := ssa.NewProgram(initial[0].Fset, buildMode) patches := make(cl.Patches, len(altPkgPaths)) - altSSAPkgs(progSSA, patches, altPkgs[1:], conf, verbose) env := llvm.New("") os.Setenv("PATH", env.BinDir()+":"+os.Getenv("PATH")) // TODO(xsw): check windows @@ -515,20 +531,24 @@ func Do(args []string, conf *Config) ([]Package, error) { buildConf: conf, crossCompile: export, cTransformer: cabi.NewTransformer(prog, export.LLVMTarget, export.TargetABI, conf.AbiMode, cabiOptimize), + sfilesCache: make(map[string][]string), } defer ctx.closePackageMetas() + ctx.initializePackageBuildState() // default runtime globals must be registered before packages are built addGlobalString(conf, "runtime.defaultGOROOT="+runtime.GOROOT(), nil) addGlobalString(conf, "runtime.buildVersion="+runtime.Version(), nil) - pkgs, err := buildSSAPkgs(ctx, initial, verbose) + altEntries := registerAltSSAPkgs(progSSA, patches, altPkgs[1:], conf, verbose) + pkgs, pkgEntries, err := registerSSAPkgs(ctx, initial, verbose) if err != nil { return nil, err } - depPkgs, err := buildSSAPkgs(ctx, altPkgs, verbose) + depPkgs, depEntries, err := registerSSAPkgs(ctx, altPkgs, verbose) if err != nil { return nil, err } + buildSSAPkgs(ctx, append(append(altEntries, pkgEntries...), depEntries...)) allPkgs := append([]*aPackage{}, pkgs...) allPkgs = append(allPkgs, depPkgs...) @@ -769,8 +789,9 @@ type context struct { testFail bool // Cache related fields - cacheManager *cacheManager - llvmVersion string + cacheManager *cacheManager + llvmVersion string + llvmVersionReady bool // go list derived file lists (SFiles, etc.) sfilesCache map[string][]string // pkg.ID -> absolute .s/.S file paths @@ -857,8 +878,6 @@ func normalizeToArchive(ctx *context, aPkg *aPackage, verbose bool) error { } func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, error) { - built := ctx.built - // Split packages into runtime tree vs others so we can defer runtime build. var runtimePkgs []*aPackage var normalPkgs []*aPackage @@ -872,91 +891,20 @@ func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, er var needRuntime, needPyInit bool - buildOne := func(aPkg *aPackage) error { - pkg := aPkg.Package - if _, ok := built[pkg.ID]; ok { - // Already built, skip but keep ExportFile for linking - return nil - } - built[pkg.ID] = none{} - - switch kind, param := cl.PkgKindOf(pkg.Types); kind { - case cl.PkgDeclOnly: - pkg.ExportFile = "" - case cl.PkgLinkIR, cl.PkgLinkExtern, cl.PkgPyModule: - if len(pkg.GoFiles) > 0 { - if err := ctx.collectFingerprint(aPkg); err != nil { - return err - } - ctx.tryLoadFromCache(aPkg) - if verbose { - if aPkg.CacheHit { - fmt.Fprintf(os.Stderr, "CACHE HIT: %s\n", pkg.PkgPath) - } else { - fmt.Fprintf(os.Stderr, "CACHE MISS: %s\n", pkg.PkgPath) - } - } - if err := buildPkg(ctx, aPkg, verbose); err != nil { - return err - } - if !aPkg.CacheHit { - if err := normalizeToArchive(ctx, aPkg, verbose); err != nil { - return err - } - if kind == cl.PkgLinkExtern { - appendExternalLinkArgs(ctx, aPkg, param) - } - if err := ctx.saveToCache(aPkg); err != nil && verbose { - fmt.Fprintf(os.Stderr, "warning: failed to save cache for %s: %v\n", pkg.PkgPath, err) - } - } - } else { - pkg.ExportFile = "" - if kind == cl.PkgLinkExtern { - appendExternalLinkArgs(ctx, aPkg, param) - } - } - default: - if err := ctx.collectFingerprint(aPkg); err != nil { - return err - } - ctx.tryLoadFromCache(aPkg) - if verbose { - if aPkg.CacheHit { - fmt.Fprintf(os.Stderr, "CACHE HIT: %s\n", pkg.PkgPath) - } else { - fmt.Fprintf(os.Stderr, "CACHE MISS: %s\n", pkg.PkgPath) - } - } - if err := buildPkg(ctx, aPkg, verbose); err != nil { - return err - } - aPkg.setNeedRuntimeOrPyInit(aPkg.LPkg.NeedRuntime, aPkg.LPkg.NeedPyInit) - needRuntime = needRuntime || aPkg.NeedRt - needPyInit = needPyInit || aPkg.NeedPyInit - if !aPkg.CacheHit { - if err := normalizeToArchive(ctx, aPkg, verbose); err != nil { - return err - } - if err := ctx.saveToCache(aPkg); err != nil && verbose { - fmt.Fprintf(os.Stderr, "warning: failed to save cache for %s: %v\n", pkg.PkgPath, err) - } - } - } - return nil - } - // Build non-runtime packages first, so we know whether runtime is actually needed. for _, p := range normalPkgs { - if err := buildOne(p); err != nil { + result, err := buildOnePackage(ctx, p, verbose) + if err != nil { return nil, err } + needRuntime = needRuntime || result.needRuntime + needPyInit = needPyInit || result.needPyInit } // Only build runtime packages when required (or host build with empty Target). if needRuntime || needPyInit || ctx.buildConf.Target == "" { for _, p := range runtimePkgs { - if err := buildOne(p); err != nil { + if _, err := buildOnePackage(ctx, p, verbose); err != nil { return nil, err } } @@ -965,6 +913,69 @@ func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, er return pkgs, nil } +type packageBuildResult struct { + needRuntime bool + needPyInit bool +} + +// buildOnePackage is the serial package pipeline. The stages are separated so +// a future scheduler can parallelize only stages with isolated package state. +func buildOnePackage(ctx *context, aPkg *aPackage, verbose bool) (packageBuildResult, error) { + pkg := aPkg.Package + if _, ok := ctx.built[pkg.ID]; ok { + return packageBuildResult{}, nil + } + ctx.built[pkg.ID] = none{} + + kind, param := cl.PkgKindOf(pkg.Types) + if kind == cl.PkgDeclOnly { + pkg.ExportFile = "" + return packageBuildResult{}, nil + } + if (kind == cl.PkgLinkIR || kind == cl.PkgLinkExtern || kind == cl.PkgPyModule) && len(pkg.GoFiles) == 0 { + pkg.ExportFile = "" + if kind == cl.PkgLinkExtern { + appendExternalLinkArgs(ctx, aPkg, param) + } + return packageBuildResult{}, nil + } + + if err := ctx.collectFingerprint(aPkg); err != nil { + return packageBuildResult{}, err + } + ctx.tryLoadFromCache(aPkg) + if verbose { + status := "MISS" + if aPkg.CacheHit { + status = "HIT" + } + fmt.Fprintf(os.Stderr, "CACHE %s: %s\n", status, pkg.PkgPath) + } + if err := buildPkg(ctx, aPkg, verbose); err != nil { + return packageBuildResult{}, err + } + + result := packageBuildResult{} + if kind != cl.PkgLinkIR && kind != cl.PkgLinkExtern && kind != cl.PkgPyModule { + aPkg.setNeedRuntimeOrPyInit(aPkg.LPkg.NeedRuntime, aPkg.LPkg.NeedPyInit) + result.needRuntime = aPkg.NeedRt + result.needPyInit = aPkg.NeedPyInit + } + if aPkg.CacheHit { + return result, nil + } + if err := normalizeToArchive(ctx, aPkg, verbose); err != nil { + return packageBuildResult{}, err + } + if kind == cl.PkgLinkExtern { + appendExternalLinkArgs(ctx, aPkg, param) + } + if err := ctx.saveToCache(aPkg); err != nil && verbose { + fmt.Fprintf(os.Stderr, "warning: failed to save cache for %s: %v\n", pkg.PkgPath, err) + } + return result, nil +} + func appendExternalLinkArgs(ctx *context, aPkg *aPackage, spec string) { // need to be linked with external library // format: ';' separated alternative link methods. e.g. @@ -1618,6 +1629,16 @@ func is32Bits(goarch string) bool { } func buildPkg(ctx *context, aPkg *aPackage, verbose bool) error { + externs, err := preparePackageModule(ctx, aPkg, verbose) + if err != nil || aPkg.CacheHit || aPkg.LPkg == nil { + return err + } + return compilePackageModule(ctx, aPkg, externs, verbose) +} + +// preparePackageModule runs the frontend and creates the package LLVM module. +// This stage remains serial because it updates Program-wide registration state. +func preparePackageModule(ctx *context, aPkg *aPackage, verbose bool) ([]string, error) { pkg := aPkg.Package pkgPath := pkg.PkgPath if debugBuild || verbose { @@ -1627,7 +1648,7 @@ func buildPkg(ctx *context, aPkg *aPackage, verbose bool) error { } if llruntime.SkipToBuild(pkgPath) { pkg.ExportFile = "" - return nil + return nil, nil } var syntax = pkg.Syntax if altPkg := aPkg.AltPkg; altPkg != nil { @@ -1645,7 +1666,7 @@ func buildPkg(ctx *context, aPkg *aPackage, verbose bool) error { embedMap, err := goembed.LoadDirectives(ctx.conf.Fset, syntax) if err != nil { - return fmt.Errorf("load go:embed directives for %s failed: %w", pkgPath, err) + return nil, fmt.Errorf("load go:embed directives for %s failed: %w", pkgPath, err) } needMeta := !aPkg.CacheHit && ctx.buildConf.packageMetaEnabled() @@ -1662,8 +1683,18 @@ func buildPkg(ctx *context, aPkg *aPackage, verbose bool) error { // If cache hit, we only needed to register types - skip compilation if aPkg.CacheHit { - return nil + return nil, nil } + return externs, nil +} + +// compilePackageModule applies LLVM transforms and emits package objects. +// It receives a module owned by aPkg and is intentionally kept separate from +// frontend setup so later PRs can give it a worker-local backend context. +func compilePackageModule(ctx *context, aPkg *aPackage, externs []string, verbose bool) error { + pkg := aPkg.Package + pkgPath := pkg.PkgPath + ret := aPkg.LPkg ctx.cTransformer.SetSkipFuncs(cabiSkipFuncsForPlan9Asm(ctx, pkgPath, ret.Module())) llabi.LowerLargeAggregates(ctx.prog.TargetData(), ret.Module()) @@ -1933,13 +1964,24 @@ func preCollectRuntimeLinknames(prog llssa.Program, pkgs []*packages.Package) { } } -func altSSAPkgs(prog *ssa.Program, patches cl.Patches, alts []*packages.Package, conf *Config, verbose bool) { +type ssaBuildEntry struct { + pkg *ssa.Package + syntax []*ast.File + fixOrder bool +} + +// registerAltSSAPkgs creates the alternate packages and patch table before any +// SSA package is built. Building is deliberately deferred so every package can +// be built under the same bounded worker pool. +func registerAltSSAPkgs(prog *ssa.Program, patches cl.Patches, alts []*packages.Package, conf *Config, verbose bool) []ssaBuildEntry { + var entries []ssaBuildEntry packages.Visit(alts, nil, func(p *packages.Package) { if typs := p.Types; typs != nil && !p.IllTyped { if debugBuild || verbose { log.Println("==> BuildSSA", p.ID) } pkgSSA := prog.CreatePackage(typs, p.Syntax, p.TypesInfo, true) + entries = append(entries, ssaBuildEntry{pkg: pkgSSA, syntax: p.Syntax}) if strings.HasPrefix(p.ID, altPkgPathPrefix) { path := p.ID[len(altPkgPathPrefix):] // Even if an alt package exists and is pulled in as a dependency of other @@ -1955,7 +1997,7 @@ func altSSAPkgs(prog *ssa.Program, patches cl.Patches, alts []*packages.Package, } } }) - prog.Build() + return entries } type aPackage struct { @@ -1981,9 +2023,13 @@ type aPackage struct { type Package = *aPackage -func buildSSAPkgs(ctx *context, initial []*packages.Package, verbose bool) ([]*aPackage, error) { +// registerSSAPkgs creates all ordinary SSA packages and returns their build +// entries. It intentionally performs no Package.Build calls: applying patches +// and registering the full package graph must remain serial. +func registerSSAPkgs(ctx *context, initial []*packages.Package, verbose bool) ([]*aPackage, []ssaBuildEntry, error) { prog := ctx.progSSA var all []*aPackage + var entries []ssaBuildEntry var errs []*packages.Package packages.Visit(initial, nil, func(p *packages.Package) { if p.Types != nil && !p.IllTyped { @@ -1993,7 +2039,10 @@ func buildSSAPkgs(ctx *context, initial []*packages.Package, verbose bool) ([]*a return } var altPkg *packages.Cached - var ssaPkg = createSSAPkg(ctx, prog, p, verbose) + ssaPkg, created := createSSAPkg(ctx, prog, p, verbose) + if created { + entries = append(entries, ssaBuildEntry{pkg: ssaPkg, syntax: p.Syntax, fixOrder: true}) + } if ctx.hasAltPkg(pkgPath) { if altPkg = ctx.dedup.Check(altPkgPathPrefix + pkgPath); altPkg == nil { return @@ -2025,9 +2074,49 @@ func buildSSAPkgs(ctx *context, initial []*packages.Package, verbose bool) ([]*a } fmt.Fprintln(os.Stderr, "cannot build SSA for package", errPkg) } - return nil, fmt.Errorf("cannot build SSA for packages") + return nil, nil, fmt.Errorf("cannot build SSA for packages") + } + return all, entries, nil +} + +// buildSSAPkgs builds registered packages with the configured bound, then +// performs ordering repair serially because it mutates package instruction +// slices. go/ssa.Package.Build is documented as safe for concurrent calls. +func buildSSAPkgs(ctx *context, entries []ssaBuildEntry) { + if len(entries) == 0 { + return + } + unique := make([]ssaBuildEntry, 0, len(entries)) + seen := make(map[*ssa.Package]bool, len(entries)) + for _, entry := range entries { + if entry.pkg == nil || seen[entry.pkg] { + continue + } + seen[entry.pkg] = true + unique = append(unique, entry) + } + workers := min(ctx.buildConf.parallelism(), len(unique)) + jobs := make(chan ssaBuildEntry) + var wg sync.WaitGroup + for range workers { + wg.Add(1) + go func() { + defer wg.Done() + for entry := range jobs { + entry.pkg.Build() + } + }() + } + for _, entry := range unique { + jobs <- entry + } + close(jobs) + wg.Wait() + for _, entry := range unique { + if entry.fixOrder { + fixSSAOrder(entry.pkg, entry.syntax) + } } - return all, nil } func formatPackageError(err packages.Error, noColumn bool) string { @@ -2175,7 +2264,7 @@ func applyPatches(ctx *context, p *packages.Package, verbose bool) { } } -func createSSAPkg(ctx *context, prog *ssa.Program, p *packages.Package, verbose bool) *ssa.Package { +func createSSAPkg(ctx *context, prog *ssa.Program, p *packages.Package, verbose bool) (*ssa.Package, bool) { pkgSSA := prog.ImportedPackage(p.ID) if pkgSSA == nil { if debugBuild || verbose { @@ -2183,11 +2272,9 @@ func createSSAPkg(ctx *context, prog *ssa.Program, p *packages.Package, verbose } applyPatches(ctx, p, verbose) pkgSSA = prog.CreatePackage(p.Types, p.Syntax, p.TypesInfo, true) - pkgSSA.Build() // TODO(xsw): build concurrently - // Apply local SSA fixups once when package SSA is first built. - fixSSAOrder(pkgSSA, p.Syntax) + return pkgSSA, true } - return pkgSSA + return pkgSSA, false } /* diff --git a/internal/build/collect.go b/internal/build/collect.go index e89db4d1c5..48cfc4726a 100644 --- a/internal/build/collect.go +++ b/internal/build/collect.go @@ -23,7 +23,6 @@ import ( "os/exec" "path/filepath" "runtime" - "sort" "strconv" "strings" @@ -196,21 +195,7 @@ func (c *context) collectPackageInputs(m *manifestBuilder, pkg *aPackage) error // collectDependencyInputs adds dependency fingerprints/versions into manifest. func (c *context) collectDependencyInputs(m *manifestBuilder, pkg *aPackage) error { - if len(pkg.Imports) == 0 { - return nil - } - - deps := make([]*packages.Package, 0, len(pkg.Imports)) - for _, dep := range pkg.Imports { - if dep == nil || dep.ID == pkg.ID { - continue - } - deps = append(deps, dep) - } - - sort.Slice(deps, func(i, j int) bool { return deps[i].ID < deps[j].ID }) - - for _, dep := range deps { + for _, dep := range effectiveDependencies(pkg) { depEntry, err := c.dependencyFingerprint(dep) if err != nil { return err @@ -221,6 +206,21 @@ func (c *context) collectDependencyInputs(m *manifestBuilder, pkg *aPackage) err return nil } +// initializePackageBuildState initializes the mutable state used by the +// package pipeline before any scheduler is introduced. This makes ownership +// explicit and avoids lazy first-use writes becoming data races later. +func (c *context) initializePackageBuildState() { + if c.sfilesCache == nil { + c.sfilesCache = make(map[string][]string) + } + if !cacheEnabled() { + return + } + c.cacheManager = newCacheManager() + c.llvmVersion = detectLLVMVersion(c) + c.llvmVersionReady = true +} + func (c *context) dependencyFingerprint(dep *packages.Package) (depEntry, error) { entry := depEntry{ID: dep.ID} if v := moduleVersion(dep.Module); v != "" { @@ -264,10 +264,11 @@ func moduleVersion(mod *gopackages.Module) string { // getLLVMVersion returns the cached LLVM version or detects it. func (c *context) getLLVMVersion() string { - if c.llvmVersion != "" { + if c.llvmVersionReady { return c.llvmVersion } c.llvmVersion = detectLLVMVersion(c) + c.llvmVersionReady = true return c.llvmVersion } diff --git a/internal/build/dependencies.go b/internal/build/dependencies.go new file mode 100644 index 0000000000..a2197623d0 --- /dev/null +++ b/internal/build/dependencies.go @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "sort" + + "github.com/goplus/llgo/internal/packages" +) + +// effectiveDependencies returns the package graph that contributes code to an +// aPackage. An alternate package can add imports beyond the original package, +// so using only Package.Imports would allow stale cache entries after an alt +// dependency changes. +func effectiveDependencies(pkg *aPackage) []*packages.Package { + if pkg == nil || pkg.Package == nil { + return nil + } + deps := make(map[string]*packages.Package) + add := func(imports map[string]*packages.Package) { + for _, dep := range imports { + if dep == nil || dep.ID == pkg.ID || (pkg.AltPkg != nil && dep.ID == pkg.AltPkg.ID) { + continue + } + deps[dep.ID] = dep + } + } + add(pkg.Imports) + if pkg.AltPkg != nil { + add(pkg.AltPkg.Imports) + } + ret := make([]*packages.Package, 0, len(deps)) + for _, dep := range deps { + ret = append(ret, dep) + } + sort.Slice(ret, func(i, j int) bool { return ret[i].ID < ret[j].ID }) + return ret +} diff --git a/internal/build/dependencies_test.go b/internal/build/dependencies_test.go new file mode 100644 index 0000000000..7f083eb13d --- /dev/null +++ b/internal/build/dependencies_test.go @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "reflect" + "testing" + + "github.com/goplus/llgo/internal/packages" +) + +func TestEffectiveDependenciesIncludesAlternateImports(t *testing.T) { + base := &packages.Package{ID: "base"} + shared := &packages.Package{ID: "shared"} + altOnly := &packages.Package{ID: "alt-only"} + alt := &packages.Package{ + ID: "alt", + Imports: map[string]*packages.Package{"shared": shared, "alt-only": altOnly}, + } + pkg := &aPackage{ + Package: &packages.Package{ID: "pkg", Imports: map[string]*packages.Package{"base": base, "shared": shared}}, + AltPkg: &packages.Cached{Package: alt}, + } + deps := effectiveDependencies(pkg) + got := make([]string, len(deps)) + for i, dep := range deps { + got[i] = dep.ID + } + if want := []string{"alt-only", "base", "shared"}; !reflect.DeepEqual(got, want) { + t.Fatalf("effectiveDependencies = %v, want %v", got, want) + } +} diff --git a/internal/build/fingerprint_test.go b/internal/build/fingerprint_test.go index 697f9ef8af..e45342a731 100644 --- a/internal/build/fingerprint_test.go +++ b/internal/build/fingerprint_test.go @@ -158,10 +158,9 @@ func TestManifestBuilder_EmptySections(t *testing.T) { m := newManifestBuilder() content := m.Build() - // Empty sections should not be written - expected := `` - if content != expected { - t.Errorf("unexpected empty manifest:\ngot:\n%s\nwant:\n%s", content, expected) + // Empty sections should not be written. + if content != "" { + t.Errorf("unexpected empty manifest:\ngot:\n%s", content) } // Should still produce a valid fingerprint diff --git a/internal/build/module_hook_test.go b/internal/build/module_hook_test.go index 99d2bde828..d91def525d 100644 --- a/internal/build/module_hook_test.go +++ b/internal/build/module_hook_test.go @@ -9,6 +9,7 @@ import ( func TestModuleHookReceivesMainPackageModule(t *testing.T) { conf := NewDefaultConf(ModeGen) + conf.Parallel = 2 counts := make(map[string]int) snapshots := make(map[string]string) diff --git a/internal/goflags/flagfile.go b/internal/goflags/flagfile.go index e8e4adf975..3586213e4e 100644 --- a/internal/goflags/flagfile.go +++ b/internal/goflags/flagfile.go @@ -27,6 +27,7 @@ var argumentListFlagNames = [...]string{ "gcflags", "gccgoflags", "ldflags", + "p", "toolexec", } diff --git a/internal/goflags/gobuild.go b/internal/goflags/gobuild.go index 6f38f42d9f..7d10074f1f 100644 --- a/internal/goflags/gobuild.go +++ b/internal/goflags/gobuild.go @@ -16,7 +16,13 @@ package goflags -import "github.com/goplus/llgo/internal/build" +import ( + "fmt" + "strconv" + "strings" + + "github.com/goplus/llgo/internal/build" +) // ApplyBuildFlags validates and appends normalized Go build flags, and maps // the supported compiler and linker semantics into typed build configuration. @@ -34,12 +40,37 @@ func ApplyBuildFlags(conf *build.Config, args []string) error { if err != nil { return err } + parallel, parallelSet, err := parseBuildParallel(all) + if err != nil { + return err + } next := *conf next.GoBuildFlags = all applyFrontendGCFlags(&next) + if parallelSet { + next.Parallel = parallel + } if linkFlags.Present { next.LinkOptions = linkFlags.Options } *conf = next return nil } + +// parseBuildParallel extracts Go's -p build concurrency flag after it has +// been normalized. Keeping it in GoBuildFlags still lets go/packages apply the +// same setting while Config.Parallel controls LLGo's own build stages. +func parseBuildParallel(flags []string) (parallel int, present bool, err error) { + for _, flag := range flags { + value, ok := strings.CutPrefix(flag, "-p=") + if !ok { + continue + } + parallel, err = strconv.Atoi(value) + if err != nil || parallel <= 0 { + return 0, false, fmt.Errorf("-p must be a positive integer, got %q", value) + } + present = true + } + return parallel, present, nil +} diff --git a/internal/goflags/gobuild_test.go b/internal/goflags/gobuild_test.go index f901e22f72..de809b7557 100644 --- a/internal/goflags/gobuild_test.go +++ b/internal/goflags/gobuild_test.go @@ -105,3 +105,28 @@ func TestApplyBuildFlagsFrontendGCFlagSemantics(t *testing.T) { }) } } + +func TestApplyBuildFlagsParallelism(t *testing.T) { + conf := &build.Config{} + if err := ApplyBuildFlags(conf, []string{"--p", "3"}); err != nil { + t.Fatal(err) + } + if conf.Parallel != 3 { + t.Fatalf("Parallel = %d, want 3", conf.Parallel) + } + if !reflect.DeepEqual(conf.GoBuildFlags, []string{"-p=3"}) { + t.Fatalf("GoBuildFlags = %#v, want [-p=3]", conf.GoBuildFlags) + } +} + +func TestApplyBuildFlagsRejectsInvalidParallelismAtomically(t *testing.T) { + conf := &build.Config{Parallel: 2, GoBuildFlags: []string{"-tags=existing"}} + want := *conf + want.GoBuildFlags = append([]string(nil), conf.GoBuildFlags...) + if err := ApplyBuildFlags(conf, []string{"-p=0"}); err == nil { + t.Fatal("ApplyBuildFlags succeeded, want error") + } + if !reflect.DeepEqual(*conf, want) { + t.Fatalf("configuration changed on error:\n got %+v\nwant %+v", *conf, want) + } +} From e111d9900ffc3cb000f0fc7641dbd5b1ebf57a17 Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Sat, 25 Jul 2026 07:37:52 +0800 Subject: [PATCH 02/12] build: address parallelism review feedback --- internal/build/build.go | 16 ++++++++++------ internal/goflags/flagfile.go | 13 ++++++++++++- internal/goflags/flagfile_test.go | 11 +++++++++++ 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/internal/build/build.go b/internal/build/build.go index cc1ba01b40..09c8c9ebfc 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -184,7 +184,7 @@ type Config struct { // bounds checks while retaining required integer conversions and nil checks. DisableBoundsChecks bool // Parallel is the maximum number of LLGo's internally parallel build tasks. - // Zero uses GOMAXPROCS, matching the Go command's default -p behavior. + // Zero uses GOMAXPROCS; command-line -p, like go build -p, must be >= 1. Parallel int // PthreadStackSize sets a custom stack size, in bytes, for pthread-backed @@ -287,7 +287,7 @@ const ( var llssaInitOnce sync.Once func (c *Config) parallelism() int { - if c != nil && c.Parallel > 0 { + if c.Parallel > 0 { return c.Parallel } return runtime.GOMAXPROCS(0) @@ -2087,16 +2087,20 @@ func buildSSAPkgs(ctx *context, entries []ssaBuildEntry) { return } unique := make([]ssaBuildEntry, 0, len(entries)) - seen := make(map[*ssa.Package]bool, len(entries)) + entryIndex := make(map[*ssa.Package]int, len(entries)) for _, entry := range entries { - if entry.pkg == nil || seen[entry.pkg] { + if entry.pkg == nil { continue } - seen[entry.pkg] = true + if index, exists := entryIndex[entry.pkg]; exists { + unique[index].fixOrder = unique[index].fixOrder || entry.fixOrder + continue + } + entryIndex[entry.pkg] = len(unique) unique = append(unique, entry) } workers := min(ctx.buildConf.parallelism(), len(unique)) - jobs := make(chan ssaBuildEntry) + jobs := make(chan ssaBuildEntry, len(unique)) var wg sync.WaitGroup for range workers { wg.Add(1) diff --git a/internal/goflags/flagfile.go b/internal/goflags/flagfile.go index 3586213e4e..48ad661fcd 100644 --- a/internal/goflags/flagfile.go +++ b/internal/goflags/flagfile.go @@ -31,6 +31,17 @@ var argumentListFlagNames = [...]string{ "toolexec", } +// wholeLineValueFlagNames is the subset whose unquoted values can themselves +// contain arbitrary flag-like words. Scalar flags such as -p still belong to +// argumentListFlagNames for normalization, but must not consume a whole line. +var wholeLineValueFlagNames = [...]string{ + "asmflags", + "gcflags", + "gccgoflags", + "ldflags", + "toolexec", +} + // ParseFlagFile parses a flags.txt-style file. Blank lines and full-line // comments are ignored. A line beginning with a Go flag whose value is itself // an argument list is kept intact, so unquoted values such as @@ -63,7 +74,7 @@ func ParseFlagFile(data string) ([]string, error) { } func wholeLineValueFlag(line string) (flag string, ok bool) { - for _, name := range argumentListFlagNames { + for _, name := range wholeLineValueFlagNames { for _, prefix := range []string{"-" + name + "=", "--" + name + "="} { value, found := strings.CutPrefix(line, prefix) if !found { diff --git a/internal/goflags/flagfile_test.go b/internal/goflags/flagfile_test.go index d7938f3e93..efda442073 100644 --- a/internal/goflags/flagfile_test.go +++ b/internal/goflags/flagfile_test.go @@ -107,3 +107,14 @@ func TestParseFlagFileErrors(t *testing.T) { } } } + +func TestParseFlagFileKeepsScalarParallelFlagSeparate(t *testing.T) { + got, err := ParseFlagFile("-p=4 -trimpath -tags=fast\n") + if err != nil { + t.Fatal(err) + } + want := []string{"-p=4", "-trimpath", "-tags=fast"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("ParseFlagFile() = %#v, want %#v", got, want) + } +} From 4520af85d0deb13df9f6794b6cbd1cdc24bf3d88 Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Mon, 27 Jul 2026 10:42:08 +0800 Subject: [PATCH 03/12] build: scope LLVM verification errors locally --- internal/build/build.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/build/build.go b/internal/build/build.go index 09c8c9ebfc..7ffabe92f7 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -1708,7 +1708,7 @@ func compilePackageModule(ctx *context, aPkg *aPackage, externs []string, verbos mod.SetTarget(ctx.prog.Target().Spec().Triple) pbo := gllvm.NewPassBuilderOptions() defer pbo.Dispose() - if err = gllvm.VerifyModule(mod, gllvm.ReturnStatusAction); err != nil { + if err := gllvm.VerifyModule(mod, gllvm.ReturnStatusAction); err != nil { return fmt.Errorf("verify LLVM module for %v failed: %w", pkgPath, err) } if err := mod.RunPasses(llvmPassPipeline(ctx.buildConf.OptLevel, ctx.buildConf.ltoMode()), ctx.prog.TargetMachine(), pbo); err != nil { From 6b50b79daaf82a2461fc5c5a8b8e3ff6461e64f5 Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Mon, 27 Jul 2026 12:26:42 +0800 Subject: [PATCH 04/12] build: bypass cache for cyclic alternate dependencies --- internal/build/build.go | 1 + internal/build/collect.go | 27 ++++++++++++++++++++++- internal/build/collect_test.go | 40 ++++++++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 1 deletion(-) diff --git a/internal/build/build.go b/internal/build/build.go index 7ffabe92f7..3bf3bda540 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -790,6 +790,7 @@ type context struct { // Cache related fields cacheManager *cacheManager + cacheDisabled map[string]none llvmVersion string llvmVersionReady bool diff --git a/internal/build/collect.go b/internal/build/collect.go index 48cfc4726a..b4e0790eca 100644 --- a/internal/build/collect.go +++ b/internal/build/collect.go @@ -41,7 +41,12 @@ func (c *context) collectFingerprint(pkg *aPackage) error { c.fingerprinting = make(map[string]bool) } if c.fingerprinting[pkg.ID] { - return fmt.Errorf("fingerprint cycle detected for %s", pkg.ID) + // Alternate packages can intentionally close a cycle in the runtime + // replacement graph after all packages have been built into SSA. A + // cycle cannot have a stable per-package cache key, so compile every + // member rather than returning an incorrect cache hit. + c.disablePackageCache(c.fingerprinting) + return nil } c.fingerprinting[pkg.ID] = true defer delete(c.fingerprinting, pkg.ID) @@ -69,6 +74,20 @@ func (c *context) collectFingerprint(pkg *aPackage) error { return nil } +func (c *context) disablePackageCache(pkgs map[string]bool) { + if c.cacheDisabled == nil { + c.cacheDisabled = make(map[string]none, len(pkgs)) + } + for id := range pkgs { + c.cacheDisabled[id] = none{} + } +} + +func (c *context) packageCacheDisabled(id string) bool { + _, disabled := c.cacheDisabled[id] + return disabled +} + // collectEnvInputs collects environment-related inputs. func (c *context) collectEnvInputs(m *manifestBuilder) { m.env.Goos = c.buildConf.Goos @@ -327,6 +346,9 @@ func (c *context) tryLoadFromCache(pkg *aPackage) bool { if !cacheEnabled() { return false } + if c.packageCacheDisabled(pkg.ID) { + return false + } // Main packages are intentionally not written to the build cache because // each executable's entry module is linked against the current main archive. @@ -452,6 +474,9 @@ func (c *context) saveToCache(pkg *aPackage) error { if !cacheEnabled() { return nil } + if c.packageCacheDisabled(pkg.ID) { + return nil + } if pkg.Fingerprint == "" || pkg.Manifest == "" { return nil diff --git a/internal/build/collect_test.go b/internal/build/collect_test.go index 0dd9d7ca4d..7cc6e85de1 100644 --- a/internal/build/collect_test.go +++ b/internal/build/collect_test.go @@ -90,6 +90,46 @@ func TestCollectFingerprint(t *testing.T) { } } +func TestCollectFingerprintAltDependencyCycleDisablesCache(t *testing.T) { + runtimePkg := &packages.Package{ID: "runtime", PkgPath: "runtime"} + osPkg := &packages.Package{ID: "runtime/internal/clite/os", PkgPath: "runtime/internal/clite/os"} + syscallPkg := &packages.Package{ID: "runtime/internal/clite/syscall", PkgPath: "runtime/internal/clite/syscall"} + runtime := &aPackage{ + Package: runtimePkg, + AltPkg: &packages.Cached{Package: &packages.Package{ + ID: "runtime/alt", + Imports: map[string]*packages.Package{"os": osPkg}, + }}, + } + os := &aPackage{Package: osPkg} + syscall := &aPackage{Package: syscallPkg} + os.Imports = map[string]*packages.Package{"syscall": syscallPkg} + syscall.Imports = map[string]*packages.Package{"runtime": runtimePkg} + ctx := &context{ + conf: &packages.Config{}, + buildConf: &Config{Goos: "js", Goarch: "wasm"}, + crossCompile: crosscompile.Export{ + LLVMTarget: "wasm32-unknown-unknown", + }, + pkgByID: map[string]Package{ + runtimePkg.ID: runtime, + osPkg.ID: os, + syscallPkg.ID: syscall, + }, + } + if err := ctx.collectFingerprint(runtime); err != nil { + t.Fatalf("collectFingerprint: %v", err) + } + for _, pkg := range []*aPackage{runtime, os, syscall} { + if !ctx.packageCacheDisabled(pkg.ID) { + t.Fatalf("cache for %s was not disabled after fingerprint cycle", pkg.ID) + } + if pkg.Fingerprint == "" || pkg.Manifest == "" { + t.Fatalf("fingerprint state for %s was not completed", pkg.ID) + } + } +} + func TestCollectFingerprintDeterminism(t *testing.T) { td := t.TempDir() From d5bf760b8ba6245f0c070bb1ad82b5974658b2a0 Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Sat, 25 Jul 2026 01:30:51 +0800 Subject: [PATCH 05/12] build: model package build units explicitly --- internal/build/build.go | 60 ++++++++++------------ internal/build/package_build.go | 77 ++++++++++++++++++++++++++++ internal/build/package_build_test.go | 57 ++++++++++++++++++++ 3 files changed, 161 insertions(+), 33 deletions(-) create mode 100644 internal/build/package_build.go create mode 100644 internal/build/package_build_test.go diff --git a/internal/build/build.go b/internal/build/build.go index 3bf3bda540..729a261ac3 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -880,21 +880,22 @@ func normalizeToArchive(ctx *context, aPkg *aPackage, verbose bool) error { func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, error) { // Split packages into runtime tree vs others so we can defer runtime build. - var runtimePkgs []*aPackage - var normalPkgs []*aPackage + var runtimePkgs []packageBuildSpec + var normalPkgs []packageBuildSpec for _, p := range pkgs { - if isRuntimePkg(p.PkgPath) { - runtimePkgs = append(runtimePkgs, p) + spec := newPackageBuildSpec(p) + if spec.runtime { + runtimePkgs = append(runtimePkgs, spec) } else { - normalPkgs = append(normalPkgs, p) + normalPkgs = append(normalPkgs, spec) } } var needRuntime, needPyInit bool // Build non-runtime packages first, so we know whether runtime is actually needed. - for _, p := range normalPkgs { - result, err := buildOnePackage(ctx, p, verbose) + for _, spec := range normalPkgs { + result, err := buildOnePackage(ctx, spec, verbose) if err != nil { return nil, err } @@ -904,8 +905,8 @@ func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, er // Only build runtime packages when required (or host build with empty Target). if needRuntime || needPyInit || ctx.buildConf.Target == "" { - for _, p := range runtimePkgs { - if _, err := buildOnePackage(ctx, p, verbose); err != nil { + for _, spec := range runtimePkgs { + if _, err := buildOnePackage(ctx, spec, verbose); err != nil { return nil, err } } @@ -914,35 +915,30 @@ func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, er return pkgs, nil } -type packageBuildResult struct { - needRuntime bool - needPyInit bool -} - // buildOnePackage is the serial package pipeline. The stages are separated so // a future scheduler can parallelize only stages with isolated package state. -func buildOnePackage(ctx *context, aPkg *aPackage, verbose bool) (packageBuildResult, error) { +func buildOnePackage(ctx *context, spec packageBuildSpec, verbose bool) (packageBuildResult, error) { + aPkg := spec.pkg pkg := aPkg.Package if _, ok := ctx.built[pkg.ID]; ok { - return packageBuildResult{}, nil + return packageBuildResultFor(spec), nil } ctx.built[pkg.ID] = none{} - kind, param := cl.PkgKindOf(pkg.Types) - if kind == cl.PkgDeclOnly { + if spec.isDeclOnly() { pkg.ExportFile = "" - return packageBuildResult{}, nil + return packageBuildResultFor(spec), nil } - if (kind == cl.PkgLinkIR || kind == cl.PkgLinkExtern || kind == cl.PkgPyModule) && len(pkg.GoFiles) == 0 { + if spec.isLinkOnly() && !spec.hasSource() { pkg.ExportFile = "" - if kind == cl.PkgLinkExtern { - appendExternalLinkArgs(ctx, aPkg, param) + if spec.kind == cl.PkgLinkExtern { + appendExternalLinkArgs(ctx, aPkg, spec.kindParam) } - return packageBuildResult{}, nil + return packageBuildResultFor(spec), nil } if err := ctx.collectFingerprint(aPkg); err != nil { - return packageBuildResult{}, err + return packageBuildResultFor(spec), err } ctx.tryLoadFromCache(aPkg) if verbose { @@ -953,28 +949,26 @@ func buildOnePackage(ctx *context, aPkg *aPackage, verbose bool) (packageBuildRe fmt.Fprintf(os.Stderr, "CACHE %s: %s\n", status, pkg.PkgPath) } if err := buildPkg(ctx, aPkg, verbose); err != nil { - return packageBuildResult{}, err + return packageBuildResultFor(spec), err } - result := packageBuildResult{} - if kind != cl.PkgLinkIR && kind != cl.PkgLinkExtern && kind != cl.PkgPyModule { + if spec.needsRuntimeSignals() { aPkg.setNeedRuntimeOrPyInit(aPkg.LPkg.NeedRuntime, aPkg.LPkg.NeedPyInit) - result.needRuntime = aPkg.NeedRt - result.needPyInit = aPkg.NeedPyInit } + result := packageBuildResultFor(spec) if aPkg.CacheHit { return result, nil } if err := normalizeToArchive(ctx, aPkg, verbose); err != nil { - return packageBuildResult{}, err + return result, err } - if kind == cl.PkgLinkExtern { - appendExternalLinkArgs(ctx, aPkg, param) + if spec.kind == cl.PkgLinkExtern { + appendExternalLinkArgs(ctx, aPkg, spec.kindParam) } if err := ctx.saveToCache(aPkg); err != nil && verbose { fmt.Fprintf(os.Stderr, "warning: failed to save cache for %s: %v\n", pkg.PkgPath, err) } - return result, nil + return packageBuildResultFor(spec), nil } func appendExternalLinkArgs(ctx *context, aPkg *aPackage, spec string) { diff --git a/internal/build/package_build.go b/internal/build/package_build.go new file mode 100644 index 0000000000..727267a813 --- /dev/null +++ b/internal/build/package_build.go @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import "github.com/goplus/llgo/cl" + +// packageBuildSpec is the immutable scheduler input for one package. It keeps +// package classification out of the execution loop, so a later DAG scheduler +// can choose work without reinterpreting frontend metadata. +type packageBuildSpec struct { + pkg *aPackage + kind int + kindParam string + runtime bool +} + +func newPackageBuildSpec(pkg *aPackage) packageBuildSpec { + kind, kindParam := cl.PkgKindOf(pkg.Types) + return packageBuildSpec{ + pkg: pkg, + kind: kind, + kindParam: kindParam, + runtime: isRuntimePkg(pkg.PkgPath), + } +} + +func (s packageBuildSpec) isDeclOnly() bool { + return s.kind == cl.PkgDeclOnly +} + +func (s packageBuildSpec) isLinkOnly() bool { + return s.kind == cl.PkgLinkIR || s.kind == cl.PkgLinkExtern || s.kind == cl.PkgPyModule +} + +func (s packageBuildSpec) hasSource() bool { + return len(s.pkg.GoFiles) > 0 +} + +func (s packageBuildSpec) needsRuntimeSignals() bool { + return !s.isLinkOnly() && !s.isDeclOnly() +} + +// packageBuildResult carries the observable output of a serial package build. +// Subsequent scheduler PRs can pass this value between worker and finalization +// stages without exposing the mutable aPackage implementation details. +type packageBuildResult struct { + spec packageBuildSpec + cacheHit bool + archiveFile string + needRuntime bool + needPyInit bool +} + +func packageBuildResultFor(spec packageBuildSpec) packageBuildResult { + pkg := spec.pkg + return packageBuildResult{ + spec: spec, + cacheHit: pkg.CacheHit, + archiveFile: pkg.ArchiveFile, + needRuntime: pkg.NeedRt, + needPyInit: pkg.NeedPyInit, + } +} diff --git a/internal/build/package_build_test.go b/internal/build/package_build_test.go new file mode 100644 index 0000000000..714525c4de --- /dev/null +++ b/internal/build/package_build_test.go @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "go/types" + "testing" + + "github.com/goplus/llgo/internal/packages" +) + +func TestPackageBuildSpecAndResult(t *testing.T) { + pkg := &aPackage{Package: &packages.Package{ + PkgPath: "example.com/p", + GoFiles: []string{"p.go"}, + Types: types.NewPackage("example.com/p", "p"), + }, NeedRt: true, NeedPyInit: true, CacheHit: true, ArchiveFile: "p.a"} + spec := newPackageBuildSpec(pkg) + if spec.isDeclOnly() || spec.isLinkOnly() || !spec.hasSource() || spec.runtime || !spec.needsRuntimeSignals() { + t.Fatalf("unexpected normal package spec: %+v", spec) + } + result := packageBuildResultFor(spec) + if !result.cacheHit || result.archiveFile != "p.a" || !result.needRuntime || !result.needPyInit { + t.Fatalf("unexpected package result: %+v", result) + } +} + +func TestPackageBuildSpecSpecialKinds(t *testing.T) { + decl := newPackageBuildSpec(&aPackage{Package: &packages.Package{ + PkgPath: "unsafe", + Types: types.Unsafe, + }}) + if !decl.isDeclOnly() || decl.needsRuntimeSignals() { + t.Fatalf("unexpected declaration-only spec: %+v", decl) + } + runtime := newPackageBuildSpec(&aPackage{Package: &packages.Package{ + PkgPath: "runtime", + Types: types.NewPackage("runtime", "runtime"), + }}) + if !runtime.runtime { + t.Fatalf("runtime package was not marked runtime: %+v", runtime) + } +} From 225a82b915341dd31a7402173ab15d6fec9ae249 Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Sat, 25 Jul 2026 07:39:33 +0800 Subject: [PATCH 06/12] test: use the llgo runtime path in build spec coverage --- internal/build/package_build_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/internal/build/package_build_test.go b/internal/build/package_build_test.go index 714525c4de..f2360ed6bc 100644 --- a/internal/build/package_build_test.go +++ b/internal/build/package_build_test.go @@ -20,6 +20,7 @@ import ( "go/types" "testing" + "github.com/goplus/llgo/internal/env" "github.com/goplus/llgo/internal/packages" ) @@ -48,8 +49,8 @@ func TestPackageBuildSpecSpecialKinds(t *testing.T) { t.Fatalf("unexpected declaration-only spec: %+v", decl) } runtime := newPackageBuildSpec(&aPackage{Package: &packages.Package{ - PkgPath: "runtime", - Types: types.NewPackage("runtime", "runtime"), + PkgPath: env.LLGoRuntimePkg, + Types: types.NewPackage(env.LLGoRuntimePkg, "runtime"), }}) if !runtime.runtime { t.Fatalf("runtime package was not marked runtime: %+v", runtime) From 7126afd5a197175df50fe3357b0162a54e09759c Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Sat, 25 Jul 2026 01:33:51 +0800 Subject: [PATCH 07/12] build: split package execution stages --- internal/build/build.go | 49 +++++++++++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/internal/build/build.go b/internal/build/build.go index 729a261ac3..ab75bf9ac5 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -918,27 +918,39 @@ func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, er // buildOnePackage is the serial package pipeline. The stages are separated so // a future scheduler can parallelize only stages with isolated package state. func buildOnePackage(ctx *context, spec packageBuildSpec, verbose bool) (packageBuildResult, error) { + skip, err := preflightPackageBuild(ctx, spec, verbose) + if err != nil || skip { + return packageBuildResultFor(spec), err + } + if err := executePackageBuild(ctx, spec, verbose); err != nil { + return packageBuildResultFor(spec), err + } + return finalizePackageBuild(ctx, spec, verbose) +} + +// preflightPackageBuild performs package classification, cache lookup, and +// other work that does not create or transform an LLVM module. It returns +// skip for packages with no executable build stage. +func preflightPackageBuild(ctx *context, spec packageBuildSpec, verbose bool) (skip bool, err error) { aPkg := spec.pkg pkg := aPkg.Package if _, ok := ctx.built[pkg.ID]; ok { - return packageBuildResultFor(spec), nil + return true, nil } ctx.built[pkg.ID] = none{} - if spec.isDeclOnly() { pkg.ExportFile = "" - return packageBuildResultFor(spec), nil + return true, nil } if spec.isLinkOnly() && !spec.hasSource() { pkg.ExportFile = "" if spec.kind == cl.PkgLinkExtern { appendExternalLinkArgs(ctx, aPkg, spec.kindParam) } - return packageBuildResultFor(spec), nil + return true, nil } - if err := ctx.collectFingerprint(aPkg); err != nil { - return packageBuildResultFor(spec), err + return false, err } ctx.tryLoadFromCache(aPkg) if verbose { @@ -948,25 +960,38 @@ func buildOnePackage(ctx *context, spec packageBuildSpec, verbose bool) (package } fmt.Fprintf(os.Stderr, "CACHE %s: %s\n", status, pkg.PkgPath) } + return false, nil +} + +// executePackageBuild creates the frontend module and, on a cache miss, runs +// the serial LLVM backend. The backend remains deliberately serial until it +// owns an isolated LLVM context. +func executePackageBuild(ctx *context, spec packageBuildSpec, verbose bool) error { + aPkg := spec.pkg if err := buildPkg(ctx, aPkg, verbose); err != nil { - return packageBuildResultFor(spec), err + return err } - if spec.needsRuntimeSignals() { aPkg.setNeedRuntimeOrPyInit(aPkg.LPkg.NeedRuntime, aPkg.LPkg.NeedPyInit) } - result := packageBuildResultFor(spec) + return nil +} + +// finalizePackageBuild publishes an archive and cache metadata after backend +// execution. Cache hits already carry their archive and metadata. +func finalizePackageBuild(ctx *context, spec packageBuildSpec, verbose bool) (packageBuildResult, error) { + aPkg := spec.pkg if aPkg.CacheHit { - return result, nil + return packageBuildResultFor(spec), nil } if err := normalizeToArchive(ctx, aPkg, verbose); err != nil { - return result, err + return packageBuildResultFor(spec), err } if spec.kind == cl.PkgLinkExtern { appendExternalLinkArgs(ctx, aPkg, spec.kindParam) } if err := ctx.saveToCache(aPkg); err != nil && verbose { - fmt.Fprintf(os.Stderr, "warning: failed to save cache for %s: %v\n", pkg.PkgPath, err) + fmt.Fprintf(os.Stderr, "warning: failed to save cache for %s: %v\n", aPkg.PkgPath, err) } return packageBuildResultFor(spec), nil } From 90046ef6f57a42a6e20cd1321c2bdd7e75ba1890 Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Sat, 25 Jul 2026 01:36:27 +0800 Subject: [PATCH 08/12] build: plan package dependency levels --- internal/build/build.go | 7 +- internal/build/package_build.go | 100 ++++++++++++++++++++++++++- internal/build/package_build_test.go | 60 ++++++++++++++++ 3 files changed, 164 insertions(+), 3 deletions(-) diff --git a/internal/build/build.go b/internal/build/build.go index ab75bf9ac5..7074ac7b7c 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -879,11 +879,14 @@ func normalizeToArchive(ctx *context, aPkg *aPackage, verbose bool) error { } func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, error) { + plan, err := newPackageBuildPlan(pkgs) + if err != nil { + return nil, err + } // Split packages into runtime tree vs others so we can defer runtime build. var runtimePkgs []packageBuildSpec var normalPkgs []packageBuildSpec - for _, p := range pkgs { - spec := newPackageBuildSpec(p) + for _, spec := range plan.specs { if spec.runtime { runtimePkgs = append(runtimePkgs, spec) } else { diff --git a/internal/build/package_build.go b/internal/build/package_build.go index 727267a813..6de5e9f399 100644 --- a/internal/build/package_build.go +++ b/internal/build/package_build.go @@ -16,7 +16,12 @@ package build -import "github.com/goplus/llgo/cl" +import ( + "fmt" + "sort" + + "github.com/goplus/llgo/cl" +) // packageBuildSpec is the immutable scheduler input for one package. It keeps // package classification out of the execution loop, so a later DAG scheduler @@ -75,3 +80,96 @@ func packageBuildResultFor(spec packageBuildSpec) packageBuildResult { needPyInit: pkg.NeedPyInit, } } + +// packageBuildPlan is the immutable dependency graph consumed by a future +// scheduler. specs retains the existing deterministic execution order until +// the LLVM backend is made worker-local; levels records the safe ready sets. +type packageBuildPlan struct { + specs []packageBuildSpec + byID map[string]packageBuildSpec + deps map[string][]string + levels [][]packageBuildSpec +} + +func newPackageBuildPlan(pkgs []*aPackage) (*packageBuildPlan, error) { + plan := &packageBuildPlan{ + specs: make([]packageBuildSpec, 0, len(pkgs)), + byID: make(map[string]packageBuildSpec, len(pkgs)), + deps: make(map[string][]string, len(pkgs)), + } + for _, pkg := range pkgs { + spec := newPackageBuildSpec(pkg) + id := spec.pkg.ID + if _, exists := plan.byID[id]; exists { + return nil, fmt.Errorf("duplicate package build spec for %s", id) + } + plan.specs = append(plan.specs, spec) + plan.byID[id] = spec + } + for _, spec := range plan.specs { + id := spec.pkg.ID + for _, dep := range effectiveDependencies(spec.pkg) { + if _, inPlan := plan.byID[dep.ID]; inPlan { + plan.deps[id] = append(plan.deps[id], dep.ID) + } + } + sort.Strings(plan.deps[id]) + } + levels, err := plan.readyLevels() + if err != nil { + return nil, err + } + plan.levels = levels + return plan, nil +} + +func (p *packageBuildPlan) readyLevels() ([][]packageBuildSpec, error) { + remaining := make(map[string]int, len(p.specs)) + dependents := make(map[string][]string, len(p.specs)) + for _, spec := range p.specs { + id := spec.pkg.ID + remaining[id] = len(p.deps[id]) + for _, dep := range p.deps[id] { + dependents[dep] = append(dependents[dep], id) + } + } + for _, ids := range dependents { + sort.Strings(ids) + } + + ready := make([]string, 0, len(p.specs)) + for id, count := range remaining { + if count == 0 { + ready = append(ready, id) + } + } + sort.Strings(ready) + levels := make([][]packageBuildSpec, 0, len(p.specs)) + for len(ready) > 0 { + ids := ready + ready = nil + level := make([]packageBuildSpec, 0, len(ids)) + for _, id := range ids { + level = append(level, p.byID[id]) + for _, dependent := range dependents[id] { + remaining[dependent]-- + if remaining[dependent] == 0 { + ready = append(ready, dependent) + } + } + } + sort.Strings(ready) + levels = append(levels, level) + } + if len(levels) == 0 && len(p.specs) == 0 { + return levels, nil + } + count := 0 + for _, level := range levels { + count += len(level) + } + if count != len(p.specs) { + return nil, fmt.Errorf("package build dependency cycle") + } + return levels, nil +} diff --git a/internal/build/package_build_test.go b/internal/build/package_build_test.go index f2360ed6bc..d713034883 100644 --- a/internal/build/package_build_test.go +++ b/internal/build/package_build_test.go @@ -18,6 +18,7 @@ package build import ( "go/types" + "reflect" "testing" "github.com/goplus/llgo/internal/env" @@ -40,6 +41,65 @@ func TestPackageBuildSpecAndResult(t *testing.T) { } } +func TestPackageBuildPlanReadyLevels(t *testing.T) { + leaf := planPackage("leaf") + left := planPackage("left", leaf.Package) + right := planPackage("right", leaf.Package) + root := planPackage("root", left.Package, right.Package) + plan, err := newPackageBuildPlan([]*aPackage{root, right, left, leaf}) + if err != nil { + t.Fatal(err) + } + var levels [][]string + for _, level := range plan.levels { + ids := make([]string, len(level)) + for i, spec := range level { + ids[i] = spec.pkg.ID + } + levels = append(levels, ids) + } + if want := [][]string{{"leaf"}, {"left", "right"}, {"root"}}; !reflect.DeepEqual(levels, want) { + t.Fatalf("ready levels = %v, want %v", levels, want) + } +} + +func TestPackageBuildPlanIncludesAlternateDependencies(t *testing.T) { + baseDep := planPackage("base") + altDep := planPackage("alt") + pkg := planPackage("pkg", baseDep.Package) + pkg.AltPkg = &packages.Cached{Package: &packages.Package{ID: "patch/pkg", Imports: map[string]*packages.Package{"alt": altDep.Package}}} + plan, err := newPackageBuildPlan([]*aPackage{pkg, baseDep, altDep}) + if err != nil { + t.Fatal(err) + } + if got, want := plan.deps["pkg"], []string{"alt", "base"}; !reflect.DeepEqual(got, want) { + t.Fatalf("plan dependencies = %v, want %v", got, want) + } +} + +func TestPackageBuildPlanRejectsCycles(t *testing.T) { + a := planPackage("a") + b := planPackage("b") + a.Imports = map[string]*packages.Package{"b": b.Package} + b.Imports = map[string]*packages.Package{"a": a.Package} + if _, err := newPackageBuildPlan([]*aPackage{a, b}); err == nil { + t.Fatal("newPackageBuildPlan succeeded, want cycle error") + } +} + +func planPackage(id string, imports ...*packages.Package) *aPackage { + depMap := make(map[string]*packages.Package, len(imports)) + for _, dep := range imports { + depMap[dep.ID] = dep + } + return &aPackage{Package: &packages.Package{ + ID: id, + PkgPath: "example.com/" + id, + Imports: depMap, + Types: types.NewPackage("example.com/"+id, id), + }} +} + func TestPackageBuildSpecSpecialKinds(t *testing.T) { decl := newPackageBuildSpec(&aPackage{Package: &packages.Package{ PkgPath: "unsafe", From cca97bd4e916752b7002694935ca5f6e8239178a Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Sat, 25 Jul 2026 07:40:16 +0800 Subject: [PATCH 09/12] build: identify package dependency cycles --- internal/build/package_build.go | 10 +++++++++- internal/build/package_build_test.go | 3 +++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/internal/build/package_build.go b/internal/build/package_build.go index 6de5e9f399..7da55c003f 100644 --- a/internal/build/package_build.go +++ b/internal/build/package_build.go @@ -19,6 +19,7 @@ package build import ( "fmt" "sort" + "strings" "github.com/goplus/llgo/cl" ) @@ -169,7 +170,14 @@ func (p *packageBuildPlan) readyLevels() ([][]packageBuildSpec, error) { count += len(level) } if count != len(p.specs) { - return nil, fmt.Errorf("package build dependency cycle") + cycle := make([]string, 0, len(p.specs)-count) + for id, unresolved := range remaining { + if unresolved > 0 { + cycle = append(cycle, id) + } + } + sort.Strings(cycle) + return nil, fmt.Errorf("package build dependency cycle involving %s", strings.Join(cycle, ", ")) } return levels, nil } diff --git a/internal/build/package_build_test.go b/internal/build/package_build_test.go index d713034883..59e7ed275a 100644 --- a/internal/build/package_build_test.go +++ b/internal/build/package_build_test.go @@ -19,6 +19,7 @@ package build import ( "go/types" "reflect" + "strings" "testing" "github.com/goplus/llgo/internal/env" @@ -84,6 +85,8 @@ func TestPackageBuildPlanRejectsCycles(t *testing.T) { b.Imports = map[string]*packages.Package{"a": a.Package} if _, err := newPackageBuildPlan([]*aPackage{a, b}); err == nil { t.Fatal("newPackageBuildPlan succeeded, want cycle error") + } else if !strings.Contains(err.Error(), "a, b") { + t.Fatalf("cycle error = %q, want package IDs", err) } } From 697eb43b932176b88d8be7babce3c6e647a56c98 Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Mon, 27 Jul 2026 12:28:10 +0800 Subject: [PATCH 10/12] build: exclude alternate imports from scheduler graph --- internal/build/dependencies.go | 22 ++++++++++++++++++++++ internal/build/dependencies_test.go | 18 ++++++++++++++++++ internal/build/package_build.go | 2 +- internal/build/package_build_test.go | 4 ++-- 4 files changed, 43 insertions(+), 3 deletions(-) diff --git a/internal/build/dependencies.go b/internal/build/dependencies.go index a2197623d0..f418e9d4aa 100644 --- a/internal/build/dependencies.go +++ b/internal/build/dependencies.go @@ -50,3 +50,25 @@ func effectiveDependencies(pkg *aPackage) []*packages.Package { sort.Slice(ret, func(i, j int) bool { return ret[i].ID < ret[j].ID }) return ret } + +// packageBuildDependencies returns the true Go import edges for scheduler +// ordering. Alternate-package imports still participate in cache fingerprints, +// but may intentionally form cycles with the runtime replacement graph after +// all packages have already been built into SSA. +func packageBuildDependencies(pkg *aPackage) []*packages.Package { + if pkg == nil || pkg.Package == nil { + return nil + } + deps := make(map[string]*packages.Package, len(pkg.Imports)) + for _, dep := range pkg.Imports { + if dep != nil && dep.ID != pkg.ID { + deps[dep.ID] = dep + } + } + ret := make([]*packages.Package, 0, len(deps)) + for _, dep := range deps { + ret = append(ret, dep) + } + sort.Slice(ret, func(i, j int) bool { return ret[i].ID < ret[j].ID }) + return ret +} diff --git a/internal/build/dependencies_test.go b/internal/build/dependencies_test.go index 7f083eb13d..06658803ab 100644 --- a/internal/build/dependencies_test.go +++ b/internal/build/dependencies_test.go @@ -44,3 +44,21 @@ func TestEffectiveDependenciesIncludesAlternateImports(t *testing.T) { t.Fatalf("effectiveDependencies = %v, want %v", got, want) } } + +func TestPackageBuildDependenciesExcludeAlternateImports(t *testing.T) { + base := &packages.Package{ID: "base"} + altOnly := &packages.Package{ID: "alt-only"} + alt := &packages.Package{ID: "patch/pkg", Imports: map[string]*packages.Package{"alt-only": altOnly}} + pkg := &aPackage{ + Package: &packages.Package{ID: "pkg", Imports: map[string]*packages.Package{"base": base}}, + AltPkg: &packages.Cached{Package: alt}, + } + deps := packageBuildDependencies(pkg) + got := make([]string, len(deps)) + for i, dep := range deps { + got[i] = dep.ID + } + if want := []string{"base"}; !reflect.DeepEqual(got, want) { + t.Fatalf("packageBuildDependencies = %v, want %v", got, want) + } +} diff --git a/internal/build/package_build.go b/internal/build/package_build.go index 7da55c003f..634124f014 100644 --- a/internal/build/package_build.go +++ b/internal/build/package_build.go @@ -109,7 +109,7 @@ func newPackageBuildPlan(pkgs []*aPackage) (*packageBuildPlan, error) { } for _, spec := range plan.specs { id := spec.pkg.ID - for _, dep := range effectiveDependencies(spec.pkg) { + for _, dep := range packageBuildDependencies(spec.pkg) { if _, inPlan := plan.byID[dep.ID]; inPlan { plan.deps[id] = append(plan.deps[id], dep.ID) } diff --git a/internal/build/package_build_test.go b/internal/build/package_build_test.go index 59e7ed275a..593509a62c 100644 --- a/internal/build/package_build_test.go +++ b/internal/build/package_build_test.go @@ -64,7 +64,7 @@ func TestPackageBuildPlanReadyLevels(t *testing.T) { } } -func TestPackageBuildPlanIncludesAlternateDependencies(t *testing.T) { +func TestPackageBuildPlanExcludesAlternateDependencies(t *testing.T) { baseDep := planPackage("base") altDep := planPackage("alt") pkg := planPackage("pkg", baseDep.Package) @@ -73,7 +73,7 @@ func TestPackageBuildPlanIncludesAlternateDependencies(t *testing.T) { if err != nil { t.Fatal(err) } - if got, want := plan.deps["pkg"], []string{"alt", "base"}; !reflect.DeepEqual(got, want) { + if got, want := plan.deps["pkg"], []string{"base"}; !reflect.DeepEqual(got, want) { t.Fatalf("plan dependencies = %v, want %v", got, want) } } From 50f92ed9cf7b6d58e62274d53e447a7d72bfa918 Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Sat, 25 Jul 2026 01:40:36 +0800 Subject: [PATCH 11/12] build: parallelize cache preflight by dependency level --- internal/build/build.go | 51 +++++++++++++++++++-------------- internal/build/collect.go | 42 ++++++++++++++++----------- internal/build/package_build.go | 48 +++++++++++++++++++++++++++++++ internal/build/plan9asm.go | 2 ++ 4 files changed, 105 insertions(+), 38 deletions(-) diff --git a/internal/build/build.go b/internal/build/build.go index 7074ac7b7c..afd560e453 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -523,15 +523,14 @@ func Do(args []string, conf *Config) ([]Package, error) { ctx := &context{env: env, conf: cfg, progSSA: progSSA, prog: prog, dedup: dedup, patches: patches, callerTracking: cl.NewCallerTracking(), built: make(map[string]none), initial: initial, mode: mode, - fingerprinting: make(map[string]bool), - pkgs: map[*packages.Package]Package{}, - pkgByID: map[string]Package{}, - output: output, - passOpt: passOpt, - buildConf: conf, - crossCompile: export, - cTransformer: cabi.NewTransformer(prog, export.LLVMTarget, export.TargetABI, conf.AbiMode, cabiOptimize), - sfilesCache: make(map[string][]string), + pkgs: map[*packages.Package]Package{}, + pkgByID: map[string]Package{}, + output: output, + passOpt: passOpt, + buildConf: conf, + crossCompile: export, + cTransformer: cabi.NewTransformer(prog, export.LLVMTarget, export.TargetABI, conf.AbiMode, cabiOptimize), + sfilesCache: make(map[string][]string), } defer ctx.closePackageMetas() ctx.initializePackageBuildState() @@ -772,7 +771,7 @@ type context struct { patches cl.Patches callerTracking *cl.CallerTracking built map[string]none - fingerprinting map[string]bool + builtMu sync.Mutex initial []*packages.Package pkgs map[*packages.Package]Package // cache for lookup pkgByID map[string]Package // cache for lookup by pkg.ID @@ -791,11 +790,15 @@ type context struct { // Cache related fields cacheManager *cacheManager cacheDisabled map[string]none + cacheManagerMu sync.Mutex + cacheDisabledMu sync.Mutex llvmVersion string llvmVersionReady bool + llvmVersionMu sync.Mutex // go list derived file lists (SFiles, etc.) sfilesCache map[string][]string // pkg.ID -> absolute .s/.S file paths + sfilesMu sync.Mutex // plan9asm package policy parsed from env. plan9asmOnce sync.Once @@ -883,6 +886,10 @@ func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, er if err != nil { return nil, err } + preflights, err := preflightPackageBuilds(ctx, plan, verbose) + if err != nil { + return nil, err + } // Split packages into runtime tree vs others so we can defer runtime build. var runtimePkgs []packageBuildSpec var normalPkgs []packageBuildSpec @@ -898,7 +905,7 @@ func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, er // Build non-runtime packages first, so we know whether runtime is actually needed. for _, spec := range normalPkgs { - result, err := buildOnePackage(ctx, spec, verbose) + result, err := buildPreflightedPackage(ctx, preflights[spec.pkg.ID], verbose) if err != nil { return nil, err } @@ -909,7 +916,7 @@ func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, er // Only build runtime packages when required (or host build with empty Target). if needRuntime || needPyInit || ctx.buildConf.Target == "" { for _, spec := range runtimePkgs { - if _, err := buildOnePackage(ctx, spec, verbose); err != nil { + if _, err := buildPreflightedPackage(ctx, preflights[spec.pkg.ID], verbose); err != nil { return nil, err } } @@ -918,17 +925,16 @@ func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, er return pkgs, nil } -// buildOnePackage is the serial package pipeline. The stages are separated so -// a future scheduler can parallelize only stages with isolated package state. -func buildOnePackage(ctx *context, spec packageBuildSpec, verbose bool) (packageBuildResult, error) { - skip, err := preflightPackageBuild(ctx, spec, verbose) - if err != nil || skip { - return packageBuildResultFor(spec), err +// buildPreflightedPackage runs the serial module/backend/finalization stages +// after parallel preflight has completed for the package's dependency level. +func buildPreflightedPackage(ctx *context, preflight packagePreflight, verbose bool) (packageBuildResult, error) { + if preflight.skip { + return packageBuildResultFor(preflight.spec), nil } - if err := executePackageBuild(ctx, spec, verbose); err != nil { - return packageBuildResultFor(spec), err + if err := executePackageBuild(ctx, preflight.spec, verbose); err != nil { + return packageBuildResultFor(preflight.spec), err } - return finalizePackageBuild(ctx, spec, verbose) + return finalizePackageBuild(ctx, preflight.spec, verbose) } // preflightPackageBuild performs package classification, cache lookup, and @@ -937,10 +943,13 @@ func buildOnePackage(ctx *context, spec packageBuildSpec, verbose bool) (package func preflightPackageBuild(ctx *context, spec packageBuildSpec, verbose bool) (skip bool, err error) { aPkg := spec.pkg pkg := aPkg.Package + ctx.builtMu.Lock() if _, ok := ctx.built[pkg.ID]; ok { + ctx.builtMu.Unlock() return true, nil } ctx.built[pkg.ID] = none{} + ctx.builtMu.Unlock() if spec.isDeclOnly() { pkg.ExportFile = "" return true, nil diff --git a/internal/build/collect.go b/internal/build/collect.go index b4e0790eca..577b1dea1c 100644 --- a/internal/build/collect.go +++ b/internal/build/collect.go @@ -34,22 +34,23 @@ import ( // collectFingerprint collects all inputs and generates fingerprint for a package. func (c *context) collectFingerprint(pkg *aPackage) error { + return c.collectFingerprintWithStack(pkg, make(map[string]bool)) +} + +func (c *context) collectFingerprintWithStack(pkg *aPackage, fingerprinting map[string]bool) error { if pkg.Manifest != "" && pkg.Fingerprint != "" { return nil } - if c.fingerprinting == nil { - c.fingerprinting = make(map[string]bool) - } - if c.fingerprinting[pkg.ID] { + if fingerprinting[pkg.ID] { // Alternate packages can intentionally close a cycle in the runtime // replacement graph after all packages have been built into SSA. A // cycle cannot have a stable per-package cache key, so compile every // member rather than returning an incorrect cache hit. - c.disablePackageCache(c.fingerprinting) + c.disablePackageCache(fingerprinting) return nil } - c.fingerprinting[pkg.ID] = true - defer delete(c.fingerprinting, pkg.ID) + fingerprinting[pkg.ID] = true + defer delete(fingerprinting, pkg.ID) m := newManifestBuilder() @@ -65,7 +66,7 @@ func (c *context) collectFingerprint(pkg *aPackage) error { } // Dependency section - if err := c.collectDependencyInputs(m, pkg); err != nil { + if err := c.collectDependencyInputs(m, pkg, fingerprinting); err != nil { return err } @@ -75,6 +76,8 @@ func (c *context) collectFingerprint(pkg *aPackage) error { } func (c *context) disablePackageCache(pkgs map[string]bool) { + c.cacheDisabledMu.Lock() + defer c.cacheDisabledMu.Unlock() if c.cacheDisabled == nil { c.cacheDisabled = make(map[string]none, len(pkgs)) } @@ -84,6 +87,8 @@ func (c *context) disablePackageCache(pkgs map[string]bool) { } func (c *context) packageCacheDisabled(id string) bool { + c.cacheDisabledMu.Lock() + defer c.cacheDisabledMu.Unlock() _, disabled := c.cacheDisabled[id] return disabled } @@ -213,9 +218,9 @@ func (c *context) collectPackageInputs(m *manifestBuilder, pkg *aPackage) error } // collectDependencyInputs adds dependency fingerprints/versions into manifest. -func (c *context) collectDependencyInputs(m *manifestBuilder, pkg *aPackage) error { +func (c *context) collectDependencyInputs(m *manifestBuilder, pkg *aPackage, fingerprinting map[string]bool) error { for _, dep := range effectiveDependencies(pkg) { - depEntry, err := c.dependencyFingerprint(dep) + depEntry, err := c.dependencyFingerprint(dep, fingerprinting) if err != nil { return err } @@ -232,15 +237,14 @@ func (c *context) initializePackageBuildState() { if c.sfilesCache == nil { c.sfilesCache = make(map[string][]string) } - if !cacheEnabled() { - return - } - c.cacheManager = newCacheManager() c.llvmVersion = detectLLVMVersion(c) c.llvmVersionReady = true + if cacheEnabled() { + c.cacheManager = newCacheManager() + } } -func (c *context) dependencyFingerprint(dep *packages.Package) (depEntry, error) { +func (c *context) dependencyFingerprint(dep *packages.Package, fingerprinting map[string]bool) (depEntry, error) { entry := depEntry{ID: dep.ID} if v := moduleVersion(dep.Module); v != "" { entry.Version = v @@ -250,7 +254,7 @@ func (c *context) dependencyFingerprint(dep *packages.Package) (depEntry, error) if c.pkgByID != nil { if aDep, ok := c.pkgByID[dep.ID]; ok { if aDep.Fingerprint == "" { - if err := c.collectFingerprint(aDep); err != nil { + if err := c.collectFingerprintWithStack(aDep, fingerprinting); err != nil { return entry, fmt.Errorf("collect fingerprint for %s: %w", dep.ID, err) } } @@ -260,7 +264,7 @@ func (c *context) dependencyFingerprint(dep *packages.Package) (depEntry, error) } temp := &aPackage{Package: dep} - if err := c.collectFingerprint(temp); err != nil { + if err := c.collectFingerprintWithStack(temp, fingerprinting); err != nil { return entry, fmt.Errorf("collect fingerprint for %s: %w", dep.ID, err) } entry.Fingerprint = temp.Fingerprint @@ -283,6 +287,8 @@ func moduleVersion(mod *gopackages.Module) string { // getLLVMVersion returns the cached LLVM version or detects it. func (c *context) getLLVMVersion() string { + c.llvmVersionMu.Lock() + defer c.llvmVersionMu.Unlock() if c.llvmVersionReady { return c.llvmVersion } @@ -334,6 +340,8 @@ func targetTriple(goos, goarch, llvmTarget, targetABI string) string { // ensureCacheManager creates cacheManager if not exists. func (c *context) ensureCacheManager() *cacheManager { + c.cacheManagerMu.Lock() + defer c.cacheManagerMu.Unlock() if c.cacheManager == nil { c.cacheManager = newCacheManager() } diff --git a/internal/build/package_build.go b/internal/build/package_build.go index 634124f014..40c3f491ed 100644 --- a/internal/build/package_build.go +++ b/internal/build/package_build.go @@ -20,6 +20,7 @@ import ( "fmt" "sort" "strings" + "sync" "github.com/goplus/llgo/cl" ) @@ -34,6 +35,53 @@ type packageBuildSpec struct { runtime bool } +type packagePreflight struct { + spec packageBuildSpec + skip bool +} + +// preflightPackageBuilds runs only cache/input work for one dependency level at +// a time. Every dependency's fingerprint is therefore complete before a worker +// reads it, while unrelated packages share the configured -p bound. +func preflightPackageBuilds(ctx *context, plan *packageBuildPlan, verbose bool) (map[string]packagePreflight, error) { + preflights := make(map[string]packagePreflight, len(plan.specs)) + for _, level := range plan.levels { + workers := min(ctx.buildConf.parallelism(), len(level)) + jobs := make(chan int) + type result struct { + index int + skip bool + err error + } + results := make(chan result, len(level)) + var wg sync.WaitGroup + for range workers { + wg.Add(1) + go func() { + defer wg.Done() + for index := range jobs { + skip, err := preflightPackageBuild(ctx, level[index], verbose) + results <- result{index: index, skip: skip, err: err} + } + }() + } + for index := range level { + jobs <- index + } + close(jobs) + wg.Wait() + close(results) + for result := range results { + if result.err != nil { + return nil, result.err + } + spec := level[result.index] + preflights[spec.pkg.ID] = packagePreflight{spec: spec, skip: result.skip} + } + } + return preflights, nil +} + func newPackageBuildSpec(pkg *aPackage) packageBuildSpec { kind, kindParam := cl.PkgKindOf(pkg.Types) return packageBuildSpec{ diff --git a/internal/build/plan9asm.go b/internal/build/plan9asm.go index 57938f22c5..9794feebd2 100644 --- a/internal/build/plan9asm.go +++ b/internal/build/plan9asm.go @@ -394,6 +394,8 @@ func pkgSFiles(ctx *context, pkg *packages.Package) ([]string, error) { } } + ctx.sfilesMu.Lock() + defer ctx.sfilesMu.Unlock() if ctx.sfilesCache == nil { ctx.sfilesCache = make(map[string][]string) } From 47824480d034948adb18726f3c98788476600234 Mon Sep 17 00:00:00 2001 From: ZhouGuangyuan Date: Sat, 25 Jul 2026 07:42:46 +0800 Subject: [PATCH 12/12] build: fix parallel preflight synchronization --- internal/build/build.go | 4 +-- internal/build/collect.go | 8 +++--- internal/build/package_build.go | 6 ++--- internal/build/package_build_test.go | 21 +++++++++++++++ internal/build/plan9asm.go | 39 +++++++++++++++++++--------- 5 files changed, 56 insertions(+), 22 deletions(-) diff --git a/internal/build/build.go b/internal/build/build.go index afd560e453..3593addca7 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -952,14 +952,14 @@ func preflightPackageBuild(ctx *context, spec packageBuildSpec, verbose bool) (s ctx.builtMu.Unlock() if spec.isDeclOnly() { pkg.ExportFile = "" - return true, nil + return true, ctx.collectFingerprint(aPkg) } if spec.isLinkOnly() && !spec.hasSource() { pkg.ExportFile = "" if spec.kind == cl.PkgLinkExtern { appendExternalLinkArgs(ctx, aPkg, spec.kindParam) } - return true, nil + return true, ctx.collectFingerprint(aPkg) } if err := ctx.collectFingerprint(aPkg); err != nil { return false, err diff --git a/internal/build/collect.go b/internal/build/collect.go index 577b1dea1c..94c590a681 100644 --- a/internal/build/collect.go +++ b/internal/build/collect.go @@ -230,15 +230,13 @@ func (c *context) collectDependencyInputs(m *manifestBuilder, pkg *aPackage, fin return nil } -// initializePackageBuildState initializes the mutable state used by the -// package pipeline before any scheduler is introduced. This makes ownership -// explicit and avoids lazy first-use writes becoming data races later. +// initializePackageBuildState initializes mutable package pipeline state that +// has to exist before parallel preflight begins. LLVM version discovery stays +// lazy and is synchronized by getLLVMVersion. func (c *context) initializePackageBuildState() { if c.sfilesCache == nil { c.sfilesCache = make(map[string][]string) } - c.llvmVersion = detectLLVMVersion(c) - c.llvmVersionReady = true if cacheEnabled() { c.cacheManager = newCacheManager() } diff --git a/internal/build/package_build.go b/internal/build/package_build.go index 40c3f491ed..08af0aefe5 100644 --- a/internal/build/package_build.go +++ b/internal/build/package_build.go @@ -130,9 +130,9 @@ func packageBuildResultFor(spec packageBuildSpec) packageBuildResult { } } -// packageBuildPlan is the immutable dependency graph consumed by a future -// scheduler. specs retains the existing deterministic execution order until -// the LLVM backend is made worker-local; levels records the safe ready sets. +// packageBuildPlan is the immutable dependency graph. levels drives bounded +// parallel preflight today; specs retains the deterministic serial order for +// the LLVM backend until it owns worker-local program state. type packageBuildPlan struct { specs []packageBuildSpec byID map[string]packageBuildSpec diff --git a/internal/build/package_build_test.go b/internal/build/package_build_test.go index 593509a62c..581691be9e 100644 --- a/internal/build/package_build_test.go +++ b/internal/build/package_build_test.go @@ -119,3 +119,24 @@ func TestPackageBuildSpecSpecialKinds(t *testing.T) { t.Fatalf("runtime package was not marked runtime: %+v", runtime) } } + +func TestPreflightFingerprintsSkippedPackage(t *testing.T) { + pkg := &aPackage{Package: &packages.Package{ + ID: "unsafe", + PkgPath: "unsafe", + Types: types.Unsafe, + }} + ctx := &context{ + conf: &packages.Config{}, + buildConf: &Config{Goos: "linux", Goarch: "amd64", ForceRebuild: true}, + built: make(map[string]none), + llvmVersionReady: true, + } + skip, err := preflightPackageBuild(ctx, newPackageBuildSpec(pkg), false) + if err != nil { + t.Fatal(err) + } + if !skip || pkg.Fingerprint == "" || pkg.Manifest == "" { + t.Fatalf("skipped package was not fingerprinted: skip=%v fingerprint=%q manifest=%q", skip, pkg.Fingerprint, pkg.Manifest) + } +} diff --git a/internal/build/plan9asm.go b/internal/build/plan9asm.go index 9794feebd2..88b2cf1595 100644 --- a/internal/build/plan9asm.go +++ b/internal/build/plan9asm.go @@ -394,12 +394,7 @@ func pkgSFiles(ctx *context, pkg *packages.Package) ([]string, error) { } } - ctx.sfilesMu.Lock() - defer ctx.sfilesMu.Unlock() - if ctx.sfilesCache == nil { - ctx.sfilesCache = make(map[string][]string) - } - if v, ok := ctx.sfilesCache[pkg.ID]; ok { + if v, ok := getCachedSFiles(ctx, pkg.ID); ok { return v, nil } @@ -447,21 +442,41 @@ func pkgSFiles(ctx *context, pkg *packages.Package) ([]string, error) { stub := filepath.Join(lp.Dir, "chacha8_stub.s") if _, err := os.Stat(stub); err == nil { paths := []string{stub} - ctx.sfilesCache[pkg.ID] = paths - return paths, nil + return cacheSFiles(ctx, pkg.ID, paths), nil } } // Embedded ARM targets currently reuse GOOS=linux metadata, but they do not // have a Linux syscall surface. Skip syscall asm in that mode so embedded // builds do not inherit Linux/ARM-specific frame layouts. if shouldSkipPlan9AsmSFilesForTarget(ctx.buildConf, pkg.PkgPath) { - ctx.sfilesCache[pkg.ID] = nil - return nil, nil + return cacheSFiles(ctx, pkg.ID, nil), nil } paths := selectedSFiles(lp.Dir, lp.SFiles) - ctx.sfilesCache[pkg.ID] = paths - return paths, nil + return cacheSFiles(ctx, pkg.ID, paths), nil +} + +func getCachedSFiles(ctx *context, pkgID string) ([]string, bool) { + ctx.sfilesMu.Lock() + defer ctx.sfilesMu.Unlock() + if ctx.sfilesCache == nil { + ctx.sfilesCache = make(map[string][]string) + } + paths, ok := ctx.sfilesCache[pkgID] + return paths, ok +} + +func cacheSFiles(ctx *context, pkgID string, paths []string) []string { + ctx.sfilesMu.Lock() + defer ctx.sfilesMu.Unlock() + if ctx.sfilesCache == nil { + ctx.sfilesCache = make(map[string][]string) + } + if cached, ok := ctx.sfilesCache[pkgID]; ok { + return cached + } + ctx.sfilesCache[pkgID] = paths + return paths } func selectedSFiles(dir string, files []string) []string {