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_verifier: bool,
107 pub(crate) enable_perfmap: bool,
108 pub(crate) opt_level: LLVMOptLevel,
109 is_pic: bool,
110 pub(crate) callbacks: Option<LLVMCallbacks>,
111 pub(crate) middlewares: Vec<Arc<dyn ModuleMiddleware>>,
113 pub(crate) num_threads: NonZero<usize>,
115 pub(crate) verbose_asm: bool,
116}
117
118impl LLVM {
119 pub fn new() -> Self {
122 Self {
123 enable_nan_canonicalization: false,
124 enable_verifier: false,
125 enable_perfmap: false,
126 opt_level: LLVMOptLevel::Aggressive,
127 is_pic: false,
128 callbacks: None,
129 middlewares: vec![],
130 verbose_asm: false,
131 num_threads: std::thread::available_parallelism().unwrap_or(NonZero::new(1).unwrap()),
132 }
133 }
134
135 pub fn opt_level(&mut self, opt_level: LLVMOptLevel) -> &mut Self {
137 self.opt_level = opt_level;
138 self
139 }
140
141 pub fn num_threads(&mut self, num_threads: NonZero<usize>) -> &mut Self {
142 self.num_threads = num_threads;
143 self
144 }
145
146 pub fn verbose_asm(&mut self, verbose_asm: bool) -> &mut Self {
147 self.verbose_asm = verbose_asm;
148 self
149 }
150
151 pub fn callbacks(&mut self, callbacks: Option<LLVMCallbacks>) -> &mut Self {
154 self.callbacks = callbacks;
155 self
156 }
157
158 fn reloc_mode(&self, binary_format: BinaryFormat) -> RelocMode {
159 if matches!(binary_format, BinaryFormat::Macho) {
160 return RelocMode::Static;
161 }
162
163 if self.is_pic {
164 RelocMode::PIC
165 } else {
166 RelocMode::Static
167 }
168 }
169
170 fn code_model(&self, binary_format: BinaryFormat) -> CodeModel {
171 if matches!(binary_format, BinaryFormat::Macho) {
177 return CodeModel::Default;
178 }
179
180 if self.is_pic {
181 CodeModel::Small
182 } else {
183 CodeModel::Large
184 }
185 }
186
187 pub(crate) fn target_operating_system(&self, target: &Target) -> OperatingSystem {
188 match target.triple().operating_system {
189 OperatingSystem::Darwin(deployment) if !self.is_pic => {
190 #[allow(clippy::match_single_binding)]
198 match target.triple().architecture {
199 Architecture::Aarch64(_) => OperatingSystem::Darwin(deployment),
200 _ => OperatingSystem::Linux,
201 }
202 }
203 other => other,
204 }
205 }
206
207 pub(crate) fn target_binary_format(&self, target: &Target) -> target_lexicon::BinaryFormat {
208 if self.is_pic {
209 target.triple().binary_format
210 } else {
211 match self.target_operating_system(target) {
212 OperatingSystem::Darwin(_) => target_lexicon::BinaryFormat::Macho,
213 _ => target_lexicon::BinaryFormat::Elf,
214 }
215 }
216 }
217
218 fn target_triple(&self, target: &Target) -> TargetTriple {
219 let architecture = if target.triple().architecture
220 == Architecture::Riscv64(target_lexicon::Riscv64Architecture::Riscv64gc)
221 {
222 target_lexicon::Architecture::Riscv64(target_lexicon::Riscv64Architecture::Riscv64)
223 } else {
224 target.triple().architecture
225 };
226 let operating_system = self.target_operating_system(target);
230 let binary_format = self.target_binary_format(target);
231
232 let triple = Triple {
233 architecture,
234 vendor: target.triple().vendor.clone(),
235 operating_system,
236 environment: target.triple().environment,
237 binary_format,
238 };
239 TargetTriple::create(&triple.to_string())
240 }
241
242 pub fn target_machine(&self, target: &Target) -> TargetMachine {
244 self.target_machine_with_opt(target, true)
245 }
246
247 pub(crate) fn target_machine_with_opt(
248 &self,
249 target: &Target,
250 enable_optimization: bool,
251 ) -> TargetMachine {
252 let triple = target.triple();
253 let cpu_features = &target.cpu_features();
254
255 match triple.architecture {
256 Architecture::X86_64 | Architecture::X86_32(_) => {
257 InkwellTarget::initialize_x86(&InitializationConfig {
258 asm_parser: true,
259 asm_printer: true,
260 base: true,
261 disassembler: true,
262 info: true,
263 machine_code: true,
264 })
265 }
266 Architecture::Aarch64(_) => InkwellTarget::initialize_aarch64(&InitializationConfig {
267 asm_parser: true,
268 asm_printer: true,
269 base: true,
270 disassembler: true,
271 info: true,
272 machine_code: true,
273 }),
274 Architecture::Riscv64(_) | Architecture::Riscv32(_) => {
275 InkwellTarget::initialize_riscv(&InitializationConfig {
276 asm_parser: true,
277 asm_printer: true,
278 base: true,
279 disassembler: true,
280 info: true,
281 machine_code: true,
282 })
283 }
284 Architecture::LoongArch64 => {
285 InkwellTarget::initialize_loongarch(&InitializationConfig {
286 asm_parser: true,
287 asm_printer: true,
288 base: true,
289 disassembler: true,
290 info: true,
291 machine_code: true,
292 })
293 }
294 _ => unimplemented!("target {} not yet supported in Wasmer", triple),
295 }
296
297 let llvm_cpu_features = cpu_features
301 .iter()
302 .map(|feature| format!("+{feature}"))
303 .join(",");
304
305 let target_triple = self.target_triple(target);
306 let llvm_target = InkwellTarget::from_triple(&target_triple).unwrap();
307 let mut llvm_target_machine_options = TargetMachineOptions::new()
308 .set_cpu(match triple.architecture {
309 Architecture::Riscv64(_) => "generic-rv64",
310 Architecture::Riscv32(_) => "generic-rv32",
311 Architecture::LoongArch64 => "generic-la64",
312 _ => "generic",
313 })
314 .set_features(match triple.architecture {
315 Architecture::Riscv64(_) => "+m,+a,+c,+d,+f",
316 Architecture::Riscv32(_) => "+m,+a,+c,+d,+f",
317 Architecture::LoongArch64 => "+f,+d",
318 _ => &llvm_cpu_features,
319 })
320 .set_level(if enable_optimization {
321 self.opt_level
322 } else {
323 LLVMOptLevel::None
324 })
325 .set_reloc_mode(self.reloc_mode(self.target_binary_format(target)))
326 .set_code_model(match triple.architecture {
327 Architecture::LoongArch64 | Architecture::Riscv64(_) | Architecture::Riscv32(_) => {
328 CodeModel::Medium
329 }
330 _ => self.code_model(self.target_binary_format(target)),
331 });
332 if let Architecture::Riscv64(_) = triple.architecture {
333 llvm_target_machine_options = llvm_target_machine_options.set_abi("lp64d");
334 }
335 let target_machine = llvm_target
336 .create_target_machine_from_options(&target_triple, llvm_target_machine_options)
337 .unwrap();
338 target_machine.set_asm_verbosity(self.verbose_asm);
339 target_machine
340 }
341}
342
343impl CompilerConfig for LLVM {
344 fn enable_pic(&mut self) {
346 self.is_pic = true;
349 }
350
351 fn enable_perfmap(&mut self) {
352 self.enable_perfmap = true
353 }
354
355 fn enable_verifier(&mut self) {
357 self.enable_verifier = true;
358 }
359
360 fn canonicalize_nans(&mut self, enable: bool) {
361 self.enable_nan_canonicalization = enable;
362 }
363
364 fn compiler(self: Box<Self>) -> Box<dyn Compiler> {
366 Box::new(LLVMCompiler::new(*self))
367 }
368
369 fn push_middleware(&mut self, middleware: Arc<dyn ModuleMiddleware>) {
371 self.middlewares.push(middleware);
372 }
373
374 fn supported_features_for_target(&self, _target: &Target) -> wasmer_types::Features {
375 let mut feats = Features::default();
376 feats.exceptions(true);
377 feats.relaxed_simd(true);
378 feats
379 }
380}
381
382impl Default for LLVM {
383 fn default() -> LLVM {
384 Self::new()
385 }
386}
387
388impl From<LLVM> for Engine {
389 fn from(config: LLVM) -> Self {
390 EngineBuilder::new(config).engine()
391 }
392}