wasmer_compiler_singlepass/
compiler.rs

1//! Support for compiling with Singlepass.
2// Allow unused imports while developing.
3#![allow(unused_imports, dead_code)]
4
5use crate::codegen::FuncGen;
6use crate::config::Singlepass;
7#[cfg(feature = "unwind")]
8use crate::dwarf::WriterRelocate;
9use crate::machine::Machine;
10use crate::machine::{
11    gen_import_call_trampoline, gen_std_dynamic_import_trampoline, gen_std_trampoline,
12};
13use crate::machine_arm64::MachineARM64;
14use crate::machine_x64::MachineX86_64;
15#[cfg(feature = "unwind")]
16use crate::unwind::{create_systemv_cie, UnwindFrame};
17use enumset::EnumSet;
18#[cfg(feature = "unwind")]
19use gimli::write::{EhFrame, FrameTable};
20#[cfg(feature = "rayon")]
21use rayon::prelude::{IntoParallelIterator, ParallelIterator};
22use std::sync::Arc;
23use wasmer_compiler::{
24    types::{
25        function::{Compilation, CompiledFunction, FunctionBody, UnwindInfo},
26        module::CompileModuleInfo,
27        section::SectionIndex,
28    },
29    Compiler, CompilerConfig, FunctionBinaryReader, FunctionBodyData, MiddlewareBinaryReader,
30    ModuleMiddleware, ModuleMiddlewareChain, ModuleTranslationState,
31};
32use wasmer_types::entity::{EntityRef, PrimaryMap};
33use wasmer_types::target::{Architecture, CallingConvention, CpuFeature, Target};
34use wasmer_types::{
35    CompileError, FunctionIndex, FunctionType, LocalFunctionIndex, MemoryIndex, ModuleInfo,
36    TableIndex, TrapCode, TrapInformation, VMOffsets,
37};
38
39/// A compiler that compiles a WebAssembly module with Singlepass.
40/// It does the compilation in one pass
41#[derive(Debug)]
42pub struct SinglepassCompiler {
43    config: Singlepass,
44}
45
46impl SinglepassCompiler {
47    /// Creates a new Singlepass compiler
48    pub fn new(config: Singlepass) -> Self {
49        Self { config }
50    }
51
52    /// Gets the config for this Compiler
53    fn config(&self) -> &Singlepass {
54        &self.config
55    }
56}
57
58impl Compiler for SinglepassCompiler {
59    fn name(&self) -> &str {
60        "singlepass"
61    }
62
63    fn deterministic_id(&self) -> String {
64        String::from("singlepass")
65    }
66
67    /// Get the middlewares for this compiler
68    fn get_middlewares(&self) -> &[Arc<dyn ModuleMiddleware>] {
69        &self.config.middlewares
70    }
71
72    /// Compile the module using Singlepass, producing a compilation result with
73    /// associated relocations.
74    fn compile_module(
75        &self,
76        target: &Target,
77        compile_info: &CompileModuleInfo,
78        _module_translation: &ModuleTranslationState,
79        function_body_inputs: PrimaryMap<LocalFunctionIndex, FunctionBodyData<'_>>,
80    ) -> Result<Compilation, CompileError> {
81        match target.triple().architecture {
82            Architecture::X86_64 => {}
83            Architecture::Aarch64(_) => {}
84            _ => {
85                return Err(CompileError::UnsupportedTarget(
86                    target.triple().architecture.to_string(),
87                ))
88            }
89        }
90
91        let calling_convention = match target.triple().default_calling_convention() {
92            Ok(CallingConvention::WindowsFastcall) => CallingConvention::WindowsFastcall,
93            Ok(CallingConvention::SystemV) => CallingConvention::SystemV,
94            Ok(CallingConvention::AppleAarch64) => CallingConvention::AppleAarch64,
95            _ => {
96                return Err(CompileError::UnsupportedTarget(
97                    "Unsupported Calling convention for Singlepass compiler".to_string(),
98                ))
99            }
100        };
101
102        // Generate the frametable
103        #[cfg(feature = "unwind")]
104        let dwarf_frametable = if function_body_inputs.is_empty() {
105            // If we have no function body inputs, we don't need to
106            // construct the `FrameTable`. Constructing it, with empty
107            // FDEs will cause some issues in Linux.
108            None
109        } else {
110            match target.triple().default_calling_convention() {
111                Ok(CallingConvention::SystemV) => {
112                    match create_systemv_cie(target.triple().architecture) {
113                        Some(cie) => {
114                            let mut dwarf_frametable = FrameTable::default();
115                            let cie_id = dwarf_frametable.add_cie(cie);
116                            Some((dwarf_frametable, cie_id))
117                        }
118                        None => None,
119                    }
120                }
121                _ => None,
122            }
123        };
124
125        let memory_styles = &compile_info.memory_styles;
126        let table_styles = &compile_info.table_styles;
127        let vmoffsets = VMOffsets::new(8, &compile_info.module);
128        let module = &compile_info.module;
129        let mut custom_sections: PrimaryMap<SectionIndex, _> = (0..module.num_imported_functions)
130            .map(FunctionIndex::new)
131            .collect::<Vec<_>>()
132            .into_par_iter_if_rayon()
133            .map(|i| {
134                gen_import_call_trampoline(
135                    &vmoffsets,
136                    i,
137                    &module.signatures[module.functions[i]],
138                    target,
139                    calling_convention,
140                )
141            })
142            .collect::<Result<Vec<_>, _>>()?
143            .into_iter()
144            .collect();
145        let (functions, fdes): (Vec<CompiledFunction>, Vec<_>) = function_body_inputs
146            .iter()
147            .collect::<Vec<(LocalFunctionIndex, &FunctionBodyData<'_>)>>()
148            .into_par_iter_if_rayon()
149            .map(|(i, input)| {
150                let middleware_chain = self
151                    .config
152                    .middlewares
153                    .generate_function_middleware_chain(i);
154                let mut reader =
155                    MiddlewareBinaryReader::new_with_offset(input.data, input.module_offset);
156                reader.set_middleware_chain(middleware_chain);
157
158                // This local list excludes arguments.
159                let mut locals = vec![];
160                let num_locals = reader.read_local_count()?;
161                for _ in 0..num_locals {
162                    let (count, ty) = reader.read_local_decl()?;
163                    for _ in 0..count {
164                        locals.push(ty);
165                    }
166                }
167
168                match target.triple().architecture {
169                    Architecture::X86_64 => {
170                        let machine = MachineX86_64::new(Some(target.clone()))?;
171                        let mut generator = FuncGen::new(
172                            module,
173                            &self.config,
174                            &vmoffsets,
175                            memory_styles,
176                            table_styles,
177                            i,
178                            &locals,
179                            machine,
180                            calling_convention,
181                        )?;
182                        while generator.has_control_frames() {
183                            generator.set_srcloc(reader.original_position() as u32);
184                            let op = reader.read_operator()?;
185                            generator.feed_operator(op)?;
186                        }
187
188                        generator.finalize(input)
189                    }
190                    Architecture::Aarch64(_) => {
191                        let machine = MachineARM64::new(Some(target.clone()));
192                        let mut generator = FuncGen::new(
193                            module,
194                            &self.config,
195                            &vmoffsets,
196                            memory_styles,
197                            table_styles,
198                            i,
199                            &locals,
200                            machine,
201                            calling_convention,
202                        )?;
203                        while generator.has_control_frames() {
204                            generator.set_srcloc(reader.original_position() as u32);
205                            let op = reader.read_operator()?;
206                            generator.feed_operator(op)?;
207                        }
208
209                        generator.finalize(input)
210                    }
211                    _ => unimplemented!(),
212                }
213            })
214            .collect::<Result<Vec<_>, CompileError>>()?
215            .into_iter()
216            .unzip();
217
218        let function_call_trampolines = module
219            .signatures
220            .values()
221            .collect::<Vec<_>>()
222            .into_par_iter_if_rayon()
223            .map(|func_type| gen_std_trampoline(func_type, target, calling_convention))
224            .collect::<Result<Vec<_>, _>>()?
225            .into_iter()
226            .collect::<PrimaryMap<_, _>>();
227
228        let dynamic_function_trampolines = module
229            .imported_function_types()
230            .collect::<Vec<_>>()
231            .into_par_iter_if_rayon()
232            .map(|func_type| {
233                gen_std_dynamic_import_trampoline(
234                    &vmoffsets,
235                    &func_type,
236                    target,
237                    calling_convention,
238                )
239            })
240            .collect::<Result<Vec<_>, _>>()?
241            .into_iter()
242            .collect::<PrimaryMap<FunctionIndex, FunctionBody>>();
243
244        #[allow(unused_mut)]
245        let mut unwind_info = UnwindInfo::default();
246
247        #[cfg(feature = "unwind")]
248        if let Some((mut dwarf_frametable, cie_id)) = dwarf_frametable {
249            for fde in fdes.into_iter().flatten() {
250                match fde {
251                    UnwindFrame::SystemV(fde) => dwarf_frametable.add_fde(cie_id, fde),
252                }
253            }
254            let mut eh_frame = EhFrame(WriterRelocate::new(target.triple().endianness().ok()));
255            dwarf_frametable.write_eh_frame(&mut eh_frame).unwrap();
256
257            let eh_frame_section = eh_frame.0.into_section();
258            custom_sections.push(eh_frame_section);
259            unwind_info.eh_frame = Some(SectionIndex::new(custom_sections.len() - 1))
260        };
261
262        let got = wasmer_compiler::types::function::GOT::empty();
263
264        Ok(Compilation {
265            functions: functions.into_iter().collect(),
266            custom_sections,
267            function_call_trampolines,
268            dynamic_function_trampolines,
269            unwind_info,
270            got,
271        })
272    }
273
274    fn get_cpu_features_used(&self, cpu_features: &EnumSet<CpuFeature>) -> EnumSet<CpuFeature> {
275        let used = CpuFeature::AVX | CpuFeature::SSE42 | CpuFeature::LZCNT | CpuFeature::BMI1;
276        cpu_features.intersection(used)
277    }
278}
279
280trait IntoParIterIfRayon {
281    type Output;
282    fn into_par_iter_if_rayon(self) -> Self::Output;
283}
284
285impl<T: Send> IntoParIterIfRayon for Vec<T> {
286    #[cfg(not(feature = "rayon"))]
287    type Output = std::vec::IntoIter<T>;
288    #[cfg(feature = "rayon")]
289    type Output = rayon::vec::IntoIter<T>;
290
291    fn into_par_iter_if_rayon(self) -> Self::Output {
292        #[cfg(not(feature = "rayon"))]
293        return self.into_iter();
294        #[cfg(feature = "rayon")]
295        return self.into_par_iter();
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302    use std::str::FromStr;
303    use target_lexicon::triple;
304    use wasmer_compiler::Features;
305    use wasmer_types::{
306        target::{CpuFeature, Triple},
307        MemoryStyle, TableStyle,
308    };
309
310    fn dummy_compilation_ingredients<'a>() -> (
311        CompileModuleInfo,
312        ModuleTranslationState,
313        PrimaryMap<LocalFunctionIndex, FunctionBodyData<'a>>,
314    ) {
315        let compile_info = CompileModuleInfo {
316            features: Features::new(),
317            module: Arc::new(ModuleInfo::new()),
318            memory_styles: PrimaryMap::<MemoryIndex, MemoryStyle>::new(),
319            table_styles: PrimaryMap::<TableIndex, TableStyle>::new(),
320        };
321        let module_translation = ModuleTranslationState::new();
322        let function_body_inputs = PrimaryMap::<LocalFunctionIndex, FunctionBodyData<'_>>::new();
323        (compile_info, module_translation, function_body_inputs)
324    }
325
326    #[test]
327    fn errors_for_unsupported_targets() {
328        let compiler = SinglepassCompiler::new(Singlepass::default());
329
330        // Compile for 32bit Linux
331        let linux32 = Target::new(triple!("i686-unknown-linux-gnu"), CpuFeature::for_host());
332        let (info, translation, inputs) = dummy_compilation_ingredients();
333        let result = compiler.compile_module(&linux32, &info, &translation, inputs);
334        match result.unwrap_err() {
335            CompileError::UnsupportedTarget(name) => assert_eq!(name, "i686"),
336            error => panic!("Unexpected error: {error:?}"),
337        };
338
339        // Compile for win32
340        let win32 = Target::new(triple!("i686-pc-windows-gnu"), CpuFeature::for_host());
341        let (info, translation, inputs) = dummy_compilation_ingredients();
342        let result = compiler.compile_module(&win32, &info, &translation, inputs);
343        match result.unwrap_err() {
344            CompileError::UnsupportedTarget(name) => assert_eq!(name, "i686"), // Windows should be checked before architecture
345            error => panic!("Unexpected error: {error:?}"),
346        };
347    }
348
349    #[test]
350    fn errors_for_unsuported_cpufeatures() {
351        let compiler = SinglepassCompiler::new(Singlepass::default());
352        let mut features =
353            CpuFeature::AVX | CpuFeature::SSE42 | CpuFeature::LZCNT | CpuFeature::BMI1;
354        // simple test
355        assert!(compiler
356            .get_cpu_features_used(&features)
357            .is_subset(CpuFeature::AVX | CpuFeature::SSE42 | CpuFeature::LZCNT | CpuFeature::BMI1));
358        // check that an AVX build don't work on SSE4.2 only host
359        assert!(!compiler
360            .get_cpu_features_used(&features)
361            .is_subset(CpuFeature::SSE42 | CpuFeature::LZCNT | CpuFeature::BMI1));
362        // check that having a host with AVX512 doesn't change anything
363        features.insert_all(CpuFeature::AVX512DQ | CpuFeature::AVX512F);
364        assert!(compiler
365            .get_cpu_features_used(&features)
366            .is_subset(CpuFeature::AVX | CpuFeature::SSE42 | CpuFeature::LZCNT | CpuFeature::BMI1));
367    }
368}