rustc_codegen_llvm/
base.rs

1//! Codegen the MIR to the LLVM IR.
2//!
3//! Hopefully useful general knowledge about codegen:
4//!
5//! * There's no way to find out the [`Ty`] type of a [`Value`]. Doing so
6//!   would be "trying to get the eggs out of an omelette" (credit:
7//!   pcwalton). You can, instead, find out its [`llvm::Type`] by calling [`val_ty`],
8//!   but one [`llvm::Type`] corresponds to many [`Ty`]s; for instance, `tup(int, int,
9//!   int)` and `rec(x=int, y=int, z=int)` will have the same [`llvm::Type`].
10//!
11//! [`Ty`]: rustc_middle::ty::Ty
12//! [`val_ty`]: crate::common::val_ty
13
14use std::time::Instant;
15
16use rustc_codegen_ssa::ModuleCodegen;
17use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
18use rustc_codegen_ssa::mono_item::MonoItemExt;
19use rustc_codegen_ssa::traits::*;
20use rustc_data_structures::small_c_str::SmallCStr;
21use rustc_hir::attrs::Linkage;
22use rustc_middle::dep_graph;
23use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrs, SanitizerFnAttrs};
24use rustc_middle::mir::mono::Visibility;
25use rustc_middle::ty::TyCtxt;
26use rustc_session::config::{DebugInfo, Offload};
27use rustc_span::Symbol;
28use rustc_target::spec::SanitizerSet;
29
30use super::ModuleLlvm;
31use crate::attributes;
32use crate::builder::Builder;
33use crate::builder::gpu_offload::OffloadGlobals;
34use crate::context::CodegenCx;
35use crate::llvm::{self, Value};
36
37pub(crate) struct ValueIter<'ll> {
38    cur: Option<&'ll Value>,
39    step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
40}
41
42impl<'ll> Iterator for ValueIter<'ll> {
43    type Item = &'ll Value;
44
45    fn next(&mut self) -> Option<&'ll Value> {
46        let old = self.cur;
47        if let Some(old) = old {
48            self.cur = unsafe { (self.step)(old) };
49        }
50        old
51    }
52}
53
54pub(crate) fn iter_globals(llmod: &llvm::Module) -> ValueIter<'_> {
55    unsafe { ValueIter { cur: llvm::LLVMGetFirstGlobal(llmod), step: llvm::LLVMGetNextGlobal } }
56}
57
58pub(crate) fn compile_codegen_unit(
59    tcx: TyCtxt<'_>,
60    cgu_name: Symbol,
61) -> (ModuleCodegen<ModuleLlvm>, u64) {
62    let start_time = Instant::now();
63
64    let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
65    let (module, _) = tcx.dep_graph.with_task(
66        dep_node,
67        tcx,
68        cgu_name,
69        module_codegen,
70        Some(dep_graph::hash_result),
71    );
72    let time_to_codegen = start_time.elapsed();
73
74    // We assume that the cost to run LLVM on a CGU is proportional to
75    // the time we needed for codegenning it.
76    let cost = time_to_codegen.as_nanos() as u64;
77
78    fn module_codegen(tcx: TyCtxt<'_>, cgu_name: Symbol) -> ModuleCodegen<ModuleLlvm> {
79        let cgu = tcx.codegen_unit(cgu_name);
80        let _prof_timer =
81            tcx.prof.generic_activity_with_arg_recorder("codegen_module", |recorder| {
82                recorder.record_arg(cgu_name.to_string());
83                recorder.record_arg(cgu.size_estimate().to_string());
84            });
85        // Instantiate monomorphizations without filling out definitions yet...
86        let llvm_module = ModuleLlvm::new(tcx, cgu_name.as_str());
87        {
88            let mut cx = CodegenCx::new(tcx, cgu, &llvm_module);
89
90            // Declare and store globals shared by all offload kernels
91            //
92            // These globals are left in the LLVM-IR host module so all kernels can access them.
93            // They are necessary for correct offload execution. We do this here to simplify the
94            // `offload` intrinsic, avoiding the need for tracking whether it's the first
95            // intrinsic call or not.
96            let has_host_offload =
97                cx.sess().opts.unstable_opts.offload.iter().any(|o| matches!(o, Offload::Host(_)));
98            if has_host_offload && !cx.sess().target.is_like_gpu {
99                cx.offload_globals.replace(Some(OffloadGlobals::declare(&cx)));
100            }
101
102            let mono_items = cx.codegen_unit.items_in_deterministic_order(cx.tcx);
103            for &(mono_item, data) in &mono_items {
104                mono_item.predefine::<Builder<'_, '_, '_>>(
105                    &mut cx,
106                    cgu_name.as_str(),
107                    data.linkage,
108                    data.visibility,
109                );
110            }
111
112            // ... and now that we have everything pre-defined, fill out those definitions.
113            for &(mono_item, item_data) in &mono_items {
114                mono_item.define::<Builder<'_, '_, '_>>(&mut cx, cgu_name.as_str(), item_data);
115            }
116
117            // If this codegen unit contains the main function, also create the
118            // wrapper here
119            if let Some(entry) =
120                maybe_create_entry_wrapper::<Builder<'_, '_, '_>>(&cx, cx.codegen_unit)
121            {
122                let attrs = attributes::sanitize_attrs(&cx, tcx, SanitizerFnAttrs::default());
123                attributes::apply_to_llfn(entry, llvm::AttributePlace::Function, &attrs);
124            }
125
126            // Define Objective-C module info and module flags. Note, the module info will
127            // also be added to the `llvm.compiler.used` variable, created later.
128            //
129            // These are only necessary when we need the linker to do its Objective-C-specific
130            // magic. We could theoretically do it unconditionally, but at a slight cost to linker
131            // performance in the common case where it's unnecessary.
132            if !cx.objc_classrefs.borrow().is_empty() || !cx.objc_selrefs.borrow().is_empty() {
133                if cx.objc_abi_version() == 1 {
134                    cx.define_objc_module_info();
135                }
136                cx.add_objc_module_flags();
137            }
138
139            // Finalize code coverage by injecting the coverage map. Note, the coverage map will
140            // also be added to the `llvm.compiler.used` variable, created next.
141            if cx.sess().instrument_coverage() {
142                cx.coverageinfo_finalize();
143            }
144
145            // Create the llvm.used variable.
146            if !cx.used_statics.is_empty() {
147                cx.create_used_variable_impl(c"llvm.used", &cx.used_statics);
148            }
149
150            // Create the llvm.compiler.used variable.
151            {
152                let compiler_used_statics = cx.compiler_used_statics.borrow();
153                if !compiler_used_statics.is_empty() {
154                    cx.create_used_variable_impl(c"llvm.compiler.used", &compiler_used_statics);
155                }
156            }
157
158            // Run replace-all-uses-with for statics that need it. This must
159            // happen after the llvm.used variables are created.
160            for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
161                unsafe {
162                    llvm::LLVMReplaceAllUsesWith(old_g, new_g);
163                    llvm::LLVMDeleteGlobal(old_g);
164                }
165            }
166
167            // Finalize debuginfo
168            if cx.sess().opts.debuginfo != DebugInfo::None {
169                cx.debuginfo_finalize();
170            }
171        }
172
173        ModuleCodegen::new_regular(cgu_name.to_string(), llvm_module)
174    }
175
176    (module, cost)
177}
178
179pub(crate) fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
180    let Some(sect) = attrs.link_section else { return };
181    let buf = SmallCStr::new(sect.as_str());
182    llvm::set_section(llval, &buf);
183}
184
185pub(crate) fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
186    match linkage {
187        Linkage::External => llvm::Linkage::ExternalLinkage,
188        Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
189        Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
190        Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
191        Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
192        Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
193        Linkage::Internal => llvm::Linkage::InternalLinkage,
194        Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
195        Linkage::Common => llvm::Linkage::CommonLinkage,
196    }
197}
198
199pub(crate) fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
200    match linkage {
201        Visibility::Default => llvm::Visibility::Default,
202        Visibility::Hidden => llvm::Visibility::Hidden,
203        Visibility::Protected => llvm::Visibility::Protected,
204    }
205}
206
207pub(crate) fn set_variable_sanitizer_attrs(llval: &Value, attrs: &CodegenFnAttrs) {
208    if attrs.sanitizers.disabled.contains(SanitizerSet::ADDRESS) {
209        unsafe { llvm::LLVMRustSetNoSanitizeAddress(llval) };
210    }
211    if attrs.sanitizers.disabled.contains(SanitizerSet::HWADDRESS) {
212        unsafe { llvm::LLVMRustSetNoSanitizeHWAddress(llval) };
213    }
214}