Skip to content

build: Go Linktime-like Unreachable Method Pruning#1736

Open
luoliwoshang wants to merge 18 commits intogoplus:mainfrom
luoliwoshang:codex/dce-analyzer-skeleton
Open

build: Go Linktime-like Unreachable Method Pruning#1736
luoliwoshang wants to merge 18 commits intogoplus:mainfrom
luoliwoshang:codex/dce-analyzer-skeleton

Conversation

@luoliwoshang
Copy link
Copy Markdown
Member

@luoliwoshang luoliwoshang commented Mar 20, 2026

Summary

  • add a phase-1 link-time method reachability analyzer under internal/build/dce
  • build analyzer input from LLVM modules, including ordinary symbol edges, UsedInIface child-type edges, method refs, and llgo.* metadata
  • compute stable type symbol -> live method indexes results with behavior aligned as closely as practical to Go linker deadcode
  • add deterministic analyzer golden coverage for real .ll cases (closureall, invoke, reflectmethod, reader, ifaceconv)
  • wire the analyzer into the exe build pipeline and emit strong ABI type overrides that clear dead abi.Method function pointers while keeping type/method layout intact
  • print [dce] live methods during build so the live method set is directly observable

Scope

  • this is the phase-1 method-liveness pipeline only
  • it does not yet rewrite arbitrary symbols or implement plugin/shared/dynlink modes
  • method overrides are emitted as strong type globals in the entry module so they override the original weak ABI type symbols at link time

Notes

Testing

  • go test ./internal/build/dce -count=1
  • go test ./internal/build -count=1
  • go run ./cmd/llgo build ./cl/_testgo/closureall
  • go run ./cmd/llgo build /Users/zhangzhiyang/Documents/Code/goplus/llgo/_demo/go/logdemo/log.go

@xgopilot
Copy link
Copy Markdown
Contributor

xgopilot bot commented Mar 20, 2026

Well-structured skeleton PR for DCE analysis. The metadata emission infrastructure in ssa/metadata.go is clean, dedup via semMetaEmitter.seen is a good design choice, and the test coverage for metadata readback is solid. A few items worth addressing: (1) GetMDString in mdtest should guard against a NULL return from LLVM, (2) emitMethodOff's first parameter should be renamed from owner to typeName for clarity, and (3) markReflectMethodCall could benefit from a bounds check on call.Args and deferring p.fn.Name() until needed.

func GetMDString(v llvm.Value) string {
var n C.uint
s := C.llgoMDString(unsafe.Pointer(v.C), &n)
return C.GoStringN(s, C.int(n))
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LLVMGetMDString returns NULL when V is not an MDString node. Passing a null s with n > 0 to C.GoStringN will segfault. Consider adding a nil guard:

Suggested change
return C.GoStringN(s, C.int(n))
var n C.uint
s := C.llgoMDString(unsafe.Pointer(v.C), &n)
if s == nil {
return ""
}
return C.GoStringN(s, C.int(n))

case "Method":
p.pkg.EmitReflectMethod(owner)
case "MethodByName":
if name, ok := constStr(call.Args[0]); ok {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

call.Args[0] is accessed without a bounds check. While current Go SSA invariants guarantee one arg for MethodByName(string), a defensive len(call.Args) > 0 guard would prevent panics if the SSA representation is ever malformed. Same applies to line 98 for the static-call branch (call.Args[len(call.Args)-1]).

)
}

func (p Package) emitMethodOff(owner string, index int, name, mtyp string) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: The first parameter is named owner, but here it actually receives a concrete type name (the call site in abiUncommonMethods passes typeName). In the sibling emit functions, owner means "the enclosing function whose reachability triggers the effect." Consider renaming to typeName to match MethodOffRow.TypeName in the dce package and the llgoMethodOffMetadata doc comment.

}

func (e *semMetaEmitter) add(mod llvm.Module, table, key string, fields ...llvm.Metadata) {
fullKey := table + ":" + key
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit (perf): fullKey is allocated via string concatenation on every call, even for duplicates. Since this runs on every MakeInterface and Imethod call, consider using a two-level map (map[string]map[string]struct{} keyed by table then key) to avoid the concatenation, or at least defer fullKey construction until after a cheaper preliminary check.

}

func (p *context) markReflectMethodCall(call *ssa.CallCommon) {
owner := p.fn.Name()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit (perf): p.fn.Name() is evaluated unconditionally for every call instruction, even though the vast majority of calls have nothing to do with reflect. Consider moving this assignment inside the conditional branches where owner is actually used, to avoid the string materialization cost on non-reflect calls.

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces the foundational structure for a dead code elimination (DCE) analyzer within the llgo project. It establishes the basic interfaces and data structures required for subsequent development, focusing on setting up the analysis pipeline rather than implementing the core analysis logic. The changes lay the groundwork for future integration with LLVM modules and method liveness computations.

Highlights

  • DCE Analyzer Skeleton: Adds the initial internal/build/dce package skeleton for dead code elimination analysis.
  • Phase-1 Contracts: Defines the Analyze/Input/Result contracts for the first phase of the DCE analysis.
  • Minimal Package Tests: Adds minimal package tests for the new analyzer entry points to ensure basic functionality.
  • LLVM Metadata Dependency: Notes that this work depends on ssa: emit go semantic metadata #1728 for the llgo metadata producer.
  • No LLVM Scanning or Liveness Computation: Clarifies that this PR is the first step only and does not yet scan LLVM modules or compute method liveness.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces the initial skeleton for a dead code elimination (DCE) analyzer in the internal/build/dce package. It defines the core data structures and API contracts for the analysis, separating the LLVM-specific parsing from the analysis logic. The PR also implements the crucial metadata emission from the SSA builder, which will be consumed by the DCE analyzer. This includes metadata for interface usage (!llgo.useiface), interface method calls (!llgo.useifacemethod), concrete type method layouts (!llgo.methodoff), and reflection-based method calls (!llgo.reflectmethod, !llgo.usenamedmethod). The changes are well-structured and thoroughly tested, including new test cases for metadata generation and readback. This provides a solid foundation for the subsequent implementation of the DCE analysis. The code quality is excellent, and I have no specific issues to report.

@luoliwoshang luoliwoshang changed the title build: add dce analyzer skeleton build: wire link-time method dce overrides Mar 20, 2026
@codecov
Copy link
Copy Markdown

codecov bot commented Mar 21, 2026

Codecov Report

❌ Patch coverage is 96.47059% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.51%. Comparing base (c70fe9c) to head (be204e0).

Files with missing lines Patch % Lines
ssa/metadata.go 94.36% 2 Missing and 2 partials ⚠️
ssa/mdtest/metadata.go 92.85% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1736      +/-   ##
==========================================
+ Coverage   88.44%   88.51%   +0.06%     
==========================================
  Files          50       52       +2     
  Lines       13656    13815     +159     
==========================================
+ Hits        12078    12228     +150     
- Misses       1369     1377       +8     
- Partials      209      210       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@luoliwoshang luoliwoshang changed the title build: wire link-time method dce overrides build: Go Linktime-like Unreachable Method Pruning in LLGo Mar 23, 2026
@luoliwoshang luoliwoshang changed the title build: Go Linktime-like Unreachable Method Pruning in LLGo build: Go Linktime-like Unreachable Method Pruning Mar 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant