use std::collections::HashMap;
use datalove_datafun_ir::{
BlockId, CallSiteId, CodeRef, CodeUnitId, FuncId, Instruction, IrBlock, IrCodeUnit, IrModule, IrModuleId,
IrType, ModuleFunctionRegistry, Operand, ParamId, ParamMode, SlotDest, SlotId, SymbolTable,
Terminator, ValueId, replace_params_in_instruction,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InlineDirective {
Inline { caller: String, callee: String },
InlineAt {
caller: String,
callee: String,
call_index: usize,
},
InlineAll { callee: String },
InlineCross {
caller_module: String,
caller: String,
callee_module: String,
callee: String,
},
InlineCrossAll {
callee_module: String,
callee: String,
},
}
pub fn parse_inline_directives(source: &str) -> Result<Vec<InlineDirective>, String> {
let mut directives = Vec::new();
for (line_num, line) in source.lines().enumerate() {
let line = line.trim();
if line.is_empty() || line.starts_with("//") {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
let directive = match parts.as_slice() {
["inline", caller, callee] => InlineDirective::Inline {
caller: (*caller).to_string(),
callee: (*callee).to_string(),
},
["inline", caller, callee, "at", idx] => {
let call_index: usize = idx.parse().map_err(|_| {
format!(
"line {}: invalid call index '{}' (expected integer)",
line_num + 1,
idx
)
})?;
InlineDirective::InlineAt {
caller: (*caller).to_string(),
callee: (*callee).to_string(),
call_index,
}
}
["inline-all", callee] => InlineDirective::InlineAll {
callee: (*callee).to_string(),
},
["inline-cross", caller_spec, callee_spec] => {
let (caller_module, caller) = parse_qualified_name(caller_spec).ok_or_else(|| {
format!(
"line {}: invalid caller specification '{}' (expected module::function)",
line_num + 1,
caller_spec
)
})?;
let (callee_module, callee) = parse_qualified_name(callee_spec).ok_or_else(|| {
format!(
"line {}: invalid callee specification '{}' (expected module::function)",
line_num + 1,
callee_spec
)
})?;
InlineDirective::InlineCross {
caller_module,
caller,
callee_module,
callee,
}
}
["inline-cross-all", callee_spec] => {
let (callee_module, callee) = parse_qualified_name(callee_spec).ok_or_else(|| {
format!(
"line {}: invalid callee specification '{}' (expected module::function)",
line_num + 1,
callee_spec
)
})?;
InlineDirective::InlineCrossAll {
callee_module,
callee,
}
}
_ => {
return Err(format!(
"line {}: invalid inline directive '{}' \
(expected 'inline caller callee', 'inline caller callee at N', \
'inline-all callee', 'inline-cross mod::caller mod::callee', \
or 'inline-cross-all mod::callee')",
line_num + 1,
line
))
}
};
directives.push(directive);
}
Ok(directives)
}
fn parse_qualified_name(spec: &str) -> Option<(String, String)> {
let parts: Vec<&str> = spec.split("::").collect();
if parts.len() == 2 {
Some((parts[0].to_string(), parts[1].to_string()))
} else {
None
}
}
#[derive(Clone, Debug)]
pub enum CallSiteFilter {
All,
AtIndex(usize),
}
#[derive(Clone, Debug)]
pub struct InlineRequest {
pub caller: FuncId,
pub callee: FuncId,
pub filter: CallSiteFilter,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct GlobalFuncId {
pub module: IrModuleId,
pub func: FuncId,
}
#[derive(Clone, Debug)]
pub struct CrossModuleInlineRequest {
pub caller: GlobalFuncId,
pub callee: GlobalFuncId,
pub filter: CallSiteFilter,
}
#[derive(Clone, Debug)]
pub enum InlineSkipReason {
CallerNotFound { name: String },
CalleeNotFound { name: String },
CallerModuleNotFound { name: String },
CalleeModuleNotFound { name: String },
RecursiveCall { func: String },
CallSiteNotFound {
caller: String,
callee: String,
index: usize,
},
NoCallsFound { caller: String, callee: String },
}
#[derive(Clone, Debug)]
pub struct InlineResult {
pub module: IrModule,
pub inlined_count: usize,
pub skipped: Vec<InlineSkipReason>,
}
#[derive(Clone)]
pub struct CrossModuleInlineResult {
pub registry: ModuleFunctionRegistry,
pub inlined_count: usize,
pub skipped: Vec<InlineSkipReason>,
}
impl std::fmt::Debug for CrossModuleInlineResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CrossModuleInlineResult")
.field("inlined_count", &self.inlined_count)
.field("skipped", &self.skipped)
.finish_non_exhaustive()
}
}
pub struct CrossModuleInlineContext {
pub module_names: HashMap<String, IrModuleId>,
pub module_symbols: HashMap<IrModuleId, SymbolTable>,
}
impl CrossModuleInlineContext {
pub fn new() -> Self {
Self {
module_names: HashMap::new(),
module_symbols: HashMap::new(),
}
}
pub fn register_module(&mut self, name: String, module_id: IrModuleId, symbols: SymbolTable) {
self.module_names.insert(name, module_id);
self.module_symbols.insert(module_id, symbols);
}
pub fn lookup_function(&self, module_name: &str, func_name: &str) -> Option<GlobalFuncId> {
let module_id = self.module_names.get(module_name)?;
let symbols = self.module_symbols.get(module_id)?;
let func_def = symbols.functions.iter().find(|f| f.name == func_name)?;
Some(GlobalFuncId {
module: *module_id,
func: func_def.id,
})
}
pub fn iter_modules(&self) -> impl Iterator<Item = (&String, &IrModuleId)> {
self.module_names.iter()
}
}
impl Default for CrossModuleInlineContext {
fn default() -> Self {
Self::new()
}
}
pub fn resolve_directives(
module: &IrModule,
directives: &[InlineDirective],
) -> (Vec<InlineRequest>, Vec<InlineSkipReason>) {
let mut requests = Vec::new();
let mut skipped = Vec::new();
let name_to_id: HashMap<&str, FuncId> = module
.symbols
.functions
.iter()
.map(|def| (def.name.as_str(), def.id))
.collect();
for directive in directives {
match directive {
InlineDirective::Inline { caller, callee } => {
let Some(&caller_id) = name_to_id.get(caller.as_str()) else {
skipped.push(InlineSkipReason::CallerNotFound {
name: caller.clone(),
});
continue;
};
let Some(&callee_id) = name_to_id.get(callee.as_str()) else {
skipped.push(InlineSkipReason::CalleeNotFound {
name: callee.clone(),
});
continue;
};
if caller_id == callee_id {
skipped.push(InlineSkipReason::RecursiveCall {
func: caller.clone(),
});
continue;
}
requests.push(InlineRequest {
caller: caller_id,
callee: callee_id,
filter: CallSiteFilter::All,
});
}
InlineDirective::InlineAt {
caller,
callee,
call_index,
} => {
let Some(&caller_id) = name_to_id.get(caller.as_str()) else {
skipped.push(InlineSkipReason::CallerNotFound {
name: caller.clone(),
});
continue;
};
let Some(&callee_id) = name_to_id.get(callee.as_str()) else {
skipped.push(InlineSkipReason::CalleeNotFound {
name: callee.clone(),
});
continue;
};
if caller_id == callee_id {
skipped.push(InlineSkipReason::RecursiveCall {
func: caller.clone(),
});
continue;
}
requests.push(InlineRequest {
caller: caller_id,
callee: callee_id,
filter: CallSiteFilter::AtIndex(*call_index),
});
}
InlineDirective::InlineAll { callee } => {
let Some(&callee_id) = name_to_id.get(callee.as_str()) else {
skipped.push(InlineSkipReason::CalleeNotFound {
name: callee.clone(),
});
continue;
};
for def in &module.symbols.functions {
if def.id != callee_id {
requests.push(InlineRequest {
caller: def.id,
callee: callee_id,
filter: CallSiteFilter::All,
});
}
}
}
InlineDirective::InlineCross { .. } | InlineDirective::InlineCrossAll { .. } => {}
}
}
(requests, skipped)
}
pub fn resolve_cross_module_directives(
ctx: &CrossModuleInlineContext,
directives: &[InlineDirective],
) -> (Vec<CrossModuleInlineRequest>, Vec<InlineSkipReason>) {
let mut requests = Vec::new();
let mut skipped = Vec::new();
for directive in directives {
match directive {
InlineDirective::InlineCross {
caller_module,
caller,
callee_module,
callee,
} => {
let Some(caller_id) = ctx.lookup_function(caller_module, caller) else {
if !ctx.module_names.contains_key(caller_module) {
skipped.push(InlineSkipReason::CallerModuleNotFound {
name: caller_module.clone(),
});
} else {
skipped.push(InlineSkipReason::CallerNotFound {
name: format!("{}::{}", caller_module, caller),
});
}
continue;
};
let Some(callee_id) = ctx.lookup_function(callee_module, callee) else {
if !ctx.module_names.contains_key(callee_module) {
skipped.push(InlineSkipReason::CalleeModuleNotFound {
name: callee_module.clone(),
});
} else {
skipped.push(InlineSkipReason::CalleeNotFound {
name: format!("{}::{}", callee_module, callee),
});
}
continue;
};
if caller_id == callee_id {
skipped.push(InlineSkipReason::RecursiveCall {
func: format!("{}::{}", caller_module, caller),
});
continue;
}
requests.push(CrossModuleInlineRequest {
caller: caller_id,
callee: callee_id,
filter: CallSiteFilter::All,
});
}
InlineDirective::InlineCrossAll {
callee_module,
callee,
} => {
let Some(callee_id) = ctx.lookup_function(callee_module, callee) else {
if !ctx.module_names.contains_key(callee_module) {
skipped.push(InlineSkipReason::CalleeModuleNotFound {
name: callee_module.clone(),
});
} else {
skipped.push(InlineSkipReason::CalleeNotFound {
name: format!("{}::{}", callee_module, callee),
});
}
continue;
};
for (_mod_name, &mod_id) in ctx.iter_modules() {
if let Some(symbols) = ctx.module_symbols.get(&mod_id) {
for func_def in &symbols.functions {
let caller_global = GlobalFuncId {
module: mod_id,
func: func_def.id,
};
if caller_global != callee_id {
requests.push(CrossModuleInlineRequest {
caller: caller_global,
callee: callee_id,
filter: CallSiteFilter::All,
});
}
}
}
}
}
InlineDirective::Inline { .. }
| InlineDirective::InlineAt { .. }
| InlineDirective::InlineAll { .. } => {}
}
}
(requests, skipped)
}
#[derive(Clone, Debug)]
pub struct CallSite {
pub block_idx: usize,
pub instr_idx: usize,
pub dest: ValueId,
pub args: Vec<Operand>,
}
fn find_call_sites(func: &IrCodeUnit, callee_id: FuncId) -> Vec<CallSite> {
let mut sites = Vec::new();
for (block_idx, block) in func.blocks.iter().enumerate() {
for (instr_idx, instr) in block.instructions.iter().enumerate() {
if let Instruction::Call { dest, func: code_ref, args, .. } = instr {
let matches = match code_ref {
CodeRef::Local(id) => id.0 == callee_id.0,
CodeRef::Module { id, .. } => id.0 == callee_id.0,
CodeRef::External { .. } => false,
};
if matches {
sites.push(CallSite {
block_idx,
instr_idx,
dest: *dest,
args: args.clone(),
});
}
}
}
}
sites
}
fn find_cross_module_call_sites(
func: &IrCodeUnit,
caller_module: IrModuleId,
target: GlobalFuncId,
) -> Vec<CallSite> {
let mut sites = Vec::new();
for (block_idx, block) in func.blocks.iter().enumerate() {
for (instr_idx, instr) in block.instructions.iter().enumerate() {
if let Instruction::Call { dest, func: code_ref, args, .. } = instr {
let matches = match code_ref {
CodeRef::Local(id) => {
caller_module == target.module && id.0 == target.func.0
}
CodeRef::Module { module, id } => {
*module == target.module && id.0 == target.func.0
}
CodeRef::External { .. } => false,
};
if matches {
sites.push(CallSite {
block_idx,
instr_idx,
dest: *dest,
args: args.clone(),
});
}
}
}
}
sites
}
struct RemapContext {
value_offset: u32,
slot_offset: u32,
block_offset: u32,
call_site_offset: u32,
}
impl RemapContext {
fn remap_value(&self, v: ValueId) -> ValueId {
ValueId(v.0 + self.value_offset)
}
fn remap_slot(&self, s: SlotId) -> SlotId {
SlotId(s.0 + self.slot_offset)
}
fn remap_call_site(&self, c: CallSiteId) -> CallSiteId {
CallSiteId(c.0 + self.call_site_offset)
}
fn remap_block(&self, b: BlockId) -> BlockId {
BlockId(b.0 + self.block_offset)
}
fn remap_operand(&self, op: &Operand) -> Operand {
match op {
Operand::Value(v) => Operand::Value(self.remap_value(*v)),
Operand::ValueRef(v) => Operand::ValueRef(self.remap_value(*v)),
Operand::Slot(s) => Operand::Slot(self.remap_slot(*s)),
Operand::Param(p) => Operand::Param(*p),
Operand::ExternalValue { unit, value } => Operand::ExternalValue {
unit: *unit,
value: *value,
},
Operand::ExternalSlot { unit, slot } => Operand::ExternalSlot {
unit: *unit,
slot: *slot,
},
}
}
fn remap_slot_dest(&self, dest: &SlotDest) -> SlotDest {
match dest {
SlotDest::Local(s) => SlotDest::Local(self.remap_slot(*s)),
SlotDest::External { unit, slot } => SlotDest::External {
unit: *unit,
slot: *slot,
},
}
}
fn remap_instruction(&self, instr: &Instruction) -> Instruction {
match instr {
Instruction::Const { dest, value } => Instruction::Const {
dest: self.remap_value(*dest),
value: value.clone(),
},
Instruction::Copy { dest, src } => Instruction::Copy {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
},
Instruction::Move { dest, src } => Instruction::Move {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
},
Instruction::BinOp { dest, op, lhs, rhs } => Instruction::BinOp {
dest: self.remap_value(*dest),
op: *op,
lhs: self.remap_operand(lhs),
rhs: self.remap_operand(rhs),
},
Instruction::UnaryOp { dest, op, operand } => Instruction::UnaryOp {
dest: self.remap_value(*dest),
op: *op,
operand: self.remap_operand(operand),
},
Instruction::BinOpChecked {
dest,
overflow,
op,
lhs,
rhs,
} => Instruction::BinOpChecked {
dest: self.remap_value(*dest),
overflow: self.remap_value(*overflow),
op: *op,
lhs: self.remap_operand(lhs),
rhs: self.remap_operand(rhs),
},
Instruction::UnaryOpChecked {
dest,
overflow,
op,
operand,
} => Instruction::UnaryOpChecked {
dest: self.remap_value(*dest),
overflow: self.remap_value(*overflow),
op: *op,
operand: self.remap_operand(operand),
},
Instruction::Widen { dest, src } => Instruction::Widen {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
},
Instruction::WidenFixed { dest, src } => Instruction::WidenFixed {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
},
Instruction::Clone { dest, src } => Instruction::Clone {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
},
Instruction::Call { site_id, dest, func, args, type_args, shape_descriptors } => Instruction::Call {
site_id: self.remap_call_site(*site_id),
dest: self.remap_value(*dest),
func: func.clone(),
args: args.iter().map(|a| self.remap_operand(a)).collect(),
type_args: type_args.clone(),
shape_descriptors: shape_descriptors.clone(),
},
Instruction::ComptimeCall {
dest, func, args, discriminant, comptime_param_indices, type_args, shape_descriptors,
} => Instruction::ComptimeCall {
dest: self.remap_value(*dest),
func: func.clone(),
args: args.iter().map(|a| self.remap_operand(a)).collect(),
discriminant: *discriminant,
comptime_param_indices: comptime_param_indices.clone(),
type_args: type_args.clone(),
shape_descriptors: shape_descriptors.clone(),
},
Instruction::Pack { dest, ty, fields } => Instruction::Pack {
dest: self.remap_value(*dest),
ty: ty.clone(),
fields: fields.iter().map(|f| self.remap_operand(f)).collect(),
},
Instruction::Unpack { dests, src } => Instruction::Unpack {
dests: dests.iter().map(|d| self.remap_value(*d)).collect(),
src: self.remap_operand(src),
},
Instruction::GetField {
dest,
src,
field_index,
} => Instruction::GetField {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
field_index: *field_index,
},
Instruction::GetFieldRef {
dest,
src,
field_index,
} => Instruction::GetFieldRef {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
field_index: *field_index,
},
Instruction::DataBorrow { dest, src } => Instruction::DataBorrow {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
},
Instruction::WrapSome { dest, inner } => Instruction::WrapSome {
dest: self.remap_value(*dest),
inner: self.remap_operand(inner),
},
Instruction::WrapNone { dest } => Instruction::WrapNone {
dest: self.remap_value(*dest),
},
Instruction::WrapOk { dest, inner } => Instruction::WrapOk {
dest: self.remap_value(*dest),
inner: self.remap_operand(inner),
},
Instruction::WrapErr { dest, inner } => Instruction::WrapErr {
dest: self.remap_value(*dest),
inner: self.remap_operand(inner),
},
Instruction::EnumVariant {
dest,
variant_index,
payload,
} => Instruction::EnumVariant {
dest: self.remap_value(*dest),
variant_index: *variant_index,
payload: payload.as_ref().map(|p| self.remap_operand(p)),
},
Instruction::EnumDiscriminant { dest, src } => Instruction::EnumDiscriminant {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
},
Instruction::EnumPayload { dest, src, variant_index } => Instruction::EnumPayload {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
variant_index: *variant_index,
},
Instruction::UnwrapOption { dest, is_some, src } => Instruction::UnwrapOption {
dest: self.remap_value(*dest),
is_some: self.remap_value(*is_some),
src: self.remap_operand(src),
},
Instruction::UnwrapResult {
ok_dest,
err_dest,
is_ok,
src,
} => Instruction::UnwrapResult {
ok_dest: self.remap_value(*ok_dest),
err_dest: self.remap_value(*err_dest),
is_ok: self.remap_value(*is_ok),
src: self.remap_operand(src),
},
Instruction::ErrorFrom { dest, inner } => Instruction::ErrorFrom {
dest: self.remap_value(*dest),
inner: self.remap_operand(inner),
},
Instruction::DataFrom { dest, inner } => Instruction::DataFrom {
dest: self.remap_value(*dest),
inner: self.remap_operand(inner),
},
Instruction::Erase { dest, src } => Instruction::Erase {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
},
Instruction::EraseTracked { dest, src } => Instruction::EraseTracked {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
},
Instruction::Reify { dest, src } => Instruction::Reify {
dest: self.remap_value(*dest),
src: self.remap_operand(src),
},
Instruction::ListNew { dest, elements, descriptor } => Instruction::ListNew {
dest: self.remap_value(*dest),
elements: elements.iter().map(|e| self.remap_operand(e)).collect(),
descriptor: *descriptor,
},
Instruction::SetNew { dest, elements, descriptor } => Instruction::SetNew {
dest: self.remap_value(*dest),
elements: elements.iter().map(|e| self.remap_operand(e)).collect(),
descriptor: *descriptor,
},
Instruction::MapNew { dest, entries, descriptor } => Instruction::MapNew {
dest: self.remap_value(*dest),
entries: entries
.iter()
.map(|(k, v)| (self.remap_operand(k), self.remap_operand(v)))
.collect(),
descriptor: *descriptor,
},
Instruction::TensorNew {
dest,
shape,
elements,
} => Instruction::TensorNew {
dest: self.remap_value(*dest),
shape: shape.clone(),
elements: elements.iter().map(|e| self.remap_operand(e)).collect(),
},
Instruction::TableNew { dest, rows } => Instruction::TableNew {
dest: self.remap_value(*dest),
rows: rows.iter().map(|r| self.remap_operand(r)).collect(),
},
Instruction::SlotStoreCopy { dest, value } => Instruction::SlotStoreCopy {
dest: self.remap_slot_dest(dest),
value: self.remap_operand(value),
},
Instruction::SlotStoreCopyTracked { dest, value } => {
Instruction::SlotStoreCopyTracked {
dest: self.remap_slot_dest(dest),
value: self.remap_operand(value),
}
}
Instruction::SlotStoreMove { dest, value } => Instruction::SlotStoreMove {
dest: self.remap_slot_dest(dest),
value: self.remap_operand(value),
},
Instruction::SlotStoreMoveTracked { dest, value } => {
Instruction::SlotStoreMoveTracked {
dest: self.remap_slot_dest(dest),
value: self.remap_operand(value),
}
}
Instruction::SetField {
slot,
field_path,
value,
} => Instruction::SetField {
slot: self.remap_slot_dest(slot),
field_path: field_path.clone(),
value: self.remap_operand(value),
},
Instruction::SetFieldTracked {
slot,
field_path,
value,
} => Instruction::SetFieldTracked {
slot: self.remap_slot_dest(slot),
field_path: field_path.clone(),
value: self.remap_operand(value),
},
Instruction::ParamStore { param, value } => Instruction::ParamStore {
param: *param,
value: self.remap_operand(value),
},
Instruction::ParamStoreTracked { param, value } => Instruction::ParamStoreTracked {
param: *param,
value: self.remap_operand(value),
},
Instruction::ParamSetField {
param,
field_path,
value,
} => Instruction::ParamSetField {
param: *param,
field_path: field_path.clone(),
value: self.remap_operand(value),
},
Instruction::ParamSetFieldTracked {
param,
field_path,
value,
} => Instruction::ParamSetFieldTracked {
param: *param,
field_path: field_path.clone(),
value: self.remap_operand(value),
},
Instruction::RefStore { dest, value } => Instruction::RefStore {
dest: self.remap_operand(dest),
value: self.remap_operand(value),
},
Instruction::RefStoreTracked { dest, value } => Instruction::RefStoreTracked {
dest: self.remap_operand(dest),
value: self.remap_operand(value),
},
Instruction::RefSetField {
dest,
field_path,
value,
} => Instruction::RefSetField {
dest: self.remap_operand(dest),
field_path: field_path.clone(),
value: self.remap_operand(value),
},
Instruction::RefSetFieldTracked {
dest,
field_path,
value,
} => Instruction::RefSetFieldTracked {
dest: self.remap_operand(dest),
field_path: field_path.clone(),
value: self.remap_operand(value),
},
Instruction::SlotLoadCopy { dest, slot } => Instruction::SlotLoadCopy {
dest: self.remap_value(*dest),
slot: self.remap_slot(*slot),
},
Instruction::SlotLoadMove { dest, slot } => Instruction::SlotLoadMove {
dest: self.remap_value(*dest),
slot: self.remap_slot(*slot),
},
Instruction::SlotLoadMoveTracked { dest, slot } => Instruction::SlotLoadMoveTracked {
dest: self.remap_value(*dest),
slot: self.remap_slot(*slot),
},
Instruction::Drop { operand } => Instruction::Drop {
operand: self.remap_operand(operand),
},
Instruction::DropTracked { operand } => Instruction::DropTracked {
operand: self.remap_operand(operand),
},
Instruction::DropViaRef { ref_value } => Instruction::DropViaRef {
ref_value: self.remap_value(*ref_value),
},
Instruction::UnitEndDrop { operand } => Instruction::UnitEndDrop {
operand: self.remap_operand(operand),
},
Instruction::UnitEndDropTracked { operand } => Instruction::UnitEndDropTracked {
operand: self.remap_operand(operand),
},
Instruction::DebugLog { operand } => Instruction::DebugLog {
operand: self.remap_operand(operand),
},
Instruction::Intrinsic {
dest,
intrinsic,
args,
} => Instruction::Intrinsic {
dest: self.remap_value(*dest),
intrinsic: intrinsic.clone(),
args: args.iter().map(|a| self.remap_operand(a)).collect(),
},
Instruction::ListGet { dest, is_valid, list, index } => Instruction::ListGet {
dest: self.remap_value(*dest),
is_valid: self.remap_value(*is_valid),
list: self.remap_operand(list),
index: self.remap_operand(index),
},
Instruction::ListBoundsCheck { is_valid, list, index } => Instruction::ListBoundsCheck {
is_valid: self.remap_value(*is_valid),
list: self.remap_operand(list),
index: self.remap_operand(index),
},
Instruction::ListSet { list, index, value } => Instruction::ListSet {
list: self.remap_operand(list),
index: self.remap_operand(index),
value: self.remap_operand(value),
},
Instruction::ListElementRef { dest, list, index } => Instruction::ListElementRef {
dest: self.remap_value(*dest),
list: self.remap_operand(list),
index: self.remap_operand(index),
},
Instruction::MapGet { dest, is_valid, map, key } => Instruction::MapGet {
dest: self.remap_value(*dest),
is_valid: self.remap_value(*is_valid),
map: self.remap_operand(map),
key: self.remap_operand(key),
},
Instruction::MapContainsKey { is_valid, map, key } => Instruction::MapContainsKey {
is_valid: self.remap_value(*is_valid),
map: self.remap_operand(map),
key: self.remap_operand(key),
},
Instruction::MapSetValue { map, key, value } => Instruction::MapSetValue {
map: self.remap_operand(map),
key: self.remap_operand(key),
value: self.remap_operand(value),
},
Instruction::MapValueRef { dest, map, key } => Instruction::MapValueRef {
dest: self.remap_value(*dest),
map: self.remap_operand(map),
key: self.remap_operand(key),
},
Instruction::MapUpsert { map, key, value } => Instruction::MapUpsert {
map: self.remap_operand(map),
key: self.remap_operand(key),
value: self.remap_operand(value),
},
Instruction::TensorGet { dest, is_valid, tensor, index } => Instruction::TensorGet {
dest: self.remap_value(*dest),
is_valid: self.remap_value(*is_valid),
tensor: self.remap_operand(tensor),
index: self.remap_operand(index),
},
Instruction::TensorBoundsCheck { is_valid, tensor, index } => Instruction::TensorBoundsCheck {
is_valid: self.remap_value(*is_valid),
tensor: self.remap_operand(tensor),
index: self.remap_operand(index),
},
Instruction::TensorSet { tensor, index, value } => Instruction::TensorSet {
tensor: self.remap_operand(tensor),
index: self.remap_operand(index),
value: self.remap_operand(value),
},
Instruction::TensorIndexRef { dest, tensor, index } => Instruction::TensorIndexRef {
dest: self.remap_value(*dest),
tensor: self.remap_operand(tensor),
index: self.remap_operand(index),
},
Instruction::Nop => Instruction::Nop,
}
}
fn remap_terminator(&self, term: &Terminator, continuation_block: BlockId) -> Terminator {
match term {
Terminator::Goto { target, args } => Terminator::Goto {
target: self.remap_block(*target),
args: args.iter().map(|a| self.remap_operand(a)).collect(),
},
Terminator::Branch {
cond,
then_block,
then_args,
else_block,
else_args,
} => Terminator::Branch {
cond: self.remap_operand(cond),
then_block: self.remap_block(*then_block),
then_args: then_args.iter().map(|a| self.remap_operand(a)).collect(),
else_block: self.remap_block(*else_block),
else_args: else_args.iter().map(|a| self.remap_operand(a)).collect(),
},
Terminator::Return { value } => {
Terminator::Goto {
target: continuation_block,
args: value.iter().map(|v| self.remap_operand(v)).collect(),
}
}
Terminator::Switch { discriminant, cases, default } => Terminator::Switch {
discriminant: self.remap_operand(discriminant),
cases: cases.iter().map(|(v, b)| (*v, self.remap_block(*b))).collect(),
default: self.remap_block(*default),
},
Terminator::UnitEnd { result } => Terminator::UnitEnd {
result: result.as_ref().map(|v| self.remap_operand(v)),
},
Terminator::UnitEarlyReturn { value } => Terminator::UnitEarlyReturn {
value: self.remap_operand(value),
},
}
}
}
pub fn inline_call_site(
caller: &IrCodeUnit,
callee: &IrCodeUnit,
site: &CallSite,
) -> Option<IrCodeUnit> {
let _caller_ctx = caller.function_context()?;
let callee_ctx = callee.function_context()?;
if !callee_ctx.descriptor_shapes.is_empty() {
return None;
}
let mut new_unit = caller.clone();
let remap = RemapContext {
value_offset: caller.value_count,
slot_offset: caller.slot_count,
block_offset: caller.blocks.len() as u32,
call_site_offset: caller.call_site_count,
};
let continuation_block_id = BlockId(remap.block_offset + callee.blocks.len() as u32);
let orig_block = &caller.blocks[site.block_idx];
let before_call: Vec<Instruction> = orig_block.instructions[..site.instr_idx].to_vec();
let after_call: Vec<Instruction> = orig_block.instructions[site.instr_idx + 1..].to_vec();
let orig_terminator = orig_block.terminator.clone();
let mut param_bindings: Vec<Instruction> = Vec::new();
let mut param_replacements: HashMap<ParamId, Operand> = HashMap::new();
for (i, (param_id, arg)) in callee_ctx.params.iter().zip(site.args.iter()).enumerate() {
let param_type = &callee_ctx.param_types[param_id.0 as usize];
let param_mode = &callee_ctx.param_modes[param_id.0 as usize];
if matches!(param_mode, ParamMode::Ref | ParamMode::Mut | ParamMode::Out) {
param_replacements.insert(*param_id, arg.clone());
} else {
let dest_value = remap.remap_value(ValueId(callee.value_count + i as u32));
let instr = if param_type.is_copy() {
Instruction::Copy {
dest: dest_value,
src: arg.clone(),
}
} else {
Instruction::Move {
dest: dest_value,
src: arg.clone(),
}
};
param_bindings.push(instr);
param_replacements.insert(*param_id, Operand::Value(dest_value));
}
}
let inlined_entry_block = remap.remap_block(BlockId(0));
new_unit.blocks[site.block_idx] = IrBlock {
id: BlockId(site.block_idx as u32),
params: orig_block.params.clone(),
instructions: before_call,
terminator: Terminator::Goto {
target: inlined_entry_block,
args: vec![],
},
};
for (i, block) in callee.blocks.iter().enumerate() {
let mut new_instructions: Vec<Instruction> = Vec::new();
if i == 0 {
new_instructions.extend(param_bindings.clone());
}
for instr in &block.instructions {
let remapped = remap.remap_instruction(instr);
let replaced = replace_params_in_instruction(&remapped, ¶m_replacements);
new_instructions.push(replaced);
}
let new_block = IrBlock {
id: remap.remap_block(block.id),
params: block.params.iter().map(|v| remap.remap_value(*v)).collect(),
instructions: new_instructions,
terminator: remap.remap_terminator(&block.terminator, continuation_block_id),
};
new_unit.blocks.push(new_block);
}
let cont_params = if callee_ctx.return_type != IrType::Unit {
vec![site.dest]
} else {
vec![]
};
let continuation_block = IrBlock {
id: continuation_block_id,
params: cont_params,
instructions: after_call,
terminator: orig_terminator,
};
new_unit.blocks.push(continuation_block);
let extra_values = callee.value_count + callee_ctx.params.len() as u32;
new_unit.value_count += extra_values;
new_unit.slot_count += callee.slot_count;
new_unit.call_site_count += callee.call_site_count;
new_unit.value_types.extend(callee.value_types.iter().cloned());
for param_id in &callee_ctx.params {
let ty = callee_ctx.param_types[param_id.0 as usize].clone();
new_unit.value_types.push(ty);
}
new_unit.slot_types.extend(callee.slot_types.iter().cloned());
for slot in &callee.tracked_slots {
new_unit.tracked_slots.push(remap.remap_slot(*slot));
}
Some(new_unit)
}
pub fn inline_module(module: &IrModule, directives: &[InlineDirective]) -> InlineResult {
let (requests, mut skipped) = resolve_directives(module, directives);
let mut current_module = module.clone();
let mut inlined_count = 0;
for request in &requests {
let caller_idx = current_module
.functions
.iter()
.position(|f| f.id.0 == request.caller.0);
let callee_idx = current_module
.functions
.iter()
.position(|f| f.id.0 == request.callee.0);
let (Some(caller_idx), Some(callee_idx)) = (caller_idx, callee_idx) else {
continue;
};
let caller = ¤t_module.functions[caller_idx];
let callee = ¤t_module.functions[callee_idx];
let call_sites = find_call_sites(caller, request.callee);
if call_sites.is_empty() {
let caller_name = caller.name.clone();
let callee_name = callee.name.clone();
skipped.push(InlineSkipReason::NoCallsFound {
caller: caller_name,
callee: callee_name,
});
continue;
}
let sites_to_inline: Vec<&CallSite> = match &request.filter {
CallSiteFilter::All => call_sites.iter().collect(),
CallSiteFilter::AtIndex(idx) => {
if *idx < call_sites.len() {
vec![&call_sites[*idx]]
} else {
let caller_name = caller.name.clone();
let callee_name = callee.name.clone();
skipped.push(InlineSkipReason::CallSiteNotFound {
caller: caller_name,
callee: callee_name,
index: *idx,
});
continue;
}
}
};
let mut updated_caller = current_module.functions[caller_idx].clone();
for site in sites_to_inline.into_iter().rev() {
let new_sites = find_call_sites(&updated_caller, request.callee);
if let Some(new_site) = new_sites.iter().find(|s| {
s.block_idx == site.block_idx && s.instr_idx == site.instr_idx
}) {
if let Some(inlined) = inline_call_site(&updated_caller, callee, new_site) {
updated_caller = inlined;
inlined_count += 1;
}
}
}
current_module.functions[caller_idx] = updated_caller;
}
InlineResult {
module: current_module,
inlined_count,
skipped,
}
}
pub fn inline_cross_module(
registry: &ModuleFunctionRegistry,
ctx: &CrossModuleInlineContext,
directives: &[InlineDirective],
) -> CrossModuleInlineResult {
let (requests, mut skipped) = resolve_cross_module_directives(ctx, directives);
let mut new_registry = registry.clone();
let mut inlined_count = 0;
for request in &requests {
let Some(caller) = new_registry.get_module_function_as_unit(request.caller.module, CodeUnitId(request.caller.func.0)) else {
continue;
};
let Some(callee) = registry.get_module_function_as_unit(request.callee.module, CodeUnitId(request.callee.func.0)) else {
continue;
};
let call_sites = find_cross_module_call_sites(caller, request.caller.module, request.callee);
if call_sites.is_empty() {
skipped.push(InlineSkipReason::NoCallsFound {
caller: caller.name.clone(),
callee: callee.name.clone(),
});
continue;
}
let sites_to_inline: Vec<&CallSite> = match &request.filter {
CallSiteFilter::All => call_sites.iter().collect(),
CallSiteFilter::AtIndex(idx) => {
if *idx < call_sites.len() {
vec![&call_sites[*idx]]
} else {
skipped.push(InlineSkipReason::CallSiteNotFound {
caller: caller.name.clone(),
callee: callee.name.clone(),
index: *idx,
});
continue;
}
}
};
let mut updated_caller = caller.clone();
for site in sites_to_inline.into_iter().rev() {
let new_sites = find_cross_module_call_sites(&updated_caller, request.caller.module, request.callee);
if let Some(new_site) = new_sites.iter().find(|s| {
s.block_idx == site.block_idx && s.instr_idx == site.instr_idx
}) {
if let Some(inlined) = inline_call_site(&updated_caller, callee, new_site) {
updated_caller = inlined;
inlined_count += 1;
}
}
}
new_registry.add_module_code_unit(request.caller.module, CodeUnitId(request.caller.func.0), std::sync::Arc::new(updated_caller));
}
CrossModuleInlineResult {
registry: new_registry,
inlined_count,
skipped,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_inline_directives() {
let source = r#"
// Comment
inline foo bar
inline baz qux at 2
inline-all helper
"#;
let directives = parse_inline_directives(source).unwrap();
assert_eq!(directives.len(), 3);
assert_eq!(
directives[0],
InlineDirective::Inline {
caller: "foo".to_string(),
callee: "bar".to_string(),
}
);
assert_eq!(
directives[1],
InlineDirective::InlineAt {
caller: "baz".to_string(),
callee: "qux".to_string(),
call_index: 2,
}
);
assert_eq!(
directives[2],
InlineDirective::InlineAll {
callee: "helper".to_string(),
}
);
}
#[test]
fn test_parse_cross_module_directives() {
let source = r#"
inline-cross main::caller base::callee
inline-cross-all helper::util
"#;
let directives = parse_inline_directives(source).unwrap();
assert_eq!(directives.len(), 2);
assert_eq!(
directives[0],
InlineDirective::InlineCross {
caller_module: "main".to_string(),
caller: "caller".to_string(),
callee_module: "base".to_string(),
callee: "callee".to_string(),
}
);
assert_eq!(
directives[1],
InlineDirective::InlineCrossAll {
callee_module: "helper".to_string(),
callee: "util".to_string(),
}
);
}
#[test]
fn test_parse_invalid_directive() {
let source = "invalid directive line";
let result = parse_inline_directives(source);
assert!(result.is_err());
}
#[test]
fn test_parse_invalid_cross_directive() {
let source = "inline-cross invalid_no_colons also_invalid";
let result = parse_inline_directives(source);
assert!(result.is_err());
}
}