1use crate::compiler::LLVMCompiler;
2pub use inkwell::OptimizationLevel as LLVMOptLevel;
3use inkwell::targets::{
4 CodeModel, InitializationConfig, RelocMode, Target as InkwellTarget, TargetMachine,
5 TargetMachineOptions, TargetTriple,
6};
7use itertools::Itertools;
8use std::fs::File;
9use std::io::{self, Write};
10use std::path::PathBuf;
11use std::sync::Arc;
12use std::{fmt::Debug, num::NonZero};
13use target_lexicon::BinaryFormat;
14use wasmer_compiler::misc::{CompiledKind, function_kind_to_filename};
15use wasmer_compiler::{Compiler, CompilerConfig, Engine, EngineBuilder, ModuleMiddleware};
16use wasmer_types::{
17 Features,
18 target::{Architecture, OperatingSystem, Target, Triple},
19};
20
21pub type InkwellModule<'ctx> = inkwell::module::Module<'ctx>;
23
24pub type InkwellMemoryBuffer = inkwell::memory_buffer::MemoryBuffer;
26
27#[derive(Debug, Clone)]
29pub struct LLVMCallbacks {
30 debug_dir: PathBuf,
31}
32
33impl LLVMCallbacks {
34 pub fn new(debug_dir: PathBuf) -> Result<Self, io::Error> {
35 std::fs::create_dir_all(&debug_dir)?;
37 Ok(Self { debug_dir })
38 }
39
40 fn base_path(&self, module_hash: &Option<String>) -> PathBuf {
41 let mut path = self.debug_dir.clone();
42 if let Some(hash) = module_hash {
43 path.push(hash);
44 }
45 std::fs::create_dir_all(&path)
46 .unwrap_or_else(|_| panic!("cannot create debug directory: {}", path.display()));
47 path
48 }
49
50 pub fn preopt_ir(
51 &self,
52 kind: &CompiledKind,
53 module_hash: &Option<String>,
54 module: &InkwellModule,
55 ) {
56 let mut path = self.base_path(module_hash);
57 path.push(function_kind_to_filename(kind, ".preopt.ll"));
58 module
59 .print_to_file(&path)
60 .expect("Error while dumping pre optimized LLVM IR");
61 }
62 pub fn postopt_ir(
63 &self,
64 kind: &CompiledKind,
65 module_hash: &Option<String>,
66 module: &InkwellModule,
67 ) {
68 let mut path = self.base_path(module_hash);
69 path.push(function_kind_to_filename(kind, ".postopt.ll"));
70 module
71 .print_to_file(&path)
72 .expect("Error while dumping post optimized LLVM IR");
73 }
74 pub fn obj_memory_buffer(
75 &self,
76 kind: &CompiledKind,
77 module_hash: &Option<String>,
78 memory_buffer: &InkwellMemoryBuffer,
79 ) {
80 let mut path = self.base_path(module_hash);
81 path.push(function_kind_to_filename(kind, ".o"));
82 let mem_buf_slice = memory_buffer.as_slice();
83 let mut file =
84 File::create(path).expect("Error while creating debug object file from LLVM IR");
85 file.write_all(mem_buf_slice).unwrap();
86 }
87
88 pub fn asm_memory_buffer(
89 &self,
90 kind: &CompiledKind,
91 module_hash: &Option<String>,
92 asm_memory_buffer: &InkwellMemoryBuffer,
93 ) {
94 let mut path = self.base_path(module_hash);
95 path.push(function_kind_to_filename(kind, ".s"));
96 let mem_buf_slice = asm_memory_buffer.as_slice();
97 let mut file =
98 File::create(path).expect("Error while creating debug assembly file from LLVM IR");
99 file.write_all(mem_buf_slice).unwrap();
100 }
101}
102
103#[derive(Debug, Clone)]
104pub struct LLVM {
105 pub(crate) enable_nan_canonicalization: bool,
106 pub(crate) enable_non_volatile_memops: bool,
107 pub(crate) enable_verifier: bool,
108 pub(crate) enable_perfmap: bool,
109 pub(crate) opt_level: LLVMOptLevel,
110 is_pic: bool,
111 pub(crate) callbacks: Option<LLVMCallbacks>,
112 pub(crate) middlewares: Vec<Arc<dyn ModuleMiddleware>>,
114 pub(crate) num_threads: NonZero<usize>,
116 pub(crate) verbose_asm: bool,
117}
118
119impl LLVM {
120 pub fn new() -> Self {
123 Self {
124 enable_nan_canonicalization: false,
125 enable_non_volatile_memops: false,
126 enable_verifier: false,
127 enable_perfmap: false,
128 opt_level: LLVMOptLevel::Aggressive,
129 is_pic: false,
130 callbacks: None,
131 middlewares: vec![],
132 verbose_asm: false,
133 num_threads: std::thread::available_parallelism().unwrap_or(NonZero::new(1).unwrap()),
134 }
135 }
136
137 pub fn opt_level(&mut self, opt_level: LLVMOptLevel) -> &mut Self {
139 self.opt_level = opt_level;
140 self
141 }
142
143 pub fn num_threads(&mut self, num_threads: NonZero<usize>) -> &mut Self {
144 self.num_threads = num_threads;
145 self
146 }
147
148 pub fn verbose_asm(&mut self, verbose_asm: bool) -> &mut Self {
149 self.verbose_asm = verbose_asm;
150 self
151 }
152
153 pub fn callbacks(&mut self, callbacks: Option<LLVMCallbacks>) -> &mut Self {
156 self.callbacks = callbacks;
157 self
158 }
159
160 pub fn non_volatile_memops(&mut self, enable_non_volatile_memops: bool) -> &mut Self {
163 self.enable_non_volatile_memops = enable_non_volatile_memops;
164 self
165 }
166
167 fn reloc_mode(&self, binary_format: BinaryFormat) -> RelocMode {
168 if matches!(binary_format, BinaryFormat::Macho) {
169 return RelocMode::Static;
170 }
171
172 if self.is_pic {
173 RelocMode::PIC
174 } else {
175 RelocMode::Static
176 }
177 }
178
179 fn code_model(&self, binary_format: BinaryFormat) -> CodeModel {
180 if matches!(binary_format, BinaryFormat::Macho) {
186 return CodeModel::Default;
187 }
188
189 if self.is_pic {
190 CodeModel::Small
191 } else {
192 CodeModel::Large
193 }
194 }
195
196 pub(crate) fn target_operating_system(&self, target: &Target) -> OperatingSystem {
197 match target.triple().operating_system {
198 OperatingSystem::Darwin(deployment) if !self.is_pic => {
199 #[allow(clippy::match_single_binding)]
207 match target.triple().architecture {
208 Architecture::Aarch64(_) => OperatingSystem::Darwin(deployment),
209 _ => OperatingSystem::Linux,
210 }
211 }
212 other => other,
213 }
214 }
215
216 pub(crate) fn target_binary_format(&self, target: &Target) -> target_lexicon::BinaryFormat {
217 if self.is_pic {
218 target.triple().binary_format
219 } else {
220 match self.target_operating_system(target) {
221 OperatingSystem::Darwin(_) => target_lexicon::BinaryFormat::Macho,
222 _ => target_lexicon::BinaryFormat::Elf,
223 }
224 }
225 }
226
227 fn target_triple(&self, target: &Target) -> TargetTriple {
228 let architecture = if target.triple().architecture
229 == Architecture::Riscv64(target_lexicon::Riscv64Architecture::Riscv64gc)
230 {
231 target_lexicon::Architecture::Riscv64(target_lexicon::Riscv64Architecture::Riscv64)
232 } else {
233 target.triple().architecture
234 };
235 let operating_system = self.target_operating_system(target);
239 let binary_format = self.target_binary_format(target);
240
241 let triple = Triple {
242 architecture,
243 vendor: target.triple().vendor.clone(),
244 operating_system,
245 environment: target.triple().environment,
246 binary_format,
247 };
248 TargetTriple::create(&triple.to_string())
249 }
250
251 pub fn target_machine(&self, target: &Target) -> TargetMachine {
253 self.target_machine_with_opt(target, true)
254 }
255
256 pub(crate) fn target_machine_with_opt(
257 &self,
258 target: &Target,
259 enable_optimization: bool,
260 ) -> TargetMachine {
261 let triple = target.triple();
262 let cpu_features = &target.cpu_features();
263
264 match triple.architecture {
265 Architecture::X86_64 | Architecture::X86_32(_) => {
266 InkwellTarget::initialize_x86(&InitializationConfig {
267 asm_parser: true,
268 asm_printer: true,
269 base: true,
270 disassembler: true,
271 info: true,
272 machine_code: true,
273 })
274 }
275 Architecture::Aarch64(_) => InkwellTarget::initialize_aarch64(&InitializationConfig {
276 asm_parser: true,
277 asm_printer: true,
278 base: true,
279 disassembler: true,
280 info: true,
281 machine_code: true,
282 }),
283 Architecture::Riscv64(_) | Architecture::Riscv32(_) => {
284 InkwellTarget::initialize_riscv(&InitializationConfig {
285 asm_parser: true,
286 asm_printer: true,
287 base: true,
288 disassembler: true,
289 info: true,
290 machine_code: true,
291 })
292 }
293 Architecture::LoongArch64 => {
294 InkwellTarget::initialize_loongarch(&InitializationConfig {
295 asm_parser: true,
296 asm_printer: true,
297 base: true,
298 disassembler: true,
299 info: true,
300 machine_code: true,
301 })
302 }
303 _ => unimplemented!("target {} not yet supported in Wasmer", triple),
304 }
305
306 let llvm_cpu_features = cpu_features
310 .iter()
311 .map(|feature| format!("+{feature}"))
312 .join(",");
313
314 let target_triple = self.target_triple(target);
315 let llvm_target = InkwellTarget::from_triple(&target_triple).unwrap();
316 let mut llvm_target_machine_options = TargetMachineOptions::new()
317 .set_cpu(match triple.architecture {
318 Architecture::Riscv64(_) => "generic-rv64",
319 Architecture::Riscv32(_) => "generic-rv32",
320 Architecture::LoongArch64 => "generic-la64",
321 _ => "generic",
322 })
323 .set_features(match triple.architecture {
324 Architecture::Riscv64(_) => "+m,+a,+c,+d,+f",
325 Architecture::Riscv32(_) => "+m,+a,+c,+d,+f",
326 Architecture::LoongArch64 => "+f,+d",
327 _ => &llvm_cpu_features,
328 })
329 .set_level(if enable_optimization {
330 self.opt_level
331 } else {
332 LLVMOptLevel::None
333 })
334 .set_reloc_mode(self.reloc_mode(self.target_binary_format(target)))
335 .set_code_model(match triple.architecture {
336 Architecture::LoongArch64 | Architecture::Riscv64(_) | Architecture::Riscv32(_) => {
337 CodeModel::Medium
338 }
339 _ => self.code_model(self.target_binary_format(target)),
340 });
341 if let Architecture::Riscv64(_) = triple.architecture {
342 llvm_target_machine_options = llvm_target_machine_options.set_abi("lp64d");
343 }
344 let target_machine = llvm_target
345 .create_target_machine_from_options(&target_triple, llvm_target_machine_options)
346 .unwrap();
347 target_machine.set_asm_verbosity(self.verbose_asm);
348 target_machine
349 }
350}
351
352impl CompilerConfig for LLVM {
353 fn enable_pic(&mut self) {
355 self.is_pic = true;
358 }
359
360 fn enable_perfmap(&mut self) {
361 self.enable_perfmap = true
362 }
363
364 fn enable_verifier(&mut self) {
366 self.enable_verifier = true;
367 }
368
369 fn enable_non_volatile_memops(&mut self) {
372 self.enable_non_volatile_memops = true;
373 }
374
375 fn canonicalize_nans(&mut self, enable: bool) {
376 self.enable_nan_canonicalization = enable;
377 }
378
379 fn compiler(self: Box<Self>) -> Box<dyn Compiler> {
381 Box::new(LLVMCompiler::new(*self))
382 }
383
384 fn push_middleware(&mut self, middleware: Arc<dyn ModuleMiddleware>) {
386 self.middlewares.push(middleware);
387 }
388
389 fn supported_features_for_target(&self, _target: &Target) -> wasmer_types::Features {
390 let mut feats = Features::default();
391 feats.exceptions(true);
392 feats.relaxed_simd(true);
393 feats.wide_arithmetic(true);
394 feats
395 }
396}
397
398impl Default for LLVM {
399 fn default() -> LLVM {
400 Self::new()
401 }
402}
403
404impl From<LLVM> for Engine {
405 fn from(config: LLVM) -> Self {
406 EngineBuilder::new(config).engine()
407 }
408}