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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
use code_translator::translate_operator;
use cranelift_codegen::entity::EntityRef;
use cranelift_codegen::ir::{self, Ebb, InstBuilder};
use cranelift_codegen::timing;
use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
use environ::{FuncEnvironment, WasmError, WasmResult};
use state::TranslationState;
use wasmparser::{self, BinaryReader};
pub struct FuncTranslator {
func_ctx: FunctionBuilderContext<Variable>,
state: TranslationState,
}
impl FuncTranslator {
pub fn new() -> Self {
Self {
func_ctx: FunctionBuilderContext::new(),
state: TranslationState::new(),
}
}
pub fn translate<FE: FuncEnvironment + ?Sized>(
&mut self,
code: &[u8],
func: &mut ir::Function,
environ: &mut FE,
) -> WasmResult<()> {
self.translate_from_reader(BinaryReader::new(code), func, environ)
}
pub fn translate_from_reader<FE: FuncEnvironment + ?Sized>(
&mut self,
mut reader: BinaryReader,
func: &mut ir::Function,
environ: &mut FE,
) -> WasmResult<()> {
let _tt = timing::wasm_translate_function();
dbg!(
"translate({} bytes, {}{})",
reader.bytes_remaining(),
func.name,
func.signature
);
debug_assert_eq!(func.dfg.num_ebbs(), 0, "Function must be empty");
debug_assert_eq!(func.dfg.num_insts(), 0, "Function must be empty");
let mut builder = FunctionBuilder::new(func, &mut self.func_ctx);
let entry_block = builder.create_ebb();
builder.append_ebb_params_for_function_params(entry_block);
builder.switch_to_block(entry_block);
builder.seal_block(entry_block);
builder.ensure_inserted_ebb();
let num_params = declare_wasm_parameters(&mut builder, entry_block);
let exit_block = builder.create_ebb();
builder.append_ebb_params_for_function_returns(exit_block);
self.state.initialize(&builder.func.signature, exit_block);
parse_local_decls(&mut reader, &mut builder, num_params)?;
parse_function_body(reader, &mut builder, &mut self.state, environ)?;
builder.finalize();
Ok(())
}
}
fn declare_wasm_parameters(builder: &mut FunctionBuilder<Variable>, entry_block: Ebb) -> usize {
let sig_len = builder.func.signature.params.len();
let mut next_local = 0;
for i in 0..sig_len {
let param_type = builder.func.signature.params[i];
if param_type.purpose == ir::ArgumentPurpose::Normal {
let local = Variable::new(next_local);
builder.declare_var(local, param_type.value_type);
next_local += 1;
let param_value = builder.ebb_params(entry_block)[i];
builder.def_var(local, param_value);
}
}
next_local
}
fn parse_local_decls(
reader: &mut BinaryReader,
builder: &mut FunctionBuilder<Variable>,
num_params: usize,
) -> WasmResult<()> {
let mut next_local = num_params;
let local_count = reader
.read_local_count()
.map_err(WasmError::from_binary_reader_error)?;
let mut locals_total = 0;
for _ in 0..local_count {
builder.set_srcloc(cur_srcloc(reader));
let (count, ty) = reader
.read_local_decl(&mut locals_total)
.map_err(WasmError::from_binary_reader_error)?;
declare_locals(builder, count, ty, &mut next_local);
}
Ok(())
}
fn declare_locals(
builder: &mut FunctionBuilder<Variable>,
count: u32,
wasm_type: wasmparser::Type,
next_local: &mut usize,
) {
use wasmparser::Type::*;
let zeroval = match wasm_type {
I32 => builder.ins().iconst(ir::types::I32, 0),
I64 => builder.ins().iconst(ir::types::I64, 0),
F32 => builder.ins().f32const(ir::immediates::Ieee32::with_bits(0)),
F64 => builder.ins().f64const(ir::immediates::Ieee64::with_bits(0)),
_ => panic!("invalid local type"),
};
let ty = builder.func.dfg.value_type(zeroval);
for _ in 0..count {
let local = Variable::new(*next_local);
builder.declare_var(local, ty);
builder.def_var(local, zeroval);
*next_local += 1;
}
}
fn parse_function_body<FE: FuncEnvironment + ?Sized>(
mut reader: BinaryReader,
builder: &mut FunctionBuilder<Variable>,
state: &mut TranslationState,
environ: &mut FE,
) -> WasmResult<()> {
debug_assert_eq!(state.control_stack.len(), 1, "State not initialized");
while !state.control_stack.is_empty() {
builder.set_srcloc(cur_srcloc(&reader));
let op = reader
.read_operator()
.map_err(WasmError::from_binary_reader_error)?;
translate_operator(op, builder, state, environ)?;
}
if state.reachable {
debug_assert!(builder.is_pristine());
if !builder.is_unreachable() {
builder.ins().return_(&state.stack);
}
}
state.stack.clear();
debug_assert!(reader.eof());
Ok(())
}
fn cur_srcloc(reader: &BinaryReader) -> ir::SourceLoc {
ir::SourceLoc::new(reader.current_position() as u32)
}
#[cfg(test)]
mod tests {
use super::FuncTranslator;
use cranelift_codegen::ir::types::I32;
use cranelift_codegen::{ir, Context};
use environ::{DummyEnvironment, FuncEnvironment};
use target_lexicon::Triple;
#[test]
fn small1() {
const BODY: [u8; 7] = [
0x00,
0x20,
0x00,
0x41,
0x01,
0x6a,
0x0b,
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::with_triple(Triple::default());
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("small1");
ctx.func.signature.params.push(ir::AbiParam::new(I32));
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
#[test]
fn small2() {
const BODY: [u8; 8] = [
0x00,
0x20,
0x00,
0x41,
0x01,
0x6a,
0x0f,
0x0b,
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::with_triple(Triple::default());
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("small2");
ctx.func.signature.params.push(ir::AbiParam::new(I32));
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
#[test]
fn infloop() {
const BODY: [u8; 16] = [
0x01,
0x01,
0x7f,
0x03,
0x7f,
0x20,
0x00,
0x41,
0x01,
0x6a,
0x21,
0x00,
0x0c,
0x00,
0x0b,
0x0b,
];
let mut trans = FuncTranslator::new();
let runtime = DummyEnvironment::with_triple(Triple::default());
let mut ctx = Context::new();
ctx.func.name = ir::ExternalName::testcase("infloop");
ctx.func.signature.returns.push(ir::AbiParam::new(I32));
trans
.translate(&BODY, &mut ctx.func, &mut runtime.func_env())
.unwrap();
dbg!("{}", ctx.func.display(None));
ctx.verify(runtime.func_env().flags()).unwrap();
}
}