wasmer_compiler_cranelift/translator/
func_translator.rs

1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/main/docs/ATTRIBUTIONS.md
3
4//! Standalone WebAssembly to Cranelift IR translator.
5//!
6//! This module defines the `FuncTranslator` type which can translate a single WebAssembly
7//! function to Cranelift IR guided by a `FuncEnvironment` which provides information about the
8//! WebAssembly module and the runtime environment.
9
10use super::code_translator::translate_operator;
11use super::func_environ::{FuncEnvironment, ReturnMode};
12use super::func_state::FuncTranslationState;
13use super::translation_utils::get_vmctx_value_label;
14use crate::translator::EXN_REF_TYPE;
15use crate::translator::code_translator::bitcast_wasm_returns;
16use core::convert::TryFrom;
17use cranelift_codegen::entity::EntityRef;
18use cranelift_codegen::ir::{self, Block, InstBuilder, ValueLabel};
19use cranelift_codegen::timing;
20use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
21use wasmer_compiler::wasmparser::RefType;
22use wasmer_compiler::{FunctionBinaryReader, ModuleTranslationState, wptype_to_type};
23use wasmer_compiler::{wasm_unsupported, wasmparser};
24use wasmer_types::{LocalFunctionIndex, WasmResult};
25
26/// WebAssembly to Cranelift IR function translator.
27///
28/// A `FuncTranslator` is used to translate a binary WebAssembly function into Cranelift IR guided
29/// by a `FuncEnvironment` object. A single translator instance can be reused to translate multiple
30/// functions which will reduce heap allocation traffic.
31pub struct FuncTranslator {
32    func_ctx: FunctionBuilderContext,
33    state: FuncTranslationState,
34}
35
36impl FuncTranslator {
37    /// Create a new translator.
38    pub fn new() -> Self {
39        Self {
40            func_ctx: FunctionBuilderContext::new(),
41            state: FuncTranslationState::new(),
42        }
43    }
44
45    /// Translate a binary WebAssembly function.
46    ///
47    /// The `code` slice contains the binary WebAssembly *function code* as it appears in the code
48    /// section of a WebAssembly module, not including the initial size of the function code. The
49    /// slice is expected to contain two parts:
50    ///
51    /// - The declaration of *locals*, and
52    /// - The function *body* as an expression.
53    ///
54    /// See [the WebAssembly specification][wasm].
55    ///
56    /// [wasm]: https://webassembly.github.io/spec/core/binary/modules.html#code-section
57    ///
58    /// The Cranelift IR function `func` should be completely empty except for the `func.signature`
59    /// and `func.name` fields. The signature may contain special-purpose arguments which are not
60    /// regarded as WebAssembly local variables. Any signature arguments marked as
61    /// `ArgumentPurpose::Normal` are made accessible as WebAssembly local variables.
62    ///
63    pub fn translate<FE: FuncEnvironment + ?Sized>(
64        &mut self,
65        module_translation_state: &ModuleTranslationState,
66        reader: &mut dyn FunctionBinaryReader,
67        func: &mut ir::Function,
68        environ: &mut FE,
69        local_function_index: LocalFunctionIndex,
70    ) -> WasmResult<()> {
71        environ.push_params_on_stack(local_function_index);
72        self.translate_from_reader(module_translation_state, reader, func, environ)
73    }
74
75    /// Translate a binary WebAssembly function from a `FunctionBinaryReader`.
76    pub fn translate_from_reader<FE: FuncEnvironment + ?Sized>(
77        &mut self,
78        module_translation_state: &ModuleTranslationState,
79        reader: &mut dyn FunctionBinaryReader,
80        func: &mut ir::Function,
81        environ: &mut FE,
82    ) -> WasmResult<()> {
83        let _tt = timing::wasm_translate_function();
84        tracing::trace!(
85            "translate({} bytes, {}{})",
86            reader.bytes_remaining(),
87            func.name,
88            func.signature
89        );
90        debug_assert_eq!(func.dfg.num_blocks(), 0, "Function must be empty");
91        debug_assert_eq!(func.dfg.num_insts(), 0, "Function must be empty");
92
93        // This clears the `FunctionBuilderContext`.
94        let mut builder = FunctionBuilder::new(func, &mut self.func_ctx);
95        builder.set_srcloc(cur_srcloc(reader));
96        let entry_block = builder.create_block();
97        builder.append_block_params_for_function_params(entry_block);
98        builder.switch_to_block(entry_block); // This also creates values for the arguments.
99        builder.seal_block(entry_block); // Declare all predecessors known.
100
101        // Make sure the entry block is inserted in the layout before we make any callbacks to
102        // `environ`. The callback functions may need to insert things in the entry block.
103        builder.ensure_inserted_block();
104
105        let num_params = declare_wasm_parameters(&mut builder, entry_block, environ);
106
107        // Set up the translation state with a single pushed control block representing the whole
108        // function and its return values.
109        let exit_block = builder.create_block();
110        builder.append_block_params_for_function_returns(exit_block);
111        self.state.initialize(&builder.func.signature, exit_block);
112
113        parse_local_decls(reader, &mut builder, num_params, environ)?;
114        parse_function_body(
115            module_translation_state,
116            reader,
117            &mut builder,
118            &mut self.state,
119            environ,
120        )?;
121
122        builder.finalize();
123        Ok(())
124    }
125}
126
127/// Declare local variables for the signature parameters that correspond to WebAssembly locals.
128///
129/// Return the number of local variables declared.
130fn declare_wasm_parameters<FE: FuncEnvironment + ?Sized>(
131    builder: &mut FunctionBuilder,
132    entry_block: Block,
133    environ: &FE,
134) -> usize {
135    let sig_len = builder.func.signature.params.len();
136    let mut next_local = 0;
137    for i in 0..sig_len {
138        let param_type = builder.func.signature.params[i];
139        // There may be additional special-purpose parameters in addition to the normal WebAssembly
140        // signature parameters. For example, a `vmctx` pointer.
141        if environ.is_wasm_parameter(&builder.func.signature, i) {
142            // This is a normal WebAssembly signature parameter, so create a local for it.
143            let local = builder.declare_var(param_type.value_type);
144            let local_index = local.index();
145            debug_assert_eq!(local_index, next_local);
146            debug_assert!(u32::try_from(local_index).is_ok());
147            next_local += 1;
148
149            let param_value = builder.block_params(entry_block)[i];
150            builder.def_var(local, param_value);
151        }
152        if param_type.purpose == ir::ArgumentPurpose::VMContext {
153            let param_value = builder.block_params(entry_block)[i];
154            builder.set_val_label(param_value, get_vmctx_value_label());
155        }
156    }
157
158    next_local
159}
160
161/// Parse the local variable declarations that precede the function body.
162///
163/// Declare local variables, starting from `num_params`.
164fn parse_local_decls<FE: FuncEnvironment + ?Sized>(
165    reader: &mut dyn FunctionBinaryReader,
166    builder: &mut FunctionBuilder,
167    num_params: usize,
168    environ: &mut FE,
169) -> WasmResult<()> {
170    let mut next_local = num_params;
171    let local_count = reader.read_local_count()?;
172
173    for _ in 0..local_count {
174        builder.set_srcloc(cur_srcloc(reader));
175        let (count, ty) = reader.read_local_decl()?;
176        declare_locals(builder, count, ty, &mut next_local, environ)?;
177    }
178
179    Ok(())
180}
181
182/// Declare `count` local variables of the same type, starting from `next_local`.
183///
184/// Fail if the type is not valid for a local.
185fn declare_locals<FE: FuncEnvironment + ?Sized>(
186    builder: &mut FunctionBuilder,
187    count: u32,
188    wasm_type: wasmparser::ValType,
189    next_local: &mut usize,
190    environ: &mut FE,
191) -> WasmResult<()> {
192    // All locals are initialized to 0.
193    use wasmparser::ValType::*;
194    let zeroval = match wasm_type {
195        I32 => builder.ins().iconst(ir::types::I32, 0),
196        I64 => builder.ins().iconst(ir::types::I64, 0),
197        F32 => builder.ins().f32const(ir::immediates::Ieee32::with_bits(0)),
198        F64 => builder.ins().f64const(ir::immediates::Ieee64::with_bits(0)),
199        V128 => {
200            let constant_handle = builder.func.dfg.constants.insert([0; 16].to_vec().into());
201            builder.ins().vconst(ir::types::I8X16, constant_handle)
202        }
203        Ref(ty) => {
204            if ty.is_func_ref() || ty.is_extern_ref() {
205                builder.ins().iconst(environ.reference_type(), 0)
206            } else if ty == RefType::EXNREF {
207                builder.ins().iconst(EXN_REF_TYPE, 0)
208            } else {
209                return Err(wasm_unsupported!("unsupported reference type: {:?}", ty));
210            }
211        }
212    };
213
214    let wasmer_ty = wptype_to_type(wasm_type).unwrap();
215    let ty = builder.func.dfg.value_type(zeroval);
216    for _ in 0..count {
217        let local = builder.declare_var(ty);
218        let local_index = local.index();
219        debug_assert_eq!(local_index, *next_local);
220        debug_assert!(u32::try_from(local_index).is_ok());
221        builder.def_var(local, zeroval);
222        builder.set_val_label(zeroval, ValueLabel::new(*next_local));
223        environ.push_local_decl_on_stack(wasmer_ty);
224        *next_local += 1;
225    }
226    Ok(())
227}
228
229/// Parse the function body in `reader`.
230///
231/// This assumes that the local variable declarations have already been parsed and function
232/// arguments and locals are declared in the builder.
233fn parse_function_body<FE: FuncEnvironment + ?Sized>(
234    module_translation_state: &ModuleTranslationState,
235    reader: &mut dyn FunctionBinaryReader,
236    builder: &mut FunctionBuilder,
237    state: &mut FuncTranslationState,
238    environ: &mut FE,
239) -> WasmResult<()> {
240    // The control stack is initialized with a single block representing the whole function.
241    debug_assert_eq!(state.control_stack.len(), 1, "State not initialized");
242
243    // Keep going until the final `End` operator which pops the outermost block.
244    while !state.control_stack.is_empty() {
245        builder.set_srcloc(cur_srcloc(reader));
246        let op = reader.read_operator()?;
247        environ.before_translate_operator(&op, builder, state)?;
248        translate_operator(module_translation_state, &op, builder, state, environ)?;
249        environ.after_translate_operator(&op, builder, state)?;
250    }
251
252    // The final `End` operator left us in the exit block where we need to manually add a return
253    // instruction.
254    //
255    // If the exit block is unreachable, it may not have the correct arguments, so we would
256    // generate a return instruction that doesn't match the signature.
257    if state.reachable {
258        //debug_assert!(builder.is_pristine());
259        if !builder.is_unreachable() {
260            match environ.return_mode() {
261                ReturnMode::NormalReturns => {
262                    bitcast_wasm_returns(environ, &mut state.stack, builder);
263                    builder.ins().return_(&state.stack)
264                }
265            };
266        }
267    }
268
269    // Discard any remaining values on the stack. Either we just returned them,
270    // or the end of the function is unreachable.
271    state.stack.clear();
272    //state.metadata_stack.clear();
273
274    debug_assert!(reader.eof());
275
276    Ok(())
277}
278
279/// Get the current source location from a reader.
280fn cur_srcloc(reader: &dyn FunctionBinaryReader) -> ir::SourceLoc {
281    // We record source locations as byte code offsets relative to the beginning of the file.
282    // This will wrap around if byte code is larger than 4 GB.
283    ir::SourceLoc::new(reader.original_position() as u32)
284}