Skip to main content

llvm_pm/
lib.rs

1// # Safety overview
2//
3// This crate wraps LLVM's C++ PassManager through an `extern "C"` FFI layer.
4// All unsafe usage falls into these categories:
5//
6// ## FFI calls (Options, PassManager constructors, run, dispose)
7// Each C++ function receives either null or a valid handle created by a prior
8// C++ call. Handles are stored in private fields and never exposed, ensuring
9// validity until `Drop`. Error strings returned by C++ stubs are malloc'd
10// and freed exactly once via `consume_c_error`.
11//
12// ## Pass trampolines (`module_pass_trampoline`, etc.)
13// These `extern "C"` callbacks bridge C++ PassManager invocations to Rust
14// `LlvmModulePass`/`LlvmFunctionPass` trait methods. Safety relies on:
15// - `user_data` pointing to a `Box<T>` kept alive in `_passes: Vec<Box<dyn Any>>`
16// - Monomorphization ensuring the correct type `T` at each call site
17// - `Module::new()` + `mem::forget()` avoiding double-free of LLVM-owned modules
18//
19// **Panic safety**: if a pass's `run_pass` panics, the unwind would cross
20// an `extern "C"` boundary. Rust >= 1.71 aborts in this case; older versions
21// exhibit undefined behavior. Users must ensure their passes do not panic.
22//
23// ## `Send` implementations
24// `ModulePassManager` and `FunctionPassManager` implement `Send` because:
25// - The C++ handle owns all internal state (no shared mutable aliases)
26// - `_passes` contains only owned `Box`es
27// - All mutation requires `&mut self`, preventing concurrent access
28//
29// ## Global analysis registries (`cgscc_analysis_passes`, etc.)
30// Use `Once` + `static mut` to lazily initialize `&'static Mutex<HashMap<…>>`.
31// The `Box` is intentionally leaked to obtain `'static` lifetime. All access
32// is synchronized through `Mutex`.
33//
34// ## Analysis result caches
35// `get_result()` stores analysis results as leaked `Box<A::Result>` (cast to
36// `usize`) in a global cache keyed by `(manager_ptr, analysis_id, ir_key)`.
37// The leaked allocation is never freed, so the returned `&A::Result` reference
38// remains valid for the program's lifetime. Type safety is maintained because
39// the cache key includes the analysis type's `id()` and the lookup is generic
40// over `A`.
41//
42// **Known limitation**: after a PassManager is dropped, a new PM *could* receive
43// the same heap address, causing `get_result` to return stale (but type-safe and
44// dereferenceable) cached results from the previous PM. This is a correctness
45// concern, not a memory-safety issue, and only affects CGSCC/loop analyses
46// registered via the Rust-side analysis manager.
47//
48// ## Drop ordering
49// `ModulePassManager::drop` calls `llvm_pm_dispose` (freeing C++ infrastructure)
50// before Rust drops `_passes`. This is correct because the C++ `RustModulePass`
51// destructor does NOT free `user_data`—it only stores a raw pointer. After
52// `llvm_pm_dispose`, no C++ code will access the pass pointers.
53
54#![doc = include_str!("../README.md")]
55
56#[cfg(any(
57    feature = "llvm10-0",
58    feature = "llvm11-0",
59    feature = "llvm12-0",
60    feature = "llvm13-0",
61    feature = "llvm14-0",
62    feature = "llvm15-0",
63    feature = "llvm16-0",
64    feature = "llvm17-0"
65))]
66pub extern crate inkwell_05 as inkwell;
67#[cfg(any(
68    feature = "llvm18-1",
69    feature = "llvm19-1",
70    feature = "llvm20-1",
71    feature = "llvm21-1",
72    feature = "llvm22-1"
73))]
74pub extern crate inkwell_09 as inkwell;
75
76pub mod traits;
77
78pub mod plugin;
79
80// Re-export the #[plugin] attribute macro at crate root for ergonomic usage:
81// #[llvm_pm::plugin(name = "...", version = "...")]
82#[cfg(feature = "plugin-macros")]
83pub use llvm_pm_macros::plugin;
84
85#[cfg(feature = "llvm-plugin-crate")]
86mod llvm_plugin_harness;
87
88use inkwell::values::AsValueRef;
89use std::collections::HashMap;
90use std::ffi::{c_void, CStr, CString};
91use std::fmt;
92use std::marker::PhantomData;
93#[cfg(feature = "llvm-plugin-crate")]
94use std::mem::ManuallyDrop;
95use std::ptr;
96use std::sync::{Mutex, Once};
97
98use llvm_pm_sys::{LLVMBasicBlockRef, LLVMModuleRef, LLVMValueRef};
99use traits::{
100    LlvmCgsccAnalysis, LlvmCgsccPass, LlvmFunctionPass, LlvmLoopAnalysis, LlvmLoopPass,
101    LlvmModulePass, PreservedAnalyses,
102};
103type AnalysisKey = *const u8;
104
105#[cfg(all(
106    feature = "llvm-plugin-crate",
107    any(
108        feature = "llvm18-1",
109        feature = "llvm19-1",
110        feature = "llvm20-1",
111        feature = "llvm21-1",
112        feature = "llvm22-1"
113    )
114))]
115compile_error!(
116    "`llvm-plugin-crate` supports llvm-plugin-compatible LLVM features (llvm10-0 .. llvm7-0)."
117);
118
119pub struct ModuleAnalysisManager {
120    inner: *mut c_void,
121    from_analysis_id: Option<AnalysisKey>,
122}
123
124impl ModuleAnalysisManager {
125    /// # Safety
126    /// `inner` must be a valid pointer to LLVM's `ModuleAnalysisManager`.
127    pub unsafe fn from_raw(inner: *mut c_void, from_analysis_id: Option<*const u8>) -> Self {
128        Self {
129            inner,
130            from_analysis_id,
131        }
132    }
133    pub fn as_raw(&self) -> *mut c_void {
134        self.inner
135    }
136    pub fn from_analysis_id(&self) -> Option<AnalysisKey> {
137        self.from_analysis_id
138    }
139}
140
141pub struct FunctionAnalysisManager {
142    inner: *mut c_void,
143    from_analysis_id: Option<AnalysisKey>,
144}
145
146impl FunctionAnalysisManager {
147    /// # Safety
148    /// `inner` must be a valid pointer to LLVM's `FunctionAnalysisManager`.
149    pub unsafe fn from_raw(inner: *mut c_void, from_analysis_id: Option<AnalysisKey>) -> Self {
150        Self {
151            inner,
152            from_analysis_id,
153        }
154    }
155    pub fn as_raw(&self) -> *mut c_void {
156        self.inner
157    }
158    pub fn from_analysis_id(&self) -> Option<AnalysisKey> {
159        self.from_analysis_id
160    }
161}
162
163/// Optimization level for the default pass pipeline.
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
165pub enum OptLevel {
166    O0,
167    O1,
168    O2,
169    O3,
170    Os,
171    Oz,
172}
173
174impl OptLevel {
175    fn to_c(self) -> llvm_pm_sys::LlvmPmOptLevel {
176        match self {
177            OptLevel::O0 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O0,
178            OptLevel::O1 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O1,
179            OptLevel::O2 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O2,
180            OptLevel::O3 => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_O3,
181            OptLevel::Os => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_Os,
182            OptLevel::Oz => llvm_pm_sys::LlvmPmOptLevel_LlvmPmOptLevel_Oz,
183        }
184    }
185}
186
187/// Error type for pass manager operations.
188#[derive(Debug)]
189pub struct Error {
190    message: String,
191}
192
193impl Error {
194    /// Returns the error message.
195    pub fn message(&self) -> &str {
196        &self.message
197    }
198}
199
200impl fmt::Display for Error {
201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202        write!(f, "{}", self.message)
203    }
204}
205
206impl std::error::Error for Error {}
207
208/// Consume a C error string into a Rust [`Error`], freeing the C string.
209///
210/// # Safety
211/// `ptr` must be a non-null pointer to a C string allocated by the C++ stubs
212/// (via `malloc`/`copyString`). Ownership is transferred to this function.
213unsafe fn consume_c_error(ptr: *mut std::ffi::c_char) -> Error {
214    // SAFETY: Caller guarantees ptr is a valid, non-null, malloc'd C string.
215    let msg = CStr::from_ptr(ptr).to_string_lossy().into_owned();
216    llvm_pm_sys::llvm_pm_dispose_message(ptr);
217    Error { message: msg }
218}
219
220// =========================================================================
221// Options
222// =========================================================================
223
224/// Builder for pass manager options.
225///
226/// Controls debug logging, IR verification, and extension point pipeline
227/// additions. Pass to [`ModulePassManager`] or [`FunctionPassManager`]
228/// constructors via `Option<&Options>`.
229pub struct Options {
230    raw: llvm_pm_sys::LlvmPmOptionsRef,
231}
232
233impl Options {
234    /// Create default options (debug logging off, verify each off).
235    pub fn new() -> Self {
236        // SAFETY: llvm_pm_options_create always returns a valid handle.
237        let raw = unsafe { llvm_pm_sys::llvm_pm_options_create() };
238        Self { raw }
239    }
240
241    /// Enable or disable debug logging output during pass execution.
242    pub fn debug_logging(&mut self, val: bool) -> &mut Self {
243        // SAFETY: self.raw is a valid options handle created by llvm_pm_options_create.
244        unsafe {
245            llvm_pm_sys::llvm_pm_options_set_debug_logging(self.raw, val as i32);
246        }
247        self
248    }
249
250    /// Enable or disable IR verification after each pass.
251    pub fn verify_each(&mut self, val: bool) -> &mut Self {
252        // SAFETY: self.raw is a valid options handle created by llvm_pm_options_create.
253        unsafe {
254            llvm_pm_sys::llvm_pm_options_set_verify_each(self.raw, val as i32);
255        }
256        self
257    }
258
259    /// Add a pass pipeline at the peephole extension point (after instcombine, function-level).
260    pub fn add_peephole_ep(&mut self, pipeline: &str) -> &mut Self {
261        let c = CString::new(pipeline).expect("pipeline contains null byte");
262        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
263        unsafe {
264            llvm_pm_sys::llvm_pm_options_add_peephole_ep(self.raw, c.as_ptr());
265        }
266        self
267    }
268
269    /// Add a pass pipeline at the optimizer-early extension point (module-level).
270    pub fn add_optimizer_early_ep(&mut self, pipeline: &str) -> &mut Self {
271        let c = CString::new(pipeline).expect("pipeline contains null byte");
272        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
273        unsafe {
274            llvm_pm_sys::llvm_pm_options_add_optimizer_early_ep(self.raw, c.as_ptr());
275        }
276        self
277    }
278
279    /// Add a pass pipeline at the optimizer-last extension point (module-level).
280    pub fn add_optimizer_last_ep(&mut self, pipeline: &str) -> &mut Self {
281        let c = CString::new(pipeline).expect("pipeline contains null byte");
282        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
283        unsafe {
284            llvm_pm_sys::llvm_pm_options_add_optimizer_last_ep(self.raw, c.as_ptr());
285        }
286        self
287    }
288
289    /// Add a pass pipeline at the vectorizer-start extension point (function-level).
290    pub fn add_vectorizer_start_ep(&mut self, pipeline: &str) -> &mut Self {
291        let c = CString::new(pipeline).expect("pipeline contains null byte");
292        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
293        unsafe {
294            llvm_pm_sys::llvm_pm_options_add_vectorizer_start_ep(self.raw, c.as_ptr());
295        }
296        self
297    }
298
299    /// Add a pass pipeline at the scalar-optimizer-late extension point (function-level).
300    pub fn add_scalar_optimizer_late_ep(&mut self, pipeline: &str) -> &mut Self {
301        let c = CString::new(pipeline).expect("pipeline contains null byte");
302        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
303        unsafe {
304            llvm_pm_sys::llvm_pm_options_add_scalar_optimizer_late_ep(self.raw, c.as_ptr());
305        }
306        self
307    }
308
309    /// Add a pass pipeline at the pipeline-start extension point (module-level).
310    pub fn add_pipeline_start_ep(&mut self, pipeline: &str) -> &mut Self {
311        let c = CString::new(pipeline).expect("pipeline contains null byte");
312        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
313        unsafe {
314            llvm_pm_sys::llvm_pm_options_add_pipeline_start_ep(self.raw, c.as_ptr());
315        }
316        self
317    }
318
319    /// Add a pass pipeline at the pipeline-early-simplification extension point (module-level).
320    pub fn add_pipeline_early_simplification_ep(&mut self, pipeline: &str) -> &mut Self {
321        let c = CString::new(pipeline).expect("pipeline contains null byte");
322        // SAFETY: self.raw is valid; c.as_ptr() is a valid null-terminated C string.
323        unsafe {
324            llvm_pm_sys::llvm_pm_options_add_pipeline_early_simplification_ep(self.raw, c.as_ptr());
325        }
326        self
327    }
328}
329
330impl Default for Options {
331    fn default() -> Self {
332        Self::new()
333    }
334}
335
336impl Drop for Options {
337    fn drop(&mut self) {
338        // SAFETY: self.raw is a valid options handle, and Drop runs at most once.
339        unsafe {
340            llvm_pm_sys::llvm_pm_options_dispose(self.raw);
341        }
342    }
343}
344
345/// Analysis manager handle for CGSCC passes and analyses.
346pub struct CgsccAnalysisManager {
347    raw: *mut c_void,
348    from_analysis_id: Option<AnalysisKey>,
349}
350
351impl CgsccAnalysisManager {
352    /// Construct from an opaque manager pointer passed by the C++ layer.
353    ///
354    /// # Safety
355    /// `raw` must be a valid pointer to LLVM's `CGSCCAnalysisManager`.
356    pub unsafe fn from_raw(raw: *mut c_void) -> Self {
357        Self {
358            raw,
359            from_analysis_id: None,
360        }
361    }
362
363    unsafe fn from_raw_with_analysis_id(
364        raw: *mut c_void,
365        from_analysis_id: Option<AnalysisKey>,
366    ) -> Self {
367        Self {
368            raw,
369            from_analysis_id,
370        }
371    }
372
373    /// Get the underlying opaque pointer.
374    pub fn as_raw(&self) -> *mut c_void {
375        self.raw
376    }
377
378    /// Register a CGSCC analysis pass.
379    pub fn add_analysis<P>(&self, pass: P)
380    where
381        P: LlvmCgsccAnalysis,
382        P: 'static,
383        <P as LlvmCgsccAnalysis>::Result: 'static,
384    {
385        extern "C" fn pass_deleter<T: LlvmCgsccAnalysis>(pass: *mut c_void) {
386            // SAFETY: Pointer was created by Box::into_raw in add_pass.
387            drop(unsafe { Box::<T>::from_raw(pass.cast()) });
388        }
389
390        fn pass_entrypoint<T>(
391            pass: *mut c_void,
392            function: &inkwell::values::FunctionValue<'_>,
393            manager: *mut c_void,
394        ) -> *mut c_void
395        where
396            T: LlvmCgsccAnalysis,
397            T::Result: 'static,
398        {
399            // SAFETY: pass is a valid pointer to T stored in registry.
400            let pass = unsafe { &*(pass as *const T) };
401            // SAFETY: manager is valid for callback duration.
402            let manager =
403                unsafe { CgsccAnalysisManager::from_raw_with_analysis_id(manager, Some(T::id())) };
404            let result = pass.run_analysis(function, &manager);
405            Box::into_raw(Box::new(result)) as *mut c_void
406        }
407
408        let manager_key = self.raw as usize;
409        let analysis_key = <P as LlvmCgsccAnalysis>::id() as usize;
410        let mut passes = cgscc_analysis_passes()
411            .lock()
412            .expect("poisoned cgscc analysis registry");
413        let entry_map = passes.entry(manager_key).or_default();
414        assert!(
415            !entry_map.contains_key(&analysis_key),
416            "analysis already registered"
417        );
418        entry_map.insert(
419            analysis_key,
420            CgsccAnalysisEntry {
421                pass: Box::into_raw(Box::new(pass)) as *mut c_void,
422                pass_deleter: pass_deleter::<P>,
423                pass_entrypoint: pass_entrypoint::<P>,
424            },
425        );
426    }
427
428    /// Get (or compute) analysis result for a function in current SCC.
429    pub fn get_result<A>(&self, function: &inkwell::values::FunctionValue<'_>) -> &A::Result
430    where
431        A: LlvmCgsccAnalysis + 'static,
432        A::Result: 'static,
433    {
434        let id = A::id();
435        assert!(
436            !matches!(self.from_analysis_id, Some(n) if n == id),
437            "Analysis cannot request its own result"
438        );
439
440        let manager_key = self.raw as usize;
441        let analysis_key = id as usize;
442        let function_key = function.as_value_ref() as usize;
443
444        if let Some(result) = self.get_cached_result::<A>(function) {
445            return result;
446        }
447
448        let passes = cgscc_analysis_passes()
449            .lock()
450            .expect("poisoned cgscc analysis registry");
451        let entry = passes
452            .get(&manager_key)
453            .and_then(|m| m.get(&analysis_key))
454            .expect("analysis was not registered");
455        let result_ptr = (entry.pass_entrypoint)(entry.pass, function, self.raw);
456        drop(passes);
457
458        let mut cache = cgscc_analysis_cache()
459            .lock()
460            .expect("poisoned cgscc analysis cache");
461        cache
462            .entry(manager_key)
463            .or_default()
464            .insert((analysis_key, function_key), result_ptr as usize);
465        // SAFETY: result_ptr points to a leaked Box<A::Result> stored in cache.
466        unsafe { &*(result_ptr as *const A::Result) }
467    }
468
469    /// Get cached analysis result if present.
470    pub fn get_cached_result<A>(
471        &self,
472        function: &inkwell::values::FunctionValue<'_>,
473    ) -> Option<&A::Result>
474    where
475        A: LlvmCgsccAnalysis + 'static,
476        A::Result: 'static,
477    {
478        let id = A::id();
479        assert!(
480            !matches!(self.from_analysis_id, Some(n) if n == id),
481            "Analysis cannot request its own result"
482        );
483
484        let manager_key = self.raw as usize;
485        let analysis_key = id as usize;
486        let function_key = function.as_value_ref() as usize;
487        let cache = cgscc_analysis_cache()
488            .lock()
489            .expect("poisoned cgscc analysis cache");
490        cache
491            .get(&manager_key)
492            .and_then(|m| m.get(&(analysis_key, function_key)))
493            // SAFETY: cached pointer values are inserted only from `Box<A::Result>` in
494            // `get_result`, keyed by the same analysis type `A`.
495            .map(|ptr| unsafe { &*((*ptr as *const c_void) as *const A::Result) })
496    }
497}
498
499/// Analysis manager handle for loop passes and analyses.
500pub struct LoopAnalysisManager {
501    raw: *mut c_void,
502    from_analysis_id: Option<AnalysisKey>,
503}
504
505impl LoopAnalysisManager {
506    /// Construct from an opaque manager pointer passed by the C++ layer.
507    ///
508    /// # Safety
509    /// `raw` must be a valid pointer to LLVM's `LoopAnalysisManager`.
510    pub unsafe fn from_raw(raw: *mut c_void) -> Self {
511        Self {
512            raw,
513            from_analysis_id: None,
514        }
515    }
516
517    unsafe fn from_raw_with_analysis_id(
518        raw: *mut c_void,
519        from_analysis_id: Option<AnalysisKey>,
520    ) -> Self {
521        Self {
522            raw,
523            from_analysis_id,
524        }
525    }
526
527    /// Get the underlying opaque pointer.
528    pub fn as_raw(&self) -> *mut c_void {
529        self.raw
530    }
531
532    /// Register a loop analysis pass.
533    pub fn add_analysis<P>(&self, pass: P)
534    where
535        P: LlvmLoopAnalysis,
536        P: 'static,
537        <P as LlvmLoopAnalysis>::Result: 'static,
538    {
539        extern "C" fn pass_deleter<T: LlvmLoopAnalysis>(pass: *mut c_void) {
540            // SAFETY: Pointer was created by Box::into_raw in add_pass.
541            drop(unsafe { Box::<T>::from_raw(pass.cast()) });
542        }
543
544        fn pass_entrypoint<T>(
545            pass: *mut c_void,
546            loop_header: LLVMBasicBlockRef,
547            manager: *mut c_void,
548        ) -> *mut c_void
549        where
550            T: LlvmLoopAnalysis,
551            T::Result: 'static,
552        {
553            // SAFETY: pass is a valid pointer to T stored in registry.
554            let pass = unsafe { &*(pass as *const T) };
555            // SAFETY: manager is valid for callback duration.
556            let manager =
557                unsafe { LoopAnalysisManager::from_raw_with_analysis_id(manager, Some(T::id())) };
558            let result = pass.run_analysis(loop_header, &manager);
559            Box::into_raw(Box::new(result)) as *mut c_void
560        }
561
562        let manager_key = self.raw as usize;
563        let analysis_key = <P as LlvmLoopAnalysis>::id() as usize;
564        let mut passes = loop_analysis_passes()
565            .lock()
566            .expect("poisoned loop analysis registry");
567        let entry_map = passes.entry(manager_key).or_default();
568        assert!(
569            !entry_map.contains_key(&analysis_key),
570            "analysis already registered"
571        );
572        entry_map.insert(
573            analysis_key,
574            LoopAnalysisEntry {
575                pass: Box::into_raw(Box::new(pass)) as *mut c_void,
576                pass_deleter: pass_deleter::<P>,
577                pass_entrypoint: pass_entrypoint::<P>,
578            },
579        );
580    }
581
582    /// Get (or compute) analysis result for a loop header.
583    pub fn get_result<A>(&self, loop_header: LLVMBasicBlockRef) -> &A::Result
584    where
585        A: LlvmLoopAnalysis + 'static,
586        A::Result: 'static,
587    {
588        let id = A::id();
589        assert!(
590            !matches!(self.from_analysis_id, Some(n) if n == id),
591            "Analysis cannot request its own result"
592        );
593
594        let manager_key = self.raw as usize;
595        let analysis_key = id as usize;
596        let loop_key = loop_header as usize;
597
598        if let Some(result) = self.get_cached_result::<A>(loop_header) {
599            return result;
600        }
601
602        let passes = loop_analysis_passes()
603            .lock()
604            .expect("poisoned loop analysis registry");
605        let entry = passes
606            .get(&manager_key)
607            .and_then(|m| m.get(&analysis_key))
608            .expect("analysis was not registered");
609        let result_ptr = (entry.pass_entrypoint)(entry.pass, loop_header, self.raw);
610        drop(passes);
611
612        let mut cache = loop_analysis_cache()
613            .lock()
614            .expect("poisoned loop analysis cache");
615        cache
616            .entry(manager_key)
617            .or_default()
618            .insert((analysis_key, loop_key), result_ptr as usize);
619        // SAFETY: result_ptr points to a leaked Box<A::Result> stored in cache.
620        unsafe { &*(result_ptr as *const A::Result) }
621    }
622
623    /// Get cached analysis result if present.
624    pub fn get_cached_result<A>(&self, loop_header: LLVMBasicBlockRef) -> Option<&A::Result>
625    where
626        A: LlvmLoopAnalysis + 'static,
627        A::Result: 'static,
628    {
629        let id = A::id();
630        assert!(
631            !matches!(self.from_analysis_id, Some(n) if n == id),
632            "Analysis cannot request its own result"
633        );
634
635        let manager_key = self.raw as usize;
636        let analysis_key = id as usize;
637        let loop_key = loop_header as usize;
638        let cache = loop_analysis_cache()
639            .lock()
640            .expect("poisoned loop analysis cache");
641        cache
642            .get(&manager_key)
643            .and_then(|m| m.get(&(analysis_key, loop_key)))
644            // SAFETY: cached pointer values are inserted only from `Box<A::Result>` in
645            // `get_result`, keyed by the same analysis type `A`.
646            .map(|ptr| unsafe { &*((*ptr as *const c_void) as *const A::Result) })
647    }
648}
649
650struct CgsccAnalysisEntry {
651    pass: *mut c_void,
652    pass_deleter: extern "C" fn(*mut c_void),
653    pass_entrypoint:
654        fn(*mut c_void, &inkwell::values::FunctionValue<'_>, *mut c_void) -> *mut c_void,
655}
656
657struct LoopAnalysisEntry {
658    pass: *mut c_void,
659    pass_deleter: extern "C" fn(*mut c_void),
660    pass_entrypoint: fn(*mut c_void, LLVMBasicBlockRef, *mut c_void) -> *mut c_void,
661}
662
663impl Drop for CgsccAnalysisEntry {
664    fn drop(&mut self) {
665        (self.pass_deleter)(self.pass);
666    }
667}
668
669impl Drop for LoopAnalysisEntry {
670    fn drop(&mut self) {
671        (self.pass_deleter)(self.pass);
672    }
673}
674
675// SAFETY: Entries contain raw pointers (`pass: *mut c_void`) to heap-allocated
676// `Box<T>` values and function pointers (`pass_deleter`, `pass_entrypoint`).
677// All access to entries is behind a `Mutex`, so no data races are possible.
678// The pointed-to data is owned exclusively by this entry (freed in Drop).
679unsafe impl Send for CgsccAnalysisEntry {}
680unsafe impl Send for LoopAnalysisEntry {}
681
682type AnalysisPassMap<T> = HashMap<usize, HashMap<usize, T>>;
683type AnalysisCacheMap = HashMap<usize, HashMap<(usize, usize), usize>>;
684
685fn cgscc_analysis_passes() -> &'static Mutex<AnalysisPassMap<CgsccAnalysisEntry>> {
686    static INIT: Once = Once::new();
687    static mut CELL: *const Mutex<AnalysisPassMap<CgsccAnalysisEntry>> = ptr::null();
688    INIT.call_once(|| {
689        let value = Box::new(Mutex::new(HashMap::new()));
690        // SAFETY: `call_once` guarantees this assignment runs once.
691        unsafe {
692            CELL = Box::into_raw(value);
693        }
694    });
695    // SAFETY: `CELL` is initialized by `call_once` before returning, then never modified.
696    unsafe { CELL.as_ref().expect("cgscc registry initialized") }
697}
698
699fn cgscc_analysis_cache() -> &'static Mutex<AnalysisCacheMap> {
700    static INIT: Once = Once::new();
701    static mut CELL: *const Mutex<AnalysisCacheMap> = ptr::null();
702    INIT.call_once(|| {
703        let value = Box::new(Mutex::new(HashMap::new()));
704        // SAFETY: `call_once` guarantees this assignment runs once.
705        unsafe {
706            CELL = Box::into_raw(value);
707        }
708    });
709    // SAFETY: `CELL` is initialized by `call_once` before returning, then never modified.
710    unsafe { CELL.as_ref().expect("cgscc cache initialized") }
711}
712
713fn loop_analysis_passes() -> &'static Mutex<AnalysisPassMap<LoopAnalysisEntry>> {
714    static INIT: Once = Once::new();
715    static mut CELL: *const Mutex<AnalysisPassMap<LoopAnalysisEntry>> = ptr::null();
716    INIT.call_once(|| {
717        let value = Box::new(Mutex::new(HashMap::new()));
718        // SAFETY: `call_once` guarantees this assignment runs once.
719        unsafe {
720            CELL = Box::into_raw(value);
721        }
722    });
723    // SAFETY: `CELL` is initialized by `call_once` before returning, then never modified.
724    unsafe { CELL.as_ref().expect("loop registry initialized") }
725}
726
727fn loop_analysis_cache() -> &'static Mutex<AnalysisCacheMap> {
728    static INIT: Once = Once::new();
729    static mut CELL: *const Mutex<AnalysisCacheMap> = ptr::null();
730    INIT.call_once(|| {
731        let value = Box::new(Mutex::new(HashMap::new()));
732        // SAFETY: `call_once` guarantees this assignment runs once.
733        unsafe {
734            CELL = Box::into_raw(value);
735        }
736    });
737    // SAFETY: `CELL` is initialized by `call_once` before returning, then never modified.
738    unsafe { CELL.as_ref().expect("loop cache initialized") }
739}
740
741fn preserved_to_c(pa: traits::PreservedAnalyses) -> std::ffi::c_int {
742    match pa {
743        PreservedAnalyses::All => 0,
744        PreservedAnalyses::None => 1,
745    }
746}
747
748/// Generic trampoline for module passes. Monomorphized per `T`.
749///
750/// # Safety
751/// - `user_data` must be a valid pointer to a `T` that was stored in
752///   [`ModulePassManager::_passes`].
753/// - `module` must be a valid `LLVMModuleRef` owned by the caller (not consumed).
754/// - `manager` must be a valid `ModuleAnalysisManager*` from the C++ layer.
755///
756/// # Panics
757/// If `T::run_pass` panics, the unwind crosses an `extern "C"` boundary.
758/// Rust >= 1.71 aborts; older versions have undefined behavior.
759pub(crate) unsafe extern "C" fn module_pass_trampoline<T: LlvmModulePass>(
760    module: LLVMModuleRef,
761    manager: *mut c_void,
762    user_data: *mut c_void,
763) -> std::ffi::c_int {
764    // SAFETY: user_data was cast from &T stored in a Box inside _passes.
765    let pass = &*(user_data as *const T);
766    // SAFETY: Module::new wraps the LLVMModuleRef without taking ownership.
767    // We must call forget() to avoid dropping (and freeing) the LLVM module,
768    // which is owned by the caller (C++ PassManager).
769    let mut module = inkwell::module::Module::new(module);
770    let manager = ModuleAnalysisManager::from_raw(manager, None);
771    let result = pass.run_pass(&mut module, &manager);
772    std::mem::forget(module);
773    preserved_to_c(result)
774}
775
776/// Generic trampoline for function passes. Monomorphized per `T`.
777///
778/// # Safety
779/// - `user_data` must be a valid pointer to a `T` that was stored in
780///   [`FunctionPassManager::_passes`].
781/// - `function` must be a valid `LLVMValueRef` representing a function.
782/// - `manager` must be a valid `FunctionAnalysisManager*` from the C++ layer.
783///
784/// # Panics
785/// If `T::run_pass` panics, the unwind crosses an `extern "C"` boundary.
786/// Rust >= 1.71 aborts; older versions have undefined behavior.
787pub(crate) unsafe extern "C" fn function_pass_trampoline<T: LlvmFunctionPass>(
788    function: LLVMValueRef,
789    manager: *mut c_void,
790    user_data: *mut c_void,
791) -> std::ffi::c_int {
792    // SAFETY: user_data was cast from &T stored in a Box inside _passes.
793    let pass = &*(user_data as *const T);
794    // SAFETY: FunctionValue::new wraps the LLVMValueRef without ownership.
795    // FunctionValue has no Drop impl, so no forget() needed.
796    let mut function = inkwell::values::FunctionValue::new(function).expect("invalid function");
797    let manager = FunctionAnalysisManager::from_raw(manager, None);
798    let result = pass.run_pass(&mut function, &manager);
799    preserved_to_c(result)
800}
801
802/// Generic trampoline for CGSCC passes. Monomorphized per `T`.
803///
804/// # Safety
805/// - `user_data` must be a valid pointer to a `T` that was stored in
806///   [`ModulePassManager::_passes`].
807/// - `function` must be a valid `LLVMValueRef` representing a function in the SCC.
808/// - `manager` must be a valid `CGSCCAnalysisManager*` from the C++ layer.
809///
810/// # Panics
811/// If `T::run_pass` panics, the unwind crosses an `extern "C"` boundary.
812/// Rust >= 1.71 aborts; older versions have undefined behavior.
813pub(crate) unsafe extern "C" fn cgscc_pass_trampoline<T: LlvmCgsccPass>(
814    function: LLVMValueRef,
815    manager: *mut c_void,
816    user_data: *mut c_void,
817) -> std::ffi::c_int {
818    // SAFETY: user_data was cast from &T stored in a Box inside _passes.
819    let pass = &*(user_data as *const T);
820    let mut function = inkwell::values::FunctionValue::new(function).expect("invalid function");
821    // SAFETY: manager is valid for callback duration (owned by C++ PM infrastructure).
822    let manager = CgsccAnalysisManager::from_raw(manager);
823    let result = pass.run_pass(&mut function, &manager);
824    preserved_to_c(result)
825}
826
827/// Generic trampoline for loop passes. Monomorphized per `T`.
828///
829/// # Safety
830/// - `user_data` must be a valid pointer to a `T` that was stored in
831///   [`FunctionPassManager::_passes`].
832/// - `header` must be a valid `LLVMBasicBlockRef` for the loop header.
833/// - `manager` must be a valid `LoopAnalysisManager*` from the C++ layer.
834///
835/// # Panics
836/// If `T::run_pass` panics, the unwind crosses an `extern "C"` boundary.
837/// Rust >= 1.71 aborts; older versions have undefined behavior.
838pub(crate) unsafe extern "C" fn loop_pass_trampoline<T: LlvmLoopPass>(
839    header: LLVMBasicBlockRef,
840    manager: *mut c_void,
841    user_data: *mut c_void,
842) -> std::ffi::c_int {
843    // SAFETY: user_data was cast from &T stored in a Box inside _passes.
844    let pass = &*(user_data as *const T);
845    // SAFETY: manager is valid for callback duration (owned by C++ PM infrastructure).
846    let manager = LoopAnalysisManager::from_raw(manager);
847    let result = pass.run_pass(header, &manager);
848    preserved_to_c(result)
849}
850
851// =========================================================================
852// ModulePassManager
853// =========================================================================
854
855/// A configured LLVM module pass manager using the new PassManager infrastructure.
856///
857/// Bundles all analysis managers, PassBuilder, StandardInstrumentations, and the
858/// ModulePassManager into a single object with correct lifetime management.
859///
860/// The lifetime `'a` is tied to the borrowed [`inkwell::targets::TargetMachine`],
861/// ensuring the target machine outlives the pass manager.
862pub struct ModulePassManager<'a> {
863    raw: llvm_pm_sys::LlvmPmPassManagerRef,
864    _passes: Vec<Box<dyn std::any::Any>>,
865    _phantom: PhantomData<&'a ()>,
866}
867
868impl<'a> fmt::Debug for ModulePassManager<'a> {
869    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
870        f.debug_struct("ModulePassManager")
871            .field("raw", &self.raw)
872            .finish()
873    }
874}
875
876impl<'a> ModulePassManager<'a> {
877    /// Create a pass manager with a standard optimization pipeline.
878    pub fn with_opt_level(
879        target_machine: Option<&'a inkwell::targets::TargetMachine>,
880        level: OptLevel,
881        options: Option<&Options>,
882    ) -> Result<Self, Error> {
883        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
884        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
885        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
886
887        // SAFETY: tm is either null or a valid LLVMTargetMachineRef from inkwell.
888        // opts is either null or a valid options handle. err_msg is a valid out-pointer.
889        let raw = unsafe {
890            llvm_pm_sys::llvm_pm_create_with_opt_level(tm, level.to_c(), opts, &mut err_msg)
891        };
892
893        if raw.is_null() {
894            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
895            Err(unsafe { consume_c_error(err_msg) })
896        } else {
897            Ok(Self {
898                raw,
899                _passes: Vec::new(),
900                _phantom: PhantomData,
901            })
902        }
903    }
904
905    /// Create a pass manager from a textual pipeline description.
906    ///
907    /// The format matches `opt -passes=...` syntax, e.g.:
908    /// - `"instcombine,dce,sroa"`
909    /// - `"default<O2>"`
910    /// - `"module(function(instcombine,sroa))"`
911    pub fn with_pipeline(
912        target_machine: Option<&'a inkwell::targets::TargetMachine>,
913        pipeline: &str,
914        options: Option<&Options>,
915    ) -> Result<Self, Error> {
916        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
917        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
918        let c_pipeline = CString::new(pipeline).map_err(|e| Error {
919            message: format!("Pipeline string contains null byte: {}", e),
920        })?;
921        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
922
923        // SAFETY: tm is either null or valid. c_pipeline is a valid null-terminated string.
924        let raw = unsafe {
925            llvm_pm_sys::llvm_pm_create_with_pipeline(tm, c_pipeline.as_ptr(), opts, &mut err_msg)
926        };
927
928        if raw.is_null() {
929            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
930            Err(unsafe { consume_c_error(err_msg) })
931        } else {
932            Ok(Self {
933                raw,
934                _passes: Vec::new(),
935                _phantom: PhantomData,
936            })
937        }
938    }
939
940    /// Create a pass manager with the full-LTO default pipeline.
941    pub fn with_lto(
942        target_machine: Option<&'a inkwell::targets::TargetMachine>,
943        level: OptLevel,
944        options: Option<&Options>,
945    ) -> Result<Self, Error> {
946        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
947        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
948        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
949
950        // SAFETY: tm is either null or valid. opts is either null or valid.
951        let raw = unsafe { llvm_pm_sys::llvm_pm_create_lto(tm, level.to_c(), opts, &mut err_msg) };
952
953        if raw.is_null() {
954            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
955            Err(unsafe { consume_c_error(err_msg) })
956        } else {
957            Ok(Self {
958                raw,
959                _passes: Vec::new(),
960                _phantom: PhantomData,
961            })
962        }
963    }
964
965    /// Create a pass manager with the full-LTO pre-link pipeline.
966    pub fn with_lto_pre_link(
967        target_machine: Option<&'a inkwell::targets::TargetMachine>,
968        level: OptLevel,
969        options: Option<&Options>,
970    ) -> Result<Self, Error> {
971        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
972        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
973        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
974
975        // SAFETY: tm is either null or valid. opts is either null or valid.
976        let raw = unsafe {
977            llvm_pm_sys::llvm_pm_create_lto_pre_link(tm, level.to_c(), opts, &mut err_msg)
978        };
979
980        if raw.is_null() {
981            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
982            Err(unsafe { consume_c_error(err_msg) })
983        } else {
984            Ok(Self {
985                raw,
986                _passes: Vec::new(),
987                _phantom: PhantomData,
988            })
989        }
990    }
991
992    /// Create a pass manager with the ThinLTO pre-link pipeline.
993    pub fn with_thin_lto_pre_link(
994        target_machine: Option<&'a inkwell::targets::TargetMachine>,
995        level: OptLevel,
996        options: Option<&Options>,
997    ) -> Result<Self, Error> {
998        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
999        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1000        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1001
1002        // SAFETY: tm is either null or valid. opts is either null or valid.
1003        let raw = unsafe {
1004            llvm_pm_sys::llvm_pm_create_thin_lto_pre_link(tm, level.to_c(), opts, &mut err_msg)
1005        };
1006
1007        if raw.is_null() {
1008            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1009            Err(unsafe { consume_c_error(err_msg) })
1010        } else {
1011            Ok(Self {
1012                raw,
1013                _passes: Vec::new(),
1014                _phantom: PhantomData,
1015            })
1016        }
1017    }
1018
1019    /// Create an empty module pass manager with no built-in passes.
1020    ///
1021    /// Use [`add_pass()`](ModulePassManager::add_pass) to add custom passes.
1022    pub fn new(
1023        target_machine: Option<&'a inkwell::targets::TargetMachine>,
1024        options: Option<&Options>,
1025    ) -> Result<Self, Error> {
1026        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1027        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1028        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1029
1030        // SAFETY: tm is either null or valid. opts is either null or valid.
1031        let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_module(tm, opts, &mut err_msg) };
1032
1033        if raw.is_null() {
1034            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1035            Err(unsafe { consume_c_error(err_msg) })
1036        } else {
1037            Ok(Self {
1038                raw,
1039                _passes: Vec::new(),
1040                _phantom: PhantomData,
1041            })
1042        }
1043    }
1044
1045    /// Add a custom module pass to this pass manager.
1046    ///
1047    /// The pass is moved into the pass manager and kept alive until the pass
1048    /// manager is dropped. The pass is appended after any existing passes in
1049    /// the pipeline.
1050    pub fn add_pass<P>(&mut self, pass: P)
1051    where
1052        P: LlvmModulePass + 'static,
1053    {
1054        let mut boxed = Box::new(pass);
1055        let ptr = &mut *boxed as *mut P as *mut c_void;
1056        // SAFETY: self.raw is a valid PM handle. module_pass_trampoline::<T> is the
1057        // correct monomorphized trampoline. The pass pointer is valid for the
1058        // lifetime of the PM because the Box is stored in _passes.
1059        unsafe {
1060            llvm_pm_sys::llvm_pm_add_module_pass(self.raw, Some(module_pass_trampoline::<P>), ptr);
1061        }
1062        self._passes.push(boxed);
1063    }
1064
1065    /// Add a custom CGSCC pass to this pass manager.
1066    ///
1067    /// The pass is adapted into the module pipeline and invoked for each
1068    /// function in each SCC.
1069    pub fn add_cgscc_pass<P>(&mut self, pass: P)
1070    where
1071        P: LlvmCgsccPass + 'static,
1072    {
1073        let mut boxed = Box::new(pass);
1074        let ptr = &mut *boxed as *mut P as *mut c_void;
1075        // SAFETY: self.raw is a valid PM handle. cgscc_pass_trampoline::<T> is the
1076        // correct monomorphized trampoline. The pass pointer is valid for the
1077        // lifetime of the PM because the Box is stored in _passes.
1078        unsafe {
1079            llvm_pm_sys::llvm_pm_add_cgscc_pass(self.raw, Some(cgscc_pass_trampoline::<P>), ptr);
1080        }
1081        self._passes.push(boxed);
1082    }
1083
1084    /// Add a custom function pass adapted through the CGSCC level.
1085    ///
1086    /// The pass is wrapped with `Module → CGSCC → Function` adaptors, so it
1087    /// runs on each function within the CGSCC traversal order.
1088    pub fn add_function_pass_via_cgscc<P>(&mut self, pass: P)
1089    where
1090        P: LlvmFunctionPass + 'static,
1091    {
1092        let mut boxed = Box::new(pass);
1093        let ptr = &mut *boxed as *mut P as *mut c_void;
1094        // SAFETY: self.raw is a valid PM handle. function_pass_trampoline::<P> is the
1095        // correct monomorphized trampoline. The pass pointer is valid for the
1096        // lifetime of the PM because the Box is stored in _passes.
1097        unsafe {
1098            llvm_pm_sys::llvm_pm_add_function_pass_via_cgscc(
1099                self.raw,
1100                Some(function_pass_trampoline::<P>),
1101                ptr,
1102            );
1103        }
1104        self._passes.push(boxed);
1105    }
1106
1107    /// Add a custom loop pass adapted through the CGSCC and function levels.
1108    ///
1109    /// The pass is wrapped with `Module → CGSCC → Function → Loop` adaptors.
1110    pub fn add_loop_pass_via_cgscc<P>(&mut self, pass: P)
1111    where
1112        P: LlvmLoopPass + 'static,
1113    {
1114        let mut boxed = Box::new(pass);
1115        let ptr = &mut *boxed as *mut P as *mut c_void;
1116        // SAFETY: self.raw is a valid PM handle. loop_pass_trampoline::<P> is the
1117        // correct monomorphized trampoline. The pass pointer is valid for the
1118        // lifetime of the PM because the Box is stored in _passes.
1119        unsafe {
1120            llvm_pm_sys::llvm_pm_add_loop_pass_via_cgscc(
1121                self.raw,
1122                Some(loop_pass_trampoline::<P>),
1123                ptr,
1124            );
1125        }
1126        self._passes.push(boxed);
1127    }
1128
1129    /// Run the optimization passes on the given module.
1130    pub fn run(&mut self, module: &inkwell::module::Module<'_>) -> Result<(), Error> {
1131        // SAFETY: self.raw is a valid PM handle. module.as_mut_ptr() returns a valid
1132        // LLVMModuleRef. &mut self ensures exclusive access to stored passes.
1133        let err = unsafe { llvm_pm_sys::llvm_pm_run(self.raw, module.as_mut_ptr()) };
1134        if err.is_null() {
1135            Ok(())
1136        } else {
1137            // SAFETY: On error, llvm_pm_run returns a valid malloc'd error string.
1138            Err(unsafe { consume_c_error(err) })
1139        }
1140    }
1141}
1142
1143impl<'a> Drop for ModulePassManager<'a> {
1144    fn drop(&mut self) {
1145        // SAFETY: self.raw is a valid PM handle, and Drop runs at most once.
1146        // The C++ side is disposed first; _passes (stored Box<dyn Any>) are
1147        // dropped automatically afterward.
1148        unsafe {
1149            llvm_pm_sys::llvm_pm_dispose(self.raw);
1150        }
1151    }
1152}
1153
1154// SAFETY: `ModulePassManager` owns all its internal state exclusively:
1155// - `raw`: opaque C handle to a bundled C++ PM (PassBuilder, analysis managers,
1156//   StandardInstrumentations). No shared mutable aliases exist.
1157// - `_passes`: Vec of owned Boxes. Not Sync, but Send (owned data).
1158// All mutating operations (`run`, `add_pass`) require `&mut self`, so the type
1159// system prevents concurrent access. Moving between threads is safe because
1160// the C++ handle and Rust Boxes are self-contained.
1161unsafe impl<'a> Send for ModulePassManager<'a> {}
1162
1163// =========================================================================
1164// FunctionPassManager
1165// =========================================================================
1166
1167/// A configured LLVM function pass manager using the new PassManager infrastructure.
1168///
1169/// Similar to [`ModulePassManager`] but runs function-level passes on individual
1170/// functions rather than entire modules.
1171///
1172/// The lifetime `'a` is tied to the borrowed [`inkwell::targets::TargetMachine`],
1173/// ensuring the target machine outlives the pass manager.
1174pub struct FunctionPassManager<'a> {
1175    raw: llvm_pm_sys::LlvmPmPassManagerRef,
1176    _passes: Vec<Box<dyn std::any::Any>>,
1177    _phantom: PhantomData<&'a ()>,
1178}
1179
1180impl<'a> fmt::Debug for FunctionPassManager<'a> {
1181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1182        f.debug_struct("FunctionPassManager")
1183            .field("raw", &self.raw)
1184            .finish()
1185    }
1186}
1187
1188impl<'a> FunctionPassManager<'a> {
1189    /// Create a function pass manager from a textual pipeline description.
1190    ///
1191    /// The pipeline should contain function-level passes, e.g. `"instcombine,dce"`.
1192    pub fn with_pipeline(
1193        target_machine: Option<&'a inkwell::targets::TargetMachine>,
1194        pipeline: &str,
1195        options: Option<&Options>,
1196    ) -> Result<Self, Error> {
1197        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1198        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1199        let c_pipeline = CString::new(pipeline).map_err(|e| Error {
1200            message: format!("Pipeline string contains null byte: {}", e),
1201        })?;
1202        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1203
1204        // SAFETY: tm is either null or valid. c_pipeline is a valid null-terminated string.
1205        let raw = unsafe {
1206            llvm_pm_sys::llvm_pm_create_function_with_pipeline(
1207                tm,
1208                c_pipeline.as_ptr(),
1209                opts,
1210                &mut err_msg,
1211            )
1212        };
1213
1214        if raw.is_null() {
1215            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1216            Err(unsafe { consume_c_error(err_msg) })
1217        } else {
1218            Ok(Self {
1219                raw,
1220                _passes: Vec::new(),
1221                _phantom: PhantomData,
1222            })
1223        }
1224    }
1225
1226    /// Create an empty function pass manager with no built-in passes.
1227    ///
1228    /// Use [`add_pass()`](FunctionPassManager::add_pass) to add custom passes.
1229    pub fn new(
1230        target_machine: Option<&'a inkwell::targets::TargetMachine>,
1231        options: Option<&Options>,
1232    ) -> Result<Self, Error> {
1233        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1234        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1235        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1236
1237        // SAFETY: tm is either null or valid. opts is either null or valid.
1238        let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_function(tm, opts, &mut err_msg) };
1239
1240        if raw.is_null() {
1241            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1242            Err(unsafe { consume_c_error(err_msg) })
1243        } else {
1244            Ok(Self {
1245                raw,
1246                _passes: Vec::new(),
1247                _phantom: PhantomData,
1248            })
1249        }
1250    }
1251
1252    /// Add a custom function pass to this pass manager.
1253    ///
1254    /// The pass is moved into the pass manager and kept alive until the pass
1255    /// manager is dropped. The pass is appended after any existing passes in
1256    /// the pipeline.
1257    pub fn add_pass<P>(&mut self, pass: P)
1258    where
1259        P: LlvmFunctionPass + 'static,
1260    {
1261        let mut boxed = Box::new(pass);
1262        let ptr = &mut *boxed as *mut P as *mut c_void;
1263        // SAFETY: self.raw is a valid PM handle. function_pass_trampoline::<T> is the
1264        // correct monomorphized trampoline. The pass pointer is valid for the
1265        // lifetime of the PM because the Box is stored in _passes.
1266        unsafe {
1267            llvm_pm_sys::llvm_pm_add_function_pass(
1268                self.raw,
1269                Some(function_pass_trampoline::<P>),
1270                ptr,
1271            );
1272        }
1273        self._passes.push(boxed);
1274    }
1275
1276    /// Add a custom loop pass to this pass manager.
1277    ///
1278    /// The pass is adapted into the function pipeline and invoked with each
1279    /// loop header basic block.
1280    pub fn add_loop_pass<P>(&mut self, pass: P)
1281    where
1282        P: traits::LlvmLoopPass + 'static,
1283    {
1284        let mut boxed = Box::new(pass);
1285        let ptr = &mut *boxed as *mut P as *mut c_void;
1286        // SAFETY: self.raw is a valid PM handle. loop_pass_trampoline::<T> is the
1287        // correct monomorphized trampoline. The pass pointer is valid for the
1288        // lifetime of the PM because the Box is stored in _passes.
1289        unsafe {
1290            llvm_pm_sys::llvm_pm_add_loop_pass(self.raw, Some(loop_pass_trampoline::<P>), ptr);
1291        }
1292        self._passes.push(boxed);
1293    }
1294
1295    /// Run the function passes on the given function.
1296    pub fn run(&mut self, function: inkwell::values::FunctionValue<'_>) -> Result<(), Error> {
1297        // SAFETY: self.raw is a valid PM handle. function.as_value_ref() returns a valid
1298        // LLVMValueRef. &mut self ensures exclusive access to stored passes.
1299        let err =
1300            unsafe { llvm_pm_sys::llvm_pm_run_on_function(self.raw, function.as_value_ref()) };
1301        if err.is_null() {
1302            Ok(())
1303        } else {
1304            // SAFETY: On error, llvm_pm_run_on_function returns a valid malloc'd error string.
1305            Err(unsafe { consume_c_error(err) })
1306        }
1307    }
1308}
1309
1310impl<'a> Drop for FunctionPassManager<'a> {
1311    fn drop(&mut self) {
1312        // SAFETY: self.raw is a valid PM handle, and Drop runs at most once.
1313        // The C++ side is disposed first; _passes (stored Box<dyn Any>) are
1314        // dropped automatically afterward.
1315        unsafe {
1316            llvm_pm_sys::llvm_pm_dispose(self.raw);
1317        }
1318    }
1319}
1320
1321// SAFETY: Same rationale as `ModulePassManager`: exclusively-owned C++ handle
1322// and Rust Boxes. All mutating operations require `&mut self`.
1323unsafe impl<'a> Send for FunctionPassManager<'a> {}
1324
1325// =========================================================================
1326// CGSCCPassManager
1327// =========================================================================
1328
1329/// A configured LLVM CGSCC pass manager using the new PassManager infrastructure.
1330///
1331/// Provides a type-level distinction for CGSCC-oriented pipelines. Internally
1332/// backed by a module-level pass manager where each pass is adapted through the
1333/// `Module → CGSCC` adaptor.
1334///
1335/// Supports adding CGSCC passes directly, as well as function and loop passes
1336/// which are adapted through the CGSCC level (`CGSCC → Function` and
1337/// `CGSCC → Function → Loop` respectively).
1338///
1339/// The lifetime `'a` is tied to the borrowed [`inkwell::targets::TargetMachine`],
1340/// ensuring the target machine outlives the pass manager.
1341pub struct CGSCCPassManager<'a> {
1342    raw: llvm_pm_sys::LlvmPmPassManagerRef,
1343    _passes: Vec<Box<dyn std::any::Any>>,
1344    _phantom: PhantomData<&'a ()>,
1345}
1346
1347impl<'a> fmt::Debug for CGSCCPassManager<'a> {
1348    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1349        f.debug_struct("CGSCCPassManager")
1350            .field("raw", &self.raw)
1351            .finish()
1352    }
1353}
1354
1355impl<'a> CGSCCPassManager<'a> {
1356    /// Create an empty CGSCC pass manager.
1357    ///
1358    /// Use [`add_pass()`](CGSCCPassManager::add_pass),
1359    /// [`add_function_pass()`](CGSCCPassManager::add_function_pass), or
1360    /// [`add_loop_pass()`](CGSCCPassManager::add_loop_pass) to add passes.
1361    pub fn new(
1362        target_machine: Option<&'a inkwell::targets::TargetMachine>,
1363        options: Option<&Options>,
1364    ) -> Result<Self, Error> {
1365        let tm = target_machine.map_or(ptr::null_mut(), |t| t.as_mut_ptr());
1366        let opts = options.map_or(ptr::null_mut(), |o| o.raw);
1367        let mut err_msg: *mut std::ffi::c_char = ptr::null_mut();
1368
1369        // SAFETY: tm is either null or valid. opts is either null or valid.
1370        let raw = unsafe { llvm_pm_sys::llvm_pm_create_empty_module(tm, opts, &mut err_msg) };
1371
1372        if raw.is_null() {
1373            // SAFETY: On error, the C++ stub sets err_msg to a valid malloc'd string.
1374            Err(unsafe { consume_c_error(err_msg) })
1375        } else {
1376            Ok(Self {
1377                raw,
1378                _passes: Vec::new(),
1379                _phantom: PhantomData,
1380            })
1381        }
1382    }
1383
1384    /// Add a custom CGSCC pass.
1385    ///
1386    /// The pass is adapted into the module pipeline via
1387    /// `createModuleToPostOrderCGSCCPassAdaptor` and invoked for each function
1388    /// in each SCC.
1389    pub fn add_pass<P>(&mut self, pass: P)
1390    where
1391        P: LlvmCgsccPass + 'static,
1392    {
1393        let mut boxed = Box::new(pass);
1394        let ptr = &mut *boxed as *mut P as *mut c_void;
1395        // SAFETY: self.raw is a valid PM handle. cgscc_pass_trampoline::<P> is the
1396        // correct monomorphized trampoline. The pass pointer is valid for the
1397        // lifetime of the PM because the Box is stored in _passes.
1398        unsafe {
1399            llvm_pm_sys::llvm_pm_add_cgscc_pass(self.raw, Some(cgscc_pass_trampoline::<P>), ptr);
1400        }
1401        self._passes.push(boxed);
1402    }
1403
1404    /// Add a custom function pass adapted through the CGSCC level.
1405    ///
1406    /// The pass is wrapped with `Module → CGSCC → Function` adaptors, so it
1407    /// runs on each function within the CGSCC traversal order.
1408    pub fn add_function_pass<P>(&mut self, pass: P)
1409    where
1410        P: LlvmFunctionPass + 'static,
1411    {
1412        let mut boxed = Box::new(pass);
1413        let ptr = &mut *boxed as *mut P as *mut c_void;
1414        // SAFETY: self.raw is a valid PM handle. function_pass_trampoline::<P> is the
1415        // correct monomorphized trampoline. The pass pointer is valid for the
1416        // lifetime of the PM because the Box is stored in _passes.
1417        unsafe {
1418            llvm_pm_sys::llvm_pm_add_function_pass_via_cgscc(
1419                self.raw,
1420                Some(function_pass_trampoline::<P>),
1421                ptr,
1422            );
1423        }
1424        self._passes.push(boxed);
1425    }
1426
1427    /// Add a custom loop pass adapted through the CGSCC and function levels.
1428    ///
1429    /// The pass is wrapped with `Module → CGSCC → Function → Loop` adaptors.
1430    pub fn add_loop_pass<P>(&mut self, pass: P)
1431    where
1432        P: LlvmLoopPass + 'static,
1433    {
1434        let mut boxed = Box::new(pass);
1435        let ptr = &mut *boxed as *mut P as *mut c_void;
1436        // SAFETY: self.raw is a valid PM handle. loop_pass_trampoline::<P> is the
1437        // correct monomorphized trampoline. The pass pointer is valid for the
1438        // lifetime of the PM because the Box is stored in _passes.
1439        unsafe {
1440            llvm_pm_sys::llvm_pm_add_loop_pass_via_cgscc(
1441                self.raw,
1442                Some(loop_pass_trampoline::<P>),
1443                ptr,
1444            );
1445        }
1446        self._passes.push(boxed);
1447    }
1448
1449    /// Run the CGSCC passes on the given module.
1450    pub fn run(&mut self, module: &inkwell::module::Module<'_>) -> Result<(), Error> {
1451        // SAFETY: self.raw is a valid PM handle. module.as_mut_ptr() returns a valid
1452        // LLVMModuleRef. &mut self ensures exclusive access to stored passes.
1453        let err = unsafe { llvm_pm_sys::llvm_pm_run(self.raw, module.as_mut_ptr()) };
1454        if err.is_null() {
1455            Ok(())
1456        } else {
1457            // SAFETY: On error, llvm_pm_run returns a valid malloc'd error string.
1458            Err(unsafe { consume_c_error(err) })
1459        }
1460    }
1461}
1462
1463impl<'a> Drop for CGSCCPassManager<'a> {
1464    fn drop(&mut self) {
1465        // SAFETY: self.raw is a valid PM handle, and Drop runs at most once.
1466        // The C++ side is disposed first; _passes (stored Box<dyn Any>) are
1467        // dropped automatically afterward.
1468        unsafe {
1469            llvm_pm_sys::llvm_pm_dispose(self.raw);
1470        }
1471    }
1472}
1473
1474// SAFETY: Same rationale as `ModulePassManager`: exclusively-owned C++ handle
1475// and Rust Boxes. All mutating operations require `&mut self`.
1476unsafe impl<'a> Send for CGSCCPassManager<'a> {}