Skip to main content

datalove_datafun_inline/
lib.rs

1//! Function inlining pass for datafun IR.
2//!
3//! This crate provides:
4//! - Inline directive types for specifying which functions to inline
5//! - Function inlining transformation on IR modules
6//! - Cross-module inlining support
7//! - Dynamic inlining for interpreter optimization
8
9
10use std::collections::HashMap;
11
12use datalove_datafun_ir::{
13    BlockId, CallSiteId, CodeRef, CodeUnitId, FuncId, Instruction, IrBlock, IrCodeUnit, IrModule, IrModuleId,
14    IrType, ModuleFunctionRegistry, Operand, ParamId, ParamMode, SlotDest, SlotId, SymbolTable,
15    Terminator, ValueId, replace_params_in_instruction,
16};
17
18/// Directive specifying which function calls to inline.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub enum InlineDirective {
21    /// Inline all calls to `callee` within `caller` (same module).
22    Inline { caller: String, callee: String },
23    /// Inline only the Nth call (0-indexed) to `callee` within `caller`.
24    InlineAt {
25        caller: String,
26        callee: String,
27        call_index: usize,
28    },
29    /// Inline all calls to `callee` in all functions (same module).
30    InlineAll { callee: String },
31    /// Cross-module: Inline all calls to `callee_module::callee` within `caller_module::caller`.
32    InlineCross {
33        caller_module: String,
34        caller: String,
35        callee_module: String,
36        callee: String,
37    },
38    /// Cross-module: Inline all calls to `callee_module::callee` in all functions across all modules.
39    InlineCrossAll {
40        callee_module: String,
41        callee: String,
42    },
43}
44
45/// Parse inline directives from source text.
46///
47/// Format:
48/// ```text
49/// inline caller_function callee_function
50/// inline caller_function callee_function at N
51/// inline-all callee_function
52/// inline-cross caller_module::caller_func callee_module::callee_func
53/// inline-cross-all callee_module::callee_func
54/// ```
55pub fn parse_inline_directives(source: &str) -> Result<Vec<InlineDirective>, String> {
56    let mut directives = Vec::new();
57
58    for (line_num, line) in source.lines().enumerate() {
59        let line = line.trim();
60
61        // Skip empty lines and comments.
62        if line.is_empty() || line.starts_with("//") {
63            continue;
64        }
65
66        let parts: Vec<&str> = line.split_whitespace().collect();
67
68        let directive = match parts.as_slice() {
69            ["inline", caller, callee] => InlineDirective::Inline {
70                caller: (*caller).to_string(),
71                callee: (*callee).to_string(),
72            },
73            ["inline", caller, callee, "at", idx] => {
74                let call_index: usize = idx.parse().map_err(|_| {
75                    format!(
76                        "line {}: invalid call index '{}' (expected integer)",
77                        line_num + 1,
78                        idx
79                    )
80                })?;
81                InlineDirective::InlineAt {
82                    caller: (*caller).to_string(),
83                    callee: (*callee).to_string(),
84                    call_index,
85                }
86            }
87            ["inline-all", callee] => InlineDirective::InlineAll {
88                callee: (*callee).to_string(),
89            },
90            ["inline-cross", caller_spec, callee_spec] => {
91                let (caller_module, caller) = parse_qualified_name(caller_spec).ok_or_else(|| {
92                    format!(
93                        "line {}: invalid caller specification '{}' (expected module::function)",
94                        line_num + 1,
95                        caller_spec
96                    )
97                })?;
98                let (callee_module, callee) = parse_qualified_name(callee_spec).ok_or_else(|| {
99                    format!(
100                        "line {}: invalid callee specification '{}' (expected module::function)",
101                        line_num + 1,
102                        callee_spec
103                    )
104                })?;
105                InlineDirective::InlineCross {
106                    caller_module,
107                    caller,
108                    callee_module,
109                    callee,
110                }
111            }
112            ["inline-cross-all", callee_spec] => {
113                let (callee_module, callee) = parse_qualified_name(callee_spec).ok_or_else(|| {
114                    format!(
115                        "line {}: invalid callee specification '{}' (expected module::function)",
116                        line_num + 1,
117                        callee_spec
118                    )
119                })?;
120                InlineDirective::InlineCrossAll {
121                    callee_module,
122                    callee,
123                }
124            }
125            _ => {
126                return Err(format!(
127                    "line {}: invalid inline directive '{}' \
128                     (expected 'inline caller callee', 'inline caller callee at N', \
129                     'inline-all callee', 'inline-cross mod::caller mod::callee', \
130                     or 'inline-cross-all mod::callee')",
131                    line_num + 1,
132                    line
133                ))
134            }
135        };
136
137        directives.push(directive);
138    }
139
140    Ok(directives)
141}
142
143/// Parse a qualified name like "module::function" into (module, function).
144fn parse_qualified_name(spec: &str) -> Option<(String, String)> {
145    let parts: Vec<&str> = spec.split("::").collect();
146    if parts.len() == 2 {
147        Some((parts[0].to_string(), parts[1].to_string()))
148    } else {
149        None
150    }
151}
152
153/// Specifies which call sites to inline.
154#[derive(Clone, Debug)]
155pub enum CallSiteFilter {
156    /// Inline all calls to the callee.
157    All,
158    /// Inline only the Nth call (0-indexed).
159    AtIndex(usize),
160}
161
162/// Request to inline specific calls (single-module).
163#[derive(Clone, Debug)]
164pub struct InlineRequest {
165    pub caller: FuncId,
166    pub callee: FuncId,
167    pub filter: CallSiteFilter,
168}
169
170/// Global function identifier (module + function).
171#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
172pub struct GlobalFuncId {
173    pub module: IrModuleId,
174    pub func: FuncId,
175}
176
177/// Request to inline specific calls (cross-module).
178#[derive(Clone, Debug)]
179pub struct CrossModuleInlineRequest {
180    pub caller: GlobalFuncId,
181    pub callee: GlobalFuncId,
182    pub filter: CallSiteFilter,
183}
184
185/// Reason why an inlining was skipped.
186#[derive(Clone, Debug)]
187pub enum InlineSkipReason {
188    /// The caller function was not found.
189    CallerNotFound { name: String },
190    /// The callee function was not found.
191    CalleeNotFound { name: String },
192    /// The caller module was not found.
193    CallerModuleNotFound { name: String },
194    /// The callee module was not found.
195    CalleeModuleNotFound { name: String },
196    /// Recursive call detected.
197    RecursiveCall { func: String },
198    /// The specified call site was not found.
199    CallSiteNotFound {
200        caller: String,
201        callee: String,
202        index: usize,
203    },
204    /// No calls to callee found in caller.
205    NoCallsFound { caller: String, callee: String },
206}
207
208/// Result of the inlining pass.
209#[derive(Clone, Debug)]
210pub struct InlineResult {
211    /// The transformed module.
212    pub module: IrModule,
213    /// Number of call sites inlined.
214    pub inlined_count: usize,
215    /// Reasons why some inlinings were skipped.
216    pub skipped: Vec<InlineSkipReason>,
217}
218
219/// Result of cross-module inlining.
220#[derive(Clone)]
221pub struct CrossModuleInlineResult {
222    /// The transformed function registry.
223    pub registry: ModuleFunctionRegistry,
224    /// Number of call sites inlined.
225    pub inlined_count: usize,
226    /// Reasons why some inlinings were skipped.
227    pub skipped: Vec<InlineSkipReason>,
228}
229
230impl std::fmt::Debug for CrossModuleInlineResult {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        f.debug_struct("CrossModuleInlineResult")
233            .field("inlined_count", &self.inlined_count)
234            .field("skipped", &self.skipped)
235            .finish_non_exhaustive()
236    }
237}
238
239/// Context for cross-module inlining operations.
240pub struct CrossModuleInlineContext {
241    /// Module name to IrModuleId mapping.
242    pub module_names: HashMap<String, IrModuleId>,
243    /// Per-module symbol tables.
244    pub module_symbols: HashMap<IrModuleId, SymbolTable>,
245}
246
247impl CrossModuleInlineContext {
248    /// Create a new cross-module inline context.
249    pub fn new() -> Self {
250        Self {
251            module_names: HashMap::new(),
252            module_symbols: HashMap::new(),
253        }
254    }
255
256    /// Register a module with its name and symbol table.
257    pub fn register_module(&mut self, name: String, module_id: IrModuleId, symbols: SymbolTable) {
258        self.module_names.insert(name, module_id);
259        self.module_symbols.insert(module_id, symbols);
260    }
261
262    /// Look up a function by module name and function name.
263    pub fn lookup_function(&self, module_name: &str, func_name: &str) -> Option<GlobalFuncId> {
264        let module_id = self.module_names.get(module_name)?;
265        let symbols = self.module_symbols.get(module_id)?;
266        let func_def = symbols.functions.iter().find(|f| f.name == func_name)?;
267        Some(GlobalFuncId {
268            module: *module_id,
269            func: func_def.id,
270        })
271    }
272
273    /// Iterate over all modules.
274    pub fn iter_modules(&self) -> impl Iterator<Item = (&String, &IrModuleId)> {
275        self.module_names.iter()
276    }
277}
278
279impl Default for CrossModuleInlineContext {
280    fn default() -> Self {
281        Self::new()
282    }
283}
284
285/// Resolve inline directives to concrete requests using the module's symbol table.
286pub fn resolve_directives(
287    module: &IrModule,
288    directives: &[InlineDirective],
289) -> (Vec<InlineRequest>, Vec<InlineSkipReason>) {
290    let mut requests = Vec::new();
291    let mut skipped = Vec::new();
292
293    // Build name to FuncId map.
294    let name_to_id: HashMap<&str, FuncId> = module
295        .symbols
296        .functions
297        .iter()
298        .map(|def| (def.name.as_str(), def.id))
299        .collect();
300
301    for directive in directives {
302        match directive {
303            InlineDirective::Inline { caller, callee } => {
304                let Some(&caller_id) = name_to_id.get(caller.as_str()) else {
305                    skipped.push(InlineSkipReason::CallerNotFound {
306                        name: caller.clone(),
307                    });
308                    continue;
309                };
310                let Some(&callee_id) = name_to_id.get(callee.as_str()) else {
311                    skipped.push(InlineSkipReason::CalleeNotFound {
312                        name: callee.clone(),
313                    });
314                    continue;
315                };
316
317                // Check for recursion.
318                if caller_id == callee_id {
319                    skipped.push(InlineSkipReason::RecursiveCall {
320                        func: caller.clone(),
321                    });
322                    continue;
323                }
324
325                requests.push(InlineRequest {
326                    caller: caller_id,
327                    callee: callee_id,
328                    filter: CallSiteFilter::All,
329                });
330            }
331
332            InlineDirective::InlineAt {
333                caller,
334                callee,
335                call_index,
336            } => {
337                let Some(&caller_id) = name_to_id.get(caller.as_str()) else {
338                    skipped.push(InlineSkipReason::CallerNotFound {
339                        name: caller.clone(),
340                    });
341                    continue;
342                };
343                let Some(&callee_id) = name_to_id.get(callee.as_str()) else {
344                    skipped.push(InlineSkipReason::CalleeNotFound {
345                        name: callee.clone(),
346                    });
347                    continue;
348                };
349
350                if caller_id == callee_id {
351                    skipped.push(InlineSkipReason::RecursiveCall {
352                        func: caller.clone(),
353                    });
354                    continue;
355                }
356
357                requests.push(InlineRequest {
358                    caller: caller_id,
359                    callee: callee_id,
360                    filter: CallSiteFilter::AtIndex(*call_index),
361                });
362            }
363
364            InlineDirective::InlineAll { callee } => {
365                let Some(&callee_id) = name_to_id.get(callee.as_str()) else {
366                    skipped.push(InlineSkipReason::CalleeNotFound {
367                        name: callee.clone(),
368                    });
369                    continue;
370                };
371
372                // Add request for each function that is not the callee.
373                for def in &module.symbols.functions {
374                    if def.id != callee_id {
375                        requests.push(InlineRequest {
376                            caller: def.id,
377                            callee: callee_id,
378                            filter: CallSiteFilter::All,
379                        });
380                    }
381                }
382            }
383
384            // Cross-module directives are skipped in single-module mode.
385            InlineDirective::InlineCross { .. } | InlineDirective::InlineCrossAll { .. } => {}
386        }
387    }
388
389    (requests, skipped)
390}
391
392/// Resolve cross-module inline directives using the context.
393pub fn resolve_cross_module_directives(
394    ctx: &CrossModuleInlineContext,
395    directives: &[InlineDirective],
396) -> (Vec<CrossModuleInlineRequest>, Vec<InlineSkipReason>) {
397    let mut requests = Vec::new();
398    let mut skipped = Vec::new();
399
400    for directive in directives {
401        match directive {
402            InlineDirective::InlineCross {
403                caller_module,
404                caller,
405                callee_module,
406                callee,
407            } => {
408                let Some(caller_id) = ctx.lookup_function(caller_module, caller) else {
409                    if !ctx.module_names.contains_key(caller_module) {
410                        skipped.push(InlineSkipReason::CallerModuleNotFound {
411                            name: caller_module.clone(),
412                        });
413                    } else {
414                        skipped.push(InlineSkipReason::CallerNotFound {
415                            name: format!("{}::{}", caller_module, caller),
416                        });
417                    }
418                    continue;
419                };
420
421                let Some(callee_id) = ctx.lookup_function(callee_module, callee) else {
422                    if !ctx.module_names.contains_key(callee_module) {
423                        skipped.push(InlineSkipReason::CalleeModuleNotFound {
424                            name: callee_module.clone(),
425                        });
426                    } else {
427                        skipped.push(InlineSkipReason::CalleeNotFound {
428                            name: format!("{}::{}", callee_module, callee),
429                        });
430                    }
431                    continue;
432                };
433
434                // Check for recursion (same function).
435                if caller_id == callee_id {
436                    skipped.push(InlineSkipReason::RecursiveCall {
437                        func: format!("{}::{}", caller_module, caller),
438                    });
439                    continue;
440                }
441
442                requests.push(CrossModuleInlineRequest {
443                    caller: caller_id,
444                    callee: callee_id,
445                    filter: CallSiteFilter::All,
446                });
447            }
448
449            InlineDirective::InlineCrossAll {
450                callee_module,
451                callee,
452            } => {
453                let Some(callee_id) = ctx.lookup_function(callee_module, callee) else {
454                    if !ctx.module_names.contains_key(callee_module) {
455                        skipped.push(InlineSkipReason::CalleeModuleNotFound {
456                            name: callee_module.clone(),
457                        });
458                    } else {
459                        skipped.push(InlineSkipReason::CalleeNotFound {
460                            name: format!("{}::{}", callee_module, callee),
461                        });
462                    }
463                    continue;
464                };
465
466                // Add request for each function in each module (except the callee itself).
467                for (_mod_name, &mod_id) in ctx.iter_modules() {
468                    if let Some(symbols) = ctx.module_symbols.get(&mod_id) {
469                        for func_def in &symbols.functions {
470                            let caller_global = GlobalFuncId {
471                                module: mod_id,
472                                func: func_def.id,
473                            };
474                            // Skip recursive calls.
475                            if caller_global != callee_id {
476                                requests.push(CrossModuleInlineRequest {
477                                    caller: caller_global,
478                                    callee: callee_id,
479                                    filter: CallSiteFilter::All,
480                                });
481                            }
482                        }
483                    }
484                }
485            }
486
487            // Single-module directives are skipped in cross-module mode.
488            InlineDirective::Inline { .. }
489            | InlineDirective::InlineAt { .. }
490            | InlineDirective::InlineAll { .. } => {}
491        }
492    }
493
494    (requests, skipped)
495}
496
497/// Information about a call site to inline.
498#[derive(Clone, Debug)]
499pub struct CallSite {
500    pub block_idx: usize,
501    pub instr_idx: usize,
502    pub dest: ValueId,
503    pub args: Vec<Operand>,
504}
505
506/// Find all call sites to a specific callee in a function (single-module).
507fn find_call_sites(func: &IrCodeUnit, callee_id: FuncId) -> Vec<CallSite> {
508    let mut sites = Vec::new();
509
510    for (block_idx, block) in func.blocks.iter().enumerate() {
511        for (instr_idx, instr) in block.instructions.iter().enumerate() {
512            if let Instruction::Call { dest, func: code_ref, args, .. } = instr {
513                // Match both Local and Module function references.
514                let matches = match code_ref {
515                    CodeRef::Local(id) => id.0 == callee_id.0,
516                    CodeRef::Module { id, .. } => id.0 == callee_id.0,
517                    CodeRef::External { .. } => false,
518                };
519                if matches {
520                    sites.push(CallSite {
521                        block_idx,
522                        instr_idx,
523                        dest: *dest,
524                        args: args.clone(),
525                    });
526                }
527            }
528        }
529    }
530
531    sites
532}
533
534/// Find all call sites to a specific callee (cross-module aware).
535fn find_cross_module_call_sites(
536    func: &IrCodeUnit,
537    caller_module: IrModuleId,
538    target: GlobalFuncId,
539) -> Vec<CallSite> {
540    let mut sites = Vec::new();
541
542    for (block_idx, block) in func.blocks.iter().enumerate() {
543        for (instr_idx, instr) in block.instructions.iter().enumerate() {
544            if let Instruction::Call { dest, func: code_ref, args, .. } = instr {
545                let matches = match code_ref {
546                    // Local call - matches if we're in the same module as target.
547                    CodeRef::Local(id) => {
548                        caller_module == target.module && id.0 == target.func.0
549                    }
550                    // Module call - check both module and func ID.
551                    CodeRef::Module { module, id } => {
552                        *module == target.module && id.0 == target.func.0
553                    }
554                    CodeRef::External { .. } => false,
555                };
556                if matches {
557                    sites.push(CallSite {
558                        block_idx,
559                        instr_idx,
560                        dest: *dest,
561                        args: args.clone(),
562                    });
563                }
564            }
565        }
566    }
567
568    sites
569}
570
571/// ID remapping context for inlining a callee into a caller.
572struct RemapContext {
573    value_offset: u32,
574    slot_offset: u32,
575    block_offset: u32,
576    call_site_offset: u32,
577}
578
579impl RemapContext {
580    fn remap_value(&self, v: ValueId) -> ValueId {
581        ValueId(v.0 + self.value_offset)
582    }
583
584    fn remap_slot(&self, s: SlotId) -> SlotId {
585        SlotId(s.0 + self.slot_offset)
586    }
587
588    fn remap_call_site(&self, c: CallSiteId) -> CallSiteId {
589        CallSiteId(c.0 + self.call_site_offset)
590    }
591
592    fn remap_block(&self, b: BlockId) -> BlockId {
593        BlockId(b.0 + self.block_offset)
594    }
595
596    fn remap_operand(&self, op: &Operand) -> Operand {
597        match op {
598            Operand::Value(v) => Operand::Value(self.remap_value(*v)),
599            Operand::ValueRef(v) => Operand::ValueRef(self.remap_value(*v)),
600            Operand::Slot(s) => Operand::Slot(self.remap_slot(*s)),
601            // Params will be replaced with actual arguments, not remapped.
602            Operand::Param(p) => Operand::Param(*p),
603            // External operands are not remapped.
604            Operand::ExternalValue { unit, value } => Operand::ExternalValue {
605                unit: *unit,
606                value: *value,
607            },
608            Operand::ExternalSlot { unit, slot } => Operand::ExternalSlot {
609                unit: *unit,
610                slot: *slot,
611            },
612        }
613    }
614
615    fn remap_slot_dest(&self, dest: &SlotDest) -> SlotDest {
616        match dest {
617            SlotDest::Local(s) => SlotDest::Local(self.remap_slot(*s)),
618            SlotDest::External { unit, slot } => SlotDest::External {
619                unit: *unit,
620                slot: *slot,
621            },
622        }
623    }
624
625    fn remap_instruction(&self, instr: &Instruction) -> Instruction {
626        match instr {
627            Instruction::Const { dest, value } => Instruction::Const {
628                dest: self.remap_value(*dest),
629                value: value.clone(),
630            },
631            Instruction::Copy { dest, src } => Instruction::Copy {
632                dest: self.remap_value(*dest),
633                src: self.remap_operand(src),
634            },
635            Instruction::Move { dest, src } => Instruction::Move {
636                dest: self.remap_value(*dest),
637                src: self.remap_operand(src),
638            },
639            Instruction::BinOp { dest, op, lhs, rhs } => Instruction::BinOp {
640                dest: self.remap_value(*dest),
641                op: *op,
642                lhs: self.remap_operand(lhs),
643                rhs: self.remap_operand(rhs),
644            },
645            Instruction::UnaryOp { dest, op, operand } => Instruction::UnaryOp {
646                dest: self.remap_value(*dest),
647                op: *op,
648                operand: self.remap_operand(operand),
649            },
650            Instruction::BinOpChecked {
651                dest,
652                overflow,
653                op,
654                lhs,
655                rhs,
656            } => Instruction::BinOpChecked {
657                dest: self.remap_value(*dest),
658                overflow: self.remap_value(*overflow),
659                op: *op,
660                lhs: self.remap_operand(lhs),
661                rhs: self.remap_operand(rhs),
662            },
663            Instruction::UnaryOpChecked {
664                dest,
665                overflow,
666                op,
667                operand,
668            } => Instruction::UnaryOpChecked {
669                dest: self.remap_value(*dest),
670                overflow: self.remap_value(*overflow),
671                op: *op,
672                operand: self.remap_operand(operand),
673            },
674            Instruction::Widen { dest, src } => Instruction::Widen {
675                dest: self.remap_value(*dest),
676                src: self.remap_operand(src),
677            },
678            Instruction::WidenFixed { dest, src } => Instruction::WidenFixed {
679                dest: self.remap_value(*dest),
680                src: self.remap_operand(src),
681            },
682            Instruction::Clone { dest, src } => Instruction::Clone {
683                dest: self.remap_value(*dest),
684                src: self.remap_operand(src),
685            },
686            // `shape_descriptors` survives the move because `inline_call_site`
687            // refuses a callee that declares shapes, so every entry here is a
688            // `Static`, which names a whole type and is valid anywhere.
689            Instruction::Call { site_id, dest, func, args, type_args, shape_descriptors } => Instruction::Call {
690                site_id: self.remap_call_site(*site_id),
691                dest: self.remap_value(*dest),
692                func: func.clone(),
693                args: args.iter().map(|a| self.remap_operand(a)).collect(),
694                type_args: type_args.clone(),
695                shape_descriptors: shape_descriptors.clone(),
696            },
697            Instruction::ComptimeCall {
698                dest, func, args, discriminant, comptime_param_indices, type_args, shape_descriptors,
699            } => Instruction::ComptimeCall {
700                dest: self.remap_value(*dest),
701                func: func.clone(),
702                args: args.iter().map(|a| self.remap_operand(a)).collect(),
703                discriminant: *discriminant,
704                comptime_param_indices: comptime_param_indices.clone(),
705                type_args: type_args.clone(),
706                shape_descriptors: shape_descriptors.clone(),
707            },
708            Instruction::Pack { dest, ty, fields } => Instruction::Pack {
709                dest: self.remap_value(*dest),
710                ty: ty.clone(),
711                fields: fields.iter().map(|f| self.remap_operand(f)).collect(),
712            },
713            Instruction::Unpack { dests, src } => Instruction::Unpack {
714                dests: dests.iter().map(|d| self.remap_value(*d)).collect(),
715                src: self.remap_operand(src),
716            },
717            Instruction::GetField {
718                dest,
719                src,
720                field_index,
721            } => Instruction::GetField {
722                dest: self.remap_value(*dest),
723                src: self.remap_operand(src),
724                field_index: *field_index,
725            },
726            Instruction::GetFieldRef {
727                dest,
728                src,
729                field_index,
730            } => Instruction::GetFieldRef {
731                dest: self.remap_value(*dest),
732                src: self.remap_operand(src),
733                field_index: *field_index,
734            },
735            Instruction::DataBorrow { dest, src } => Instruction::DataBorrow {
736                dest: self.remap_value(*dest),
737                src: self.remap_operand(src),
738            },
739            Instruction::WrapSome { dest, inner } => Instruction::WrapSome {
740                dest: self.remap_value(*dest),
741                inner: self.remap_operand(inner),
742            },
743            Instruction::WrapNone { dest } => Instruction::WrapNone {
744                dest: self.remap_value(*dest),
745            },
746            Instruction::WrapOk { dest, inner } => Instruction::WrapOk {
747                dest: self.remap_value(*dest),
748                inner: self.remap_operand(inner),
749            },
750            Instruction::WrapErr { dest, inner } => Instruction::WrapErr {
751                dest: self.remap_value(*dest),
752                inner: self.remap_operand(inner),
753            },
754            Instruction::EnumVariant {
755                dest,
756                variant_index,
757                payload,
758            } => Instruction::EnumVariant {
759                dest: self.remap_value(*dest),
760                variant_index: *variant_index,
761                payload: payload.as_ref().map(|p| self.remap_operand(p)),
762            },
763            Instruction::EnumDiscriminant { dest, src } => Instruction::EnumDiscriminant {
764                dest: self.remap_value(*dest),
765                src: self.remap_operand(src),
766            },
767            Instruction::EnumPayload { dest, src, variant_index } => Instruction::EnumPayload {
768                dest: self.remap_value(*dest),
769                src: self.remap_operand(src),
770                variant_index: *variant_index,
771            },
772            Instruction::UnwrapOption { dest, is_some, src } => Instruction::UnwrapOption {
773                dest: self.remap_value(*dest),
774                is_some: self.remap_value(*is_some),
775                src: self.remap_operand(src),
776            },
777            Instruction::UnwrapResult {
778                ok_dest,
779                err_dest,
780                is_ok,
781                src,
782            } => Instruction::UnwrapResult {
783                ok_dest: self.remap_value(*ok_dest),
784                err_dest: self.remap_value(*err_dest),
785                is_ok: self.remap_value(*is_ok),
786                src: self.remap_operand(src),
787            },
788            Instruction::ErrorFrom { dest, inner } => Instruction::ErrorFrom {
789                dest: self.remap_value(*dest),
790                inner: self.remap_operand(inner),
791            },
792            Instruction::DataFrom { dest, inner } => Instruction::DataFrom {
793                dest: self.remap_value(*dest),
794                inner: self.remap_operand(inner),
795            },
796            Instruction::Erase { dest, src } => Instruction::Erase {
797                dest: self.remap_value(*dest),
798                src: self.remap_operand(src),
799            },
800            Instruction::EraseTracked { dest, src } => Instruction::EraseTracked {
801                dest: self.remap_value(*dest),
802                src: self.remap_operand(src),
803            },
804            Instruction::Reify { dest, src } => Instruction::Reify {
805                dest: self.remap_value(*dest),
806                src: self.remap_operand(src),
807            },
808            Instruction::ListNew { dest, elements, descriptor } => Instruction::ListNew {
809                dest: self.remap_value(*dest),
810                elements: elements.iter().map(|e| self.remap_operand(e)).collect(),
811                descriptor: *descriptor,
812            },
813            Instruction::SetNew { dest, elements, descriptor } => Instruction::SetNew {
814                dest: self.remap_value(*dest),
815                elements: elements.iter().map(|e| self.remap_operand(e)).collect(),
816                descriptor: *descriptor,
817            },
818            Instruction::MapNew { dest, entries, descriptor } => Instruction::MapNew {
819                dest: self.remap_value(*dest),
820                entries: entries
821                    .iter()
822                    .map(|(k, v)| (self.remap_operand(k), self.remap_operand(v)))
823                    .collect(),
824                descriptor: *descriptor,
825            },
826            Instruction::TensorNew {
827                dest,
828                shape,
829                elements,
830            } => Instruction::TensorNew {
831                dest: self.remap_value(*dest),
832                shape: shape.clone(),
833                elements: elements.iter().map(|e| self.remap_operand(e)).collect(),
834            },
835            Instruction::TableNew { dest, rows } => Instruction::TableNew {
836                dest: self.remap_value(*dest),
837                rows: rows.iter().map(|r| self.remap_operand(r)).collect(),
838            },
839            Instruction::SlotStoreCopy { dest, value } => Instruction::SlotStoreCopy {
840                dest: self.remap_slot_dest(dest),
841                value: self.remap_operand(value),
842            },
843            Instruction::SlotStoreCopyTracked { dest, value } => {
844                Instruction::SlotStoreCopyTracked {
845                    dest: self.remap_slot_dest(dest),
846                    value: self.remap_operand(value),
847                }
848            }
849            Instruction::SlotStoreMove { dest, value } => Instruction::SlotStoreMove {
850                dest: self.remap_slot_dest(dest),
851                value: self.remap_operand(value),
852            },
853            Instruction::SlotStoreMoveTracked { dest, value } => {
854                Instruction::SlotStoreMoveTracked {
855                    dest: self.remap_slot_dest(dest),
856                    value: self.remap_operand(value),
857                }
858            }
859            Instruction::SetField {
860                slot,
861                field_path,
862                value,
863            } => Instruction::SetField {
864                slot: self.remap_slot_dest(slot),
865                field_path: field_path.clone(),
866                value: self.remap_operand(value),
867            },
868            Instruction::SetFieldTracked {
869                slot,
870                field_path,
871                value,
872            } => Instruction::SetFieldTracked {
873                slot: self.remap_slot_dest(slot),
874                field_path: field_path.clone(),
875                value: self.remap_operand(value),
876            },
877            Instruction::ParamStore { param, value } => Instruction::ParamStore {
878                param: *param,
879                value: self.remap_operand(value),
880            },
881            Instruction::ParamStoreTracked { param, value } => Instruction::ParamStoreTracked {
882                param: *param,
883                value: self.remap_operand(value),
884            },
885            Instruction::ParamSetField {
886                param,
887                field_path,
888                value,
889            } => Instruction::ParamSetField {
890                param: *param,
891                field_path: field_path.clone(),
892                value: self.remap_operand(value),
893            },
894            Instruction::ParamSetFieldTracked {
895                param,
896                field_path,
897                value,
898            } => Instruction::ParamSetFieldTracked {
899                param: *param,
900                field_path: field_path.clone(),
901                value: self.remap_operand(value),
902            },
903            Instruction::RefStore { dest, value } => Instruction::RefStore {
904                dest: self.remap_operand(dest),
905                value: self.remap_operand(value),
906            },
907            Instruction::RefStoreTracked { dest, value } => Instruction::RefStoreTracked {
908                dest: self.remap_operand(dest),
909                value: self.remap_operand(value),
910            },
911            Instruction::RefSetField {
912                dest,
913                field_path,
914                value,
915            } => Instruction::RefSetField {
916                dest: self.remap_operand(dest),
917                field_path: field_path.clone(),
918                value: self.remap_operand(value),
919            },
920            Instruction::RefSetFieldTracked {
921                dest,
922                field_path,
923                value,
924            } => Instruction::RefSetFieldTracked {
925                dest: self.remap_operand(dest),
926                field_path: field_path.clone(),
927                value: self.remap_operand(value),
928            },
929            Instruction::SlotLoadCopy { dest, slot } => Instruction::SlotLoadCopy {
930                dest: self.remap_value(*dest),
931                slot: self.remap_slot(*slot),
932            },
933            Instruction::SlotLoadMove { dest, slot } => Instruction::SlotLoadMove {
934                dest: self.remap_value(*dest),
935                slot: self.remap_slot(*slot),
936            },
937            Instruction::SlotLoadMoveTracked { dest, slot } => Instruction::SlotLoadMoveTracked {
938                dest: self.remap_value(*dest),
939                slot: self.remap_slot(*slot),
940            },
941            Instruction::Drop { operand } => Instruction::Drop {
942                operand: self.remap_operand(operand),
943            },
944            Instruction::DropTracked { operand } => Instruction::DropTracked {
945                operand: self.remap_operand(operand),
946            },
947            Instruction::DropViaRef { ref_value } => Instruction::DropViaRef {
948                ref_value: self.remap_value(*ref_value),
949            },
950            Instruction::UnitEndDrop { operand } => Instruction::UnitEndDrop {
951                operand: self.remap_operand(operand),
952            },
953            Instruction::UnitEndDropTracked { operand } => Instruction::UnitEndDropTracked {
954                operand: self.remap_operand(operand),
955            },
956            Instruction::DebugLog { operand } => Instruction::DebugLog {
957                operand: self.remap_operand(operand),
958            },
959            Instruction::Intrinsic {
960                dest,
961                intrinsic,
962                args,
963            } => Instruction::Intrinsic {
964                dest: self.remap_value(*dest),
965                intrinsic: intrinsic.clone(),
966                args: args.iter().map(|a| self.remap_operand(a)).collect(),
967            },
968            Instruction::ListGet { dest, is_valid, list, index } => Instruction::ListGet {
969                dest: self.remap_value(*dest),
970                is_valid: self.remap_value(*is_valid),
971                list: self.remap_operand(list),
972                index: self.remap_operand(index),
973            },
974            Instruction::ListBoundsCheck { is_valid, list, index } => Instruction::ListBoundsCheck {
975                is_valid: self.remap_value(*is_valid),
976                list: self.remap_operand(list),
977                index: self.remap_operand(index),
978            },
979            Instruction::ListSet { list, index, value } => Instruction::ListSet {
980                list: self.remap_operand(list),
981                index: self.remap_operand(index),
982                value: self.remap_operand(value),
983            },
984            Instruction::ListElementRef { dest, list, index } => Instruction::ListElementRef {
985                dest: self.remap_value(*dest),
986                list: self.remap_operand(list),
987                index: self.remap_operand(index),
988            },
989            Instruction::MapGet { dest, is_valid, map, key } => Instruction::MapGet {
990                dest: self.remap_value(*dest),
991                is_valid: self.remap_value(*is_valid),
992                map: self.remap_operand(map),
993                key: self.remap_operand(key),
994            },
995            Instruction::MapContainsKey { is_valid, map, key } => Instruction::MapContainsKey {
996                is_valid: self.remap_value(*is_valid),
997                map: self.remap_operand(map),
998                key: self.remap_operand(key),
999            },
1000            Instruction::MapSetValue { map, key, value } => Instruction::MapSetValue {
1001                map: self.remap_operand(map),
1002                key: self.remap_operand(key),
1003                value: self.remap_operand(value),
1004            },
1005            Instruction::MapValueRef { dest, map, key } => Instruction::MapValueRef {
1006                dest: self.remap_value(*dest),
1007                map: self.remap_operand(map),
1008                key: self.remap_operand(key),
1009            },
1010            Instruction::MapUpsert { map, key, value } => Instruction::MapUpsert {
1011                map: self.remap_operand(map),
1012                key: self.remap_operand(key),
1013                value: self.remap_operand(value),
1014            },
1015            Instruction::TensorGet { dest, is_valid, tensor, index } => Instruction::TensorGet {
1016                dest: self.remap_value(*dest),
1017                is_valid: self.remap_value(*is_valid),
1018                tensor: self.remap_operand(tensor),
1019                index: self.remap_operand(index),
1020            },
1021            Instruction::TensorBoundsCheck { is_valid, tensor, index } => Instruction::TensorBoundsCheck {
1022                is_valid: self.remap_value(*is_valid),
1023                tensor: self.remap_operand(tensor),
1024                index: self.remap_operand(index),
1025            },
1026            Instruction::TensorSet { tensor, index, value } => Instruction::TensorSet {
1027                tensor: self.remap_operand(tensor),
1028                index: self.remap_operand(index),
1029                value: self.remap_operand(value),
1030            },
1031            Instruction::TensorIndexRef { dest, tensor, index } => Instruction::TensorIndexRef {
1032                dest: self.remap_value(*dest),
1033                tensor: self.remap_operand(tensor),
1034                index: self.remap_operand(index),
1035            },
1036            Instruction::Nop => Instruction::Nop,
1037        }
1038    }
1039
1040    fn remap_terminator(&self, term: &Terminator, continuation_block: BlockId) -> Terminator {
1041        match term {
1042            Terminator::Goto { target, args } => Terminator::Goto {
1043                target: self.remap_block(*target),
1044                args: args.iter().map(|a| self.remap_operand(a)).collect(),
1045            },
1046            Terminator::Branch {
1047                cond,
1048                then_block,
1049                then_args,
1050                else_block,
1051                else_args,
1052            } => Terminator::Branch {
1053                cond: self.remap_operand(cond),
1054                then_block: self.remap_block(*then_block),
1055                then_args: then_args.iter().map(|a| self.remap_operand(a)).collect(),
1056                else_block: self.remap_block(*else_block),
1057                else_args: else_args.iter().map(|a| self.remap_operand(a)).collect(),
1058            },
1059            Terminator::Return { value } => {
1060                // Return becomes a goto to the continuation block.
1061                Terminator::Goto {
1062                    target: continuation_block,
1063                    args: value.iter().map(|v| self.remap_operand(v)).collect(),
1064                }
1065            }
1066            Terminator::Switch { discriminant, cases, default } => Terminator::Switch {
1067                discriminant: self.remap_operand(discriminant),
1068                cases: cases.iter().map(|(v, b)| (*v, self.remap_block(*b))).collect(),
1069                default: self.remap_block(*default),
1070            },
1071            // UnitEnd/UnitEarlyReturn shouldn't appear in function bodies being inlined.
1072            Terminator::UnitEnd { result } => Terminator::UnitEnd {
1073                result: result.as_ref().map(|v| self.remap_operand(v)),
1074            },
1075            Terminator::UnitEarlyReturn { value } => Terminator::UnitEarlyReturn {
1076                value: self.remap_operand(value),
1077            },
1078        }
1079    }
1080}
1081
1082/// Inline a single call site in a function.
1083///
1084/// Returns the new function with the call inlined, or None if inlining failed.
1085pub fn inline_call_site(
1086    caller: &IrCodeUnit,
1087    callee: &IrCodeUnit,
1088    site: &CallSite,
1089) -> Option<IrCodeUnit> {
1090    // Get function contexts - inlining only works on functions.
1091    let _caller_ctx = caller.function_context()?;
1092    let callee_ctx = callee.function_context()?;
1093
1094    // A callee that declares shapes cannot be moved. Its body refers to them by
1095    // index -- `DescriptorRef::Own` on a call, `descriptor` on a `ListNew` --
1096    // and an index into the callee's list means a different shape, or nothing at
1097    // all, in the caller's. Renumbering them would mean merging the two lists
1098    // and rewriting the caller's own signature, which is not an inlining.
1099    if !callee_ctx.descriptor_shapes.is_empty() {
1100        return None;
1101    }
1102
1103    let mut new_unit = caller.clone();
1104
1105    // Set up remapping context.
1106    let remap = RemapContext {
1107        value_offset: caller.value_count,
1108        slot_offset: caller.slot_count,
1109        block_offset: caller.blocks.len() as u32,
1110        call_site_offset: caller.call_site_count,
1111    };
1112
1113    // The continuation block receives the return value.
1114    // Its block ID is after all the inlined blocks.
1115    let continuation_block_id = BlockId(remap.block_offset + callee.blocks.len() as u32);
1116
1117    // Split the original block at the call site.
1118    let orig_block = &caller.blocks[site.block_idx];
1119
1120    // Instructions before the call stay in the original block.
1121    let before_call: Vec<Instruction> = orig_block.instructions[..site.instr_idx].to_vec();
1122
1123    // Instructions after the call go to the continuation block.
1124    let after_call: Vec<Instruction> = orig_block.instructions[site.instr_idx + 1..].to_vec();
1125
1126    // The original terminator goes to the continuation block.
1127    let orig_terminator = orig_block.terminator.clone();
1128
1129    // Build parameter binding instructions for In params only.
1130    // Ref params don't need bindings - we directly substitute the argument operand.
1131    // Also build a map from ParamId to replacement operand for use in substitution.
1132    let mut param_bindings: Vec<Instruction> = Vec::new();
1133    let mut param_replacements: HashMap<ParamId, Operand> = HashMap::new();
1134
1135    for (i, (param_id, arg)) in callee_ctx.params.iter().zip(site.args.iter()).enumerate() {
1136        let param_type = &callee_ctx.param_types[param_id.0 as usize];
1137        let param_mode = &callee_ctx.param_modes[param_id.0 as usize];
1138
1139        if matches!(param_mode, ParamMode::Ref | ParamMode::Mut | ParamMode::Out) {
1140            // Ref/Mut/Out params borrow - directly use the argument operand.
1141            // No binding needed, no ownership transfer.
1142            // For Mut/Out params, ParamStore/ParamStoreTracked will be converted to RefStore/RefStoreTracked.
1143            param_replacements.insert(*param_id, arg.clone());
1144        } else {
1145            // In params transfer ownership - create a binding.
1146            let dest_value = remap.remap_value(ValueId(callee.value_count + i as u32));
1147
1148            let instr = if param_type.is_copy() {
1149                Instruction::Copy {
1150                    dest: dest_value,
1151                    src: arg.clone(),
1152                }
1153            } else {
1154                Instruction::Move {
1155                    dest: dest_value,
1156                    src: arg.clone(),
1157                }
1158            };
1159            param_bindings.push(instr);
1160            param_replacements.insert(*param_id, Operand::Value(dest_value));
1161        }
1162    }
1163
1164    // Update the original block: keep instructions before call, jump to inlined entry.
1165    let inlined_entry_block = remap.remap_block(BlockId(0));
1166    new_unit.blocks[site.block_idx] = IrBlock {
1167        id: BlockId(site.block_idx as u32),
1168        params: orig_block.params.clone(),
1169        instructions: before_call,
1170        terminator: Terminator::Goto {
1171            target: inlined_entry_block,
1172            args: vec![],
1173        },
1174    };
1175
1176    // Copy callee blocks with remapped IDs.
1177    for (i, block) in callee.blocks.iter().enumerate() {
1178        let mut new_instructions: Vec<Instruction> = Vec::new();
1179
1180        // Add parameter bindings to the entry block.
1181        if i == 0 {
1182            new_instructions.extend(param_bindings.clone());
1183        }
1184
1185        // Remap and copy instructions, replacing Param operands with the replacements.
1186        for instr in &block.instructions {
1187            let remapped = remap.remap_instruction(instr);
1188            // Replace Param operands with the corresponding replacement operands.
1189            let replaced = replace_params_in_instruction(&remapped, &param_replacements);
1190            new_instructions.push(replaced);
1191        }
1192
1193        let new_block = IrBlock {
1194            id: remap.remap_block(block.id),
1195            params: block.params.iter().map(|v| remap.remap_value(*v)).collect(),
1196            instructions: new_instructions,
1197            terminator: remap.remap_terminator(&block.terminator, continuation_block_id),
1198        };
1199        new_unit.blocks.push(new_block);
1200    }
1201
1202    // Create continuation block.
1203    // If the callee returns a value, it becomes a block parameter.
1204    let cont_params = if callee_ctx.return_type != IrType::Unit {
1205        vec![site.dest]
1206    } else {
1207        vec![]
1208    };
1209
1210    let continuation_block = IrBlock {
1211        id: continuation_block_id,
1212        params: cont_params,
1213        instructions: after_call,
1214        terminator: orig_terminator,
1215    };
1216    new_unit.blocks.push(continuation_block);
1217
1218    // Update function metadata.
1219    // Add callee's values + param binding values.
1220    let extra_values = callee.value_count + callee_ctx.params.len() as u32;
1221    new_unit.value_count += extra_values;
1222    new_unit.slot_count += callee.slot_count;
1223    new_unit.call_site_count += callee.call_site_count;
1224
1225    // Extend type arrays.
1226    new_unit.value_types.extend(callee.value_types.iter().cloned());
1227    // Add types for param binding values.
1228    for param_id in &callee_ctx.params {
1229        let ty = callee_ctx.param_types[param_id.0 as usize].clone();
1230        new_unit.value_types.push(ty);
1231    }
1232    new_unit.slot_types.extend(callee.slot_types.iter().cloned());
1233
1234    // Extend tracked slots (with offset).
1235    for slot in &callee.tracked_slots {
1236        new_unit.tracked_slots.push(remap.remap_slot(*slot));
1237    }
1238
1239    Some(new_unit)
1240}
1241
1242
1243/// Perform function inlining on a module according to the given directives.
1244pub fn inline_module(module: &IrModule, directives: &[InlineDirective]) -> InlineResult {
1245    let (requests, mut skipped) = resolve_directives(module, directives);
1246
1247    let mut current_module = module.clone();
1248    let mut inlined_count = 0;
1249
1250    for request in &requests {
1251        // Find caller and callee in current state of module.
1252        // Compare CodeUnitId.0 with FuncId.0 since they both wrap u32.
1253        let caller_idx = current_module
1254            .functions
1255            .iter()
1256            .position(|f| f.id.0 == request.caller.0);
1257        let callee_idx = current_module
1258            .functions
1259            .iter()
1260            .position(|f| f.id.0 == request.callee.0);
1261
1262        let (Some(caller_idx), Some(callee_idx)) = (caller_idx, callee_idx) else {
1263            continue;
1264        };
1265
1266        let caller = &current_module.functions[caller_idx];
1267        let callee = &current_module.functions[callee_idx];
1268
1269        // Find call sites.
1270        let call_sites = find_call_sites(caller, request.callee);
1271
1272        if call_sites.is_empty() {
1273            let caller_name = caller.name.clone();
1274            let callee_name = callee.name.clone();
1275            skipped.push(InlineSkipReason::NoCallsFound {
1276                caller: caller_name,
1277                callee: callee_name,
1278            });
1279            continue;
1280        }
1281
1282        // Determine which sites to inline.
1283        let sites_to_inline: Vec<&CallSite> = match &request.filter {
1284            CallSiteFilter::All => call_sites.iter().collect(),
1285            CallSiteFilter::AtIndex(idx) => {
1286                if *idx < call_sites.len() {
1287                    vec![&call_sites[*idx]]
1288                } else {
1289                    let caller_name = caller.name.clone();
1290                    let callee_name = callee.name.clone();
1291                    skipped.push(InlineSkipReason::CallSiteNotFound {
1292                        caller: caller_name,
1293                        callee: callee_name,
1294                        index: *idx,
1295                    });
1296                    continue;
1297                }
1298            }
1299        };
1300
1301        // Inline each site (in reverse order to avoid index invalidation).
1302        let mut updated_caller = current_module.functions[caller_idx].clone();
1303        for site in sites_to_inline.into_iter().rev() {
1304            // Recompute site location in updated caller.
1305            let new_sites = find_call_sites(&updated_caller, request.callee);
1306            // Find the matching site by comparing block and instruction indices.
1307            // For simplicity, just use the site directly if it's still valid.
1308            if let Some(new_site) = new_sites.iter().find(|s| {
1309                s.block_idx == site.block_idx && s.instr_idx == site.instr_idx
1310            }) {
1311                if let Some(inlined) = inline_call_site(&updated_caller, callee, new_site) {
1312                    updated_caller = inlined;
1313                    inlined_count += 1;
1314                }
1315            }
1316        }
1317
1318        current_module.functions[caller_idx] = updated_caller;
1319    }
1320
1321    InlineResult {
1322        module: current_module,
1323        inlined_count,
1324        skipped,
1325    }
1326}
1327
1328/// Perform cross-module function inlining according to the given directives.
1329///
1330/// This function handles inlining functions across module boundaries.
1331pub fn inline_cross_module(
1332    registry: &ModuleFunctionRegistry,
1333    ctx: &CrossModuleInlineContext,
1334    directives: &[InlineDirective],
1335) -> CrossModuleInlineResult {
1336    let (requests, mut skipped) = resolve_cross_module_directives(ctx, directives);
1337
1338    // Clone the registry for mutation.
1339    let mut new_registry = registry.clone();
1340    let mut inlined_count = 0;
1341
1342    for request in &requests {
1343        // Get the caller and callee code units.
1344        let Some(caller) = new_registry.get_module_function_as_unit(request.caller.module, CodeUnitId(request.caller.func.0)) else {
1345            continue;
1346        };
1347        let Some(callee) = registry.get_module_function_as_unit(request.callee.module, CodeUnitId(request.callee.func.0)) else {
1348            continue;
1349        };
1350
1351        // Find call sites (cross-module aware).
1352        let call_sites = find_cross_module_call_sites(caller, request.caller.module, request.callee);
1353
1354        if call_sites.is_empty() {
1355            skipped.push(InlineSkipReason::NoCallsFound {
1356                caller: caller.name.clone(),
1357                callee: callee.name.clone(),
1358            });
1359            continue;
1360        }
1361
1362        // Determine which sites to inline.
1363        let sites_to_inline: Vec<&CallSite> = match &request.filter {
1364            CallSiteFilter::All => call_sites.iter().collect(),
1365            CallSiteFilter::AtIndex(idx) => {
1366                if *idx < call_sites.len() {
1367                    vec![&call_sites[*idx]]
1368                } else {
1369                    skipped.push(InlineSkipReason::CallSiteNotFound {
1370                        caller: caller.name.clone(),
1371                        callee: callee.name.clone(),
1372                        index: *idx,
1373                    });
1374                    continue;
1375                }
1376            }
1377        };
1378
1379        // Inline each site (in reverse order to avoid index invalidation).
1380        let mut updated_caller = caller.clone();
1381        for site in sites_to_inline.into_iter().rev() {
1382            // Recompute site location in updated caller.
1383            let new_sites = find_cross_module_call_sites(&updated_caller, request.caller.module, request.callee);
1384            // Find the matching site by comparing block and instruction indices.
1385            if let Some(new_site) = new_sites.iter().find(|s| {
1386                s.block_idx == site.block_idx && s.instr_idx == site.instr_idx
1387            }) {
1388                if let Some(inlined) = inline_call_site(&updated_caller, callee, new_site) {
1389                    updated_caller = inlined;
1390                    inlined_count += 1;
1391                }
1392            }
1393        }
1394
1395        // Update the registry with the modified caller.
1396        new_registry.add_module_code_unit(request.caller.module, CodeUnitId(request.caller.func.0), std::sync::Arc::new(updated_caller));
1397    }
1398
1399    CrossModuleInlineResult {
1400        registry: new_registry,
1401        inlined_count,
1402        skipped,
1403    }
1404}
1405
1406#[cfg(test)]
1407mod tests {
1408    use super::*;
1409
1410    #[test]
1411    fn test_parse_inline_directives() {
1412        let source = r#"
1413            // Comment
1414            inline foo bar
1415            inline baz qux at 2
1416            inline-all helper
1417        "#;
1418
1419        let directives = parse_inline_directives(source).unwrap();
1420        assert_eq!(directives.len(), 3);
1421
1422        assert_eq!(
1423            directives[0],
1424            InlineDirective::Inline {
1425                caller: "foo".to_string(),
1426                callee: "bar".to_string(),
1427            }
1428        );
1429
1430        assert_eq!(
1431            directives[1],
1432            InlineDirective::InlineAt {
1433                caller: "baz".to_string(),
1434                callee: "qux".to_string(),
1435                call_index: 2,
1436            }
1437        );
1438
1439        assert_eq!(
1440            directives[2],
1441            InlineDirective::InlineAll {
1442                callee: "helper".to_string(),
1443            }
1444        );
1445    }
1446
1447    #[test]
1448    fn test_parse_cross_module_directives() {
1449        let source = r#"
1450            inline-cross main::caller base::callee
1451            inline-cross-all helper::util
1452        "#;
1453
1454        let directives = parse_inline_directives(source).unwrap();
1455        assert_eq!(directives.len(), 2);
1456
1457        assert_eq!(
1458            directives[0],
1459            InlineDirective::InlineCross {
1460                caller_module: "main".to_string(),
1461                caller: "caller".to_string(),
1462                callee_module: "base".to_string(),
1463                callee: "callee".to_string(),
1464            }
1465        );
1466
1467        assert_eq!(
1468            directives[1],
1469            InlineDirective::InlineCrossAll {
1470                callee_module: "helper".to_string(),
1471                callee: "util".to_string(),
1472            }
1473        );
1474    }
1475
1476    #[test]
1477    fn test_parse_invalid_directive() {
1478        let source = "invalid directive line";
1479        let result = parse_inline_directives(source);
1480        assert!(result.is_err());
1481    }
1482
1483    #[test]
1484    fn test_parse_invalid_cross_directive() {
1485        let source = "inline-cross invalid_no_colons also_invalid";
1486        let result = parse_inline_directives(source);
1487        assert!(result.is_err());
1488    }
1489}