diff --git a/cl/caller_tracking_precompute_test.go b/cl/caller_tracking_precompute_test.go new file mode 100644 index 0000000000..58663c57fa --- /dev/null +++ b/cl/caller_tracking_precompute_test.go @@ -0,0 +1,80 @@ +//go:build !llgo + +/* + * 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 cl + +import ( + "sync" + "testing" + + gossa "golang.org/x/tools/go/ssa" +) + +func TestCallerTrackingPrecomputeFreezesConcurrentReads(t *testing.T) { + dep, root := buildCallerFrameSSAProgram(t, + "example.com/dep", `package dep +import "runtime" +func Where() { runtime.Caller(0) } +`, + "example.com/root", `package root +import "example.com/dep" +func Logs() { dep.Where() } +`) + tracking := NewCallerTracking() + tracking.Precompute([]*gossa.Package{root}) + if !tracking.frozen { + t.Fatal("CallerTracking was not frozen after precomputation") + } + if !runtimeCallerBaseSet(tracking, dep)[dep.Func("Where")] { + t.Fatal("precomputed base set lost runtime caller function") + } + if !runtimeCallerFuncSet(tracking, root)[root.Func("Logs")] { + t.Fatal("precomputed extended set lost cross-package caller") + } + + var wg sync.WaitGroup + errs := make(chan struct{}, 32) + for range 32 { + wg.Add(1) + go func() { + defer wg.Done() + if !runtimeCallerBaseSet(tracking, dep)[dep.Func("Where")] || !runtimeCallerFuncSet(tracking, root)[root.Func("Logs")] { + errs <- struct{}{} + } + }() + } + wg.Wait() + close(errs) + if len(errs) != 0 { + t.Fatal("concurrent read lost precomputed caller tracking data") + } + + // A worker can encounter a package outside the precomputed program. Once + // frozen, that must be a read-only miss rather than lazy map mutation. + delete(tracking.base, dep) + if got := runtimeCallerBaseSet(tracking, dep); got != nil { + t.Fatalf("frozen base lookup for unknown package = %v, want nil", got) + } + delete(tracking.extended, root) + if got := runtimeCallerFuncSet(tracking, root); got != nil { + t.Fatalf("frozen extended lookup for unknown package = %v, want nil", got) + } + + // Repeated setup is intentionally a no-op after the tracker is frozen. + tracking.Precompute(nil) +} diff --git a/cl/instr.go b/cl/instr.go index ddbcb58806..ee43aa1edf 100644 --- a/cl/instr.go +++ b/cl/instr.go @@ -25,6 +25,7 @@ import ( "log" "os" "regexp" + "sort" "strings" "golang.org/x/tools/go/ssa" @@ -924,6 +925,9 @@ func runtimeCallerFuncSet(c *CallerTracking, pkg *ssa.Package) map[*ssa.Function if set, ok := c.extended[pkg]; ok { return set } + if c.frozen { + return nil + } base := runtimeCallerBaseSet(c, pkg) out := make(map[*ssa.Function]bool, len(base)) for fn := range base { @@ -983,6 +987,7 @@ func runtimeCallerFuncSet(c *CallerTracking, pkg *ssa.Package) map[*ssa.Function type CallerTracking struct { base map[*ssa.Package]map[*ssa.Function]bool extended map[*ssa.Package]map[*ssa.Function]bool + frozen bool } // NewCallerTracking creates the caller-tracking memoization for one @@ -994,6 +999,45 @@ func NewCallerTracking() *CallerTracking { } } +// Precompute resolves caller-tracking state for every package in the supplied +// SSA programs, then freezes the memoization for concurrent reads. Drivers +// must call it after SSA Build and before compiling packages on independent +// LLVM contexts. A frozen tracker deliberately returns no data for an unknown +// package instead of mutating its maps from a worker. +func (c *CallerTracking) Precompute(pkgs []*ssa.Package) { + if c == nil || c.frozen { + return + } + all := make(map[*ssa.Package]bool) + for _, pkg := range pkgs { + if pkg == nil { + continue + } + all[pkg] = true + if pkg.Prog != nil { + for _, programPkg := range pkg.Prog.AllPackages() { + if programPkg != nil { + all[programPkg] = true + } + } + } + } + ordered := make([]*ssa.Package, 0, len(all)) + for pkg := range all { + ordered = append(ordered, pkg) + } + sort.Slice(ordered, func(i, j int) bool { + return llssa.PathOf(ordered[i].Pkg) < llssa.PathOf(ordered[j].Pkg) + }) + for _, pkg := range ordered { + runtimeCallerBaseSet(c, pkg) + } + for _, pkg := range ordered { + runtimeCallerFuncSet(c, pkg) + } + c.frozen = true +} + func isProgramUniqueFrame(pkg *ssa.Package, fn *ssa.Function) bool { if fn == nil || fn.Parent() != nil { return false @@ -1012,6 +1056,9 @@ func runtimeCallerBaseSet(c *CallerTracking, pkg *ssa.Package) map[*ssa.Function if set, ok := c.base[pkg]; ok { return set } + if c.frozen { + return nil + } set := computeRuntimeCallerBaseSet(pkg) c.base[pkg] = set return set diff --git a/internal/build/build.go b/internal/build/build.go index 2de1f96536..f652695fba 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -177,6 +177,9 @@ type Config struct { // default. PCLNModeSet bool AllowNoBody bool // allow declarations without bodies, as go tool compile does + // Parallel is the maximum number of LLGo's internally parallel build tasks. + // 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 // goroutines. A zero value keeps the platform pthread default. @@ -267,7 +270,19 @@ const ( loadSyntax = loadTypes | packages.NeedSyntax | packages.NeedTypesInfo ) +var llssaInitOnce sync.Once + +func (c *Config) parallelism() int { + if 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 } @@ -355,7 +370,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, @@ -364,7 +381,14 @@ func Do(args []string, conf *Config) ([]Package, error) { OptLevel: conf.OptLevel, } - prog := llssa.NewProgram(target) + funcInfo := conf.Mode != ModeGen && conf.PCLNMode != PCLNNone + // Site records are inline-asm fragments inside function bodies. Darwin + // DWARF builds avoid them because they disturb LLDB lexical scopes; Linux + // still needs them because its restricted dynamic symbol table cannot + // reconstruct every Go entry PC through dlsym. External mode always needs + // final-PC sites for sidecar construction. + backendTemplate := newBackendProgramTemplate(target, conf, funcInfo, shouldEnablePCLNSites(conf, funcInfo, emitDebugInfo)) + prog := backendTemplate.newProgram() if conf.Mode != ModeGen { // ModeGen callers (llgen and the golden suites) read LPkg.String() // after Do returns and dispose the program themselves; every other @@ -374,19 +398,6 @@ func Do(args []string, conf *Config) ([]Package, error) { // harness) otherwise accumulate every compile's C++-side memory. defer prog.Dispose() } - prog.EnableGoGlobalDCE(conf.goGlobalDCEEnabled()) - if conf.PthreadStackSize > 0 { - prog.SetPthreadStackSize(uint64(conf.PthreadStackSize)) - } - prog.EnableLTOPluginMarkers(conf.LTOPlugin.Enabled()) - funcInfo := conf.Mode != ModeGen && conf.PCLNMode != PCLNNone - prog.EnableFuncInfoMetadata(funcInfo) - // Site records are inline-asm fragments inside function bodies. Darwin - // DWARF builds avoid them because they disturb LLDB lexical scopes; Linux - // still needs them because its restricted dynamic symbol table cannot - // reconstruct every Go entry PC through dlsym. External mode always needs - // final-PC sites for sidecar construction. - prog.EnableFuncInfoSites(shouldEnablePCLNSites(conf, funcInfo, emitDebugInfo)) sizes := func(sizes types.Sizes, compiler, arch string) types.Sizes { if arch == "wasm" { sizes = &types.StdSizes{WordSize: 4, MaxAlign: 4} @@ -477,9 +488,14 @@ func Do(args []string, conf *Config) ([]Package, error) { if !IsOptimizeEnabled() { buildMode |= ssa.NaiveForm } + backendTemplate.runtimePackage = func() *types.Package { return altPkgs[0].Types } + backendTemplate.pythonPackage = func() *types.Package { return dedup.Check(llssa.PkgPython).Types } + backendTemplate.runtimeLinknames = altPkgs + backendTemplate.llvmTarget = export.LLVMTarget + backendTemplate.targetABI = export.TargetABI + backendTemplate.cabiOptimize = cabiOptimize 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 @@ -488,27 +504,34 @@ 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), - } + 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), + backend: backendTemplate, + sfilesCache: make(map[string][]string), + } + 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...)) + // CallerTracking owns plain maps. Resolve every possible query while the + // SSA graph is still serial, so worker-local backend sessions only read it. + ctx.callerTracking.Precompute(ctx.progSSA.AllPackages()) allPkgs := append([]*aPackage{}, pkgs...) allPkgs = append(allPkgs, depPkgs...) @@ -720,7 +743,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 @@ -733,15 +756,20 @@ type context struct { crossCompile crosscompile.Export cTransformer *cabi.Transformer + backend backendProgramTemplate testFail bool // Cache related fields - cacheManager *cacheManager - llvmVersion string + cacheManager *cacheManager + cacheManagerMu 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 @@ -753,6 +781,82 @@ type context struct { pclnExternal *pclnmap.Data } +// backendProgramTemplate contains all state a backend Program needs without +// sharing an LLVM context. The current serial path keeps one Program in +// context.prog; the next stage will create one backendSession per worker from +// this template. +type backendProgramTemplate struct { + target *llssa.Target + goGlobalDCE bool + pthreadStackSize int64 + ltoPluginMarkers bool + funcInfoMetadata bool + funcInfoSites bool + runtimePackage func() *types.Package + pythonPackage func() *types.Package + runtimeLinknames []*packages.Package + llvmTarget string + targetABI string + abiMode cabi.Mode + cabiOptimize bool +} + +type backendSession struct { + prog llssa.Program + transformer *cabi.Transformer +} + +func newBackendProgramTemplate(target *llssa.Target, conf *Config, funcInfoMetadata, funcInfoSites bool) backendProgramTemplate { + var targetCopy *llssa.Target + if target != nil { + copy := *target + targetCopy = © + } + return backendProgramTemplate{ + target: targetCopy, + goGlobalDCE: conf.goGlobalDCEEnabled(), + pthreadStackSize: conf.PthreadStackSize, + ltoPluginMarkers: conf.LTOPlugin.Enabled(), + funcInfoMetadata: funcInfoMetadata, + funcInfoSites: funcInfoSites, + abiMode: conf.AbiMode, + } +} + +func (t backendProgramTemplate) newProgram() llssa.Program { + var target *llssa.Target + if t.target != nil { + copy := *t.target + target = © + } + prog := llssa.NewProgram(target) + prog.EnableGoGlobalDCE(t.goGlobalDCE) + if t.pthreadStackSize > 0 { + prog.SetPthreadStackSize(uint64(t.pthreadStackSize)) + } + prog.EnableLTOPluginMarkers(t.ltoPluginMarkers) + prog.EnableFuncInfoMetadata(t.funcInfoMetadata) + prog.EnableFuncInfoSites(t.funcInfoSites) + if t.runtimePackage != nil { + prog.SetRuntime(t.runtimePackage) + } + if t.pythonPackage != nil { + prog.SetPython(t.pythonPackage) + } + if len(t.runtimeLinknames) != 0 { + preCollectRuntimeLinknames(prog, t.runtimeLinknames) + } + return prog +} + +func (t backendProgramTemplate) newSession() backendSession { + prog := t.newProgram() + return backendSession{ + prog: prog, + transformer: cabi.NewTransformer(prog, t.llvmTarget, t.targetABI, t.abiMode, t.cabiOptimize), + } +} + func (c *context) compiler() *clang.Cmd { config := clang.NewConfig( c.crossCompile.CC, @@ -813,106 +917,41 @@ func normalizeToArchive(ctx *context, aPkg *aPackage, verbose bool) error { } func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, error) { - built := ctx.built - + plan, err := newPackageBuildPlan(pkgs) + 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 []*aPackage - var normalPkgs []*aPackage - for _, p := range pkgs { - if isRuntimePkg(p.PkgPath) { - runtimePkgs = append(runtimePkgs, p) + var runtimePkgs []packageBuildSpec + var normalPkgs []packageBuildSpec + for _, spec := range plan.specs { + if spec.runtime { + runtimePkgs = append(runtimePkgs, spec) } else { - normalPkgs = append(normalPkgs, p) + normalPkgs = append(normalPkgs, spec) } } 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 { + for _, spec := range normalPkgs { + result, err := buildPreflightedPackage(ctx, preflights[spec.pkg.ID], 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 { + for _, spec := range runtimePkgs { + if _, err := buildPreflightedPackage(ctx, preflights[spec.pkg.ID], verbose); err != nil { return nil, err } } @@ -921,6 +960,99 @@ func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, er return pkgs, nil } +// 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, preflight.spec, verbose); err != nil { + return packageBuildResultFor(preflight.spec), err + } + return finalizePackageBuild(ctx, preflight.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 + 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 = "" + // Declaration-only packages still occur in the link graph through a + // different packages.Package instance. Publish an empty summary so the + // linker can treat that occurrence like every other skipped package. + aPkg.Summary = summarizePackage(aPkg) + return true, ctx.collectFingerprint(aPkg) + } + if spec.isLinkOnly() && !spec.hasSource() { + pkg.ExportFile = "" + if spec.kind == cl.PkgLinkExtern { + appendExternalLinkArgs(ctx, aPkg, spec.kindParam) + } + // Link-only packages do not create an LLVM module, but their linker + // arguments are still consumed by linkMainPkg through PackageSummary. + aPkg.Summary = summarizePackage(aPkg) + return true, ctx.collectFingerprint(aPkg) + } + if err := ctx.collectFingerprint(aPkg); err != nil { + return false, err + } + ctx.tryLoadFromCache(aPkg) + if verbose { + status := "MISS" + if aPkg.CacheHit { + status = "HIT" + } + 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 err + } + if spec.needsRuntimeSignals() { + aPkg.setNeedRuntimeOrPyInit(aPkg.LPkg.NeedRuntime, aPkg.LPkg.NeedPyInit) + } + 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 packageBuildResultFor(spec), nil + } + if err := normalizeToArchive(ctx, aPkg, verbose); err != nil { + return packageBuildResultFor(spec), err + } + if spec.kind == cl.PkgLinkExtern { + appendExternalLinkArgs(ctx, aPkg, spec.kindParam) + } + // Snapshot every linker-facing LLVM fact before cache publication. The + // summary is the hand-off point to a future worker-local Program. + aPkg.Summary = summarizePackage(aPkg) + if err := ctx.saveToCache(aPkg); err != nil && verbose { + fmt.Fprintf(os.Stderr, "warning: failed to save cache for %s: %v\n", aPkg.PkgPath, err) + } + return packageBuildResultFor(spec), nil +} + func appendExternalLinkArgs(ctx *context, aPkg *aPackage, spec string) { // need to be linked with external library // format: ';' separated alternative link methods. e.g. @@ -1162,39 +1294,51 @@ func linkMainPkg(ctx *context, pkg *packages.Package, pkgs []*aPackage, outputPa aPkg = ctx.pkgByID[p.ID] } if p.ExportFile != "" && aPkg != nil { // skip packages that only contain declarations + // Runtime packages are built on demand. For a target that does not + // require the runtime, preserve the historical behavior of omitting + // those unbuilt packages from the link rather than requiring a + // linker summary that no backend ever produced. + if aPkg.Summary == nil && isRuntimePkg(aPkg.PkgPath) { + return + } linkedPkgs[p.ID] = true linkedOrder = append(linkedOrder, aPkg) } }) + linkedSummaries := make([]*PackageSummary, len(linkedOrder)) + for i, aPkg := range linkedOrder { + if aPkg.Summary == nil { + return fmt.Errorf("package %s has no linker summary", aPkg.PkgPath) + } + linkedSummaries[i] = aPkg.Summary + } // packages.Visit with a post callback yields dependencies before importers. // Reverse that order so static archives are linked after the objects that use them. for i := len(linkedOrder) - 1; i >= 0; i-- { - aPkg := linkedOrder[i] - p := aPkg.Package + summary := linkedSummaries[i] // Defer linking runtime packages unless we actually need the runtime. - if isRuntimePkg(p.PkgPath) { - rtLinkArgs = append(rtLinkArgs, aPkg.LinkArgs...) - if aPkg.ArchiveFile != "" { - rtLinkInputs = append(rtLinkInputs, aPkg.ArchiveFile) + if isRuntimePkg(summary.PkgPath) { + rtLinkArgs = append(rtLinkArgs, summary.LinkArgs...) + if summary.ArchiveFile != "" { + rtLinkInputs = append(rtLinkInputs, summary.ArchiveFile) } continue } // Only let non-runtime packages influence whether runtime is needed. - need1, need2 := aPkg.isNeedRuntimeOrPyInit() - needRuntime = needRuntime || need1 - needPyInit = needPyInit || need2 - needAbiInit |= aPkg.LPkg.NeedAbiInit - for k, _ := range aPkg.LPkg.MethodByIndex { - methodByIndex[k] = none{} + needRuntime = needRuntime || summary.NeedRuntime + needPyInit = needPyInit || summary.NeedPyInit + needAbiInit |= summary.NeedAbiInit + for _, method := range summary.MethodByIndex { + methodByIndex[method] = none{} } - for k, _ := range aPkg.LPkg.MethodByName { - methodByName[k] = none{} + for _, method := range summary.MethodByName { + methodByName[method] = none{} } - linkArgs = append(linkArgs, aPkg.LinkArgs...) - if aPkg.ArchiveFile != "" { - archiveInputs = append(archiveInputs, aPkg.ArchiveFile) + linkArgs = append(linkArgs, summary.LinkArgs...) + if summary.ArchiveFile != "" { + archiveInputs = append(archiveInputs, summary.ArchiveFile) } } @@ -1211,9 +1355,9 @@ func linkMainPkg(ctx *context, pkg *packages.Package, pkgs []*aPackage, outputPa var pcLineInfo []pcLineRecord var funcInfoStubs []funcInfoStubRecord if ctx.buildConf.PCLNMode != PCLNNone { - funcInfo = prepareFuncInfoTableRecords(collectFuncInfo(linkedOrder), nil) - pcLineInfo = collectPCLineInfo(linkedOrder) - funcInfoStubs = collectFuncInfoStubRecords(linkedOrder, funcInfo) + funcInfo = prepareFuncInfoTableRecords(collectFuncInfoSummaries(linkedSummaries), nil) + pcLineInfo = collectPCLineInfoSummaries(linkedSummaries) + funcInfoStubs = collectFuncInfoStubRecordsSummaries(linkedSummaries, funcInfo) } entryPkg := genMainModule(ctx, llssa.PkgRuntime, pkg, &genConfig{ rtInit: needRuntime, @@ -1221,7 +1365,7 @@ func linkMainPkg(ctx *context, pkg *packages.Package, pkgs []*aPackage, outputPa abiInit: needAbiInit, methodByIndex: methodByIndex, methodByName: methodByName, - abiSymbols: linkedModuleGlobals(linkedOrder), + abiSymbols: linkedPackageGlobals(linkedSummaries), funcInfo: funcInfo, pcLineInfo: pcLineInfo, funcInfoStubs: funcInfoStubs, @@ -1256,7 +1400,7 @@ func linkMainPkg(ctx *context, pkg *packages.Package, pkgs []*aPackage, outputPa } } } - linkArgs = append(linkArgs, cSharedExportArgs(ctx, linkedOrder)...) + linkArgs = append(linkArgs, cSharedExportArgs(ctx, linkedSummaries)...) err = linkObjFiles(ctx, outputPath, linkInputs, linkArgs, verbose) if err != nil { @@ -1267,19 +1411,22 @@ func linkMainPkg(ctx *context, pkg *packages.Package, pkgs []*aPackage, outputPa } func linkedModuleGlobals(pkgs []Package) map[string]none { - if len(pkgs) == 0 { + return linkedPackageGlobals(summariesForPackages(pkgs)) +} + +func linkedPackageGlobals(summaries []*PackageSummary) map[string]none { + if len(summaries) == 0 { return nil } seen := make(map[string]none) - for _, pkg := range pkgs { - if pkg == nil || pkg.LPkg == nil { + for _, summary := range summaries { + if summary == nil { continue } - for g := pkg.LPkg.Module().FirstGlobal(); !g.IsNil(); g = gllvm.NextGlobal(g) { - if g.IsDeclaration() { - continue + for _, name := range summary.GlobalSymbols { + if name != "" { + seen[name] = none{} } - seen[g.Name()] = none{} } } return seen @@ -1352,16 +1499,16 @@ func linkObjFiles(ctx *context, app string, objFiles, linkArgs []string, verbose // cSharedExportArgs keeps //export functions as shared-library link roots. The // functions live in package archives and otherwise remain unreferenced, so the // linker can omit both their object files and dynamic symbols. -func cSharedExportArgs(ctx *context, pkgs []*aPackage) []string { +func cSharedExportArgs(ctx *context, summaries []*PackageSummary) []string { if ctx == nil || ctx.buildConf == nil || ctx.buildConf.BuildMode != BuildModeCShared { return nil } exports := make(map[string]none) - for _, pkg := range pkgs { - if pkg == nil || pkg.LPkg == nil { + for _, summary := range summaries { + if summary == nil { continue } - for _, name := range pkg.LPkg.ExportFuncs() { + for _, name := range summary.CSharedExports { if name != "" { exports[name] = none{} } @@ -1570,6 +1717,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 { @@ -1579,7 +1736,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 { @@ -1597,7 +1754,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) } ret, externs, err := cl.NewPackageExWithEmbed(ctx.prog, ctx.callerTracking, ctx.patches, aPkg.rewriteVars, aPkg.SSA, syntax, embedMap) @@ -1610,8 +1767,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()) @@ -1625,7 +1792,7 @@ func buildPkg(ctx *context, aPkg *aPackage, verbose bool) error { 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 err } if err := mod.RunPasses(llvmPassPipeline(ctx.buildConf.OptLevel, ctx.buildConf.ltoMode()), ctx.prog.TargetMachine(), pbo); err != nil { @@ -1881,13 +2048,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 @@ -1903,7 +2081,7 @@ func altSSAPkgs(prog *ssa.Program, patches cl.Patches, alts []*packages.Package, } } }) - prog.Build() + return entries } type aPackage struct { @@ -1911,6 +2089,10 @@ type aPackage struct { SSA *ssa.Package AltPkg *packages.Cached LPkg llssa.Package + // Summary is the immutable linker-facing result captured after the package + // module is compiled. Linkers must use it instead of reading LPkg so a + // future backend worker can release its LLVM program after object emission. + Summary *PackageSummary NeedRt bool NeedPyInit bool @@ -1928,9 +2110,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 { @@ -1940,7 +2126,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 @@ -1972,9 +2161,53 @@ 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)) + entryIndex := make(map[*ssa.Package]int, len(entries)) + for _, entry := range entries { + if entry.pkg == nil { + continue + } + 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, len(unique)) + 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 { @@ -2122,7 +2355,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 { @@ -2130,11 +2363,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/build_test.go b/internal/build/build_test.go index c26241cc20..640636c4a2 100644 --- a/internal/build/build_test.go +++ b/internal/build/build_test.go @@ -59,6 +59,26 @@ func TestNeedsLinuxNoPIE(t *testing.T) { } } +func TestBackendProgramTemplateCreatesIsolatedSessions(t *testing.T) { + conf := &Config{Goos: "linux", Goarch: "amd64"} + template := newBackendProgramTemplate(&llssa.Target{GOOS: conf.Goos, GOARCH: conf.Goarch}, conf, true, true) + first := template.newSession() + defer first.prog.Dispose() + second := template.newSession() + defer second.prog.Dispose() + if first.transformer == nil || second.transformer == nil { + t.Fatal("backend session missing C ABI transformer") + } + if !first.prog.FuncInfoMetadataEnabled() || !first.prog.FuncInfoSitesEnabled() { + t.Fatal("backend template did not preserve funcinfo configuration") + } + firstModule := first.prog.NewPackage("example.com/first", "first").Module() + secondModule := second.prog.NewPackage("example.com/second", "second").Module() + if firstModule.Context().C == secondModule.Context().C { + t.Fatal("backend sessions share an LLVM context") + } +} + func TestNeedsLinuxExportDynamic(t *testing.T) { t.Setenv(llgoFuncInfo, "") ctx := &context{buildConf: &Config{Goos: "linux"}} @@ -610,22 +630,18 @@ func TestCSharedExportArgs(t *testing.T) { if got := cSharedExportArgs(nil, nil); got != nil { t.Fatalf("nil cSharedExportArgs = %v, want nil", got) } - prog := llssa.NewProgram(nil) - lpkg := prog.NewPackage("example.com/p", "example.com/p") - lpkg.SetExport("example.com/p.Z", "Zed") - lpkg.SetExport("example.com/p.A", "Add") - pkgs := []*aPackage{{LPkg: lpkg}} + summaries := []*PackageSummary{{CSharedExports: []string{"Add", "Zed"}}} ctx := &context{buildConf: &Config{BuildMode: BuildModeCShared, Goos: "linux"}} - if got, want := strings.Join(cSharedExportArgs(ctx, pkgs), " "), "-Wl,--undefined=Add -Wl,--undefined=Zed"; got != want { + if got, want := strings.Join(cSharedExportArgs(ctx, summaries), " "), "-Wl,--undefined=Add -Wl,--undefined=Zed"; got != want { t.Fatalf("linux cSharedExportArgs = %q, want %q", got, want) } ctx.buildConf.Goos = "darwin" - if got, want := strings.Join(cSharedExportArgs(ctx, pkgs), " "), "-Wl,-u,_Add -Wl,-u,_Zed"; got != want { + if got, want := strings.Join(cSharedExportArgs(ctx, summaries), " "), "-Wl,-u,_Add -Wl,-u,_Zed"; got != want { t.Fatalf("darwin cSharedExportArgs = %q, want %q", got, want) } ctx.buildConf.BuildMode = BuildModeExe - if got := cSharedExportArgs(ctx, pkgs); got != nil { + if got := cSharedExportArgs(ctx, summaries); got != nil { t.Fatalf("executable cSharedExportArgs = %v, want nil", got) } } diff --git a/internal/build/collect.go b/internal/build/collect.go index d77879537f..1b26fb74c6 100644 --- a/internal/build/collect.go +++ b/internal/build/collect.go @@ -23,7 +23,6 @@ import ( "os/exec" "path/filepath" "runtime" - "sort" "strconv" "strings" @@ -34,17 +33,18 @@ 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] { return fmt.Errorf("fingerprint cycle detected for %s", pkg.ID) } - c.fingerprinting[pkg.ID] = true - defer delete(c.fingerprinting, pkg.ID) + fingerprinting[pkg.ID] = true + defer delete(fingerprinting, pkg.ID) m := newManifestBuilder() @@ -60,7 +60,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 } @@ -193,23 +193,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 { - 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 { - depEntry, err := c.dependencyFingerprint(dep) +func (c *context) collectDependencyInputs(m *manifestBuilder, pkg *aPackage, fingerprinting map[string]bool) error { + for _, dep := range effectiveDependencies(pkg) { + depEntry, err := c.dependencyFingerprint(dep, fingerprinting) if err != nil { return err } @@ -219,7 +205,19 @@ func (c *context) collectDependencyInputs(m *manifestBuilder, pkg *aPackage) err return nil } -func (c *context) dependencyFingerprint(dep *packages.Package) (depEntry, error) { +// 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) + } + if cacheEnabled() { + c.cacheManager = newCacheManager() + } +} + +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 @@ -229,7 +227,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) } } @@ -239,7 +237,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 @@ -262,10 +260,13 @@ func moduleVersion(mod *gopackages.Module) string { // getLLVMVersion returns the cached LLVM version or detects it. func (c *context) getLLVMVersion() string { - if c.llvmVersion != "" { + c.llvmVersionMu.Lock() + defer c.llvmVersionMu.Unlock() + if c.llvmVersionReady { return c.llvmVersion } c.llvmVersion = detectLLVMVersion(c) + c.llvmVersionReady = true return c.llvmVersion } @@ -312,6 +313,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() } @@ -324,6 +327,12 @@ func (c *context) tryLoadFromCache(pkg *aPackage) bool { if !cacheEnabled() { return false } + // C archive/shared builds still generate their public headers from live + // package declarations. Keep that compatibility path uncached until header + // declaration rendering is also represented by PackageSummary. + if c.buildConf != nil && (c.buildConf.BuildMode == BuildModeCArchive || c.buildConf.BuildMode == BuildModeCShared) { + 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. @@ -360,6 +369,13 @@ func (c *context) tryLoadFromCache(pkg *aPackage) bool { if err != nil { return false } + // Old manifests did not carry the linker-facing package summary. Treat + // those entries as misses rather than linking with incomplete ABI/metadata + // state. Released builds naturally invalidate caches through LLGo version; + // development builds safely repopulate the affected entries on demand. + if meta.Summary == nil { + return false + } // Use the .a archive directly for linking (no extraction needed) pkg.ArchiveFile = paths.Archive @@ -367,6 +383,7 @@ func (c *context) tryLoadFromCache(pkg *aPackage) bool { pkg.NeedRt = meta.NeedRt pkg.NeedPyInit = meta.NeedPyInit pkg.CacheHit = true + pkg.Summary = summaryFromMetadata(pkg, meta) return true } @@ -381,6 +398,7 @@ func parseManifestMetadata(content string) (*cacheArchiveMetadata, error) { meta.LinkArgs = append([]string(nil), data.Metadata.LinkArgs...) meta.NeedRt = data.Metadata.NeedRt meta.NeedPyInit = data.Metadata.NeedPyInit + meta.Summary = data.Metadata.Summary } return meta, nil } @@ -434,6 +452,7 @@ type cacheArchiveMetadata struct { LinkArgs []string NeedRt bool NeedPyInit bool + Summary *packageSummaryMetadata } // saveToCache saves a built package to cache. @@ -483,17 +502,17 @@ func (c *context) saveToCache(pkg *aPackage) error { if err != nil { return fmt.Errorf("decode manifest: %w", err) } + if pkg.Summary == nil { + pkg.Summary = summarizePackage(pkg) + } meta := &manifestMetadata{ LinkArgs: append([]string(nil), pkg.LinkArgs...), NeedRt: pkg.NeedRt, NeedPyInit: pkg.NeedPyInit, + Summary: pkg.Summary.metadata(), } - if len(meta.LinkArgs) == 0 && !meta.NeedRt && !meta.NeedPyInit { - data.Metadata = nil - } else { - data.Metadata = meta - } + data.Metadata = meta manifestWithMeta, err := buildManifestYAML(data) if err != nil { diff --git a/internal/build/collect_test.go b/internal/build/collect_test.go index ee4c163a86..8767e369de 100644 --- a/internal/build/collect_test.go +++ b/internal/build/collect_test.go @@ -22,6 +22,7 @@ import ( "os" "os/exec" "path/filepath" + "reflect" "runtime" "strings" "testing" @@ -787,6 +788,81 @@ func TestTryLoadFromCache_ForceRebuild(t *testing.T) { } } +func TestTryLoadFromCacheRestoresPackageSummary(t *testing.T) { + td := t.TempDir() + oldFunc := cacheRootFunc + cacheRootFunc = func() string { return td } + defer func() { cacheRootFunc = oldFunc }() + + ctx := &context{ + conf: &packages.Config{}, + buildConf: &Config{Goos: "darwin", Goarch: "arm64"}, + crossCompile: crosscompile.Export{ + LLVMTarget: "arm64-apple-darwin", + }, + } + pkg := &aPackage{ + Package: &packages.Package{ID: "example.com/cached", PkgPath: "example.com/cached", Name: "cached"}, + Fingerprint: "summary-test", + Manifest: func() string { + m := newManifestBuilder() + m.env.Goos = "darwin" + m.pkg.PkgPath = "example.com/cached" + return m.Build() + }(), + NeedRt: true, + NeedPyInit: true, + LinkArgs: []string{"-lcached"}, + Summary: &PackageSummary{ + ID: "example.com/cached", + PkgPath: "example.com/cached", + LinkArgs: []string{"-lcached"}, + NeedRuntime: true, + NeedPyInit: true, + NeedAbiInit: 3, + MethodByIndex: []int{1}, + MethodByName: []string{"Method"}, + GlobalSymbols: []string{"example.com/cached.global"}, + FuncInfo: []funcInfoRecord{{symbol: "example.com/cached.fn", name: "Fn", file: "p.go", line: 7}}, + PCLineInfo: []pcLineRecord{{id: 9, symbol: "example.com/cached.fn", file: "p.go", line: 8}}, + FuncInfoStubs: []string{closureStubPrefix + "example.com/cached.fn"}, + CSharedExports: []string{"Cached"}, + }, + } + want := *pkg.Summary + obj, err := os.CreateTemp(td, "cached-*.o") + if err != nil { + t.Fatal(err) + } + if _, err := obj.WriteString("object"); err != nil { + t.Fatal(err) + } + if err := obj.Close(); err != nil { + t.Fatal(err) + } + pkg.ObjFiles = []string{obj.Name()} + if err := ctx.saveToCache(pkg); err != nil { + t.Fatalf("saveToCache: %v", err) + } + + pkg.ObjFiles = nil + pkg.ArchiveFile = "" + pkg.LinkArgs = nil + pkg.NeedRt = false + pkg.NeedPyInit = false + pkg.Summary = nil + if !ctx.tryLoadFromCache(pkg) { + t.Fatal("tryLoadFromCache = false, want summary cache hit") + } + if pkg.Summary == nil { + t.Fatal("cache hit did not restore package summary") + } + want.ArchiveFile = pkg.ArchiveFile + if !reflect.DeepEqual(pkg.Summary, &want) { + t.Fatalf("restored summary = %#v, want %#v", pkg.Summary, &want) + } +} + func TestSaveToCache_MainPackage(t *testing.T) { td := t.TempDir() oldFunc := cacheRootFunc @@ -935,8 +1011,8 @@ func TestSaveToCache_Success(t *testing.T) { if data.Env.Goos != "darwin" { t.Errorf("manifest should contain original env content") } - if data.Metadata != nil { - t.Errorf("metadata should be empty when no link args/runtime flags") + if data.Metadata == nil || data.Metadata.Summary == nil { + t.Errorf("metadata should preserve an empty linker summary") } // Check archive exists 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.go b/internal/build/fingerprint.go index 242a8c7afa..901ec64f6c 100644 --- a/internal/build/fingerprint.go +++ b/internal/build/fingerprint.go @@ -37,9 +37,10 @@ type depEntry struct { // manifestMetadata stores metadata produced during build but not part of the fingerprint. type manifestMetadata struct { - LinkArgs []string `yaml:"link_args,omitempty"` - NeedRt bool `yaml:"need_rt,omitempty"` - NeedPyInit bool `yaml:"need_py_init,omitempty"` + LinkArgs []string `yaml:"link_args,omitempty"` + NeedRt bool `yaml:"need_rt,omitempty"` + NeedPyInit bool `yaml:"need_py_init,omitempty"` + Summary *packageSummaryMetadata `yaml:"summary,omitempty"` } // manifestData is the structured representation of manifest content. diff --git a/internal/build/fingerprint_test.go b/internal/build/fingerprint_test.go index 54bba13694..9f765afe21 100644 --- a/internal/build/fingerprint_test.go +++ b/internal/build/fingerprint_test.go @@ -135,10 +135,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/funcinfo_table.go b/internal/build/funcinfo_table.go index 30089f1c7a..7945ca289d 100644 --- a/internal/build/funcinfo_table.go +++ b/internal/build/funcinfo_table.go @@ -86,12 +86,16 @@ type funcInfoSymbolIndexRecord struct { } func collectFuncInfo(pkgs []Package) []funcInfoRecord { + return collectFuncInfoSummaries(summariesForPackages(pkgs)) +} + +func collectFuncInfoSummaries(summaries []*PackageSummary) []funcInfoRecord { seen := make(map[string]funcInfoRecord) - for _, pkg := range pkgs { - if pkg == nil || pkg.LPkg == nil { + for _, summary := range summaries { + if summary == nil { continue } - for _, rec := range readFuncInfo(pkg.LPkg.Module()) { + for _, rec := range summary.FuncInfo { if rec.symbol == "" { continue } @@ -114,13 +118,17 @@ func collectFuncInfo(pkgs []Package) []funcInfoRecord { } func collectPCLineInfo(pkgs []Package) []pcLineRecord { + return collectPCLineInfoSummaries(summariesForPackages(pkgs)) +} + +func collectPCLineInfoSummaries(summaries []*PackageSummary) []pcLineRecord { var out []pcLineRecord seen := make(map[uint64]none) - for _, pkg := range pkgs { - if pkg == nil || pkg.LPkg == nil { + for _, summary := range summaries { + if summary == nil { continue } - for _, rec := range readPCLineInfo(pkg.LPkg.Module()) { + for _, rec := range summary.PCLineInfo { if rec.id == 0 || rec.symbol == "" { continue } @@ -144,6 +152,10 @@ func collectPCLineInfo(pkgs []Package) []pcLineRecord { } func collectFuncInfoStubRecords(pkgs []Package, records []funcInfoRecord) []funcInfoStubRecord { + return collectFuncInfoStubRecordsSummaries(summariesForPackages(pkgs), records) +} + +func collectFuncInfoStubRecordsSummaries(summaries []*PackageSummary, records []funcInfoRecord) []funcInfoStubRecord { if len(records) == 0 { return nil } @@ -154,23 +166,16 @@ func collectFuncInfoStubRecords(pkgs []Package, records []funcInfoRecord) []func } } seen := make(map[string]funcInfoStubRecord) - for _, pkg := range pkgs { - if pkg == nil || pkg.LPkg == nil { + for _, summary := range summaries { + if summary == nil { continue } - fn := pkg.LPkg.Module().FirstFunction() - for !fn.IsNil() { - if fn.IsDeclaration() || fn.BasicBlocksCount() == 0 { - fn = llvm.NextFunction(fn) - continue - } - name := fn.Name() + for _, name := range summary.FuncInfoStubs { if target, ok := strings.CutPrefix(name, closureStubPrefix); ok { if idx := recordBySymbol[target]; idx != 0 { seen[name] = funcInfoStubRecord{symbol: name, funcIndex: idx} } } - fn = llvm.NextFunction(fn) } } if len(seen) == 0 { 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/build/package_build.go b/internal/build/package_build.go new file mode 100644 index 0000000000..4ee5f925b8 --- /dev/null +++ b/internal/build/package_build.go @@ -0,0 +1,231 @@ +/* + * 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 ( + "fmt" + "sort" + "strings" + "sync" + + "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 +} + +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{ + 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, + } +} + +// 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 + 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) { + 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 new file mode 100644 index 0000000000..ff38f14e41 --- /dev/null +++ b/internal/build/package_build_test.go @@ -0,0 +1,142 @@ +/* + * 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" + "reflect" + "strings" + "testing" + + "github.com/goplus/llgo/internal/env" + "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 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") + } else if !strings.Contains(err.Error(), "a, b") { + t.Fatalf("cycle error = %q, want package IDs", err) + } +} + +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", + Types: types.Unsafe, + }}) + if !decl.isDeclOnly() || decl.needsRuntimeSignals() { + t.Fatalf("unexpected declaration-only spec: %+v", decl) + } + runtime := newPackageBuildSpec(&aPackage{Package: &packages.Package{ + PkgPath: env.LLGoRuntimePkg, + Types: types.NewPackage(env.LLGoRuntimePkg, "runtime"), + }}) + if !runtime.runtime { + 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 == "" || pkg.Summary == nil { + t.Fatalf("skipped package was not fully prepared: skip=%v fingerprint=%q manifest=%q summary=%#v", skip, pkg.Fingerprint, pkg.Manifest, pkg.Summary) + } +} diff --git a/internal/build/package_summary.go b/internal/build/package_summary.go new file mode 100644 index 0000000000..db13bed841 --- /dev/null +++ b/internal/build/package_summary.go @@ -0,0 +1,230 @@ +/* + * 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" + "strings" + + "github.com/xgo-dev/llvm" +) + +// PackageSummary is the immutable output a package contributes to the final +// link. It deliberately contains no LLVM values: a backend worker can produce +// it, emit its object, and then dispose its worker-local Program. +// +// C archive/shared header declarations still use LPkg for now. They have a +// separate type-rendering boundary and are kept on the serial compatibility +// path until that boundary is represented here as well. +type PackageSummary struct { + ID string + PkgPath string + + LinkArgs []string + ArchiveFile string + NeedRuntime bool + NeedPyInit bool + + NeedAbiInit int + MethodByIndex []int + MethodByName []string + GlobalSymbols []string + + FuncInfo []funcInfoRecord + PCLineInfo []pcLineRecord + FuncInfoStubs []string + CSharedExports []string +} + +// packageSummaryMetadata is the cache-safe representation of PackageSummary. +// Keep it separate from the in-memory type so the linker-facing structs can +// retain compact unexported record fields. +type packageSummaryMetadata struct { + NeedAbiInit int `yaml:"need_abi_init,omitempty"` + MethodByIndex []int `yaml:"method_by_index,omitempty"` + MethodByName []string `yaml:"method_by_name,omitempty"` + GlobalSymbols []string `yaml:"global_symbols,omitempty"` + + FuncInfo []funcInfoMetadata `yaml:"func_info,omitempty"` + PCLineInfo []pcLineMetadata `yaml:"pcline_info,omitempty"` + FuncInfoStubs []string `yaml:"func_info_stubs,omitempty"` + CSharedExports []string `yaml:"c_shared_exports,omitempty"` +} + +type funcInfoMetadata struct { + Symbol string `yaml:"symbol"` + Name string `yaml:"name,omitempty"` + File string `yaml:"file,omitempty"` + Line uint32 `yaml:"line,omitempty"` + Column uint32 `yaml:"column,omitempty"` +} + +type pcLineMetadata struct { + ID uint64 `yaml:"id"` + Symbol string `yaml:"symbol"` + File string `yaml:"file,omitempty"` + Line uint32 `yaml:"line,omitempty"` + Column uint32 `yaml:"column,omitempty"` +} + +func summarizePackage(pkg *aPackage) *PackageSummary { + if pkg == nil { + return nil + } + summary := &PackageSummary{ + LinkArgs: append([]string(nil), pkg.LinkArgs...), + ArchiveFile: pkg.ArchiveFile, + NeedRuntime: pkg.NeedRt, + NeedPyInit: pkg.NeedPyInit, + } + if pkg.Package != nil { + summary.ID = pkg.ID + summary.PkgPath = pkg.PkgPath + } + if pkg.LPkg == nil { + return summary + } + + lpkg := pkg.LPkg + if summary.PkgPath == "" { + summary.PkgPath = lpkg.Path() + } + summary.NeedAbiInit = lpkg.NeedAbiInit + for method := range lpkg.MethodByIndex { + summary.MethodByIndex = append(summary.MethodByIndex, method) + } + sort.Ints(summary.MethodByIndex) + for method := range lpkg.MethodByName { + summary.MethodByName = append(summary.MethodByName, method) + } + sort.Strings(summary.MethodByName) + + mod := lpkg.Module() + for global := mod.FirstGlobal(); !global.IsNil(); global = llvm.NextGlobal(global) { + if !global.IsDeclaration() { + summary.GlobalSymbols = append(summary.GlobalSymbols, global.Name()) + } + } + sort.Strings(summary.GlobalSymbols) + summary.FuncInfo = readFuncInfo(mod) + summary.PCLineInfo = readPCLineInfo(mod) + for fn := mod.FirstFunction(); !fn.IsNil(); fn = llvm.NextFunction(fn) { + if fn.IsDeclaration() || fn.BasicBlocksCount() == 0 { + continue + } + if _, ok := strings.CutPrefix(fn.Name(), closureStubPrefix); ok { + summary.FuncInfoStubs = append(summary.FuncInfoStubs, fn.Name()) + } + } + sort.Strings(summary.FuncInfoStubs) + for _, name := range lpkg.ExportFuncs() { + if name != "" { + summary.CSharedExports = append(summary.CSharedExports, name) + } + } + sort.Strings(summary.CSharedExports) + return summary +} + +func (s *PackageSummary) metadata() *packageSummaryMetadata { + if s == nil { + return nil + } + meta := &packageSummaryMetadata{ + NeedAbiInit: s.NeedAbiInit, + MethodByIndex: append([]int(nil), s.MethodByIndex...), + MethodByName: append([]string(nil), s.MethodByName...), + GlobalSymbols: append([]string(nil), s.GlobalSymbols...), + FuncInfoStubs: append([]string(nil), s.FuncInfoStubs...), + CSharedExports: append([]string(nil), s.CSharedExports...), + } + for _, rec := range s.FuncInfo { + meta.FuncInfo = append(meta.FuncInfo, funcInfoMetadata{ + Symbol: rec.symbol, + Name: rec.name, + File: rec.file, + Line: rec.line, + Column: rec.column, + }) + } + for _, rec := range s.PCLineInfo { + meta.PCLineInfo = append(meta.PCLineInfo, pcLineMetadata{ + ID: rec.id, + Symbol: rec.symbol, + File: rec.file, + Line: rec.line, + Column: rec.column, + }) + } + return meta +} + +func summaryFromMetadata(pkg *aPackage, meta *cacheArchiveMetadata) *PackageSummary { + if pkg == nil || pkg.Package == nil || meta == nil || meta.Summary == nil { + return nil + } + summary := &PackageSummary{ + ID: pkg.ID, + PkgPath: pkg.PkgPath, + LinkArgs: append([]string(nil), pkg.LinkArgs...), + ArchiveFile: pkg.ArchiveFile, + NeedRuntime: pkg.NeedRt, + NeedPyInit: pkg.NeedPyInit, + NeedAbiInit: meta.Summary.NeedAbiInit, + MethodByIndex: append([]int(nil), meta.Summary.MethodByIndex...), + MethodByName: append([]string(nil), meta.Summary.MethodByName...), + GlobalSymbols: append([]string(nil), meta.Summary.GlobalSymbols...), + FuncInfoStubs: append([]string(nil), meta.Summary.FuncInfoStubs...), + CSharedExports: append([]string(nil), meta.Summary.CSharedExports...), + } + for _, rec := range meta.Summary.FuncInfo { + summary.FuncInfo = append(summary.FuncInfo, funcInfoRecord{ + symbol: rec.Symbol, + name: rec.Name, + file: rec.File, + line: rec.Line, + column: rec.Column, + }) + } + for _, rec := range meta.Summary.PCLineInfo { + summary.PCLineInfo = append(summary.PCLineInfo, pcLineRecord{ + id: rec.ID, + symbol: rec.Symbol, + file: rec.File, + line: rec.Line, + column: rec.Column, + }) + } + return summary +} + +func summariesForPackages(pkgs []Package) []*PackageSummary { + summaries := make([]*PackageSummary, 0, len(pkgs)) + for _, pkg := range pkgs { + if pkg == nil { + continue + } + summary := pkg.Summary + if summary == nil { + summary = summarizePackage(pkg) + } + if summary != nil { + summaries = append(summaries, summary) + } + } + return summaries +} diff --git a/internal/build/package_summary_test.go b/internal/build/package_summary_test.go new file mode 100644 index 0000000000..87a60f42ea --- /dev/null +++ b/internal/build/package_summary_test.go @@ -0,0 +1,86 @@ +/* + * 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" + "reflect" + "testing" + + "github.com/xgo-dev/llvm" + + "github.com/goplus/llgo/internal/packages" + llssa "github.com/goplus/llgo/ssa" +) + +func TestPackageSummaryCapturesLinkerFacts(t *testing.T) { + prog := llssa.NewProgram(nil) + defer prog.Dispose() + lpkg := prog.NewPackage("example.com/p", "p") + lpkg.NeedAbiInit = 3 + lpkg.RecordReflectMethodByIndex(4) + lpkg.RecordReflectMethodByIndex(1) + lpkg.RecordReflectMethodByName("B") + lpkg.RecordReflectMethodByName("A") + lpkg.SetExport("example.com/p.Export", "Export") + lpkg.EmitFuncInfo("example.com/p.live", "example.com/p.Live", "p.go", 17, 2) + lpkg.EmitPCLineInfo(42, "example.com/p.live", "p.go", 18, 3) + lpkg.NewFunc(closureStubPrefix+"example.com/p.live", llssa.NoArgsNoRet, llssa.InGo).MakeBody(1).Return() + + i32 := lpkg.Module().Context().Int32Type() + defined := llvm.AddGlobal(lpkg.Module(), i32, "example.com/p.defined") + defined.SetInitializer(llvm.ConstInt(i32, 1, false)) + llvm.AddGlobal(lpkg.Module(), i32, "example.com/p.declared") + + pkg := &aPackage{ + Package: &packages.Package{ + ID: "example.com/p", + PkgPath: "example.com/p", + Types: types.NewPackage("example.com/p", "p"), + }, + LPkg: lpkg, + NeedRt: true, + NeedPyInit: true, + LinkArgs: []string{"-lp"}, + ArchiveFile: "p.a", + } + summary := summarizePackage(pkg) + if got, want := summary.MethodByIndex, []int{1, 4}; !reflect.DeepEqual(got, want) { + t.Fatalf("MethodByIndex = %v, want %v", got, want) + } + if got, want := summary.MethodByName, []string{"A", "B"}; !reflect.DeepEqual(got, want) { + t.Fatalf("MethodByName = %v, want %v", got, want) + } + if got, want := summary.GlobalSymbols, []string{"example.com/p.defined"}; !reflect.DeepEqual(got, want) { + t.Fatalf("GlobalSymbols = %v, want %v", got, want) + } + if got, want := summary.FuncInfoStubs, []string{closureStubPrefix + "example.com/p.live"}; !reflect.DeepEqual(got, want) { + t.Fatalf("FuncInfoStubs = %v, want %v", got, want) + } + if got := collectFuncInfoSummaries([]*PackageSummary{summary}); len(got) != 1 || got[0].symbol != "example.com/p.live" { + t.Fatalf("func info from summary = %+v, want live record", got) + } + if got := linkedPackageGlobals([]*PackageSummary{summary}); len(got) != 1 { + t.Fatalf("globals from summary = %#v, want one defined global", got) + } + + loadedPkg := &aPackage{Package: pkg.Package, LinkArgs: []string{"-lp"}, ArchiveFile: "p.a", NeedRt: true, NeedPyInit: true} + loaded := summaryFromMetadata(loadedPkg, &cacheArchiveMetadata{Summary: summary.metadata()}) + if !reflect.DeepEqual(loaded, summary) { + t.Fatalf("cache summary round trip = %#v, want %#v", loaded, summary) + } +} diff --git a/internal/build/plan9asm.go b/internal/build/plan9asm.go index 10e8913c16..5f8cef390b 100644 --- a/internal/build/plan9asm.go +++ b/internal/build/plan9asm.go @@ -391,10 +391,7 @@ func pkgSFiles(ctx *context, pkg *packages.Package) ([]string, error) { } } - 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 } @@ -442,21 +439,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 { diff --git a/internal/goflags/flagfile.go b/internal/goflags/flagfile.go index e8e4adf975..48ad661fcd 100644 --- a/internal/goflags/flagfile.go +++ b/internal/goflags/flagfile.go @@ -23,6 +23,18 @@ import ( ) var argumentListFlagNames = [...]string{ + "asmflags", + "gcflags", + "gccgoflags", + "ldflags", + "p", + "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", @@ -62,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) + } +} 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) + } +}