-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstruction.rs
More file actions
276 lines (241 loc) · 8.92 KB
/
Copy pathinstruction.rs
File metadata and controls
276 lines (241 loc) · 8.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//! Instruction code generation and terminator handling.
//!
//! Converts IR instructions and terminators into Rust code,
//! delegating to the backend for most operations.
use crate::backend::Backend;
use crate::ir::*;
use anyhow::Result;
use std::collections::HashMap;
/// Generate code for a single instruction with module info.
///
/// `caller_has_host` indicates whether the calling function has a `host` parameter in scope.
/// This is used by `call_indirect` to determine whether to pass `host` to dispatched functions.
pub fn generate_instruction_with_info<B: Backend>(
backend: &B,
instr: &IrInstr,
info: &ModuleInfo,
caller_has_host: bool,
) -> Result<String> {
let code = match instr {
IrInstr::Const { dest, value } => backend.emit_const(*dest, value),
IrInstr::BinOp { dest, op, lhs, rhs } => backend.emit_binop(*dest, *op, *lhs, *rhs),
IrInstr::UnOp { dest, op, operand } => backend.emit_unop(*dest, *op, *operand),
IrInstr::Load {
dest,
ty,
addr,
offset,
width,
sign,
} => return backend.emit_load(*dest, *ty, *addr, *offset, *width, *sign),
IrInstr::Store {
ty,
addr,
value,
offset,
width,
} => return backend.emit_store(*ty, *addr, *value, *offset, *width),
IrInstr::Call {
dest,
func_idx,
args,
} => {
// Call to local function (imports are handled by CallImport)
let has_globals = info.has_mutable_globals();
let has_memory = info.has_memory;
let has_table = info.has_table();
backend.emit_call(
*dest,
func_idx.as_usize(),
args,
has_globals,
has_memory,
has_table,
)
}
IrInstr::CallImport {
dest,
module_name,
func_name,
args,
..
} => backend.emit_call_import(*dest, module_name, func_name, args),
IrInstr::CallIndirect {
dest,
type_idx,
table_idx,
args,
} => generate_call_indirect(
*dest,
type_idx.clone(),
*table_idx,
args,
info,
caller_has_host,
),
IrInstr::Assign { dest, src } => backend.emit_assign(*dest, *src),
IrInstr::GlobalGet { dest, index } => match info.resolve_global(*index) {
ResolvedGlobal::Imported(_idx, g) => {
format!(" {} = host.get_{}();", dest, g.name)
}
ResolvedGlobal::Local(idx, g) => {
let is_mutable = g.mutable;
backend.emit_global_get(*dest, idx.as_usize(), is_mutable)
}
},
IrInstr::GlobalSet { index, value } => match info.resolve_global(*index) {
ResolvedGlobal::Imported(_idx, g) => {
format!(" host.set_{}({});", g.name, value)
}
ResolvedGlobal::Local(idx, _g) => backend.emit_global_set(idx.as_usize(), *value),
},
IrInstr::MemorySize { dest } => backend.emit_memory_size(*dest),
IrInstr::MemoryGrow { dest, delta } => backend.emit_memory_grow(*dest, *delta),
IrInstr::MemoryCopy { dst, src, len } => backend.emit_memory_copy(*dst, *src, *len),
IrInstr::MemoryFill { dst, val, len } => backend.emit_memory_fill(*dst, *val, *len),
IrInstr::MemoryInit {
dst,
src_offset,
len,
segment,
} => backend.emit_memory_init(
*dst,
*src_offset,
*len,
&format!("PASSIVE_SEGMENT_{segment}"),
),
IrInstr::DataDrop { segment } => backend.emit_data_drop(*segment),
IrInstr::Select {
dest,
val1,
val2,
condition,
} => backend.emit_select(*dest, *val1, *val2, *condition),
// Phi nodes must be lowered to Assign instructions by the lower_phis pass
// before codegen runs. Reaching this arm is a compiler bug.
IrInstr::Phi { .. } => {
unreachable!(
"IrInstr::Phi must be lowered before codegen (lower_phis pass missed this block)"
)
}
};
Ok(code)
}
/// Generate code for a terminator with BlockId to index mapping.
pub fn generate_terminator_with_mapping<B: Backend>(
backend: &B,
term: &IrTerminator,
block_id_to_index: &HashMap<BlockId, usize>,
func_return_type: Option<WasmType>,
) -> String {
match term {
IrTerminator::Return { value } => {
// If the function has a return type but the return has no value,
// this is dead code after `unreachable` — emit a trap instead
// of `return Ok(())` which would be a type mismatch.
if value.is_none() && func_return_type.is_some() {
return backend.emit_unreachable();
}
backend.emit_return(*value)
}
IrTerminator::Jump { target } => {
let idx = block_id_to_index[target];
backend.emit_jump_to_index(idx)
}
IrTerminator::BranchIf {
condition,
if_true,
if_false,
} => {
let true_idx = block_id_to_index[if_true];
let false_idx = block_id_to_index[if_false];
backend.emit_branch_if_to_index(*condition, true_idx, false_idx)
}
IrTerminator::BranchTable {
index,
targets,
default,
} => {
let target_indices: Vec<usize> = targets.iter().map(|t| block_id_to_index[t]).collect();
let default_idx = block_id_to_index[default];
backend.emit_branch_table_to_index(*index, &target_indices, default_idx)
}
IrTerminator::Unreachable => backend.emit_unreachable(),
}
}
/// Generate inline dispatch code for `call_indirect`.
///
/// The generated code:
/// 1. Looks up the table entry by index
/// 2. Checks the type signature matches
/// 3. Dispatches to the matching function via a match on func_index
///
/// `caller_has_host` indicates whether the calling function has a `host` parameter.
/// Each dispatch arm will only pass `host` to its target if both:
/// - The target function needs_host, AND
/// - The caller has_host in scope
fn generate_call_indirect(
dest: Option<VarId>,
type_idx: TypeIdx,
table_idx: VarId,
args: &[VarId],
info: &ModuleInfo,
caller_has_host: bool,
) -> String {
let has_globals = info.has_mutable_globals();
let has_memory = info.has_memory;
let has_table = info.has_table();
// Canonicalize the type index for structural equivalence (Wasm spec §4.4.9).
// Two different type indices with identical (params, results) must match.
let type_idx_usize = type_idx.as_usize();
let canon_idx = info
.canonical_type
.get(type_idx_usize)
.copied()
.unwrap_or(type_idx_usize);
let mut code = String::new();
// Look up the table entry
code.push_str(&format!(
" let __entry = table.get({table_idx} as u32)?;\n"
));
// Type check (compares canonical indices — FuncRef.type_index is
// also stored as canonical during element segment initialization)
code.push_str(&format!(
" if __entry.type_index != {canon_idx} {{ return Err(WasmTrap::IndirectCallTypeMismatch); }}\n"
));
// Build dispatch match — only dispatch to functions with matching
// canonical type (structural equivalence)
let dest_prefix = match dest {
Some(d) => format!("{d} = "),
None => String::new(),
};
code.push_str(&format!(
" {dest_prefix}match __entry.func_index {{\n"
));
for (func_idx, ir_func) in info.ir_functions.iter().enumerate() {
if ir_func.type_idx.as_usize() == canon_idx {
// Per-arm args generation: only pass host if both target needs it AND caller has it
let mut arm_base: Vec<String> = args.iter().map(|a| a.to_string()).collect();
if ir_func.needs_host && caller_has_host {
arm_base.push("host".to_string());
}
let arm_call_args = crate::codegen::utils::build_inner_call_args(
&arm_base,
has_globals,
"globals",
has_memory,
"memory",
has_table,
"table",
);
let arm_args_str = arm_call_args.join(", ");
code.push_str(&format!(
" {} => func_{}({})?,\n",
func_idx, func_idx, arm_args_str
));
}
}
code.push_str(" _ => return Err(WasmTrap::UndefinedElement),\n");
code.push_str(" };");
code
}