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
17pub type InkwellModule<'ctx> = inkwell::module::Module<'ctx>;
19
20pub type InkwellMemoryBuffer = inkwell::memory_buffer::MemoryBuffer;
22
23#[derive(Debug, Clone)]
25pub enum CompiledKind {
26 Local(LocalFunctionIndex),
28 FunctionCallTrampoline(FunctionType),
30 DynamicFunctionTrampoline(FunctionType),
32 Module,
34}
35
36pub 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 pub(crate) middlewares: Vec<Arc<dyn ModuleMiddleware>>,
55 pub(crate) num_threads: NonZero<usize>,
57}
58
59impl LLVM {
60 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 pub fn opt_level(&mut self, opt_level: LLVMOptLevel) -> &mut Self {
78 self.opt_level = opt_level;
79 self
80 }
81
82 pub fn enable_pass_params_opt(&mut self) -> &mut Self {
85 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 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 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 #[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 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 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 _ => unimplemented!("target {} not yet supported in Wasmer", triple),
236 }
237
238 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 unsafe {
273 pub struct MyTargetMachine {
280 pub target_machine: *const u8,
281 }
282 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 fn enable_pic(&mut self) {
309 self.is_pic = true;
312 }
313
314 fn enable_perfmap(&mut self) {
315 self.enable_perfmap = true
316 }
317
318 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 fn compiler(self: Box<Self>) -> Box<dyn Compiler> {
329 Box::new(LLVMCompiler::new(*self))
330 }
331
332 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}