Skip to content

RFC-031: Optimization Levels and Pass Manager ​

References:

Abstract ​

This document proposes introducing an optimization level system and a pass manager into YaoXiang, changing compiler optimizations from an "all-or-nothing" model to configurable optimization bundles. The optimization levels (O0-O3) define different combinations of optimization strategies, while the pass manager runs optimization passes in dependency order. This document also defines a standard interface for optimization passes, providing an architectural foundation for future extensions such as monomorphization, inlining, and constant folding.

Core goal: Give users a clear way to trade off compilation speed, binary size, and runtime performance.

Motivation ​

Why are optimization levels needed? ​

The compiler currently has no optimization configuration, and all code goes through the same processing pipeline. This leads to:

  1. Poor debugging experience: Optimization is unnecessary while debugging, but it cannot be disabled
  2. No control over binary size: Generic monomorphization bloats the binary, but it cannot be disabled
  3. Unpredictable compilation speed: It is impossible to choose "fast compilation" or "deep optimization" based on the scenario
  4. Unordered optimization passes: Future optimization passes will have dependencies on one another and require centralized management

Current Problems ​

yaoxiang
# Current: all code goes through the same processing
# - During debugging: optimization is unnecessary, but it cannot be disabled
# - In production: optimization is needed, but its depth cannot be configured
# - Generic functions: generate multiple copies of the code, but cannot be controlled

identity: (T: Type) -> (x: T) -> T = (x) => x
x = identity(42)        # generates identity_Int
s = identity("hello")   # generates identity_String
# Users cannot choose "no monomorphization" (type-erasure mode)

Value of Optimization Levels ​

ScenarioRequirementsOptimization Level
Development/debuggingFast compilation, preserve debug informationO0
Day-to-day developmentBasic optimization, balance compilation speedO1
Testing/CIStandard optimization, validate production behaviorO2
Production releaseDeep optimization, maximum performanceO3
Scripting/rapid prototypingAutomatically selected (based on the target platform)Auto

Proposal ​

Core Design ​

1. Optimization Level Definitions ​

rust
/// Optimization level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum OptLevel {
    /// O0: No optimization (debug mode)
    /// - Preserve all debug information
    /// - Perform no optimization transformations
    /// - Fastest compilation speed
    /// - Use case: development/debugging, rapid iteration
    O0,

    /// O1: Basic optimization (default)
    /// - Monomorphize on demand (do not generate unused specializations)
    /// - Basic constant folding
    /// - Basic dead code elimination
    /// - Use case: day-to-day development
    #[default]
    O1,

    /// O2: Standard optimization
    /// - Monomorphize on demand
    /// - Full constant folding
    /// - Full dead code elimination
    /// - Inline small functions
    /// - Tail-call optimization
    /// - Use cases: testing, CI, production releases
    O2,

    /// O3: Aggressive optimization
    /// - Full monomorphization (pre-generate all possible type combinations)
    /// - Aggressive inlining
    /// - All optimization passes
    /// - May increase compilation time and binary size
    /// - Use case: extreme performance requirements
    O3,

    /// Auto: Automatic selection
    /// - Automatically select an optimization strategy based on the target platform and available resources
    /// - Use case: scripting, rapid prototyping
    Auto,
}

2. Optimization Pass Interface ​

rust
/// Optimization pass interface
pub trait OptimizationPass {
    /// Pass name (used for logging and dependency declarations)
    fn name(&self) -> &str;

    /// Runs the pass
    fn run(&self, module: &mut ModuleIR, config: &PassConfig) -> PassResult;

    /// Other passes that this pass depends on and that must run first
    fn dependencies(&self) -> Vec<&str> {
        vec![]
    }

    /// Whether this pass should run under the current configuration
    fn should_run(&self, config: &PassConfig) -> bool {
        true
    }
}

/// Pass configuration
#[derive(Debug, Clone)]
pub struct PassConfig {
    /// Optimization level
    pub opt_level: OptLevel,
    /// Whether debug information is enabled
    pub debug_info: bool,
    /// Target platform
    pub target_platform: TargetPlatform,
}

/// Pass execution result
#[derive(Debug, Default)]
pub struct PassResult {
    /// Whether the IR was modified
    pub changed: bool,
    /// Statistics
    pub stats: PassStats,
}

/// Pass statistics
#[derive(Debug, Default)]
pub struct PassStats {
    /// Number of functions inlined
    pub functions_inlined: usize,
    /// Number of functions monomorphized
    pub functions_monomorphized: usize,
    /// Number of dead-code items removed
    pub dead_code_removed: usize,
    /// Number of constants folded
    pub constants_folded: usize,
}

3. Pass Manager ​

rust
/// Optimizer
pub struct Optimizer {
    /// List of registered passes (sorted in dependency order)
    passes: Vec<Box<dyn OptimizationPass>>,
}

impl Optimizer {
    /// Creates an optimizer for the specified optimization level
    pub fn for_opt_level(level: OptLevel) -> Self {
        let passes = Self::create_passes_for_level(level);
        Self { passes }
    }

    /// Creates the pass list for the specified level
    fn create_passes_for_level(level: OptLevel) -> Vec<Box<dyn OptimizationPass>> {
        match level {
            OptLevel::O0 => {
                vec![
                    // Debug mode: minimal optimization; perform only necessary cleanup
                    Box::new(ConstFoldPass::minimal()),
                ]
            }
            OptLevel::O1 => {
                vec![
                    // Basic optimization
                    Box::new(ConstFoldPass::basic()),
                    Box::new(MonomorphizePass::on_demand()),
                    Box::new(DcePass::basic()),
                ]
            }
            OptLevel::O2 => {
                vec![
                    // Standard optimization
                    Box::new(ConstFoldPass::full()),
                    Box::new(MonomorphizePass::on_demand()),
                    Box::new(DcePass::full()),
                    Box::new(InlinePass::small_functions()),
                    Box::new(TcoPass::new()),
                ]
            }
            OptLevel::O3 => {
                vec![
                    // Aggressive optimization
                    Box::new(ConstFoldPass::full()),
                    Box::new(MonomorphizePass::full()),
                    Box::new(InlinePass::aggressive()),
                    Box::new(DcePass::full()),
                    Box::new(TcoPass::new()),
                    // More aggressive optimizations...
                ]
            }
            OptLevel::Auto => {
                // Automatic selection: decide based on the target platform
                Self::create_passes_for_level(OptLevel::O1)
            }
        }
    }

    /// Runs all optimization passes
    pub fn run(&self, module: &mut ModuleIR, config: &PassConfig) -> OptimizerResult {
        let mut total_stats = OptimizerStats::default();

        for pass in &self.passes {
            if !pass.should_run(config) {
                continue;
            }

            let result = pass.run(module, config);
            total_stats.merge(result.stats);
        }

        OptimizerResult {
            module: module.clone(),
            stats: total_stats,
        }
    }
}

Examples ​

Command-Line Usage ​

bash
# Debug mode: no optimization
yaoxiang build --opt-level O0

# Day-to-day development: basic optimization (default)
yaoxiang build

# Production release: standard optimization
yaoxiang build --opt-level O2

# Extreme performance: aggressive optimization
yaoxiang build --opt-level O3

# Automatic selection
yaoxiang build --opt-level Auto

Configuration File ​

json
{
  "optimization_level": "O2",
  "mono": {
    "enabled": true,
    "strategy": "OnDemand"
  },
  "debug_info": false
}

API Usage ​

rust
use yaoxiang::frontend::{Compiler, CompileConfig, OptLevel};

// Debug mode
let config = CompileConfig::new()
    .with_opt_level(OptLevel::O0);
let mut compiler = Compiler::with_config(config);

// Production mode
let config = CompileConfig::new()
    .with_opt_level(OptLevel::O2);
let mut compiler = Compiler::with_config(config);

Syntax Changes ​

There are no syntax changes. Optimization levels are compiler settings and do not affect the language syntax.

Detailed Design ​

Mapping Between Optimization Levels and Passes ​

PassO0O1O2O3Description
Constant FoldingMinimalBasicFullFullEvaluate constant expressions at compile time
Monomorphization❌On demandOn demandFullSpecialize generic functions
Dead Code Elimination❌BasicFullFullRemove unused code
Function Inlining❌❌Small functionsAggressiveInsert the function body at the call site
Tail-Call Optimization❌❌✅✅Convert tail recursion into a loop
Escape Analysis❌❌❌✅Determine stack/heap allocation
Loop Optimization❌❌❌✅Loop unrolling and loop-invariant code motion

Monomorphization Strategy ​

rust
/// Monomorphization strategy
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum MonoStrategy {
    /// No monomorphization — type erasure; generic functions have only one copy of the code
    /// Advantage: smaller binary, faster compilation
    /// Disadvantage: dynamic dispatch overhead at runtime
    Erased,

    /// On-demand monomorphization — generate code only for type combinations that are actually used
    /// Advantage: zero-cost abstraction, no runtime overhead
    /// Disadvantage: binary size may balloon
    #[default]
    OnDemand,

    /// Full monomorphization — pre-generate all possible type combinations
    /// Advantage: all calls resolved at compile time
    /// Disadvantage: slower compilation, larger binary
    Full,
}

/// Monomorphization configuration
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MonoConfig {
    /// Whether monomorphization is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Monomorphization strategy
    #[serde(default)]
    pub strategy: MonoStrategy,

    /// Whether DCE (dead code elimination) is enabled
    #[serde(default = "default_true")]
    pub dce_enabled: bool,

    /// Maximum specialization depth (prevents infinitely recursive generics)
    #[serde(default = "default_max_mono_depth")]
    pub max_depth: usize,
}

impl Default for MonoConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            strategy: MonoStrategy::OnDemand,
            dce_enabled: true,
            max_depth: 100,
        }
    }
}

Compilation Pipeline Integration ​

rust
// src/frontend/pipeline.rs

impl Pipeline {
    fn run_ir_generation(
        &mut self,
        source_name: &str,
        source: &str,
        ast: &Module,
        type_result: &TypeCheckResult,
        phase_durations: &mut Vec<(CompilationPhase, u64)>,
    ) -> IRResult {
        let start = Instant::now();

        // 1. Generate the base IR
        let mut ir = middle::generate_ir(ast, type_result)?;

        // 2. Run optimization passes according to the optimization level
        let optimizer = Optimizer::for_opt_level(self.config.optimization_level);
        let pass_config = PassConfig {
            opt_level: self.config.optimization_level,
            debug_info: self.config.generate_debug_info,
            target_platform: TargetPlatform::detect(),
        };

        let result = optimizer.run(&mut ir, &pass_config);

        let duration = start.elapsed().as_millis() as u64;
        phase_durations.push((CompilationPhase::Optimization, duration));

        IRResult::success(result.module)
    }
}

Type System Impact ​

There is no direct impact. Optimization passes operate at the IR layer and do not affect the type system.

Runtime Behavior ​

Optimization LevelRuntime Behavior
O0No optimization; preserve all debug information
O1Basic optimization; preserve basic debug information
O2Standard optimization; no debug information
O3Aggressive optimization; no debug information

Key point: No runtime changes are required. Optimization passes affect only the IR layer and code-generation layer. The runtime looks up execution by function name/ID and is unaware of the optimization process.

Compiler Changes ​

ComponentChange
frontend/config.rsAdd the OptLevel enum and MonoConfig
frontend/pipeline.rsIntegrate the pass manager
middle/passes/optimizer/Add the optimization pass module
middle/passes/mono/Refactor to use the standard pass interface
CLIAdd the --opt-level argument

Backward Compatibility ​

  • ✅ Fully backward compatible
  • The default optimization level is O1, which preserves the current behavior
  • Users can explicitly specify an optimization level to override the default behavior

Trade-offs ​

Advantages ​

  • Flexibility: Users can select an optimization strategy based on the scenario
  • Extensibility: The standard pass interface makes it easy to add new optimizations
  • Predictability: The behavior of each optimization level is clearly defined
  • Debugging-friendly: O0 mode preserves complete debug information

Disadvantages ​

  • Increased complexity: Multiple optimization levels must be maintained
  • Larger test matrix: The behavior of every optimization level must be tested
  • Documentation burden: The meaning of every optimization level must be explained

Alternatives ​

OptionWhy It Was Not Selected
Only an on/off stateProvides no fine-grained control over optimization depth
GCC/LLVM-style -O numbersInconsistent with YaoXiang's configuration system
An independent switch for each passRequires users to understand each pass and complicates usage
Deferring to v2.0Monomorphization has been implemented but not integrated; the architectural issues must be resolved first

Implementation Strategy ​

Phase Breakdown ​

  1. Phase 1 (current): Define the optimization levels and pass interface
  2. Phase 2: Implement the monomorphization pass (based on the existing mono/ module)
  3. Phase 3: Implement the constant folding and dead code elimination passes
  4. Phase 4: Implement the function inlining and tail-call optimization passes
  5. Phase 5: Implement aggressive optimization passes (escape analysis and loop optimization)

Dependencies ​

  • The monomorphization module from RFC-011 (Generic System)
  • The optimization pass interface from RFC-028 (JIT Compiler)
  • Shares its optimization pass design with RFC-018 (LLVM AOT)

Risks ​

  • Performance regression: Optimization passes may introduce bugs that cause performance degradation
  • Increased compilation time: Optimization passes increase compilation time
  • Binary bloat: Monomorphization may significantly increase binary size

Open Questions ​

  • [ ] Should O3 enable escape analysis by default? (@Chenxu: performance test data is required)
  • [ ] Are Os (optimize for size) and Oz (optimize aggressively for size) levels needed?
  • [ ] Should optimization levels affect the level of debug information?
  • [ ] How should circular dependencies between optimization passes be handled?

Appendix A: Design Decision Record ​

DecisionResolutionDateRecorded by
Optimization level namingUse O0-O3 + Auto2026-06-16Chenxu
Default optimization levelO1 (basic optimization)2026-06-16Chenxu
Monomorphization strategySupport Erased/OnDemand/Full2026-06-16Chenxu
Pass interface designtrait + dependency declarations2026-06-16Chenxu

Appendix B: Glossary ​

TermDefinition
Optimization PassAn independent module that performs a single transformation on IR
MonomorphizationA code-generation strategy that specializes generic functions for concrete types
Constant FoldingEvaluating constant expressions at compile time
Dead Code EliminationRemoving unreachable or unused code from a program
Function InliningInserting a function body at the call site to avoid function-call overhead
Tail-Call OptimizationConverting tail recursion into a loop to avoid stack overflow
Escape AnalysisDetermining whether a variable escapes its scope and deciding between stack and heap allocation

References ​


Lifecycle and Disposition ​

This RFC defines the architecture for optimization levels and provides a unified framework for future optimization passes.

Relationship to monomorphization: Monomorphization is one of the optimization passes and will be implemented as the first pass after this RFC is accepted.