wasmer_compiler_llvm/
config.rs

1use crate::compiler::LLVMCompiler;
2use inkwell::targets::{
3    CodeModel, InitializationConfig, RelocMode, Target as InkwellTarget, TargetMachine,
4    TargetTriple,
5};
6pub use inkwell::OptimizationLevel as LLVMOptLevel;
7use itertools::Itertools;
8use std::sync::Arc;
9use std::{fmt::Debug, num::NonZero};
10use target_lexicon::BinaryFormat;
11use wasmer_compiler::{Compiler, CompilerConfig, Engine, EngineBuilder, ModuleMiddleware};
12use wasmer_types::{
13    target::{Architecture, OperatingSystem, Target, Triple},
14    Features, FunctionType, LocalFunctionIndex,
15};
16
17/// The InkWell ModuleInfo type
18pub type InkwellModule<'ctx> = inkwell::module::Module<'ctx>;
19
20/// The InkWell MemoryBuffer type
21pub type InkwellMemoryBuffer = inkwell::memory_buffer::MemoryBuffer;
22
23/// The compiled function kind, used for debugging in the `LLVMCallbacks`.
24#[derive(Debug, Clone)]
25pub enum CompiledKind {
26    // A locally-defined function in the Wasm file.
27    Local(LocalFunctionIndex),
28    // A function call trampoline for a given signature.
29    FunctionCallTrampoline(FunctionType),
30    // A dynamic function trampoline for a given signature.
31    DynamicFunctionTrampoline(FunctionType),
32    // An entire Wasm module.
33    Module,
34}
35
36/// Callbacks to the different LLVM compilation phases.
37pub trait LLVMCallbacks: Debug + Send + Sync {
38    fn preopt_ir(&self, function: &CompiledKind, module: &InkwellModule);
39    fn postopt_ir(&self, function: &CompiledKind, module: &InkwellModule);
40    fn obj_memory_buffer(&self, function: &CompiledKind, memory_buffer: &InkwellMemoryBuffer);
41    fn asm_memory_buffer(&self, function: &CompiledKind, memory_buffer: &InkwellMemoryBuffer);
42}
43
44#[derive(Debug, Clone)]
45pub struct LLVM {
46    pub(crate) enable_nan_canonicalization: bool,
47    pub(crate) enable_g0m0_opt: bool,
48    pub(crate) enable_verifier: bool,
49    pub(crate) enable_perfmap: bool,
50    pub(crate) opt_level: LLVMOptLevel,
51    is_pic: bool,
52    pub(crate) callbacks: Option<Arc<dyn LLVMCallbacks>>,
53    /// The middleware chain.
54    pub(crate) middlewares: Vec<Arc<dyn ModuleMiddleware>>,
55    /// Number of threads to use when compiling a module.
56    pub(crate) num_threads: NonZero<usize>,
57}
58
59impl LLVM {
60    /// Creates a new configuration object with the default configuration
61    /// specified.
62    pub fn new() -> Self {
63        Self {
64            enable_nan_canonicalization: false,
65            enable_verifier: false,
66            enable_perfmap: false,
67            opt_level: LLVMOptLevel::Aggressive,
68            is_pic: false,
69            callbacks: None,
70            middlewares: vec![],
71            enable_g0m0_opt: false,
72            num_threads: std::thread::available_parallelism().unwrap_or(NonZero::new(1).unwrap()),
73        }
74    }
75
76    /// The optimization levels when optimizing the IR.
77    pub fn opt_level(&mut self, opt_level: LLVMOptLevel) -> &mut Self {
78        self.opt_level = opt_level;
79        self
80    }
81
82    /// (warning: experimental) Pass the value of the first (#0) global and the base pointer of the
83    /// first (#0) memory as parameter between guest functions.
84    pub fn enable_pass_params_opt(&mut self) -> &mut Self {
85        // internally, the "pass_params" opt is known as g0m0 opt.
86        self.enable_g0m0_opt = true;
87        self
88    }
89
90    pub fn num_threads(&mut self, num_threads: NonZero<usize>) -> &mut Self {
91        self.num_threads = num_threads;
92        self
93    }
94
95    /// Callbacks that will triggered in the different compilation
96    /// phases in LLVM.
97    pub fn callbacks(&mut self, callbacks: Option<Arc<dyn LLVMCallbacks>>) -> &mut Self {
98        self.callbacks = callbacks;
99        self
100    }
101
102    fn reloc_mode(&self, binary_format: BinaryFormat) -> RelocMode {
103        if matches!(binary_format, BinaryFormat::Macho) {
104            return RelocMode::Static;
105        }
106
107        if self.is_pic {
108            RelocMode::PIC
109        } else {
110            RelocMode::Static
111        }
112    }
113
114    fn code_model(&self, binary_format: BinaryFormat) -> CodeModel {
115        // We normally use the large code model, but when targeting shared
116        // objects, we are required to use PIC. If we use PIC anyways, we lose
117        // any benefit from large code model and there's some cost on all
118        // platforms, plus some platforms (MachO) don't support PIC + large
119        // at all.
120        if matches!(binary_format, BinaryFormat::Macho) {
121            return CodeModel::Default;
122        }
123
124        if self.is_pic {
125            CodeModel::Small
126        } else {
127            CodeModel::Large
128        }
129    }
130
131    pub(crate) fn target_operating_system(&self, target: &Target) -> OperatingSystem {
132        if target.triple().operating_system == OperatingSystem::Darwin && !self.is_pic {
133            // LLVM detects static relocation + darwin + 64-bit and
134            // force-enables PIC because MachO doesn't support that
135            // combination. They don't check whether they're targeting
136            // MachO, they check whether the OS is set to Darwin.
137            //
138            // Since both linux and darwin use SysV ABI, this should work.
139            //  but not in the case of Aarch64, there the ABI is slightly different
140            #[allow(clippy::match_single_binding)]
141            match target.triple().architecture {
142                Architecture::Aarch64(_) => OperatingSystem::Darwin,
143                _ => OperatingSystem::Linux,
144            }
145        } else {
146            target.triple().operating_system
147        }
148    }
149
150    pub(crate) fn target_binary_format(&self, target: &Target) -> target_lexicon::BinaryFormat {
151        if self.is_pic {
152            target.triple().binary_format
153        } else {
154            match self.target_operating_system(target) {
155                OperatingSystem::Darwin => target_lexicon::BinaryFormat::Macho,
156                _ => target_lexicon::BinaryFormat::Elf,
157            }
158        }
159    }
160
161    fn target_triple(&self, target: &Target) -> TargetTriple {
162        let architecture = if target.triple().architecture
163            == Architecture::Riscv64(target_lexicon::Riscv64Architecture::Riscv64gc)
164        {
165            target_lexicon::Architecture::Riscv64(target_lexicon::Riscv64Architecture::Riscv64)
166        } else {
167            target.triple().architecture
168        };
169        // Hack: we're using is_pic to determine whether this is a native
170        // build or not.
171
172        let operating_system = self.target_operating_system(target);
173        let binary_format = self.target_binary_format(target);
174
175        let triple = Triple {
176            architecture,
177            vendor: target.triple().vendor.clone(),
178            operating_system,
179            environment: target.triple().environment,
180            binary_format,
181        };
182        TargetTriple::create(&triple.to_string())
183    }
184
185    /// Generates the target machine for the current target
186    pub fn target_machine(&self, target: &Target) -> TargetMachine {
187        let triple = target.triple();
188        let cpu_features = &target.cpu_features();
189
190        match triple.architecture {
191            Architecture::X86_64 | Architecture::X86_32(_) => {
192                InkwellTarget::initialize_x86(&InitializationConfig {
193                    asm_parser: true,
194                    asm_printer: true,
195                    base: true,
196                    disassembler: true,
197                    info: true,
198                    machine_code: true,
199                })
200            }
201            Architecture::Aarch64(_) => InkwellTarget::initialize_aarch64(&InitializationConfig {
202                asm_parser: true,
203                asm_printer: true,
204                base: true,
205                disassembler: true,
206                info: true,
207                machine_code: true,
208            }),
209            Architecture::Riscv64(_) => InkwellTarget::initialize_riscv(&InitializationConfig {
210                asm_parser: true,
211                asm_printer: true,
212                base: true,
213                disassembler: true,
214                info: true,
215                machine_code: true,
216            }),
217            Architecture::LoongArch64 => {
218                InkwellTarget::initialize_loongarch(&InitializationConfig {
219                    asm_parser: true,
220                    asm_printer: true,
221                    base: true,
222                    disassembler: true,
223                    info: true,
224                    machine_code: true,
225                })
226            }
227            // Architecture::Arm(_) => InkwellTarget::initialize_arm(&InitializationConfig {
228            //     asm_parser: true,
229            //     asm_printer: true,
230            //     base: true,
231            //     disassembler: true,
232            //     info: true,
233            //     machine_code: true,
234            // }),
235            _ => unimplemented!("target {} not yet supported in Wasmer", triple),
236        }
237
238        // The CPU features formatted as LLVM strings
239        // We can safely map to gcc-like features as the CPUFeatures
240        // are compliant with the same string representations as gcc.
241        let llvm_cpu_features = cpu_features
242            .iter()
243            .map(|feature| format!("+{feature}"))
244            .join(",");
245
246        let target_triple = self.target_triple(target);
247        let llvm_target = InkwellTarget::from_triple(&target_triple).unwrap();
248        let llvm_target_machine = llvm_target
249            .create_target_machine(
250                &target_triple,
251                match triple.architecture {
252                    Architecture::Riscv64(_) => "generic-rv64",
253                    Architecture::LoongArch64 => "generic-la64",
254                    _ => "generic",
255                },
256                match triple.architecture {
257                    Architecture::Riscv64(_) => "+m,+a,+c,+d,+f",
258                    Architecture::LoongArch64 => "+f,+d",
259                    _ => &llvm_cpu_features,
260                },
261                self.opt_level,
262                self.reloc_mode(self.target_binary_format(target)),
263                match triple.architecture {
264                    Architecture::LoongArch64 | Architecture::Riscv64(_) => CodeModel::Medium,
265                    _ => self.code_model(self.target_binary_format(target)),
266                },
267            )
268            .unwrap();
269
270        if let Architecture::Riscv64(_) = triple.architecture {
271            // TODO: totally non-portable way to change ABI
272            unsafe {
273                // This structure mimic the internal structure from inkwell
274                // that is defined as
275                //  #[derive(Debug)]
276                //  pub struct TargetMachine {
277                //    pub(crate) target_machine: LLVMTargetMachineRef,
278                //  }
279                pub struct MyTargetMachine {
280                    pub target_machine: *const u8,
281                }
282                // It is use to live patch the create LLVMTargetMachine
283                // to hard change the ABI and force "-mabi=lp64d" ABI
284                // instead of the default that don't use float registers
285                // because there is no current way to do this change
286
287                let my_target_machine: MyTargetMachine = std::mem::transmute(llvm_target_machine);
288
289                *((my_target_machine.target_machine as *mut u8).offset(0x410) as *mut u64) = 5;
290                std::ptr::copy_nonoverlapping(
291                    "lp64d\0".as_ptr(),
292                    (my_target_machine.target_machine as *mut u8).offset(0x418),
293                    6,
294                );
295
296                std::mem::transmute::<MyTargetMachine, inkwell::targets::TargetMachine>(
297                    my_target_machine,
298                )
299            }
300        } else {
301            llvm_target_machine
302        }
303    }
304}
305
306impl CompilerConfig for LLVM {
307    /// Emit code suitable for dlopen.
308    fn enable_pic(&mut self) {
309        // TODO: although we can emit PIC, the object file parser does not yet
310        // support all the relocations.
311        self.is_pic = true;
312    }
313
314    fn enable_perfmap(&mut self) {
315        self.enable_perfmap = true
316    }
317
318    /// Whether to verify compiler IR.
319    fn enable_verifier(&mut self) {
320        self.enable_verifier = true;
321    }
322
323    fn canonicalize_nans(&mut self, enable: bool) {
324        self.enable_nan_canonicalization = enable;
325    }
326
327    /// Transform it into the compiler.
328    fn compiler(self: Box<Self>) -> Box<dyn Compiler> {
329        Box::new(LLVMCompiler::new(*self))
330    }
331
332    /// Pushes a middleware onto the back of the middleware chain.
333    fn push_middleware(&mut self, middleware: Arc<dyn ModuleMiddleware>) {
334        self.middlewares.push(middleware);
335    }
336
337    fn supported_features_for_target(&self, _target: &Target) -> wasmer_types::Features {
338        let mut feats = Features::default();
339        feats.exceptions(true);
340        feats
341    }
342}
343
344impl Default for LLVM {
345    fn default() -> LLVM {
346        Self::new()
347    }
348}
349
350impl From<LLVM> for Engine {
351    fn from(config: LLVM) -> Self {
352        EngineBuilder::new(config).engine()
353    }
354}