Skip to main content

rustc_codegen_llvm/
mono_item.rs

1use std::ffi::CString;
2
3use rustc_abi::AddressSpace;
4use rustc_attr_ir::Linkage;
5use rustc_codegen_ssa::traits::*;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LOCAL_CRATE};
8use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
9use rustc_middle::mono::Visibility;
10use rustc_middle::ty::layout::{FnAbiOf, HasTypingEnv, LayoutOf};
11use rustc_middle::ty::{self, Instance, Ty, TypeVisitableExt};
12use rustc_span::bug;
13use rustc_structures::CrateType;
14use rustc_target::callconv::{FnAbi, PassMode};
15use rustc_target::spec::{Arch, RelocModel};
16use tracing::debug;
17
18use crate::abi::FnAbiLlvmExt;
19use crate::builder::Builder;
20use crate::context::CodegenCx;
21use crate::diagnostics::SymbolAlreadyDefined;
22use crate::{base, llvm};
23
24impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> {
25    fn predefine_static(
26        &mut self,
27        def_id: DefId,
28        linkage: Linkage,
29        visibility: Visibility,
30        symbol_name: &str,
31    ) {
32        let instance = Instance::mono(self.tcx, def_id);
33        let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!() };
34        // Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
35        // out the llvm type from the actual evaluated initializer.
36        let ty =
37            if nested { self.tcx.types.unit } else { instance.ty(self.tcx, self.typing_env()) };
38        let llty = self.type_array(self.type_i8(), self.layout_of(ty).size.bytes());
39
40        let g = self.define_global(symbol_name, llty).unwrap_or_else(|| {
41            self.sess()
42                .dcx()
43                .emit_fatal(SymbolAlreadyDefined { span: self.tcx.def_span(def_id), symbol_name })
44        });
45
46        llvm::set_linkage(g, base::linkage_to_llvm(linkage));
47        self.set_visibility(g, linkage, visibility);
48
49        self.assume_dso_local(g, false);
50
51        let attrs = self.tcx.codegen_instance_attrs(instance.def);
52        self.add_static_aliases(g, &attrs.foreign_item_symbol_aliases);
53
54        self.instances.borrow_mut().insert(instance, g);
55    }
56
57    fn predefine_fn(
58        &mut self,
59        instance: Instance<'tcx>,
60        linkage: Linkage,
61        visibility: Visibility,
62        symbol_name: &str,
63    ) {
64        if !!instance.args.has_infer() {
    ::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
65
66        let attrs = self.tcx.codegen_instance_attrs(instance.def);
67
68        let lldecl =
69            self.predefine_without_aliases(instance, &attrs, linkage, visibility, symbol_name);
70        self.add_function_aliases(instance, lldecl, &attrs, &attrs.foreign_item_symbol_aliases);
71
72        self.instances.borrow_mut().insert(instance, lldecl);
73    }
74}
75
76impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
77    fn predefine_without_aliases(
78        &self,
79        instance: Instance<'tcx>,
80        attrs: &CodegenFnAttrs,
81        linkage: Linkage,
82        visibility: Visibility,
83        symbol_name: &str,
84    ) -> llvm::Value<'ll> {
85        let fn_abi: &FnAbi<'tcx, Ty<'tcx>> = self.fn_abi_of_instance(instance, ty::List::empty());
86        let lldecl = self.declare_fn(symbol_name, fn_abi, Some(instance));
87        llvm::set_linkage(lldecl, base::linkage_to_llvm(linkage));
88        base::set_link_section(lldecl, attrs);
89        if (linkage == Linkage::LinkOnceODR || linkage == Linkage::WeakODR)
90            && self.tcx.sess.target.supports_comdat()
91        {
92            llvm::SetUniqueComdat(self.llmod, lldecl);
93        }
94        self.set_visibility(lldecl, linkage, visibility);
95
96        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/mono_item.rs:96",
                        "rustc_codegen_llvm::mono_item", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/mono_item.rs"),
                        ::tracing_core::__macro_support::Option::Some(96u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::mono_item"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("predefine_fn: instance = {0:?}",
                                                    instance) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("predefine_fn: instance = {:?}", instance);
97
98        self.assume_dso_local(lldecl, false);
99
100        lldecl
101    }
102
103    /// LLVM has the concept of an `alias`.
104    /// We need this for the "externally implementable items" feature,
105    /// though it's generally useful.
106    ///
107    /// On macos, though this might be a more general problem, function symbols
108    /// have a fixed target architecture. This is necessary, since macos binaries
109    /// may contain code for both ARM and x86 macs.
110    ///
111    /// LLVM *can* add attributes for target architecture to function symbols,
112    /// cannot do so for statics, but importantly, also cannot for aliases
113    /// *even* when aliases may refer to a function symbol.
114    ///
115    /// This is not a problem: instead of using LLVM aliases, we can just generate
116    /// a new function symbol (with target architecture!) which effectively comes down to:
117    ///
118    /// ```ignore (illustrative example)
119    /// fn alias_name(...args) {
120    ///     original_name(...args)
121    /// }
122    /// ```
123    ///
124    /// That's also an alias.
125    ///
126    /// This does mean that the alias symbol has a different address than the original symbol
127    /// (assuming no optimizations by LLVM occur). This is unacceptable for statics.
128    /// So for statics we do want to use LLVM aliases, which is fine,
129    /// since for those we don't care about target architecture anyway.
130    ///
131    /// So, this function is for static aliases. See [`add_function_aliases`](Self::add_function_aliases) for the alternative.
132    fn add_static_aliases(
133        &self,
134        aliasee: llvm::Value<'ll>,
135        aliases: &[(DefId, Linkage, Visibility)],
136    ) {
137        let ty = self.get_type_of_global(aliasee);
138
139        for (alias, linkage, visibility) in aliases {
140            let instance = Instance::mono(self.tcx, *alias);
141            let symbol_name = self.tcx.symbol_name(instance);
142            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/mono_item.rs:142",
                        "rustc_codegen_llvm::mono_item", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/mono_item.rs"),
                        ::tracing_core::__macro_support::Option::Some(142u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::mono_item"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("STATIC ALIAS: {0:?} {1:?} {2:?}",
                                                    alias, linkage, visibility) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};tracing::debug!("STATIC ALIAS: {alias:?} {linkage:?} {visibility:?}");
143
144            let lldecl = llvm::add_alias(
145                self.llmod,
146                ty,
147                AddressSpace::ZERO,
148                aliasee,
149                &CString::new(symbol_name.name).unwrap(),
150            );
151            // Add the alias name to the set of cached items, so there is no duplicate
152            // instance added to it during the normal `external static` codegen
153            let prev_entry = self.instances.borrow_mut().insert(instance, lldecl);
154
155            // If there already was a previous entry, then `add_static_aliases` was called multiple times for the same `alias`
156            // which would result in incorrect codegen
157            if !prev_entry.is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("An instance was already present for {0:?}",
                instance));
    }
};assert!(prev_entry.is_none(), "An instance was already present for {instance:?}");
158
159            llvm::set_visibility(lldecl, base::visibility_to_llvm(*visibility));
160            llvm::set_linkage(lldecl, base::linkage_to_llvm(*linkage));
161        }
162    }
163
164    /// See [`add_static_aliases`](Self::add_static_aliases) for docs.
165    fn add_function_aliases(
166        &self,
167        aliasee_instance: Instance<'tcx>,
168        aliasee: llvm::Value<'ll>,
169        attrs: &CodegenFnAttrs,
170        aliases: &[(DefId, Linkage, Visibility)],
171    ) {
172        for (alias, linkage, visibility) in aliases {
173            let symbol_name = self.tcx.symbol_name(Instance::mono(self.tcx, *alias));
174            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/mono_item.rs:174",
                        "rustc_codegen_llvm::mono_item", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/mono_item.rs"),
                        ::tracing_core::__macro_support::Option::Some(174u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::mono_item"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("FUNCTION ALIAS: generating fn {0} that calls {1:?} ({2:?} {3:?} {4:?})",
                                                    symbol_name.name, aliasee_instance, alias, linkage,
                                                    visibility) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};tracing::debug!(
175                "FUNCTION ALIAS: generating fn {} that calls {aliasee_instance:?} ({alias:?} {linkage:?} {visibility:?})",
176                symbol_name.name
177            );
178
179            // predefine another copy of the original instance
180            // with a new symbol name
181            let alias_lldecl = self.predefine_without_aliases(
182                aliasee_instance,
183                attrs,
184                *linkage,
185                *visibility,
186                symbol_name.name,
187            );
188
189            let fn_abi: &FnAbi<'tcx, Ty<'tcx>> =
190                self.fn_abi_of_instance(aliasee_instance, ty::List::empty());
191
192            // both the alias and the aliasee have the same ty
193            let fn_ty = fn_abi.llvm_type(self);
194            let start_llbb = Builder::append_block(self, alias_lldecl, "start");
195            let mut start_bx = Builder::build(self, start_llbb);
196
197            let num_params = llvm::count_params(alias_lldecl);
198            let mut args = Vec::with_capacity(num_params as usize);
199            for index in 0..num_params {
200                args.push(llvm::get_param(alias_lldecl, index));
201            }
202
203            // For an indirect return, the alias's own first parameter is the
204            // caller-provided return slot: forward it to the aliasee as such.
205            let (return_slot, args) = if fn_abi.ret.is_indirect() {
206                let (sret_ptr, rest) = args.split_first().unwrap();
207                (ReturnSlot::Indirect(*sret_ptr), rest)
208            } else {
209                (ReturnSlot::Direct, &args[..])
210            };
211            let call = start_bx.call(
212                fn_ty,
213                Some(attrs),
214                Some(fn_abi),
215                aliasee,
216                return_slot,
217                args,
218                None,
219                Some(aliasee_instance),
220            );
221
222            match &fn_abi.ret.mode {
223                PassMode::Ignore | PassMode::Indirect { .. } => start_bx.ret_void(),
224                PassMode::Direct(_) | PassMode::Pair { .. } | PassMode::Cast { .. } => {
225                    start_bx.ret(call)
226                }
227                PassMode::IndirectUnsized { .. } => ::rustc_span::macros::bug_impl(None,
    format_args!("unsized returns are not supported"), Location::caller())bug!("unsized returns are not supported"),
228            }
229        }
230    }
231
232    /// A definition or declaration can be assumed to be local to a group of
233    /// libraries that form a single DSO or executable.
234    /// Marks the local as DSO if so.
235    pub(crate) fn assume_dso_local(&self, llval: llvm::Value<'ll>, is_declaration: bool) -> bool {
236        let assume = self.should_assume_dso_local(llval, is_declaration);
237        if assume {
238            llvm::set_dso_local(llval);
239        }
240        assume
241    }
242
243    fn set_visibility(&self, lldecl: llvm::Value<'ll>, linkage: Linkage, visibility: Visibility) {
244        // If we're compiling the compiler-builtins crate, i.e., the equivalent of
245        // compiler-rt, then we want to implicitly compile everything with hidden
246        // visibility as we're going to link this object all over the place but
247        // don't want the symbols to get exported.
248        if linkage != Linkage::Internal && self.tcx.is_compiler_builtins(LOCAL_CRATE) {
249            llvm::set_visibility(lldecl, llvm::Visibility::Hidden);
250        } else {
251            llvm::set_visibility(lldecl, base::visibility_to_llvm(visibility));
252        }
253    }
254
255    fn should_assume_dso_local(&self, llval: llvm::Value<'ll>, is_declaration: bool) -> bool {
256        let linkage = llvm::get_linkage(llval);
257        let visibility = llvm::get_visibility(llval);
258
259        if #[allow(non_exhaustive_omitted_patterns)] match linkage {
    llvm::Linkage::InternalLinkage | llvm::Linkage::PrivateLinkage => true,
    _ => false,
}matches!(linkage, llvm::Linkage::InternalLinkage | llvm::Linkage::PrivateLinkage) {
260            return true;
261        }
262
263        if visibility != llvm::Visibility::Default && linkage != llvm::Linkage::ExternalWeakLinkage
264        {
265            return true;
266        }
267
268        // Symbols from executables can't really be imported any further.
269        let all_exe = self.tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable);
270        let is_declaration_for_linker =
271            is_declaration || linkage == llvm::Linkage::AvailableExternallyLinkage;
272        if all_exe && !is_declaration_for_linker {
273            return true;
274        }
275
276        // PowerPC64 prefers TOC indirection to avoid copy relocations.
277        if self.tcx.sess.target.arch == Arch::PowerPC64 {
278            return false;
279        }
280
281        // Match clang by only supporting COFF and ELF for now.
282        if self.tcx.sess.target.is_like_darwin {
283            return false;
284        }
285
286        // With pie relocation model, calls of functions defined in the translation
287        // unit can use copy relocations.
288        if self.tcx.sess.relocation_model() == RelocModel::Pie && !is_declaration {
289            return true;
290        }
291
292        // Thread-local variables generally don't support copy relocations.
293        let is_thread_local_var = llvm::LLVMIsAGlobalVariable(llval)
294            .is_some_and(|v| llvm::LLVMIsThreadLocal(v).is_true());
295        if is_thread_local_var {
296            return false;
297        }
298
299        // Respect the direct-access-external-data to override default behavior if present.
300        if let Some(direct) = self.tcx.sess.direct_access_external_data() {
301            return direct;
302        }
303
304        // Static relocation model should force copy relocations everywhere.
305        self.tcx.sess.relocation_model() == RelocModel::Static
306    }
307}