Skip to content

llgo/embed:compile with Oz & link with -s for embed target to reduce size#1301

Merged
xushiwei merged 3 commits intogoplus:mainfrom
luoliwoshang:xtensa/o0
Sep 26, 2025
Merged

llgo/embed:compile with Oz & link with -s for embed target to reduce size#1301
xushiwei merged 3 commits intogoplus:mainfrom
luoliwoshang:xtensa/o0

Conversation

@luoliwoshang
Copy link
Member

@luoliwoshang luoliwoshang commented Sep 15, 2025

fixed #1312

before

2025-09-16T08:14:33.7708327Z ld.lld: error: section 'text' will not fit in region 'iram_seg': overflowed by 13157 bytes

with current pr 190KB -> 86KB

lib/_demo/emptycheck on  task3/machine [?] via 🐹 v1.24.6 took 7s 
❯ ls -lh ./oz-s.elf                                             
-rwxr-xr-x@ 1 zhangzhiyang  staff    86K Sep 18 15:23 ./oz-s.elf

@niupilot
Copy link

niupilot bot commented Sep 15, 2025

PR Review for #1301

Todo List:

  • Read and analyze the changes in targets/xtensa.json
  • Understand the context of xtensa target configuration
  • Review code quality and best practices
  • Check for potential bugs or issues
  • Evaluate architecture and design decisions
  • Verify documentation consistency
  • Provide comprehensive review feedback

Code Review Feedback

📝 Summary of Changes

This PR adds the -Os optimization flag to the xtensa target configuration and removes trailing newline for consistency.

File Modified: targets/xtensa.json:22

  • Added: -Os flag to the cflags array
  • Removed: trailing newline for file consistency

Positive Aspects

  1. Appropriate Optimization Choice: The -Os flag (optimize for size) is excellent for embedded/bare-metal xtensa targets where memory is typically constrained.

  2. Consistent with Target Purpose: Given that xtensa is used by ESP32/ESP8266 microcontrollers (confirmed by checking esp32.json and esp8266.json which inherit from xtensa), size optimization is crucial for these resource-constrained devices.

  3. File Format Consistency: Removing the trailing newline matches the pattern used in other target files.

🔍 Technical Analysis

Optimization Flag Placement: The -Os flag is correctly placed at the end of the cflags array, which is appropriate as optimization flags typically come after other compilation flags.

Inheritance Impact: Since ESP32 and ESP8266 targets inherit from xtensa, this change will benefit all Xtensa-based microcontrollers in the project, providing consistent size optimization across the platform.

Compatibility: No conflicts detected with existing flags. The -Os flag works well with the existing options like -ffunction-sections and -fdata-sections.

🚨 Potential Considerations

  1. Debug vs Release Builds: -Os optimizes for size which may make debugging more difficult. Consider if this should be conditional based on build type, though for embedded targets this is typically acceptable.

  2. Performance Trade-offs: Size optimization may reduce performance compared to -O2 or -O3. However, for memory-constrained embedded systems, this trade-off is usually worthwhile.

📋 Architecture & Design

The change follows the existing target configuration pattern well. The xtensa target serves as a base configuration that ESP-specific targets inherit from, making this a logical place for the optimization flag.

📚 Documentation Consistency

No documentation updates needed: The README.md doesn't contain specific references to xtensa target configurations or optimization flags, so no updates are required.

🎯 Recommendations

  1. Consider adding a comment: While not strictly necessary, a brief comment explaining the rationale for -Os could be helpful for future maintainers.

  2. Testing: Ensure that existing ESP32/ESP8266 projects still compile and function correctly with this optimization level.

Final Assessment

This is a solid improvement that:

  • ✅ Follows best practices for embedded development
  • ✅ Uses appropriate optimization for the target platform
  • ✅ Maintains consistency with existing codebase patterns
  • ✅ Benefits all Xtensa-based targets through inheritance

Recommendation: APPROVE

The change is technically sound, follows established patterns, and provides meaningful optimization for embedded Xtensa targets without introducing any apparent risks.


👉 Want me to re-run this review? Just type /review in the comments! For more usage examples, visit CodeAgent GitHub Repository.

Copy link

@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.

Summary of Changes

Hello @luoliwoshang, 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 a build optimization for the Xtensa target by incorporating the -Os compiler flag. This change is intended to reduce the overall compiled code size, which is particularly beneficial for embedded systems and environments where memory and storage resources are constrained.

Highlights

  • Build Optimization: The -Os compiler flag has been added to the cflags for the xtensa target, enabling optimization for code size.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

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 issue 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.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

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

@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 adds the -Os compiler flag to the xtensa target configuration, which optimizes for code size. This is a suitable and standard optimization for embedded targets. The change itself is correct. However, I've noticed a potential inconsistency in the targets/xtensa.json file where goarch is set to arm while the llvm-target is xtensa. Since Xtensa is not an ARM-based architecture, this might lead to subtle bugs or confusion. While this is outside the changed lines of this pull request, it would be beneficial to review this configuration for correctness.

@codecov
Copy link

codecov bot commented Sep 15, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.10%. Comparing base (18e0365) to head (bbcbddf).
⚠️ Report is 12 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1301      +/-   ##
==========================================
- Coverage   90.10%   90.10%   -0.01%     
==========================================
  Files          43       43              
  Lines       12562    12561       -1     
==========================================
- Hits        11319    11318       -1     
  Misses       1087     1087              
  Partials      156      156              

☔ 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 marked this pull request as draft September 15, 2025 02:51
@luoliwoshang luoliwoshang marked this pull request as ready for review September 16, 2025 08:42
@niupilot
Copy link

niupilot bot commented Sep 16, 2025

PR Review: Optimization Level Changes

Todo List:

  • Read and analyze the modified file
  • Review the specific changes made
  • Evaluate code quality and best practices
  • Check for potential bugs or issues
  • Provide feedback on optimization level changes
  • Submit comprehensive review

Summary

This PR modifies the cross-compilation configuration in UseTarget() function at internal/crosscompile/crosscompile.go:485 to add the -Oz optimization flag by default for embedded target builds.

Change Analysis:

  • Before: var ccflags []string (empty slice, then later populated)
  • After: ccflags := []string{"-Oz"} (initialized with size optimization flag)

Code Quality & Best Practices ✅

The change is well-implemented and follows good practices:

  1. Initialization Pattern: Using slice literal initialization is more idiomatic than declaring an empty slice and appending later
  2. Consistent Positioning: The -Oz flag is added at the beginning of ccflags, ensuring it won't be overridden by later flags
  3. Targeted Application: Only affects embedded targets via UseTarget(), not general cross-compilation via use() function

Technical Assessment ✅

Optimization Flag Choice: -Oz is an excellent choice for embedded targets:

  • Size-Focused: Prioritizes code size reduction over execution speed
  • Embedded-Appropriate: Critical for microcontrollers with limited flash/RAM
  • LLVM Compatible: Well-supported across all target architectures in the codebase

Documentation Alignment: The PR description correctly references Clang documentation:

-Oz: Like -Os (and thus -O2), but reduces code size further.

Architecture & Design ✅

Separation of Concerns: The change correctly applies only to embedded targets:

  • UseTarget() (embedded targets) → gets -Oz optimization
  • use() (general cross-compilation) → unchanged behavior
  • ✅ Native compilation → unchanged behavior

This maintains backward compatibility while optimizing for the appropriate use case.

No Issues Detected ✅

  • No bugs or logic errors
  • No breaking changes
  • No performance regressions expected
  • Maintains existing API compatibility

Suggestions for Future Enhancements

While this change is solid, consider these potential improvements for future iterations:

  1. Configurable Optimization: Allow targets to specify optimization level in their JSON config

    {
      "optimization": "-Os",  // or "-Oz", "-O2", etc.
      "llvm-target": "...",
      ...
    }
  2. Debug Build Support: Consider providing a debug mode that uses -O0 -g for development

Conclusion

Approval Recommended

This is a focused, well-implemented change that appropriately optimizes embedded target builds for size constraints. The code is clean, follows best practices, and maintains compatibility with existing functionality.

The -Oz flag choice is technically sound for the embedded use case and aligns perfectly with the typical requirements of microcontroller development where flash memory is often severely constrained.


👉 Want me to re-run this review? Just type /review in the comments! For more usage examples, visit CodeAgent GitHub Repository.

@luoliwoshang luoliwoshang changed the title target:xtensa with -Os cflag crosscompile:Oz optimize level for embed target Sep 16, 2025
@luoliwoshang luoliwoshang mentioned this pull request Sep 16, 2025
3 tasks
@luoliwoshang luoliwoshang changed the title crosscompile:Oz optimize level for embed target llgo/embed:Oz optimize level for embed target Sep 16, 2025
@luoliwoshang luoliwoshang changed the title llgo/embed:Oz optimize level for embed target llgo/embed:compile with Oz & link with -s for embed target to reduce size Sep 19, 2025
@xushiwei xushiwei merged commit c4223df into goplus:main Sep 26, 2025
43 checks passed
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.

llgo/embed: binary size optimization using -Oz flag

4 participants