Skip to main content

rustc_codegen_llvm/back/
llvm_backend.rs

1//! Module containing [`LlvmCodegenBackend`], which implements [`CodegenBackend`]
2//! and related traits for the LLVM codegen backend.
3
4use std::any::Any;
5use std::cell::OnceCell;
6use std::ffi::CStr;
7use std::marker::PhantomData;
8use std::mem::ManuallyDrop;
9use std::path::PathBuf;
10use std::ptr;
11
12use rustc_ast::expand::allocator::AllocatorMethod;
13use rustc_codegen_ssa::back::lto::ThinModule;
14use rustc_codegen_ssa::back::write::{
15    CodegenContext, FatLtoInput, ModuleConfig, SharedEmitter, TargetMachineFactoryConfig,
16    TargetMachineFactoryFn, ThinLtoInput,
17};
18use rustc_codegen_ssa::traits::{CodegenBackend, ExtraBackendMethods, WriteBackendMethods};
19use rustc_codegen_ssa::{
20    CachedModuleCodegen, CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, TargetConfig,
21    target_features,
22};
23use rustc_data_structures::profiling::SelfProfilerRef;
24use rustc_errors::{DiagCtxt, DiagCtxtHandle};
25use rustc_metadata::EncodedMetadata;
26use rustc_middle::dep_graph::{BorrowedIncrCompSession, IncrCompSession};
27use rustc_middle::ty::TyCtxt;
28use rustc_session::config::{JobsMode, LtoCli, OptLevel, OutputFilenames, PrintKind, PrintRequest};
29use rustc_session::{CodegenBackendInit, EarlySession, Session};
30use rustc_span::{Symbol, sym};
31use rustc_target::spec::{RelocModel, SplitDebuginfo, TlsModel};
32
33use crate::back::owned_target_machine::OwnedTargetMachine;
34use crate::back::write::{create_informational_target_machine, create_target_machine};
35use crate::context::{self, SimpleCx};
36use crate::llvm::{self, ToLlvmBool};
37use crate::llvm_util::{self, target_config};
38use crate::{allocator, back, base};
39
40#[derive(#[automatically_derived]impl ::core::clone::Clone for LlvmCodegenBackend {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        LlvmCodegenBackend(::core::clone::Clone::clone(&self.0))
    }
}Clone)]
41pub struct LlvmCodegenBackend(());
42
43struct TimeTraceProfiler {}
44
45impl TimeTraceProfiler {
46    fn new() -> Self {
47        unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
48        TimeTraceProfiler {}
49    }
50}
51
52impl Drop for TimeTraceProfiler {
53    fn drop(&mut self) {
54        unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
55    }
56}
57
58impl ExtraBackendMethods for LlvmCodegenBackend {
59    type Module = ModuleLlvm;
60
61    fn codegen_allocator<'tcx>(
62        &self,
63        tcx: TyCtxt<'tcx>,
64        module_name: &str,
65        methods: &[AllocatorMethod],
66    ) -> ModuleLlvm {
67        let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
68        module_llvm.with_module_refs(|ModuleRefs { llcx, llmod, .. }| {
69            let cx = SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size());
70            unsafe { allocator::codegen(tcx, cx, module_name, methods) };
71        });
72        module_llvm
73    }
74    fn compile_codegen_unit(
75        &self,
76        tcx: TyCtxt<'_>,
77        cgu_name: Symbol,
78        bitcode_needed: bool,
79    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
80        base::compile_codegen_unit(tcx, cgu_name, bitcode_needed)
81    }
82}
83
84impl WriteBackendMethods for LlvmCodegenBackend {
85    type Module = ModuleLlvm;
86    type ModuleBuffer = back::lto::ModuleBuffer;
87    type TargetMachine = OwnedTargetMachine;
88    type ThinData = back::lto::ThinData;
89
90    fn thread_profiler() -> Box<dyn Any> {
91        Box::new(TimeTraceProfiler::new())
92    }
93    fn target_machine_factory(&self, sess: &Session) -> TargetMachineFactoryFn<Self> {
94        back::write::target_machine_factory(sess, sess.opts.optimize)
95    }
96    fn optimize_and_codegen_fat_lto(
97        sess: &Session,
98        cgcx: &CodegenContext,
99        shared_emitter: &SharedEmitter,
100        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
101        exported_symbols_for_lto: &[String],
102        each_linked_rlib_for_lto: &[PathBuf],
103        modules: Vec<FatLtoInput<Self>>,
104    ) -> CompiledModule {
105        let module = back::lto::run_fat(
106            cgcx,
107            &sess.prof,
108            shared_emitter,
109            tm_factory,
110            exported_symbols_for_lto,
111            each_linked_rlib_for_lto,
112            modules,
113        );
114
115        let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
116        let dcx = dcx.handle();
117        back::lto::run_pass_manager(cgcx, &sess.prof, dcx, &module, false);
118
119        back::write::codegen(cgcx, &sess.prof, shared_emitter, module, &cgcx.module_config)
120    }
121    fn run_thin_lto(
122        cgcx: &CodegenContext,
123        prof: &SelfProfilerRef,
124        incr_comp_session: Option<&BorrowedIncrCompSession>,
125        dcx: DiagCtxtHandle<'_>,
126        exported_symbols_for_lto: &[String],
127        each_linked_rlib_for_lto: &[PathBuf],
128        modules: Vec<ThinLtoInput<Self>>,
129    ) -> (Vec<ThinModule<Self>>, Vec<CachedModuleCodegen>) {
130        back::lto::run_thin(
131            cgcx,
132            prof,
133            incr_comp_session,
134            dcx,
135            exported_symbols_for_lto,
136            each_linked_rlib_for_lto,
137            modules,
138        )
139    }
140    fn optimize(
141        cgcx: &CodegenContext,
142        prof: &SelfProfilerRef,
143        shared_emitter: &SharedEmitter,
144        module: &mut ModuleCodegen<Self::Module>,
145        config: &ModuleConfig,
146    ) {
147        back::write::optimize(cgcx, prof, shared_emitter, module, config);
148    }
149    fn optimize_and_codegen_thin(
150        cgcx: &CodegenContext,
151        prof: &SelfProfilerRef,
152        shared_emitter: &SharedEmitter,
153        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
154        thin: ThinModule<Self>,
155    ) -> CompiledModule {
156        back::lto::optimize_and_codegen_thin_module(cgcx, prof, shared_emitter, tm_factory, thin)
157    }
158    fn codegen(
159        cgcx: &CodegenContext,
160        prof: &SelfProfilerRef,
161        shared_emitter: &SharedEmitter,
162        module: ModuleCodegen<Self::Module>,
163        config: &ModuleConfig,
164    ) -> CompiledModule {
165        back::write::codegen(cgcx, prof, shared_emitter, module, config)
166    }
167    fn serialize_module(module: Self::Module, is_thin: bool) -> Self::ModuleBuffer {
168        module.with_module_refs(|ModuleRefs { llmod, .. }| {
169            back::lto::ModuleBuffer::new(llmod, is_thin)
170        })
171    }
172}
173
174impl LlvmCodegenBackend {
175    pub fn new() -> Box<dyn CodegenBackend> {
176        Box::new(LlvmCodegenBackend(()))
177    }
178}
179
180impl CodegenBackend for LlvmCodegenBackend {
181    fn name(&self) -> &'static str {
182        "llvm"
183    }
184
185    fn init(&mut self, sess: &EarlySession) -> (CodegenBackendInit, TargetConfig) {
186        llvm_util::init(sess); // Make sure llvm is inited
187
188        // Target features: first compute just the base set, as that's what `target_config` needs.
189        // Then add `-Ctarget-feature`.
190        let mut backend_target_features = llvm_util::base_llvm_features(sess);
191        let config = target_config(sess, &backend_target_features);
192        target_features::flag_to_backend_features(
193            sess,
194            llvm_util::extend_with_llvm_features_for_rust_feature(
195                sess,
196                &mut backend_target_features,
197            ),
198        );
199
200        // autodiff is based on Enzyme, a library which we might not have available, when it was
201        // neither build, nor downloaded via rustup. If autodiff is used, but not available we emit
202        // an early error here and abort compilation.
203        {
204            use rustc_session::config::AutoDiff;
205
206            use crate::back::lto::enable_autodiff_settings;
207            if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
208                match llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot) {
209                    Ok(_) => {}
210                    Err(llvm::EnzymeLibraryError::NotFound { err }) => {
211                        sess.dcx().emit_fatal(crate::diagnostics::AutoDiffComponentMissing { err });
212                    }
213                    Err(llvm::EnzymeLibraryError::LoadFailed { err }) => {
214                        sess.dcx()
215                            .emit_fatal(crate::diagnostics::AutoDiffComponentUnavailable { err });
216                    }
217                }
218                enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
219            }
220        }
221
222        // -Zllvm-tpde requires the TPDE pass plugin, which may not be available. If TPDE is used but not available,
223        // we emit an early error here and abort compilation.
224        {
225            match llvm::TpdeWrapper::get_or_init(
226                &sess.opts.sysroot,
227                &sess.opts.unstable_opts.llvm_tpde,
228            ) {
229                Ok(_) => {}
230                Err(llvm::TpdeLibraryError::NotFound { err }) => {
231                    sess.dcx().emit_fatal(crate::diagnostics::TpdeComponentMissing { err });
232                }
233                Err(llvm::TpdeLibraryError::LoadFailed { err }) => {
234                    sess.dcx().emit_fatal(crate::diagnostics::TpdeComponentUnavailable { err });
235                }
236            }
237
238            if sess.opts.unstable_opts.llvm_tpde.is_some() {
239                if !#[allow(non_exhaustive_omitted_patterns)] match sess.opts.optimize {
    OptLevel::No | OptLevel::Less => true,
    _ => false,
}matches!(sess.opts.optimize, OptLevel::No | OptLevel::Less) {
240                    sess.dcx().emit_warn(crate::diagnostics::TpdeHighOptLevel);
241                }
242
243                if #[allow(non_exhaustive_omitted_patterns)] match sess.opts.jobs.frontend {
    JobsMode::Sequential => true,
    _ => false,
}matches!(sess.opts.jobs.frontend, JobsMode::Sequential) {
244                    sess.dcx().emit_warn(crate::diagnostics::TpdeSerialFrontend);
245                }
246
247                if sess.target.requires_lto
248                    || !#[allow(non_exhaustive_omitted_patterns)] match sess.early_lto() {
    LtoCli::No | LtoCli::Unspecified => true,
    _ => false,
}matches!(sess.early_lto(), LtoCli::No | LtoCli::Unspecified)
249                {
250                    sess.dcx().emit_fatal(crate::diagnostics::TpdeLtoUsed);
251                }
252
253                // JUSTIFICATION: the session doesn't exist at this point.
254                #[allow(rustc::bad_opt_access)]
255                if sess.opts.cg.split_debuginfo.unwrap_or(sess.target.split_debuginfo)
256                    != SplitDebuginfo::Off
257                {
258                    sess.dcx().emit_fatal(crate::diagnostics::TpdeSplitDebugInfoUsed);
259                }
260            }
261        }
262
263        // Intrinsics whose fallback body will not be used by the LLVM backend.
264        let replaced_intrinsics = {
265            #[rustfmt::skip]
266            let will_not_use_fallback = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [sym::unchecked_funnel_shl, sym::unchecked_funnel_shr,
                sym::carrying_mul_add, sym::carryless_mul, sym::integer_max,
                sym::integer_min, sym::sin, sym::cos, sym::powf, sym::powi,
                sym::sqrt, sym::exp, sym::exp2, sym::log, sym::log10,
                sym::log2, sym::floor, sym::ceil, sym::trunc, sym::round,
                sym::round_ties_even, sym::fma, sym::copysign]))vec![
267                // These are mapped to LLVM intrinsics instead.
268                sym::unchecked_funnel_shl,
269                sym::unchecked_funnel_shr,
270                sym::carrying_mul_add,
271                sym::carryless_mul,
272                sym::integer_max,
273                sym::integer_min,
274
275                // Fallback via libm/compiler-builtins, but the LLVM intrinsic is used instead.
276                sym::sin,
277                sym::cos,
278                sym::powf,
279                sym::powi,
280                sym::sqrt,
281                sym::exp,
282                sym::exp2,
283                sym::log,
284                sym::log10,
285                sym::log2,
286                sym::floor, sym::ceil, sym::trunc,
287                sym::round, sym::round_ties_even,
288                sym::fma,
289
290                sym::copysign,
291            ];
292
293            will_not_use_fallback
294        };
295
296        // `type_id_eq` is a safe choice since *all* backends use the fallback body for that. When
297        // adding more intrinsics, keep in mind that the distributed standard library is compiled
298        // with the LLVM backend but might later be included in a project built with cranelift or
299        // GCC. Adding an intrinsic here can therefore mean the fallback body is used with
300        // cranelift/GCC even if they have dedicated implementations.
301        let fallback_intrinsics = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [sym::type_id_eq]))vec![sym::type_id_eq];
302
303        let init = CodegenBackendInit {
304            backend_target_features,
305            replaced_rustc_intrinsics: replaced_intrinsics,
306            fallback_rustc_intrinsics: fallback_intrinsics,
307            thin_lto_supported: true,
308        };
309
310        (init, config)
311    }
312
313    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
314        use std::fmt::Write;
315        match req.kind {
316            PrintKind::RelocationModels => {
317                out.write_fmt(format_args!("Available relocation models:\n"))writeln!(out, "Available relocation models:").unwrap();
318                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
319                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
320                }
321                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
322            }
323            PrintKind::CodeModels => {
324                out.write_fmt(format_args!("Available code models:\n"))writeln!(out, "Available code models:").unwrap();
325                for name in &["tiny", "small", "kernel", "medium", "large"] {
326                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
327                }
328                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
329            }
330            PrintKind::TlsModels => {
331                out.write_fmt(format_args!("Available TLS models:\n"))writeln!(out, "Available TLS models:").unwrap();
332                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
333                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
334                }
335                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
336            }
337            PrintKind::StackProtectorStrategies => {
338                out.write_fmt(format_args!("Available stack protector strategies:\n    all\n        Generate stack canaries in all functions.\n\n    strong\n        Generate stack canaries in a function if it either:\n        - has a local variable of `[T; N]` type, regardless of `T` and `N`\n        - takes the address of a local variable.\n\n          (Note that a local variable being borrowed is not equivalent to its\n          address being taken: e.g. some borrows may be removed by optimization,\n          while by-value argument passing may be implemented with reference to a\n          local stack variable in the ABI.)\n\n    basic\n        Generate stack canaries in functions with local variables of `[T; N]`\n        type, where `T` is byte-sized and `N` >= 8.\n\n    none\n        Do not generate stack canaries.\n\n"))writeln!(
339                    out,
340                    r#"Available stack protector strategies:
341    all
342        Generate stack canaries in all functions.
343
344    strong
345        Generate stack canaries in a function if it either:
346        - has a local variable of `[T; N]` type, regardless of `T` and `N`
347        - takes the address of a local variable.
348
349          (Note that a local variable being borrowed is not equivalent to its
350          address being taken: e.g. some borrows may be removed by optimization,
351          while by-value argument passing may be implemented with reference to a
352          local stack variable in the ABI.)
353
354    basic
355        Generate stack canaries in functions with local variables of `[T; N]`
356        type, where `T` is byte-sized and `N` >= 8.
357
358    none
359        Do not generate stack canaries.
360"#
361                )
362                .unwrap();
363            }
364            _other => llvm_util::print(req, out, sess),
365        }
366    }
367
368    fn print_passes(&self) {
369        llvm_util::print_passes();
370    }
371
372    fn print_version(&self) {
373        llvm_util::print_version();
374    }
375
376    fn has_zstd(&self) -> bool {
377        llvm::LLVMRustLLVMHasZstdCompression()
378    }
379
380    fn has_mnemonic(&self, sess: &Session, mnemonic: &str) -> bool {
381        llvm_util::target_has_mnemonic(sess, mnemonic)
382    }
383
384    fn target_cpu(&self, sess: &Session) -> String {
385        crate::llvm_util::target_cpu(sess).to_string()
386    }
387
388    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
389        use rustc_session::config::Offload;
390
391        if tcx.sess.opts.unstable_opts.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    Offload::Device(_) => true,
    _ => false,
}matches!(o, Offload::Device(_)))
392            || tcx.sess.opts.unstable_opts.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    Offload::Host(_) => true,
    _ => false,
}matches!(o, Offload::Host(_)))
393        {
394            match llvm::RustOffloadWrapper::get_or_init(&tcx.sess.opts.sysroot) {
395                Ok(_) => {}
396                Err(llvm::RustOffloadLibraryError::NotFound { err }) => {
397                    tcx.sess
398                        .dcx()
399                        .emit_fatal(crate::diagnostics::RustOffloadComponentMissing { err });
400                }
401                Err(llvm::RustOffloadLibraryError::LoadFailed { err }) => {
402                    tcx.sess
403                        .dcx()
404                        .emit_fatal(crate::diagnostics::RustOffloadComponentUnavailable { err });
405                }
406            }
407        }
408
409        Box::new(rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx))
410    }
411
412    fn join_codegen(
413        &self,
414        ongoing_codegen: Box<dyn Any>,
415        sess: &Session,
416        incr_comp_session: Option<&mut IncrCompSession>,
417        crate_info: &CrateInfo,
418    ) -> CompiledModules {
419        ongoing_codegen
420            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
421            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
422            .join(sess, incr_comp_session, crate_info)
423    }
424
425    fn post_codegen_metrics(&self, sess: &Session, outputs: &OutputFilenames) {
426        if sess.opts.unstable_opts.llvm_time_trace {
427            sess.time("llvm_dump_timing_file", || {
428                let file_name = outputs.with_extension("llvm_timings.json");
429                llvm_util::time_trace_profiler_finish(&file_name);
430            });
431        }
432
433        if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
434            let timings =
435                llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
436            { ::std::io::_print(format_args!("{0}", timings)); };print!("{timings}");
437        }
438
439        if sess.print_llvm_stats() {
440            let stats =
441                llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
442            { ::std::io::_print(format_args!("{0}", stats)); };print!("{stats}");
443        }
444
445        if let Some(out_path) = sess.print_llvm_stats_json() {
446            let llvm_stats_json =
447                llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatisticsJSON(s) }).unwrap();
448
449            if !llvm_stats_json.is_empty() {
450                if let Err(e) = std::fs::write(out_path, llvm_stats_json) {
451                    sess.dcx().err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to write stats to {0}: {1}",
                out_path, e))
    })format!("failed to write stats to {out_path}: {e}"));
452                }
453            } else {
454                sess.dcx().warn(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("requested to print LLVM statistics to JSON file {0}, but the codegen backend did not provide any statistics",
                out_path))
    })format!(
455                    "requested to print LLVM statistics to JSON file {out_path}, but the codegen backend \
456                    did not provide any statistics",
457                ));
458            }
459        }
460    }
461
462    fn link(
463        &self,
464        sess: &Session,
465        compiled_modules: CompiledModules,
466        crate_info: CrateInfo,
467        metadata: EncodedMetadata,
468        outputs: &OutputFilenames,
469    ) {
470        use rustc_codegen_ssa::back::link::link_binary;
471
472        use crate::back::archive::LlvmArchiveBuilderBuilder;
473
474        // Run the linker on any artifacts that resulted from the LLVM run.
475        // This should produce either a finished executable or library.
476        link_binary(
477            sess,
478            &LlvmArchiveBuilderBuilder,
479            compiled_modules,
480            crate_info,
481            metadata,
482            outputs,
483            self.name(),
484        );
485    }
486}
487
488pub struct ModuleLlvm {
489    llcx_raw: ptr::NonNull<llvm::ContextRaw>,
490    llmod_raw: ptr::NonNull<llvm::ModuleRaw>,
491
492    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
493    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
494    tm: ManuallyDrop<OwnedTargetMachine>,
495
496    /// Saved ThinLTO buffer for embedding in the object file.
497    ///
498    /// This is currently a `OnceCell` to avoid aliasing problems when writing to it
499    /// from code that also wants to pass around a shared ref to `ModuleCodegen`.
500    pub(crate) thin_lto_buffer: OnceCell<Vec<u8>>,
501}
502
503// An LLVM context can only be used by one thread at a time. But we can move the entire context and
504// all objects inside it to another thread (needed for parallel codegen). This is sound because
505// `ModuleLlvm` owns the context and only allows borrowing LLVM objects tied to the context.
506unsafe impl Send for ModuleLlvm {}
507
508/// Shared helper to call [`llvm::LLVMContextCreate`] and then configure
509/// [`llvm::LLVMContextSetDiscardValueNames`].
510fn create_context_and_set_fewer_names(fewer_names: bool) -> ptr::NonNull<llvm::ContextRaw> {
511    unsafe {
512        let llcx_raw = llvm::LLVMContextCreate();
513        llvm::LLVMContextSetDiscardValueNames(
514            llvm::wrap_llcx(llcx_raw),
515            fewer_names.to_llvm_bool(),
516        );
517        llcx_raw
518    }
519}
520
521impl ModuleLlvm {
522    pub(crate) fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
523        unsafe {
524            let llcx_raw = create_context_and_set_fewer_names(tcx.sess.fewer_names());
525            let llmod_raw =
526                context::create_module(tcx, llvm::wrap_llcx(llcx_raw), mod_name).llmod_raw();
527            ModuleLlvm {
528                llmod_raw,
529                llcx_raw,
530                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
531                thin_lto_buffer: OnceCell::new(),
532            }
533        }
534    }
535
536    pub(crate) fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
537        unsafe {
538            let llcx_raw = create_context_and_set_fewer_names(tcx.sess.fewer_names());
539            let llmod_raw =
540                context::create_module(tcx, llvm::wrap_llcx(llcx_raw), mod_name).llmod_raw();
541            ModuleLlvm {
542                llmod_raw,
543                llcx_raw,
544                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess)),
545                thin_lto_buffer: OnceCell::new(),
546            }
547        }
548    }
549
550    pub(crate) fn parse(
551        cgcx: &CodegenContext,
552        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
553        name: &CStr,
554        buffer: &[u8],
555        dcx: DiagCtxtHandle<'_>,
556    ) -> Self {
557        unsafe {
558            let llcx_raw = create_context_and_set_fewer_names(cgcx.fewer_names);
559            let llmod_raw =
560                back::lto::parse_module(llvm::wrap_llcx(llcx_raw), name, buffer, dcx).llmod_raw();
561            let tm = tm_factory(dcx, TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()));
562
563            ModuleLlvm {
564                llmod_raw,
565                llcx_raw,
566                tm: ManuallyDrop::new(tm),
567                thin_lto_buffer: OnceCell::new(),
568            }
569        }
570    }
571
572    /// Passes a [`ModuleRefs`] struct to a callback function, giving it scoped
573    /// access to the resources owned by this module.
574    ///
575    /// Passing the references to a callback ensures that they have coherent
576    /// `'ll` lifetimes, and that they can't escape the callback.
577    pub(crate) fn with_module_refs<R>(
578        &self,
579        inner_fn: impl for<'ll> FnOnce(ModuleRefs<'ll>) -> R,
580    ) -> R {
581        let llcx = unsafe { llvm::wrap_llcx(self.llcx_raw) };
582        let llmod = unsafe { llvm::wrap_llmod(llcx, self.llmod_raw) };
583        inner_fn(ModuleRefs { llcx, llmod, tm: self.tm.raw(), _ph: PhantomData })
584    }
585}
586
587impl Drop for ModuleLlvm {
588    fn drop(&mut self) {
589        unsafe {
590            ManuallyDrop::drop(&mut self.tm);
591            llvm::LLVMContextDispose(self.llcx_raw);
592        }
593    }
594}
595
596/// Bundle of references provided by [`ModuleLlvm::with_module_refs`].
597#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'ll>
    ::core::clone::TrivialClone for ModuleRefs<'ll> {
}
#[automatically_derived]impl<'ll> ::core::clone::Clone for ModuleRefs<'ll> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<llvm::Context<'ll>>;
        let _: ::core::clone::AssertParamIsClone<llvm::Module<'ll>>;
        let _: ::core::clone::AssertParamIsClone<&'ll llvm::TargetMachine>;
        let _:
                ::core::clone::AssertParamIsClone<PhantomData<fn(&'ll ())
                    -> &'ll ()>>;
        *self
    }
}Clone, #[automatically_derived]impl<'ll> ::core::marker::Copy for ModuleRefs<'ll> { }Copy)]
598pub(crate) struct ModuleRefs<'ll> {
599    pub(crate) llcx: llvm::Context<'ll>,
600    pub(crate) llmod: llvm::Module<'ll>,
601    pub(crate) tm: &'ll llvm::TargetMachine,
602    /// Make sure `'ll` is invariant, even if no fields happen to require that.
603    ///
604    /// FIXME(Zalathar): Consider using `PhantomInvariantLifetime` when the API
605    /// for that is settled.
606    _ph: PhantomData<fn(&'ll ()) -> &'ll ()>,
607}