use std::collections::HashMap;
use eyre::{Context as _, OptionExt as _};
use walrus::{
ir::*, ConstExpr, DataKind, FunctionId, GlobalId, MemoryId, Module, ValType,
};
use crate::{
generator::{shared_global::SharedGlobalFnsName, Generator, GeneratorCtx},
instrs::InstrRewrite as _,
unique_name::UniqueName,
util::{
ResultUtil, WalrusFID as _, WalrusUtilExport as _, WalrusUtilFuncs as _,
WalrusUtilModule as _,
},
};
#[derive(Debug, Clone)]
pub struct LoweringResult {
pub combined_memory: MemoryId,
pub offset_globals: Vec<Option<GlobalId>>,
}
#[derive(Debug, Default)]
pub struct MultiMemoryLowering {
result: Option<LoweringResult>,
before_memory_count: usize,
memory_size_fns: Vec<FunctionId>,
memory_grow_fns: Vec<FunctionId>,
memory_idx_map: HashMap<MemoryId, usize>,
lock_read_acquire: Option<FunctionId>,
lock_read_release: Option<FunctionId>,
lock_write_acquire: Option<FunctionId>,
lock_write_release: Option<FunctionId>,
}
impl MultiMemoryLowering {
pub fn new() -> Self {
Self::default()
}
pub fn result(&self) -> Option<&LoweringResult> {
self.result.as_ref()
}
pub fn lower_memory(
&mut self,
module: &mut Module,
ctx: &GeneratorCtx,
) -> eyre::Result<()> {
let mem_count = module.memories.iter().count();
if mem_count <= 1 {
log::info!("MultiMemoryLowering: skipping (only {} memory)", mem_count);
return Ok(());
}
self.before_memory_count = mem_count;
self.build_memory_idx_map(module);
if ctx.threads {
self.resolve_lock_fns(module)?;
}
let (combined_initial, combined_max, is_shared, import_info) =
Self::compute_combined_params(module)?;
let offset_globals = self.make_offset_globals(module)?;
self.adjust_data_segments(module, &offset_globals)?;
self.create_memory_size_fns(module, &offset_globals)?;
self.create_memory_grow_fns(module, &offset_globals, ctx.threads)?;
self.rewrite_instructions(module, &offset_globals, ctx.threads)?;
let combined_id = self.replace_memories(
module,
combined_initial,
combined_max,
is_shared,
import_info,
)?;
self.result = Some(LoweringResult {
combined_memory: combined_id,
offset_globals,
});
if ctx.threads {
self.replace_globals_with_shared_alt(module, ctx)
.wrap_err("Failed to replace offset globals with shared alternatives")?;
}
self.cleanup_vfs_locker(module, ctx)?;
Ok(())
}
fn build_memory_idx_map(&mut self, module: &Module) {
self.memory_idx_map.clear();
for (i, mem) in module.memories.iter().enumerate() {
self.memory_idx_map.insert(mem.id(), i);
}
}
fn resolve_lock_fns(&mut self, module: &Module) -> eyre::Result<()> {
for export in module.exports.iter() {
match export.name.as_str() {
"__wasip1_vfs_memory_lock_read_acquire" => {
if let walrus::ExportItem::Function(fid) = export.item {
self.lock_read_acquire = Some(fid);
}
}
"__wasip1_vfs_memory_lock_read_release" => {
if let walrus::ExportItem::Function(fid) = export.item {
self.lock_read_release = Some(fid);
}
}
"__wasip1_vfs_memory_lock_write_acquire" => {
if let walrus::ExportItem::Function(fid) = export.item {
self.lock_write_acquire = Some(fid);
}
}
"__wasip1_vfs_memory_lock_write_release" => {
if let walrus::ExportItem::Function(fid) = export.item {
self.lock_write_release = Some(fid);
}
}
_ => {}
}
}
Ok(())
}
fn compute_combined_params(
module: &Module,
) -> eyre::Result<(u64, Option<u64>, bool, Option<(String, String)>)> {
let mut total_initial: u64 = 0;
let mut total_max: u64 = 0;
let mut has_max = false;
let mut is_shared = false;
let mut import_info = None;
for (i, mem) in module.memories.iter().enumerate() {
total_initial += mem.initial;
if let Some(max) = mem.maximum {
total_max += max;
has_max = true;
}
if i == 0 {
is_shared = mem.shared;
if let Some(import_id) = mem.import {
let import = module.imports.get(import_id);
import_info =
Some((import.module.to_string(), import.name.to_string()));
}
}
}
let max = if has_max {
Some(total_max.min(65536))
} else {
None
};
Ok((total_initial, max, is_shared, import_info))
}
fn make_offset_globals(
&self,
module: &mut Module,
) -> eyre::Result<Vec<Option<GlobalId>>> {
let mut offset_globals = Vec::new();
let mut running_offset: u64 = 0;
let initials: Vec<u64> = module.memories.iter().map(|m| m.initial).collect();
for (i, initial) in initials.into_iter().enumerate() {
if i == 0 {
offset_globals.push(None);
} else {
let byte_offset = (running_offset * 65536) as i32;
let gid = module.globals.add_local(
ValType::I32,
true,
false,
ConstExpr::Value(Value::I32(byte_offset)),
);
offset_globals.push(Some(gid));
}
running_offset += initial;
}
Ok(offset_globals)
}
fn adjust_data_segments(
&self,
module: &mut Module,
offset_globals: &[Option<GlobalId>],
) -> eyre::Result<()> {
let adjustments: Vec<_> = module
.data
.iter()
.filter_map(|data| {
if let DataKind::Active { memory, offset: _ } = &data.kind {
let idx = self.memory_idx_map.get(memory)?;
if *idx > 0 {
let byte_offset =
self.get_initial_offset_from_globals(module, offset_globals, *idx);
Some((data.id(), byte_offset as i32))
} else {
None
}
} else {
None
}
})
.collect();
for (data_id, add_offset) in adjustments {
let data = module.data.get_mut(data_id);
if let DataKind::Active { offset, .. } = &mut data.kind {
if let ConstExpr::Value(Value::I32(v)) = offset {
*v += add_offset;
}
}
}
Ok(())
}
fn get_initial_offset_from_globals(
&self,
module: &Module,
offset_globals: &[Option<GlobalId>],
idx: usize,
) -> u64 {
if idx == 0 {
return 0;
}
if let Some(Some(gid)) = offset_globals.get(idx) {
if let walrus::GlobalKind::Local(ConstExpr::Value(Value::I32(v))) =
&module.globals.get(*gid).kind
{
return *v as u64;
}
}
0
}
fn create_memory_size_fns(
&mut self,
module: &mut Module,
offset_globals: &[Option<GlobalId>],
) -> eyre::Result<()> {
self.memory_size_fns.clear();
let mem_count = self.before_memory_count;
for idx in 0..mem_count {
let is_last = idx == mem_count - 1;
let fid = if mem_count == 1 {
module.add_func(&[], &[ValType::I32], |builder, _| {
builder.func_body().i32_const(0);
Ok(())
})?
} else if idx == 0 {
let next_gid = offset_globals[1]
.ok_or_eyre("Expected offset global for memory 1")?;
module.add_func(&[], &[ValType::I32], |builder, _| {
builder
.func_body()
.global_get(next_gid)
.i32_const(16)
.binop(BinaryOp::I32ShrU);
Ok(())
})?
} else if is_last {
let this_gid = offset_globals[idx]
.ok_or_eyre("Expected offset global for last memory")?;
let dummy_mem_id = module.memories.iter().next().unwrap().id();
module.add_func(&[], &[ValType::I32], move |builder, _| {
builder
.func_body()
.memory_size(dummy_mem_id)
.global_get(this_gid)
.i32_const(16)
.binop(BinaryOp::I32ShrU)
.binop(BinaryOp::I32Sub);
Ok(())
})?
} else {
let this_gid = offset_globals[idx]
.ok_or_eyre("Expected offset global")?;
let next_gid = offset_globals[idx + 1]
.ok_or_eyre("Expected next offset global")?;
module.add_func(&[], &[ValType::I32], |builder, _| {
builder
.func_body()
.global_get(next_gid)
.global_get(this_gid)
.binop(BinaryOp::I32Sub)
.i32_const(16)
.binop(BinaryOp::I32ShrU);
Ok(())
})?
};
self.memory_size_fns.push(fid);
}
Ok(())
}
fn create_memory_grow_fns(
&mut self,
module: &mut Module,
offset_globals: &[Option<GlobalId>],
threads: bool,
) -> eyre::Result<()> {
self.memory_grow_fns.clear();
let mem_count = self.before_memory_count;
let size_fns = self.memory_size_fns.clone();
for idx in 0..mem_count {
let size_fn = size_fns[idx];
let globals_to_update: Vec<GlobalId> = ((idx + 1)..offset_globals.len())
.filter_map(|i| offset_globals[i])
.collect();
let next_offset_global = if idx + 1 < mem_count { offset_globals[idx + 1] } else { None };
let lock_write_acquire = if threads { self.lock_write_acquire } else { None };
let lock_write_release = if threads { self.lock_write_release } else { None };
let dummy_mem_id = module.memories.iter().next().unwrap().id();
let return_size = module.locals.add(ValType::I32);
let combined_size = module.locals.add(ValType::I32);
let shift_bytes = module.locals.add(ValType::I32);
let fid = module.add_func(&[ValType::I32], &[ValType::I32], move |mut builder, args| {
let page_delta = args[0];
let mut body = builder.func_body();
body.call(size_fn).local_set(return_size);
if let Some(acq) = lock_write_acquire { body.call(acq); }
body.memory_size(dummy_mem_id).local_set(combined_size);
body.local_get(page_delta).memory_grow(dummy_mem_id);
body.i32_const(-1).binop(BinaryOp::I32Eq);
body.if_else(None, |then| {
if let Some(rel) = lock_write_release { then.call(rel); }
then.i32_const(-1).return_();
}, |_| {});
if let Some(next_gid) = next_offset_global {
body.local_get(page_delta).i32_const(16).binop(BinaryOp::I32Shl).local_set(shift_bytes);
body.global_get(next_gid).local_get(shift_bytes).binop(BinaryOp::I32Add);
body.global_get(next_gid);
body.local_get(combined_size).i32_const(16).binop(BinaryOp::I32Shl).global_get(next_gid).binop(BinaryOp::I32Sub);
body.memory_copy(dummy_mem_id, dummy_mem_id);
for gid in &globals_to_update {
body.global_get(*gid).local_get(shift_bytes).binop(BinaryOp::I32Add).global_set(*gid);
}
}
if let Some(rel) = lock_write_release { body.call(rel); }
body.local_get(return_size);
Ok(())
})?;
self.memory_grow_fns.push(fid);
}
Ok(())
}
fn rewrite_instructions(
&self,
module: &mut Module,
offset_globals: &[Option<GlobalId>],
threads: bool,
) -> eyre::Result<()> {
let memory_idx_map = self.memory_idx_map.clone();
let grow_fns = self.memory_grow_fns.clone();
let size_fns = self.memory_size_fns.clone();
let func_ids: Vec<_> = module.funcs.iter_local().map(|(id, _)| id).collect();
let skip_fids: std::collections::HashSet<_> = grow_fns
.iter()
.chain(size_fns.iter())
.copied()
.collect();
for fid in func_ids {
if skip_fids.contains(&fid) {
continue;
}
let tmp_i32_1 = module.locals.add(ValType::I32);
let tmp_i32_2 = module.locals.add(ValType::I32);
let tmp_i32_3 = module.locals.add(ValType::I32);
let tmp_i64_1 = module.locals.add(ValType::I64);
let tmp_i64_2 = module.locals.add(ValType::I64);
let tmp_f32_1 = module.locals.add(ValType::F32);
let tmp_f64_1 = module.locals.add(ValType::F64);
let tmp_v128_1 = module.locals.add(ValType::V128);
let func = module.funcs.get_mut(fid).kind.unwrap_local_mut();
Self::rewrite_func_instructions(
func,
&memory_idx_map,
offset_globals,
&grow_fns,
&size_fns,
threads,
self.lock_read_acquire,
self.lock_read_release,
[tmp_i32_1, tmp_i32_2, tmp_i32_3],
[tmp_i64_1, tmp_i64_2],
tmp_f32_1,
tmp_f64_1,
tmp_v128_1,
)?;
}
Ok(())
}
fn store_kind_val_type(kind: &StoreKind) -> ValType {
match kind {
StoreKind::I32 { .. } | StoreKind::I32_8 { .. } | StoreKind::I32_16 { .. } => ValType::I32,
StoreKind::I64 { .. } | StoreKind::I64_8 { .. } | StoreKind::I64_16 { .. } | StoreKind::I64_32 { .. } => ValType::I64,
StoreKind::F32 => ValType::F32,
StoreKind::F64 => ValType::F64,
StoreKind::V128 => ValType::V128,
}
}
fn load_kind_val_type(kind: &LoadKind) -> ValType {
match kind {
LoadKind::I32 { .. } | LoadKind::I32_8 { .. } | LoadKind::I32_16 { .. } => ValType::I32,
LoadKind::I64 { .. } | LoadKind::I64_8 { .. } | LoadKind::I64_16 { .. } | LoadKind::I64_32 { .. } => ValType::I64,
LoadKind::F32 => ValType::F32,
LoadKind::F64 => ValType::F64,
LoadKind::V128 => ValType::V128,
}
}
fn atomic_width_val_type(width: &AtomicWidth) -> ValType {
match width {
AtomicWidth::I32 | AtomicWidth::I32_8 | AtomicWidth::I32_16 => ValType::I32,
AtomicWidth::I64 | AtomicWidth::I64_8 | AtomicWidth::I64_16 | AtomicWidth::I64_32 => ValType::I64,
}
}
fn rewrite_func_instructions(
func: &mut walrus::LocalFunction,
memory_idx_map: &HashMap<MemoryId, usize>,
offset_globals: &[Option<GlobalId>],
grow_fns: &[FunctionId],
size_fns: &[FunctionId],
threads: bool,
lock_acquire: Option<FunctionId>,
lock_release: Option<FunctionId>,
tmp_i32: [walrus::LocalId; 3],
tmp_i64: [walrus::LocalId; 2],
tmp_f32: walrus::LocalId,
tmp_f64: walrus::LocalId,
tmp_v128: walrus::LocalId,
) -> eyre::Result<()> {
let get_tmp1 = |val_type: ValType| match val_type {
ValType::I32 => tmp_i32[0],
ValType::I64 => tmp_i64[0],
ValType::F32 => tmp_f32,
ValType::F64 => tmp_f64,
ValType::V128 => tmp_v128,
_ => unreachable!(),
};
let get_tmp2 = |val_type: ValType| match val_type {
ValType::I32 => tmp_i32[1],
ValType::I64 => tmp_i64[1],
ValType::F32 => tmp_f32,
ValType::F64 => tmp_f64,
ValType::V128 => tmp_v128,
_ => unreachable!(),
};
let get_tmp3 = |val_type: ValType| match val_type {
ValType::I32 => tmp_i32[2],
_ => unreachable!(),
};
let mut seq_ids = vec![func.entry_block()];
let mut visited = std::collections::HashSet::new();
while let Some(seq_id) = seq_ids.pop() {
if !visited.insert(seq_id) {
continue;
}
let seq = func.block_mut(seq_id);
let mut new_instrs = Vec::with_capacity(seq.instrs.len() * 2);
for (instr, loc) in std::mem::take(&mut seq.instrs) {
match &instr {
Instr::Block(b) => seq_ids.push(b.seq),
Instr::Loop(l) => seq_ids.push(l.seq),
Instr::IfElse(ie) => {
seq_ids.push(ie.consequent);
seq_ids.push(ie.alternative);
}
Instr::BrIf(bi) => seq_ids.push(bi.block),
Instr::Br(b) => seq_ids.push(b.block),
Instr::BrTable(bt) => {
seq_ids.push(bt.default);
for blk in &bt.blocks {
seq_ids.push(*blk);
}
}
_ => {}
}
match &instr {
Instr::MemoryGrow(MemoryGrow { memory }) => {
if let Some(&idx) = memory_idx_map.get(memory) {
new_instrs.push((Instr::Call(Call { func: grow_fns[idx] }), loc));
} else {
new_instrs.push((instr.clone(), loc));
}
}
Instr::MemorySize(MemorySize { memory }) => {
if let Some(&idx) = memory_idx_map.get(memory) {
new_instrs.push((Instr::Call(Call { func: size_fns[idx] }), loc));
} else {
new_instrs.push((instr.clone(), loc));
}
}
Instr::Load(Load { memory, kind, .. }) => {
let idx = memory_idx_map.get(memory).copied().unwrap_or(0);
if idx > 0 {
if let Some(Some(offset_gid)) = offset_globals.get(idx) {
let tmp_addr = get_tmp1(ValType::I32);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_addr }), loc));
if threads {
if let Some(acq) = lock_acquire {
new_instrs.push((Instr::Call(Call { func: acq }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_addr }), loc));
new_instrs.push((Instr::GlobalGet(GlobalGet { global: *offset_gid }), loc));
new_instrs.push((Instr::Binop(Binop { op: BinaryOp::I32Add }), loc));
new_instrs.push((instr.clone(), loc));
let tmp_val = get_tmp2(Self::load_kind_val_type(kind));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_val }), loc));
if threads {
if let Some(rel) = lock_release {
new_instrs.push((Instr::Call(Call { func: rel }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_val }), loc));
continue;
}
}
new_instrs.push((instr.clone(), loc));
}
Instr::LoadSimd(LoadSimd { memory, .. }) => {
let idx = memory_idx_map.get(memory).copied().unwrap_or(0);
if idx > 0 {
if let Some(Some(offset_gid)) = offset_globals.get(idx) {
let tmp_addr = get_tmp1(ValType::I32);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_addr }), loc));
if threads {
if let Some(acq) = lock_acquire {
new_instrs.push((Instr::Call(Call { func: acq }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_addr }), loc));
new_instrs.push((Instr::GlobalGet(GlobalGet { global: *offset_gid }), loc));
new_instrs.push((Instr::Binop(Binop { op: BinaryOp::I32Add }), loc));
new_instrs.push((instr.clone(), loc));
let tmp_val = get_tmp1(ValType::V128);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_val }), loc));
if threads {
if let Some(rel) = lock_release {
new_instrs.push((Instr::Call(Call { func: rel }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_val }), loc));
continue;
}
}
new_instrs.push((instr.clone(), loc));
}
Instr::Store(Store { memory, kind, .. }) => {
let idx = memory_idx_map.get(memory).copied().unwrap_or(0);
if idx > 0 {
if let Some(Some(offset_gid)) = offset_globals.get(idx) {
let tmp_val = get_tmp1(Self::store_kind_val_type(kind));
let tmp_addr = get_tmp2(ValType::I32);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_val }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_addr }), loc));
if threads {
if let Some(acq) = lock_acquire {
new_instrs.push((Instr::Call(Call { func: acq }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_addr }), loc));
new_instrs.push((Instr::GlobalGet(GlobalGet { global: *offset_gid }), loc));
new_instrs.push((Instr::Binop(Binop { op: BinaryOp::I32Add }), loc));
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_val }), loc));
new_instrs.push((instr.clone(), loc));
if threads {
if let Some(rel) = lock_release {
new_instrs.push((Instr::Call(Call { func: rel }), loc));
}
}
continue;
}
}
new_instrs.push((instr.clone(), loc));
}
Instr::AtomicRmw(AtomicRmw { memory, width, .. }) => {
let idx = memory_idx_map.get(memory).copied().unwrap_or(0);
if idx > 0 {
if let Some(Some(offset_gid)) = offset_globals.get(idx) {
let tmp_val = get_tmp1(Self::atomic_width_val_type(width));
let tmp_addr = get_tmp2(ValType::I32);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_val }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_addr }), loc));
if threads {
if let Some(acq) = lock_acquire {
new_instrs.push((Instr::Call(Call { func: acq }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_addr }), loc));
new_instrs.push((Instr::GlobalGet(GlobalGet { global: *offset_gid }), loc));
new_instrs.push((Instr::Binop(Binop { op: BinaryOp::I32Add }), loc));
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_val }), loc));
new_instrs.push((instr.clone(), loc));
let tmp_res = tmp_val;
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_res }), loc));
if threads {
if let Some(rel) = lock_release {
new_instrs.push((Instr::Call(Call { func: rel }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_res }), loc));
continue;
}
}
new_instrs.push((instr.clone(), loc));
}
Instr::Cmpxchg(Cmpxchg { memory, width, .. }) => {
let idx = memory_idx_map.get(memory).copied().unwrap_or(0);
if idx > 0 {
if let Some(Some(offset_gid)) = offset_globals.get(idx) {
let val_type = Self::atomic_width_val_type(width);
let tmp_repl = get_tmp1(val_type);
let tmp_exp = get_tmp2(val_type);
let tmp_addr = get_tmp3(ValType::I32);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_repl }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_exp }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_addr }), loc));
if threads {
if let Some(acq) = lock_acquire {
new_instrs.push((Instr::Call(Call { func: acq }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_addr }), loc));
new_instrs.push((Instr::GlobalGet(GlobalGet { global: *offset_gid }), loc));
new_instrs.push((Instr::Binop(Binop { op: BinaryOp::I32Add }), loc));
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_exp }), loc));
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_repl }), loc));
new_instrs.push((instr.clone(), loc));
let tmp_res = tmp_repl;
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_res }), loc));
if threads {
if let Some(rel) = lock_release {
new_instrs.push((Instr::Call(Call { func: rel }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_res }), loc));
continue;
}
}
new_instrs.push((instr.clone(), loc));
}
Instr::MemoryCopy(MemoryCopy { src, dst }) => {
let src_idx = memory_idx_map.get(src).copied().unwrap_or(0);
let dst_idx = memory_idx_map.get(dst).copied().unwrap_or(0);
let src_off = offset_globals.get(src_idx).copied().flatten();
let dst_off = offset_globals.get(dst_idx).copied().flatten();
if src_off.is_some() || dst_off.is_some() {
let tmp_len = get_tmp1(ValType::I32);
let tmp_src = get_tmp2(ValType::I32);
let tmp_dst = get_tmp3(ValType::I32);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_len }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_src }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_dst }), loc));
if threads {
if let Some(acq) = lock_acquire {
new_instrs.push((Instr::Call(Call { func: acq }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_dst }), loc));
if let Some(d_off) = dst_off {
new_instrs.push((Instr::GlobalGet(GlobalGet { global: d_off }), loc));
new_instrs.push((Instr::Binop(Binop { op: BinaryOp::I32Add }), loc));
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_src }), loc));
if let Some(s_off) = src_off {
new_instrs.push((Instr::GlobalGet(GlobalGet { global: s_off }), loc));
new_instrs.push((Instr::Binop(Binop { op: BinaryOp::I32Add }), loc));
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_len }), loc));
new_instrs.push((instr.clone(), loc));
if threads {
if let Some(rel) = lock_release {
new_instrs.push((Instr::Call(Call { func: rel }), loc));
}
}
continue;
}
new_instrs.push((instr.clone(), loc));
}
Instr::MemoryFill(MemoryFill { memory }) => {
let idx = memory_idx_map.get(memory).copied().unwrap_or(0);
if idx > 0 {
if let Some(Some(offset_gid)) = offset_globals.get(idx) {
let tmp_len = get_tmp1(ValType::I32);
let tmp_val = get_tmp2(ValType::I32);
let tmp_dst = get_tmp3(ValType::I32);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_len }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_val }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_dst }), loc));
if threads {
if let Some(acq) = lock_acquire {
new_instrs.push((Instr::Call(Call { func: acq }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_dst }), loc));
new_instrs.push((Instr::GlobalGet(GlobalGet { global: *offset_gid }), loc));
new_instrs.push((Instr::Binop(Binop { op: BinaryOp::I32Add }), loc));
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_val }), loc));
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_len }), loc));
new_instrs.push((instr.clone(), loc));
if threads {
if let Some(rel) = lock_release {
new_instrs.push((Instr::Call(Call { func: rel }), loc));
}
}
continue;
}
}
new_instrs.push((instr.clone(), loc));
}
Instr::MemoryInit(MemoryInit { memory, data: _ }) => {
let idx = memory_idx_map.get(memory).copied().unwrap_or(0);
if idx > 0 {
if let Some(Some(offset_gid)) = offset_globals.get(idx) {
let tmp_len = get_tmp1(ValType::I32);
let tmp_src = get_tmp2(ValType::I32);
let tmp_dst = get_tmp3(ValType::I32);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_len }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_src }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_dst }), loc));
if threads {
if let Some(acq) = lock_acquire {
new_instrs.push((Instr::Call(Call { func: acq }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_dst }), loc));
new_instrs.push((Instr::GlobalGet(GlobalGet { global: *offset_gid }), loc));
new_instrs.push((Instr::Binop(Binop { op: BinaryOp::I32Add }), loc));
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_src }), loc));
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_len }), loc));
new_instrs.push((instr.clone(), loc));
if threads {
if let Some(rel) = lock_release {
new_instrs.push((Instr::Call(Call { func: rel }), loc));
}
}
continue;
}
}
new_instrs.push((instr.clone(), loc));
}
Instr::AtomicWait(AtomicWait { memory, sixty_four, .. }) => {
let idx = memory_idx_map.get(memory).copied().unwrap_or(0);
if idx > 0 {
if let Some(Some(offset_gid)) = offset_globals.get(idx) {
let tmp_timeout = get_tmp1(ValType::I64);
let tmp_expected = if *sixty_four {
get_tmp2(ValType::I64)
} else {
get_tmp1(ValType::I32)
};
let tmp_addr = get_tmp2(ValType::I32);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_timeout }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_expected }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_addr }), loc));
if threads {
if let Some(acq) = lock_acquire {
new_instrs.push((Instr::Call(Call { func: acq }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_addr }), loc));
new_instrs.push((Instr::GlobalGet(GlobalGet { global: *offset_gid }), loc));
new_instrs.push((Instr::Binop(Binop { op: BinaryOp::I32Add }), loc));
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_expected }), loc));
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_timeout }), loc));
new_instrs.push((instr.clone(), loc));
let tmp_res = get_tmp3(ValType::I32);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_res }), loc));
if threads {
if let Some(rel) = lock_release {
new_instrs.push((Instr::Call(Call { func: rel }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_res }), loc));
continue;
}
}
new_instrs.push((instr.clone(), loc));
}
Instr::AtomicNotify(AtomicNotify { memory, .. }) => {
let idx = memory_idx_map.get(memory).copied().unwrap_or(0);
if idx > 0 {
if let Some(Some(offset_gid)) = offset_globals.get(idx) {
let tmp_count = get_tmp1(ValType::I32);
let tmp_addr = get_tmp2(ValType::I32);
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_count }), loc));
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_addr }), loc));
if threads {
if let Some(acq) = lock_acquire {
new_instrs.push((Instr::Call(Call { func: acq }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_addr }), loc));
new_instrs.push((Instr::GlobalGet(GlobalGet { global: *offset_gid }), loc));
new_instrs.push((Instr::Binop(Binop { op: BinaryOp::I32Add }), loc));
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_count }), loc));
new_instrs.push((instr.clone(), loc));
let tmp_res = tmp_count;
new_instrs.push((Instr::LocalSet(LocalSet { local: tmp_res }), loc));
if threads {
if let Some(rel) = lock_release {
new_instrs.push((Instr::Call(Call { func: rel }), loc));
}
}
new_instrs.push((Instr::LocalGet(LocalGet { local: tmp_res }), loc));
continue;
}
}
new_instrs.push((instr.clone(), loc));
}
_ => {
new_instrs.push((instr.clone(), loc));
}
}
}
func.block_mut(seq_id).instrs = new_instrs;
}
Ok(())
}
fn replace_memories(
&self,
module: &mut Module,
initial: u64,
max: Option<u64>,
shared: bool,
import_info: Option<(String, String)>,
) -> eyre::Result<MemoryId> {
let mem_ids: Vec<MemoryId> = module.memories.iter().map(|m| m.id()).collect();
let export_ids: Vec<_> = module
.exports
.iter()
.filter(|e| matches!(e.item, walrus::ExportItem::Memory(_)))
.map(|e| e.id())
.collect();
let had_exports = !export_ids.is_empty();
for eid in export_ids {
module.exports.delete(eid);
}
let import_ids: Vec<_> = module
.imports
.iter()
.filter(|i| matches!(i.kind, walrus::ImportKind::Memory(_)))
.map(|i| i.id())
.collect();
for iid in import_ids {
module.imports.delete(iid);
}
for mid in &mem_ids {
module.memories.delete(*mid);
}
let combined = module.memories.add_local(shared, false, initial, max, None);
if had_exports {
module.exports.add("memory", combined);
}
if let Some((mod_name, base_name)) = import_info {
let import_id = module.imports.add(&mod_name, &base_name, combined);
module.memories.get_mut(combined).import = Some(import_id);
}
let all_local_fids: Vec<_> = module.funcs.iter_local().map(|(id, _)| id).collect();
for fid in all_local_fids {
if let walrus::FunctionKind::Local(func) = &mut module.funcs.get_mut(fid).kind {
let mut seq_ids = vec![func.entry_block()];
let mut visited = std::collections::HashSet::new();
while let Some(seq_id) = seq_ids.pop() {
if !visited.insert(seq_id) { continue; }
let seq = func.block_mut(seq_id);
for (instr, _) in &mut seq.instrs {
match instr {
Instr::Block(b) => seq_ids.push(b.seq),
Instr::Loop(l) => seq_ids.push(l.seq),
Instr::IfElse(ie) => { seq_ids.push(ie.consequent); seq_ids.push(ie.alternative); }
Instr::BrIf(bi) => seq_ids.push(bi.block),
Instr::Br(b) => seq_ids.push(b.block),
Instr::BrTable(bt) => { seq_ids.push(bt.default); seq_ids.extend(&bt.blocks); }
Instr::MemorySize(m) => m.memory = combined,
Instr::MemoryGrow(m) => m.memory = combined,
Instr::MemoryCopy(m) => { m.src = combined; m.dst = combined; },
Instr::MemoryFill(m) => m.memory = combined,
Instr::MemoryInit(m) => m.memory = combined,
Instr::Load(m) => m.memory = combined,
Instr::Store(m) => m.memory = combined,
Instr::AtomicRmw(m) => m.memory = combined,
Instr::Cmpxchg(m) => m.memory = combined,
Instr::AtomicWait(m) => m.memory = combined,
Instr::AtomicNotify(m) => m.memory = combined,
Instr::LoadSimd(m) => m.memory = combined,
Instr::AtomicFence(_) => {},
_ => {}
}
}
}
}
}
let all_local_fids: Vec<_> = module.funcs.iter_local().map(|(id, _)| id).collect();
for fid in all_local_fids {
if let walrus::FunctionKind::Local(func) = &module.funcs.get(fid).kind {
let mut seq_ids = vec![func.entry_block()];
let mut visited = std::collections::HashSet::new();
while let Some(seq_id) = seq_ids.pop() {
if !visited.insert(seq_id) { continue; }
let seq = func.block(seq_id);
for (instr, _) in &seq.instrs {
match instr {
Instr::Block(b) => seq_ids.push(b.seq),
Instr::Loop(l) => seq_ids.push(l.seq),
Instr::IfElse(ie) => { seq_ids.push(ie.consequent); seq_ids.push(ie.alternative); }
Instr::BrIf(bi) => seq_ids.push(bi.block),
Instr::Br(b) => seq_ids.push(b.block),
Instr::BrTable(bt) => { seq_ids.push(bt.default); seq_ids.extend(&bt.blocks); }
Instr::MemorySize(m) => { if mem_ids.contains(&m.memory) { panic!("Leaked MemoryId in MemorySize"); } },
Instr::MemoryGrow(m) => { if mem_ids.contains(&m.memory) { panic!("Leaked MemoryId in MemoryGrow"); } },
Instr::MemoryInit(m) => { if mem_ids.contains(&m.memory) { panic!("Leaked MemoryId in MemoryInit"); } },
Instr::MemoryFill(m) => { if mem_ids.contains(&m.memory) { panic!("Leaked MemoryId in MemoryFill"); } },
Instr::Load(m) => { if mem_ids.contains(&m.memory) { panic!("Leaked MemoryId in Load"); } },
Instr::Store(m) => { if mem_ids.contains(&m.memory) { panic!("Leaked MemoryId in Store"); } },
Instr::AtomicRmw(m) => { if mem_ids.contains(&m.memory) { panic!("Leaked MemoryId in AtomicRmw"); } },
Instr::Cmpxchg(m) => { if mem_ids.contains(&m.memory) { panic!("Leaked MemoryId in Cmpxchg"); } },
Instr::AtomicWait(m) => { if mem_ids.contains(&m.memory) { panic!("Leaked MemoryId in AtomicWait"); } },
Instr::AtomicNotify(m) => { if mem_ids.contains(&m.memory) { panic!("Leaked MemoryId in AtomicNotify"); } },
Instr::LoadSimd(m) => { if mem_ids.contains(&m.memory) { panic!("Leaked MemoryId in LoadSimd"); } },
Instr::MemoryCopy(m) => {
if mem_ids.contains(&m.src) { panic!("Leaked src in MemoryCopy"); }
if mem_ids.contains(&m.dst) { panic!("Leaked dst in MemoryCopy"); }
}
_ => {}
}
}
}
}
}
let data_ids: Vec<_> = module.data.iter().map(|d| d.id()).collect();
for did in data_ids {
let data = module.data.get_mut(did);
if let DataKind::Active { memory, .. } = &mut data.kind {
*memory = combined;
}
}
Ok(combined)
}
fn replace_globals_with_shared_alt(
&self,
module: &mut Module,
ctx: &GeneratorCtx,
) -> eyre::Result<()> {
let result = self.result.as_ref().ok_or_eyre(
"replace_globals_with_shared_alt called before lowering",
)?;
let mut global_mappings: Vec<(GlobalId, &str)> = Vec::new();
for (i, og) in result.offset_globals.iter().enumerate() {
if let Some(gid) = og {
if i <= ctx.target_names.len() {
global_mappings.push((*gid, ctx.target_names[i - 1].as_ref()));
} else {
global_mappings.push((*gid, "vfs_external_memory_manager"));
}
}
}
if global_mappings.is_empty() {
return Ok(());
}
log::info!("Replacing {} offset globals with shared alternatives:", global_mappings.len());
let init_fn = ctx.starts.init_offset_global.get_fid(&module.exports)?;
let grow_fn_set: std::collections::HashSet<FunctionId> =
self.memory_grow_fns.iter().copied().collect();
let size_fn_set: std::collections::HashSet<FunctionId> =
self.memory_size_fns.iter().copied().collect();
for (global_id, target_name) in &global_mappings {
let global_id = *global_id;
let init_value = match module.globals.get(global_id).kind {
walrus::GlobalKind::Local(ConstExpr::Value(Value::I32(v))) => v,
_ => eyre::bail!("Offset global is not a mutable i32 local"),
};
log::info!(" - {}: initial value = {}", target_name, init_value);
let alt_set = UniqueName::SharedGlobalFnsForTarget(
&SharedGlobalFnsName::GlobalAltSet,
target_name,
)
.get_fid(&module.exports)
.wrap_err_with(|| format!("Missing GlobalAltSet for {target_name}"))?;
let alt_set_with_lock = UniqueName::SharedGlobalFnsForTarget(
&SharedGlobalFnsName::GlobalAltSetWithLock,
target_name,
)
.get_fid(&module.exports)
.wrap_err_with(|| format!("Missing GlobalAltSetWithLock for {target_name}"))?;
let alt_init_once = UniqueName::SharedGlobalFnsForTarget(
&SharedGlobalFnsName::GlobalAltInitOnce,
target_name,
)
.get_fid(&module.exports)
.wrap_err_with(|| format!("Missing GlobalAltInitOnce for {target_name}"))?;
let alt_get_with_lock = UniqueName::SharedGlobalFnsForTarget(
&SharedGlobalFnsName::GlobalAltGet,
target_name,
)
.get_fid(&module.exports)
.wrap_err_with(|| format!("Missing GlobalAltGet for {target_name}"))?;
let alt_get_no_wait = UniqueName::SharedGlobalFnsForTarget(
&SharedGlobalFnsName::GlobalAltGetNoWait,
target_name,
)
.get_fid(&module.exports)
.wrap_err_with(|| format!("Missing GlobalAltGetNoWait for {target_name}"))?;
let alt_pos = UniqueName::SharedGlobalFnsForTarget(
&SharedGlobalFnsName::GlobalAltPos,
target_name,
)
.get_fid(&module.exports)
.wrap_err_with(|| format!("Missing GlobalAltPos for {target_name}"))?;
module
.exports
.erase_with(alt_pos, ctx.unstable_print_debug)?;
let init_local = module.funcs.get_mut(init_fn).kind.unwrap_local_mut();
init_local
.builder_mut()
.func_body()
.i32_const(init_value)
.call(alt_init_once);
for grow_fid in &self.memory_grow_fns {
module.funcs.flat_rewrite(
|instr, _| match instr {
Instr::GlobalGet(GlobalGet { global }) if *global == global_id => {
*instr = Instr::Call(Call {
func: alt_get_no_wait,
});
}
Instr::GlobalSet(GlobalSet { global }) if *global == global_id => {
*instr = Instr::Call(Call {
func: alt_set,
});
}
_ => {}
},
*grow_fid,
true,
)?;
}
for size_fid in &self.memory_size_fns {
module.funcs.flat_rewrite(
|instr, _| match instr {
Instr::GlobalGet(GlobalGet { global }) if *global == global_id => {
*instr = Instr::Call(Call {
func: alt_get_with_lock,
});
}
Instr::GlobalSet(GlobalSet { global }) if *global == global_id => {
*instr = Instr::Call(Call {
func: alt_set_with_lock,
});
}
_ => {}
},
*size_fid,
true,
)?;
}
let exclude: Vec<FunctionId> = grow_fn_set
.iter()
.chain(size_fn_set.iter())
.copied()
.collect();
module
.funcs
.all_rewrite(
|instr, _| match instr {
Instr::GlobalSet(GlobalSet { global }) if *global == global_id => {
*instr = Instr::Call(Call {
func: alt_set_with_lock,
});
}
Instr::GlobalGet(GlobalGet { global }) if *global == global_id => {
*instr = Instr::Call(Call {
func: alt_get_with_lock,
});
}
_ => {}
},
&exclude,
)
.wrap_err("Failed to rewrite global set/get")?;
module.globals.delete(global_id);
module
.exports
.erase_with(alt_set_with_lock, ctx.unstable_print_debug)?;
module
.exports
.erase_with(alt_set, ctx.unstable_print_debug)?;
module
.exports
.erase_with(alt_init_once, ctx.unstable_print_debug)?;
module
.exports
.erase_with(alt_get_with_lock, ctx.unstable_print_debug)?;
module
.exports
.erase_with(alt_get_no_wait, ctx.unstable_print_debug)?;
}
Ok(())
}
fn cleanup_vfs_locker(
&self,
module: &mut Module,
ctx: &GeneratorCtx,
) -> eyre::Result<()> {
if let Some(alt_id) = (
"wasip1-vfs_single_memory",
&UniqueName::SharedGlobalFns(&SharedGlobalFnsName::MemoryGrowAlt),
)
.get_fid(&module.imports)
.ok()
{
let combined = self
.result
.as_ref()
.map(|r| r.combined_memory)
.unwrap_or_else(|| module.memories.iter().next().unwrap().id());
module
.replace_imported_func(alt_id, |(builder, args)| {
builder.func_body().local_get(args[0]).memory_grow(combined);
})
.to_eyre()
.wrap_err("Failed to replace memory_grow_alt import")?;
}
if let Some(base_locker) =
UniqueName::SharedGlobalFns(&SharedGlobalFnsName::LockerBase)
.get_fid(&module.exports)
.ok()
{
module
.exports
.erase_with(base_locker, ctx.unstable_print_debug)?;
}
Ok(())
}
}
impl Generator for MultiMemoryLowering {}