Skip to main content

llvm_pm/
lib.rs

1//! Safe Rust wrapper for LLVM's new PassManager.
2//!
3//! Provides [`ModulePassManager`] and [`FunctionPassManager`] for running optimization
4//! passes on LLVM modules and functions using the new PassBuilder-based infrastructure
5//! (LLVM 10+).
6//!
7//! # Example
8//!
9//! ```ignore
10//! use inkwell::context::Context;
11//! use llvm_pm::{ModulePassManager, OptLevel};
12//!
13//! let context = Context::create();
14//! let module = context.create_module("my_module");
15//!
16//! let mut pm = ModulePassManager::with_opt_level(None, OptLevel::O2, None)
17//!     .expect("Failed to create pass manager");
18//! pm.run(&module).expect("Pass execution failed");
19//! ```
20
21#[cfg(any(
22    feature = "llvm10-0",
23    feature = "llvm11-0",
24    feature = "llvm12-0",
25    feature = "llvm13-0",
26    feature = "llvm14-0",
27    feature = "llvm15-0",
28    feature = "llvm16-0",
29    feature = "llvm17-0",
30    feature = "llvm18-0"
31))]
32pub extern crate inkwell_05 as inkwell;
33#[cfg(any(
34    feature = "llvm19-1",
35    feature = "llvm20-1",
36    feature = "llvm21-1",
37    feature = "llvm22-1"
38))]
39pub extern crate inkwell_09 as inkwell;
40
41pub mod traits;
42
43#[cfg(feature = "llvm-plugin-crate")]
44mod llvm_plugin_harness;
45
46use inkwell::values::AsValueRef;
47use std::cell::OnceCell;
48use std::collections::HashMap;
49use std::ffi::{c_void, CStr, CString};
50use std::fmt;
51use std::marker::PhantomData;
52#[cfg(feature = "llvm-plugin-crate")]
53use std::mem::ManuallyDrop;
54use std::ptr;
55use std::sync::{Mutex, Once};
56
57pub use llvm_pm_sys::{LLVMBasicBlockRef, LLVMModuleRef, LLVMValueRef};
58use traits::{
59    LlvmCgsccAnalysis, LlvmCgsccPass, LlvmFunctionPass, LlvmLoopAnalysis, LlvmLoopPass,
60    LlvmModulePass, PreservedAnalyses,
61};
62pub type AnalysisKey = *const u8;
63
64#[cfg(all(
65    feature = "llvm-plugin-crate",
66    any(
67        feature = "llvm19-1",
68        feature = "llvm20-1",
69        feature = "llvm21-1",
70        feature = "llvm22-1"
71    )
72))]
73compile_error!(
74    "`llvm-plugin-crate` supports llvm-plugin-compatible LLVM features (llvm10-0 .. llvm18-0)."
75);
76
77pub struct ModuleAnalysisManager {
78    inner: *mut c_void,
79    from_analysis_id: Option<AnalysisKey>,
80}
81
82impl ModuleAnalysisManager {
83    /// # Safety
84    /// `inner` must be a valid pointer to LLVM's `ModuleAnalysisManager`.
85    pub unsafe fn from_raw(inner: *mut c_void, from_analysis_id: Option<AnalysisKey>) -> Self {
86        Self {
87            inner,
88            from_analysis_id,
89        }
90    }
91    pub fn as_raw(&self) -> *mut c_void {
92        self.inner
93    }
94    pub fn from_analysis_id(&self) -> Option<AnalysisKey> {
95        self.from_analysis_id
96    }
97}
98
99pub struct FunctionAnalysisManager {
100    inner: *mut c_void,
101    from_analysis_id: Option<AnalysisKey>,
102}
103
104impl FunctionAnalysisManager {
105    /// # Safety
106    /// `inner` must be a valid pointer to LLVM's `FunctionAnalysisManager`.
107    pub unsafe fn from_raw(inner: *mut c_void, from_analysis_id: Option<AnalysisKey>) -> Self {
108        Self {
109            inner,
110            from_analysis_id,
111        }
112    }
113    pub fn as_raw(&self) -> *mut c_void {
114        self.inner
115    }
116    pub fn from_analysis_id(&self) -> Option<AnalysisKey> {
117        self.from_analysis_id
118    }
119}
120
121/// Optimization level for the default pass pipeline.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
123pub enum OptLevel {
124    O0,
125    O1,
126    O2,
127    O3,
128    Os,
129    Oz,
130}
131
132impl OptLevel {
133    fn to_c(self) -> llvm_pm_sys::LlvmPmOptLevel {
134        match self {
135            OptLevel::O0 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O0,
136            OptLevel::O1 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O1,
137            OptLevel::O2 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O2,
138            OptLevel::O3 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O3,
139            OptLevel::Os => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_Os,
140            OptLevel::Oz => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_Oz,
141        }
142    }
143}
144
145/// Error type for pass manager operations.
146#[derive(Debug)]
147pub struct Error {
148    message: String,
149}
150
151impl Error {
152    /// Returns the error message.
153    pub fn message(&self) -> &str {
154        &self.message
155    }
156}
157
158impl fmt::Display for Error {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        write!(f, "{}", self.message)
161    }
162}
163
164impl std::error::Error for Error {}
165
166/// Consume a C error string into a Rust [`Error`], freeing the C string.
167///
168/// # Safety
169/// `ptr` must be a non-null pointer to a C string allocated by the C++ stubs
170/// (via `malloc`/`copyString`). Ownership is transferred to this function.
171unsafe fn consume_c_error(ptr: *mut std::ffi::c_char) -> Error {
172    // SAFETY: Caller guarantees ptr is a valid, non-null, malloc'd C string.
173    let msg = CStr::from_ptr(ptr).to_string_lossy().into_owned();
174    llvm_pm_sys::llvm_pm_dispose_message(ptr);
175    Error { message: msg }
176}
177
178// =========================================================================
179// Options
180// =========================================================================
181
182/// Builder for pass manager options.
183///
184/// Controls debug logging, IR verification, and extension point pipeline
185/// additions. Pass to [`ModulePassManager`] or [`FunctionPassManager`]
186/// constructors via `Option<&Options>`.
187pub struct Options {
188    raw: llvm_pm_sys::LlvmPmOptionsRef,
189}
190
191impl Options {
192    /// Create default options (debug logging off, verify each off).
193    pub fn new() -> Self {
194        // SAFETY: llvm_pm_options_create always returns a valid handle.
195        let raw = unsafe { llvm_pm_sys::llvm_pm_options_create() };
196        Self { raw }
197    }
198
199    /// Enable or disable debug logging output during pass execution.
200    pub fn debug_logging(&mut self, val: bool) -> &mut Self {
201        // SAFETY: self.raw is a valid options handle created by llvm_pm_options_create.
202        unsafe {
203            llvm_pm_sys::llvm_pm_options_set_debug_logging(self.raw, val as i32);
204        }
205        self
206    }
207
208    /// Enable or disable IR verification after each pass.
209    pub fn verify_each(&mut self, val: bool) -> &mut Self {
210        // SAFETY: self.raw is a valid options handle created by llvm_pm_options_create.
211        unsafe {
212            llvm_pm_sys::llvm_pm_options_set_verify_each(self.raw, val as i32);
213        }
214        self
215    }
216
217    /// Add a pass pipeline at the peephole extension point (after instcombine, function-level).
218    pub fn add_peephole_ep(&mut self, pipeline: &str) -> &mut Self {
219        let c = CString::new(pipeline).expect("pipeline contains null byte");
220        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
221        unsafe {
222            llvm_pm_sys::llvm_pm_options_add_peephole_ep(self.raw, c.as_ptr());
223        }
224        self
225    }
226
227    /// Add a pass pipeline at the optimizer-early extension point (module-level).
228    pub fn add_optimizer_early_ep(&mut self, pipeline: &str) -> &mut Self {
229        let c = CString::new(pipeline).expect("pipeline contains null byte");
230        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
231        unsafe {
232            llvm_pm_sys::llvm_pm_options_add_optimizer_early_ep(self.raw, c.as_ptr());
233        }
234        self
235    }
236
237    /// Add a pass pipeline at the optimizer-last extension point (module-level).
238    pub fn add_optimizer_last_ep(&mut self, pipeline: &str) -> &mut Self {
239        let c = CString::new(pipeline).expect("pipeline contains null byte");
240        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
241        unsafe {
242            llvm_pm_sys::llvm_pm_options_add_optimizer_last_ep(self.raw, c.as_ptr());
243        }
244        self
245    }
246
247    /// Add a pass pipeline at the vectorizer-start extension point (function-level).
248    pub fn add_vectorizer_start_ep(&mut self, pipeline: &str) -> &mut Self {
249        let c = CString::new(pipeline).expect("pipeline contains null byte");
250        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
251        unsafe {
252            llvm_pm_sys::llvm_pm_options_add_vectorizer_start_ep(self.raw, c.as_ptr());
253        }
254        self
255    }
256
257    /// Add a pass pipeline at the scalar-optimizer-late extension point (function-level).
258    pub fn add_scalar_optimizer_late_ep(&mut self, pipeline: &str) -> &mut Self {
259        let c = CString::new(pipeline).expect("pipeline contains null byte");
260        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
261        unsafe {
262            llvm_pm_sys::llvm_pm_options_add_scalar_optimizer_late_ep(self.raw, c.as_ptr());
263        }
264        self
265    }
266
267    /// Add a pass pipeline at the pipeline-start extension point (module-level).
268    pub fn add_pipeline_start_ep(&mut self, pipeline: &str) -> &mut Self {
269        let c = CString::new(pipeline).expect("pipeline contains null byte");
270        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
271        unsafe {
272            llvm_pm_sys::llvm_pm_options_add_pipeline_start_ep(self.raw, c.as_ptr());
273        }
274        self
275    }
276
277    /// Add a pass pipeline at the pipeline-early-simplification extension point (module-level).
278    pub fn add_pipeline_early_simplification_ep(&mut self, pipeline: &str) -> &mut Self {
279        let c = CString::new(pipeline).expect("pipeline contains null byte");
280        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
281        unsafe {
282            llvm_pm_sys::llvm_pm_options_add_pipeline_early_simplification_ep(self.raw, c.as_ptr());
283        }
284        self
285    }
286}
287
288impl Default for Options {
289    fn default() -> Self {
290        Self::new()
291    }
292}
293
294impl Drop for Options {
295    fn drop(&mut self) {
296        // SAFETY: self.raw is a valid options handle, and Drop runs at most once.
297        unsafe {
298            llvm_pm_sys::llvm_pm_options_dispose(self.raw);
299        }
300    }
301}
302
303/// Analysis manager handle for CGSCC passes and analyses.
304pub struct CgsccAnalysisManager {
305    raw: *mut c_void,
306    from_analysis_id: Option<AnalysisKey>,
307}
308
309impl CgsccAnalysisManager {
310    /// Construct from an opaque manager pointer passed by the C++ layer.
311    ///
312    /// # Safety
313    /// `raw` must be a valid pointer to LLVM's `CGSCCAnalysisManager`.
314    pub unsafe fn from_raw(raw: *mut c_void) -> Self {
315        Self {
316            raw,
317            from_analysis_id: None,
318        }
319    }
320
321    unsafe fn from_raw_with_analysis_id(
322        raw: *mut c_void,
323        from_analysis_id: Option<AnalysisKey>,
324    ) -> Self {
325        Self {
326            raw,
327            from_analysis_id,
328        }
329    }
330
331    /// Get the underlying opaque pointer.
332    pub fn as_raw(&self) -> *mut c_void {
333        self.raw
334    }
335
336    /// Register a CGSCC analysis pass.
337    pub fn add_analysis<P>(&self, pass: P)
338    where
339        P: LlvmCgsccAnalysis,
340        P: 'static,
341        <P as LlvmCgsccAnalysis>::Result: 'static,
342    {
343        extern "C" fn pass_deleter<T: LlvmCgsccAnalysis>(pass: *mut c_void) {
344            // SAFETY: Pointer was created by Box::into_raw in add_pass.
345            drop(unsafe { Box::<T>::from_raw(pass.cast()) });
346        }
347
348        fn pass_entrypoint<T>(
349            pass: *mut c_void,
350            function: &inkwell::values::FunctionValue<'_>,
351            manager: *mut c_void,
352        ) -> *mut c_void
353        where
354            T: LlvmCgsccAnalysis,
355            T::Result: 'static,
356        {
357            // SAFETY: pass is a valid pointer to T stored in registry.
358            let pass = unsafe { &*(pass as *const T) };
359            // SAFETY: manager is valid for callback duration.
360            let manager =
361                unsafe { CgsccAnalysisManager::from_raw_with_analysis_id(manager, Some(T::id())) };
362            let result = pass.run_analysis(function, &manager);
363            Box::into_raw(Box::new(result)) as *mut c_void
364        }
365
366        let manager_key = self.raw as usize;
367        let analysis_key = <P as LlvmCgsccAnalysis>::id() as usize;
368        let mut passes = cgscc_analysis_passes()
369            .lock()
370            .expect("poisoned cgscc analysis registry");
371        let entry_map = passes.entry(manager_key).or_default();
372        assert!(
373            !entry_map.contains_key(&analysis_key),
374            "analysis already registered"
375        );
376        entry_map.insert(
377            analysis_key,
378            CgsccAnalysisEntry {
379                pass: Box::into_raw(Box::new(pass)) as *mut c_void,
380                pass_deleter: pass_deleter::<P>,
381                pass_entrypoint: pass_entrypoint::<P>,
382            },
383        );
384    }
385
386    /// Get (or compute) analysis result for a function in current SCC.
387    pub fn get_result<A>(&self, function: &inkwell::values::FunctionValue<'_>) -> &A::Result
388    where
389        A: LlvmCgsccAnalysis + 'static,
390        A::Result: 'static,
391    {
392        let id = A::id();
393        assert!(
394            !matches!(self.from_analysis_id, Some(n) if n == id),
395            "Analysis cannot request its own result"
396        );
397
398        let manager_key = self.raw as usize;
399        let analysis_key = id as usize;
400        let function_key = function.as_value_ref() as usize;
401
402        if let Some(result) = self.get_cached_result::<A>(function) {
403            return result;
404        }
405
406        let passes = cgscc_analysis_passes()
407            .lock()
408            .expect("poisoned cgscc analysis registry");
409        let entry = passes
410            .get(&manager_key)
411            .and_then(|m| m.get(&analysis_key))
412            .expect("analysis was not registered");
413        let result_ptr = (entry.pass_entrypoint)(entry.pass, function, self.raw);
414        drop(passes);
415
416        let mut cache = cgscc_analysis_cache()
417            .lock()
418            .expect("poisoned cgscc analysis cache");
419        cache
420            .entry(manager_key)
421            .or_default()
422            .insert((analysis_key, function_key), result_ptr as usize);
423        // SAFETY: result_ptr points to a leaked Box<A::Result> stored in cache.
424        unsafe { &*(result_ptr as *const A::Result) }
425    }
426
427    /// Get cached analysis result if present.
428    pub fn get_cached_result<A>(
429        &self,
430        function: &inkwell::values::FunctionValue<'_>,
431    ) -> Option<&A::Result>
432    where
433        A: LlvmCgsccAnalysis + 'static,
434        A::Result: 'static,
435    {
436        let id = A::id();
437        assert!(
438            !matches!(self.from_analysis_id, Some(n) if n == id),
439            "Analysis cannot request its own result"
440        );
441
442        let manager_key = self.raw as usize;
443        let analysis_key = id as usize;
444        let function_key = function.as_value_ref() as usize;
445        let cache = cgscc_analysis_cache()
446            .lock()
447            .expect("poisoned cgscc analysis cache");
448        cache
449            .get(&manager_key)
450            .and_then(|m| m.get(&(analysis_key, function_key)))
451            // SAFETY: cached pointer values are inserted only from `Box<A::Result>` in
452            // `get_result`, keyed by the same analysis type `A`.
453            .map(|ptr| unsafe { &*((*ptr as *const c_void) as *const A::Result) })
454    }
455}
456
457/// Analysis manager handle for loop passes and analyses.
458pub struct LoopAnalysisManager {
459    raw: *mut c_void,
460    from_analysis_id: Option<AnalysisKey>,
461}
462
463impl LoopAnalysisManager {
464    /// Construct from an opaque manager pointer passed by the C++ layer.
465    ///
466    /// # Safety
467    /// `raw` must be a valid pointer to LLVM's `LoopAnalysisManager`.
468    pub unsafe fn from_raw(raw: *mut c_void) -> Self {
469        Self {
470            raw,
471            from_analysis_id: None,
472        }
473    }
474
475    unsafe fn from_raw_with_analysis_id(
476        raw: *mut c_void,
477        from_analysis_id: Option<AnalysisKey>,
478    ) -> Self {
479        Self {
480            raw,
481            from_analysis_id,
482        }
483    }
484
485    /// Get the underlying opaque pointer.
486    pub fn as_raw(&self) -> *mut c_void {
487        self.raw
488    }
489
490    /// Register a loop analysis pass.
491    pub fn add_analysis<P>(&self, pass: P)
492    where
493        P: LlvmLoopAnalysis,
494        P: 'static,
495        <P as LlvmLoopAnalysis>::Result: 'static,
496    {
497        extern "C" fn pass_deleter<T: LlvmLoopAnalysis>(pass: *mut c_void) {
498            // SAFETY: Pointer was created by Box::into_raw in add_pass.
499            drop(unsafe { Box::<T>::from_raw(pass.cast()) });
500        }
501
502        fn pass_entrypoint<T>(
503            pass: *mut c_void,
504            loop_header: LLVMBasicBlockRef,
505            manager: *mut c_void,
506        ) -> *mut c_void
507        where
508            T: LlvmLoopAnalysis,
509            T::Result: 'static,
510        {
511            // SAFETY: pass is a valid pointer to T stored in registry.
512            let pass = unsafe { &*(pass as *const T) };
513            // SAFETY: manager is valid for callback duration.
514            let manager =
515                unsafe { LoopAnalysisManager::from_raw_with_analysis_id(manager, Some(T::id())) };
516            let result = pass.run_analysis(loop_header, &manager);
517            Box::into_raw(Box::new(result)) as *mut c_void
518        }
519
520        let manager_key = self.raw as usize;
521        let analysis_key = <P as LlvmLoopAnalysis>::id() as usize;
522        let mut passes = loop_analysis_passes()
523            .lock()
524            .expect("poisoned loop analysis registry");
525        let entry_map = passes.entry(manager_key).or_default();
526        assert!(
527            !entry_map.contains_key(&analysis_key),
528            "analysis already registered"
529        );
530        entry_map.insert(
531            analysis_key,
532            LoopAnalysisEntry {
533                pass: Box::into_raw(Box::new(pass)) as *mut c_void,
534                pass_deleter: pass_deleter::<P>,
535                pass_entrypoint: pass_entrypoint::<P>,
536            },
537        );
538    }
539
540    /// Get (or compute) analysis result for a loop header.
541    pub fn get_result<A>(&self, loop_header: LLVMBasicBlockRef) -> &A::Result
542    where
543        A: LlvmLoopAnalysis + 'static,
544        A::Result: 'static,
545    {
546        let id = A::id();
547        assert!(
548            !matches!(self.from_analysis_id, Some(n) if n == id),
549            "Analysis cannot request its own result"
550        );
551
552        let manager_key = self.raw as usize;
553        let analysis_key = id as usize;
554        let loop_key = loop_header as usize;
555
556        if let Some(result) = self.get_cached_result::<A>(loop_header) {
557            return result;
558        }
559
560        let passes = loop_analysis_passes()
561            .lock()
562            .expect("poisoned loop analysis registry");
563        let entry = passes
564            .get(&manager_key)
565            .and_then(|m| m.get(&analysis_key))
566            .expect("analysis was not registered");
567        let result_ptr = (entry.pass_entrypoint)(entry.pass, loop_header, self.raw);
568        drop(passes);
569
570        let mut cache = loop_analysis_cache()
571            .lock()
572            .expect("poisoned loop analysis cache");
573        cache
574            .entry(manager_key)
575            .or_default()
576            .insert((analysis_key, loop_key), result_ptr as usize);
577        // SAFETY: result_ptr points to a leaked Box<A::Result> stored in cache.
578        unsafe { &*(result_ptr as *const A::Result) }
579    }
580
581    /// Get cached analysis result if present.
582    pub fn get_cached_result<A>(&self, loop_header: LLVMBasicBlockRef) -> Option<&A::Result>
583    where
584        A: LlvmLoopAnalysis + 'static,
585        A::Result: 'static,
586    {
587        let id = A::id();
588        assert!(
589            !matches!(self.from_analysis_id, Some(n) if n == id),
590            "Analysis cannot request its own result"
591        );
592
593        let manager_key = self.raw as usize;
594        let analysis_key = id as usize;
595        let loop_key = loop_header as usize;
596        let cache = loop_analysis_cache()
597            .lock()
598            .expect("poisoned loop analysis cache");
599        cache
600            .get(&manager_key)
601            .and_then(|m| m.get(&(analysis_key, loop_key)))
602            // SAFETY: cached pointer values are inserted only from `Box<A::Result>` in
603            // `get_result`, keyed by the same analysis type `A`.
604            .map(|ptr| unsafe { &*((*ptr as *const c_void) as *const A::Result) })
605    }
606}
607
608struct CgsccAnalysisEntry {
609    pass: *mut c_void,
610    pass_deleter: extern "C" fn(*mut c_void),
611    pass_entrypoint:
612        fn(*mut c_void, &inkwell::values::FunctionValue<'_>, *mut c_void) -> *mut c_void,
613}
614
615struct LoopAnalysisEntry {
616    pass: *mut c_void,
617    pass_deleter: extern "C" fn(*mut c_void),
618    pass_entrypoint: fn(*mut c_void, LLVMBasicBlockRef, *mut c_void) -> *mut c_void,
619}
620
621impl Drop for CgsccAnalysisEntry {
622    fn drop(&mut self) {
623        (self.pass_deleter)(self.pass);
624    }
625}
626
627impl Drop for LoopAnalysisEntry {
628    fn drop(&mut self) {
629        (self.pass_deleter)(self.pass);
630    }
631}
632
633// SAFETY: Entries are only accessed under a mutex and contain raw pointers to heap
634// allocations owned by this process.
635unsafe impl Send for CgsccAnalysisEntry {}
636unsafe impl Send for LoopAnalysisEntry {}
637
638struct SyncOnceCell<T>(OnceCell<T>);
639
640impl<T> SyncOnceCell<T> {
641    const fn new() -> Self {
642        Self(OnceCell::new())
643    }
644}
645
646// SAFETY: Access to initialization is synchronized externally via `Once`.
647// After initialization, only shared references are handed out and `T: Sync`.
648unsafe impl<T: Sync> Sync for SyncOnceCell<T> {}
649
650fn cgscc_analysis_passes() -> &'static Mutex<HashMap<usize, HashMap<usize, CgsccAnalysisEntry>>> {
651    static INIT: Once = Once::new();
652    static CELL: SyncOnceCell<Mutex<HashMap<usize, HashMap<usize, CgsccAnalysisEntry>>>> =
653        SyncOnceCell::new();
654    INIT.call_once(|| {
655        let _ = CELL.0.set(Mutex::new(HashMap::new()));
656    });
657    CELL.0.get().expect("cgscc registry initialized")
658}
659
660fn cgscc_analysis_cache() -> &'static Mutex<HashMap<usize, HashMap<(usize, usize), usize>>> {
661    static INIT: Once = Once::new();
662    static CELL: SyncOnceCell<Mutex<HashMap<usize, HashMap<(usize, usize), usize>>>> =
663        SyncOnceCell::new();
664    INIT.call_once(|| {
665        let _ = CELL.0.set(Mutex::new(HashMap::new()));
666    });
667    CELL.0.get().expect("cgscc cache initialized")
668}
669
670fn loop_analysis_passes() -> &'static Mutex<HashMap<usize, HashMap<usize, LoopAnalysisEntry>>> {
671    static INIT: Once = Once::new();
672    static CELL: SyncOnceCell<Mutex<HashMap<usize, HashMap<usize, LoopAnalysisEntry>>>> =
673        SyncOnceCell::new();
674    INIT.call_once(|| {
675        let _ = CELL.0.set(Mutex::new(HashMap::new()));
676    });
677    CELL.0.get().expect("loop registry initialized")
678}
679
680fn loop_analysis_cache() -> &'static Mutex<HashMap<usize, HashMap<(usize, usize), usize>>> {
681    static INIT: Once = Once::new();
682    static CELL: SyncOnceCell<Mutex<HashMap<usize, HashMap<(usize, usize), usize>>>> =
683        SyncOnceCell::new();
684    INIT.call_once(|| {
685        let _ = CELL.0.set(Mutex::new(HashMap::new()));
686    });
687    CELL.0.get().expect("loop cache initialized")
688}
689
690fn preserved_to_c(pa: traits::PreservedAnalyses) -> std::ffi::c_int {
691    match pa {
692        PreservedAnalyses::All => 0,
693        PreservedAnalyses::None => 1,
694    }
695}
696
697/// Generic trampoline for module passes. Monomorphized per `T`.
698///
699/// # Safety
700/// `user_data` must be a valid pointer to a `T` that was stored in
701/// [`ModulePassManager::_passes`]. `module` must be a valid `LLVMModuleRef`.
702unsafe extern "C" fn module_pass_trampoline<T: LlvmModulePass>(
703    module: LLVMModuleRef,
704    manager: *mut c_void,
705    user_data: *mut c_void,
706) -> std::ffi::c_int {
707    // SAFETY: user_data was cast from &T stored in a Box inside _passes.
708    let pass = &*(user_data as *const T);
709    let mut module = inkwell::module::Module::new(module);
710    let manager = ModuleAnalysisManager::from_raw(manager, None);
711    let result = pass.run_pass(&mut module, &manager);
712    std::mem::forget(module);
713    preserved_to_c(result)
714}
715
716/// Generic trampoline for function passes. Monomorphized per `T`.
717///
718/// # Safety
719/// `user_data` must be a valid pointer to a `T` that was stored in
720/// [`FunctionPassManager::_passes`]. `function` must be a valid `LLVMValueRef`.
721unsafe extern "C" fn function_pass_trampoline<T: LlvmFunctionPass>(
722    function: LLVMValueRef,
723    manager: *mut c_void,
724    user_data: *mut c_void,
725) -> std::ffi::c_int {
726    let pass = &*(user_data as *const T);
727    let mut function = inkwell::values::FunctionValue::new(function).expect("invalid function");
728    let manager = FunctionAnalysisManager::from_raw(manager, None);
729    let result = pass.run_pass(&mut function, &manager);
730    preserved_to_c(result)
731}
732
733/// Generic trampoline for CGSCC passes. Monomorphized per `T`.
734///
735/// # Safety
736/// `user_data` must be a valid pointer to a `T` that was stored in
737/// [`ModulePassManager::_passes`]. `function` must be a valid `LLVMValueRef`.
738unsafe extern "C" fn cgscc_pass_trampoline<T: LlvmCgsccPass>(
739    function: LLVMValueRef,
740    manager: *mut c_void,
741    user_data: *mut c_void,
742) -> std::ffi::c_int {
743    let pass = &*(user_data as *const T);
744    let mut function = inkwell::values::FunctionValue::new(function).expect("invalid function");
745    let manager = CgsccAnalysisManager::from_raw(manager);
746    let result = pass.run_pass(&mut function, &manager);
747    preserved_to_c(result)
748}
749
750/// Generic trampoline for loop passes. Monomorphized per `T`.
751///
752/// # Safety
753/// `user_data` must be a valid pointer to a `T` that was stored in
754/// [`FunctionPassManager::_passes`]. `header` must be a valid `LLVMBasicBlockRef`.
755unsafe extern "C" fn loop_pass_trampoline<T: LlvmLoopPass>(
756    header: LLVMBasicBlockRef,
757    manager: *mut c_void,
758    user_data: *mut c_void,
759) -> std::ffi::c_int {
760    let pass = &*(user_data as *const T);
761    let manager = LoopAnalysisManager::from_raw(manager);
762    let result = pass.run_pass(header, &manager);
763    preserved_to_c(result)
764}
765
766// =========================================================================
767// ModulePassManager
768// =========================================================================
769
770/// A configured LLVM module pass manager using the new PassManager infrastructure.
771///
772/// Bundles all analysis managers, PassBuilder, StandardInstrumentations, and the
773/// ModulePassManager into a single object with correct lifetime management.
774///
775/// The lifetime `'a` is tied to the borrowed [`inkwell::targets::TargetMachine`],
776/// ensuring the target machine outlives the pass manager.
777pub struct ModulePassManager<'a> {
778    raw: llvm_pm_sys::LlvmPmPassManagerRef,
779    _passes: Vec<Box<dyn std::any::Any>>,
780    _phantom: PhantomData<&'a ()>,
781}
782
783impl<'a> fmt::Debug for ModulePassManager<'a> {
784    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785        f.debug_struct("ModulePassManager")
786            .field("raw", &self.raw)
787            .finish()
788    }
789}
790
791impl<'a> ModulePassManager<'a> {
792    /// Create a pass manager with a standard optimization pipeline.
793    pub fn with_opt_level(
794        target_machine: Option<&'a inkwell::targets::TargetMachine>,
795        level: OptLevel,
796        options: Option<&Options>,
797    ) -> Result<Self, Error> {
798        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
799        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
800        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
801
802        // SAFETY: tm is either null or a valid LLVMTargetMachineRef from inkwell.
803        // opts is either null or a valid options handle. err_msg is a valid out-pointer.
804        let raw = unsafe {
805            llvm_pm_sys::llvm_pm_create_with_opt_level(tm, level.to_c(), opts, &mut err_msg)
806        };
807
808        if raw.is_null() {
809            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
810            Err(unsafe { consume_c_error(err_msg) })
811        } else {
812            Ok(Self {
813                raw,
814                _passes: Vec::new(),
815                _phantom: PhantomData,
816            })
817        }
818    }
819
820    /// Create a pass manager from a textual pipeline description.
821    ///
822    /// The format matches `opt -passes=...` syntax, e.g.:
823    /// - `"instcombine,dce,sroa"`
824    /// - `"default<O2>"`
825    /// - `"module(function(instcombine,sroa))"`
826    pub fn with_pipeline(
827        target_machine: Option<&'a inkwell::targets::TargetMachine>,
828        pipeline: &str,
829        options: Option<&Options>,
830    ) -> Result<Self, Error> {
831        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
832        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
833        let c_pipeline = CString::new(pipeline).map_err(|e| Error {
834            message: format!("Pipeline string contains null byte: {}", e),
835        })?;
836        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
837
838        // SAFETY: tm is either null or valid. c_pipeline is a valid null-terminated string.
839        let raw = unsafe {
840            llvm_pm_sys::llvm_pm_create_with_pipeline(tm, c_pipeline.as_ptr(), opts, &mut err_msg)
841        };
842
843        if raw.is_null() {
844            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
845            Err(unsafe { consume_c_error(err_msg) })
846        } else {
847            Ok(Self {
848                raw,
849                _passes: Vec::new(),
850                _phantom: PhantomData,
851            })
852        }
853    }
854
855    /// Create a pass manager with the full-LTO default pipeline.
856    pub fn with_lto(
857        target_machine: Option<&'a inkwell::targets::TargetMachine>,
858        level: OptLevel,
859        options: Option<&Options>,
860    ) -> Result<Self, Error> {
861        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
862        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
863        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
864
865        // SAFETY: tm is either null or valid. opts is either null or valid.
866        let raw = unsafe { llvm_pm_sys::llvm_pm_create_lto(tm, level.to_c(), opts, &mut err_msg) };
867
868        if raw.is_null() {
869            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
870            Err(unsafe { consume_c_error(err_msg) })
871        } else {
872            Ok(Self {
873                raw,
874                _passes: Vec::new(),
875                _phantom: PhantomData,
876            })
877        }
878    }
879
880    /// Create a pass manager with the full-LTO pre-link pipeline.
881    pub fn with_lto_pre_link(
882        target_machine: Option<&'a inkwell::targets::TargetMachine>,
883        level: OptLevel,
884        options: Option<&Options>,
885    ) -> Result<Self, Error> {
886        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
887        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
888        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
889
890        // SAFETY: tm is either null or valid. opts is either null or valid.
891        let raw = unsafe {
892            llvm_pm_sys::llvm_pm_create_lto_pre_link(tm, level.to_c(), opts, &mut err_msg)
893        };
894
895        if raw.is_null() {
896            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
897            Err(unsafe { consume_c_error(err_msg) })
898        } else {
899            Ok(Self {
900                raw,
901                _passes: Vec::new(),
902                _phantom: PhantomData,
903            })
904        }
905    }
906
907    /// Create a pass manager with the ThinLTO pre-link pipeline.
908    pub fn with_thin_lto_pre_link(
909        target_machine: Option<&'a inkwell::targets::TargetMachine>,
910        level: OptLevel,
911        options: Option<&Options>,
912    ) -> Result<Self, Error> {
913        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
914        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
915        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
916
917        // SAFETY: tm is either null or valid. opts is either null or valid.
918        let raw = unsafe {
919            llvm_pm_sys::llvm_pm_create_thin_lto_pre_link(tm, level.to_c(), opts, &mut err_msg)
920        };
921
922        if raw.is_null() {
923            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
924            Err(unsafe { consume_c_error(err_msg) })
925        } else {
926            Ok(Self {
927                raw,
928                _passes: Vec::new(),
929                _phantom: PhantomData,
930            })
931        }
932    }
933
934    /// Create an empty module pass manager with no built-in passes.
935    ///
936    /// Use [`add_pass()`](ModulePassManager::add_pass) to add custom passes.
937    pub fn new(
938        target_machine: Option<&'a inkwell::targets::TargetMachine>,
939        options: Option<&Options>,
940    ) -> Result<Self, Error> {
941        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
942        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
943        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
944
945        // SAFETY: tm is either null or valid. opts is either null or valid.
946        let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_module(tm, opts, &mut err_msg) };
947
948        if raw.is_null() {
949            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
950            Err(unsafe { consume_c_error(err_msg) })
951        } else {
952            Ok(Self {
953                raw,
954                _passes: Vec::new(),
955                _phantom: PhantomData,
956            })
957        }
958    }
959
960    /// Add a custom module pass to this pass manager.
961    ///
962    /// The pass is moved into the pass manager and kept alive until the pass
963    /// manager is dropped. The pass is appended after any existing passes in
964    /// the pipeline.
965    pub fn add_pass<P>(&mut self, pass: P)
966    where
967        P: LlvmModulePass + 'static,
968    {
969        let mut boxed = Box::new(pass);
970        let ptr = &mut *boxed as *mut P as *mut c_void;
971        // SAFETY: self.raw is a valid PM handle. module_pass_trampoline::<T> is the
972        // correct monomorphized trampoline. The pass pointer is valid for the
973        // lifetime of the PM because the Box is stored in _passes.
974        unsafe {
975            llvm_pm_sys::llvm_pm_add_module_pass(self.raw, Some(module_pass_trampoline::<P>), ptr);
976        }
977        self._passes.push(boxed);
978    }
979
980    /// Add a custom CGSCC pass to this pass manager.
981    ///
982    /// The pass is adapted into the module pipeline and invoked for each
983    /// function in each SCC.
984    pub fn add_cgscc_pass<P>(&mut self, pass: P)
985    where
986        P: LlvmCgsccPass + 'static,
987    {
988        let mut boxed = Box::new(pass);
989        let ptr = &mut *boxed as *mut P as *mut c_void;
990        // SAFETY: self.raw is a valid PM handle. cgscc_pass_trampoline::<T> is the
991        // correct monomorphized trampoline. The pass pointer is valid for the
992        // lifetime of the PM because the Box is stored in _passes.
993        unsafe {
994            llvm_pm_sys::llvm_pm_add_cgscc_pass(self.raw, Some(cgscc_pass_trampoline::<P>), ptr);
995        }
996        self._passes.push(boxed);
997    }
998
999    /// Run the optimization passes on the given module.
1000    pub fn run(&mut self, module: &inkwell::module::Module<'_>) -> Result<(), Error> {
1001        // SAFETY: self.raw is a valid PM handle. module.as_mut_ptr() returns a valid
1002        // LLVMModuleRef. &mut self ensures exclusive access to stored passes.
1003        let err = unsafe { llvm_pm_sys::llvm_pm_run(self.raw, module.as_mut_ptr()) };
1004        if err.is_null() {
1005            Ok(())
1006        } else {
1007            // SAFETY: On error, llvm_pm_run returns a valid malloc'd error string.
1008            Err(unsafe { consume_c_error(err) })
1009        }
1010    }
1011}
1012
1013impl<'a> Drop for ModulePassManager<'a> {
1014    fn drop(&mut self) {
1015        // SAFETY: self.raw is a valid PM handle, and Drop runs at most once.
1016        // The C++ side is disposed first; _passes (stored Box<dyn Any>) are
1017        // dropped automatically afterward.
1018        unsafe {
1019            llvm_pm_sys::llvm_pm_dispose(self.raw);
1020        }
1021    }
1022}
1023
1024// SAFETY: The bundled pass manager owns all its internal state (analysis managers,
1025// PassBuilder, etc.) and does not share mutable state with other instances.
1026// Stored passes are only accessed via &mut self methods.
1027// Moving between threads is safe; concurrent access is prevented by requiring
1028// exclusive access for operations.
1029unsafe impl<'a> Send for ModulePassManager<'a> {}
1030
1031// =========================================================================
1032// FunctionPassManager
1033// =========================================================================
1034
1035/// A configured LLVM function pass manager using the new PassManager infrastructure.
1036///
1037/// Similar to [`ModulePassManager`] but runs function-level passes on individual
1038/// functions rather than entire modules.
1039///
1040/// The lifetime `'a` is tied to the borrowed [`inkwell::targets::TargetMachine`],
1041/// ensuring the target machine outlives the pass manager.
1042pub struct FunctionPassManager<'a> {
1043    raw: llvm_pm_sys::LlvmPmPassManagerRef,
1044    _passes: Vec<Box<dyn std::any::Any>>,
1045    _phantom: PhantomData<&'a ()>,
1046}
1047
1048impl<'a> fmt::Debug for FunctionPassManager<'a> {
1049    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1050        f.debug_struct("FunctionPassManager")
1051            .field("raw", &self.raw)
1052            .finish()
1053    }
1054}
1055
1056impl<'a> FunctionPassManager<'a> {
1057    /// Create a function pass manager from a textual pipeline description.
1058    ///
1059    /// The pipeline should contain function-level passes, e.g. `"instcombine,dce"`.
1060    pub fn with_pipeline(
1061        target_machine: Option<&'a inkwell::targets::TargetMachine>,
1062        pipeline: &str,
1063        options: Option<&Options>,
1064    ) -> Result<Self, Error> {
1065        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1066        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1067        let c_pipeline = CString::new(pipeline).map_err(|e| Error {
1068            message: format!("Pipeline string contains null byte: {}", e),
1069        })?;
1070        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1071
1072        // SAFETY: tm is either null or valid. c_pipeline is a valid null-terminated string.
1073        let raw = unsafe {
1074            llvm_pm_sys::llvm_pm_create_function_with_pipeline(
1075                tm,
1076                c_pipeline.as_ptr(),
1077                opts,
1078                &mut err_msg,
1079            )
1080        };
1081
1082        if raw.is_null() {
1083            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1084            Err(unsafe { consume_c_error(err_msg) })
1085        } else {
1086            Ok(Self {
1087                raw,
1088                _passes: Vec::new(),
1089                _phantom: PhantomData,
1090            })
1091        }
1092    }
1093
1094    /// Create an empty function pass manager with no built-in passes.
1095    ///
1096    /// Use [`add_pass()`](FunctionPassManager::add_pass) to add custom passes.
1097    pub fn new(
1098        target_machine: Option<&'a inkwell::targets::TargetMachine>,
1099        options: Option<&Options>,
1100    ) -> Result<Self, Error> {
1101        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1102        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1103        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1104
1105        // SAFETY: tm is either null or valid. opts is either null or valid.
1106        let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_function(tm, opts, &mut err_msg) };
1107
1108        if raw.is_null() {
1109            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1110            Err(unsafe { consume_c_error(err_msg) })
1111        } else {
1112            Ok(Self {
1113                raw,
1114                _passes: Vec::new(),
1115                _phantom: PhantomData,
1116            })
1117        }
1118    }
1119
1120    /// Add a custom function pass to this pass manager.
1121    ///
1122    /// The pass is moved into the pass manager and kept alive until the pass
1123    /// manager is dropped. The pass is appended after any existing passes in
1124    /// the pipeline.
1125    pub fn add_pass<P>(&mut self, pass: P)
1126    where
1127        P: LlvmFunctionPass + 'static,
1128    {
1129        let mut boxed = Box::new(pass);
1130        let ptr = &mut *boxed as *mut P as *mut c_void;
1131        // SAFETY: self.raw is a valid PM handle. function_pass_trampoline::<T> is the
1132        // correct monomorphized trampoline. The pass pointer is valid for the
1133        // lifetime of the PM because the Box is stored in _passes.
1134        unsafe {
1135            llvm_pm_sys::llvm_pm_add_function_pass(
1136                self.raw,
1137                Some(function_pass_trampoline::<P>),
1138                ptr,
1139            );
1140        }
1141        self._passes.push(boxed);
1142    }
1143
1144    /// Add a custom loop pass to this pass manager.
1145    ///
1146    /// The pass is adapted into the function pipeline and invoked with each
1147    /// loop header basic block.
1148    pub fn add_loop_pass<P>(&mut self, pass: P)
1149    where
1150        P: traits::LlvmLoopPass + 'static,
1151    {
1152        let mut boxed = Box::new(pass);
1153        let ptr = &mut *boxed as *mut P as *mut c_void;
1154        // SAFETY: self.raw is a valid PM handle. loop_pass_trampoline::<T> is the
1155        // correct monomorphized trampoline. The pass pointer is valid for the
1156        // lifetime of the PM because the Box is stored in _passes.
1157        unsafe {
1158            llvm_pm_sys::llvm_pm_add_loop_pass(self.raw, Some(loop_pass_trampoline::<P>), ptr);
1159        }
1160        self._passes.push(boxed);
1161    }
1162
1163    /// Run the function passes on the given function.
1164    pub fn run(&mut self, function: inkwell::values::FunctionValue<'_>) -> Result<(), Error> {
1165        use inkwell::values::AsValueRef;
1166        // SAFETY: self.raw is a valid PM handle. function.as_value_ref() returns a valid
1167        // LLVMValueRef. &mut self ensures exclusive access to stored passes.
1168        let err =
1169            unsafe { llvm_pm_sys::llvm_pm_run_on_function(self.raw, function.as_value_ref()) };
1170        if err.is_null() {
1171            Ok(())
1172        } else {
1173            // SAFETY: On error, llvm_pm_run_on_function returns a valid malloc'd error string.
1174            Err(unsafe { consume_c_error(err) })
1175        }
1176    }
1177}
1178
1179impl<'a> Drop for FunctionPassManager<'a> {
1180    fn drop(&mut self) {
1181        // SAFETY: self.raw is a valid PM handle, and Drop runs at most once.
1182        // The C++ side is disposed first; _passes (stored Box<dyn Any>) are
1183        // dropped automatically afterward.
1184        unsafe {
1185            llvm_pm_sys::llvm_pm_dispose(self.raw);
1186        }
1187    }
1188}
1189
1190// SAFETY: The bundled pass manager owns all its internal state (analysis managers,
1191// PassBuilder, etc.) and does not share mutable state with other instances.
1192// Stored passes are only accessed via &mut self methods.
1193// Moving between threads is safe; concurrent access is prevented by requiring
1194// exclusive (&mut) access for operations.
1195unsafe impl<'a> Send for FunctionPassManager<'a> {}