rustc_codegen_llvm/
mono_item.rs

1use std::ffi::CString;
2
3use rustc_abi::AddressSpace;
4use rustc_codegen_ssa::traits::*;
5use rustc_hir::attrs::Linkage;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LOCAL_CRATE};
8use rustc_middle::bug;
9use rustc_middle::mir::mono::Visibility;
10use rustc_middle::ty::layout::{FnAbiOf, HasTypingEnv, LayoutOf};
11use rustc_middle::ty::{self, Instance, TypeVisitableExt};
12use rustc_session::config::CrateType;
13use rustc_target::spec::{Arch, RelocModel};
14use tracing::debug;
15
16use crate::context::CodegenCx;
17use crate::errors::SymbolAlreadyDefined;
18use crate::type_of::LayoutLlvmExt;
19use crate::{base, llvm};
20
21impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> {
22    fn predefine_static(
23        &mut self,
24        def_id: DefId,
25        linkage: Linkage,
26        visibility: Visibility,
27        symbol_name: &str,
28    ) {
29        let instance = Instance::mono(self.tcx, def_id);
30        let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
31        // Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
32        // out the llvm type from the actual evaluated initializer.
33        let ty =
34            if nested { self.tcx.types.unit } else { instance.ty(self.tcx, self.typing_env()) };
35        let llty = self.layout_of(ty).llvm_type(self);
36
37        let g = self.define_global(symbol_name, llty).unwrap_or_else(|| {
38            self.sess()
39                .dcx()
40                .emit_fatal(SymbolAlreadyDefined { span: self.tcx.def_span(def_id), symbol_name })
41        });
42
43        llvm::set_linkage(g, base::linkage_to_llvm(linkage));
44        llvm::set_visibility(g, base::visibility_to_llvm(visibility));
45        self.assume_dso_local(g, false);
46
47        let attrs = self.tcx.codegen_instance_attrs(instance.def);
48        self.add_aliases(g, &attrs.foreign_item_symbol_aliases);
49
50        self.instances.borrow_mut().insert(instance, g);
51    }
52
53    fn predefine_fn(
54        &mut self,
55        instance: Instance<'tcx>,
56        linkage: Linkage,
57        visibility: Visibility,
58        symbol_name: &str,
59    ) {
60        assert!(!instance.args.has_infer());
61
62        let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty());
63        let lldecl = self.declare_fn(symbol_name, fn_abi, Some(instance));
64        llvm::set_linkage(lldecl, base::linkage_to_llvm(linkage));
65        let attrs = self.tcx.codegen_instance_attrs(instance.def);
66        base::set_link_section(lldecl, &attrs);
67        if (linkage == Linkage::LinkOnceODR || linkage == Linkage::WeakODR)
68            && self.tcx.sess.target.supports_comdat()
69        {
70            llvm::SetUniqueComdat(self.llmod, lldecl);
71        }
72
73        // If we're compiling the compiler-builtins crate, e.g., the equivalent of
74        // compiler-rt, then we want to implicitly compile everything with hidden
75        // visibility as we're going to link this object all over the place but
76        // don't want the symbols to get exported.
77        if linkage != Linkage::Internal && self.tcx.is_compiler_builtins(LOCAL_CRATE) {
78            llvm::set_visibility(lldecl, llvm::Visibility::Hidden);
79        } else {
80            llvm::set_visibility(lldecl, base::visibility_to_llvm(visibility));
81        }
82
83        debug!("predefine_fn: instance = {:?}", instance);
84
85        self.assume_dso_local(lldecl, false);
86
87        self.add_aliases(lldecl, &attrs.foreign_item_symbol_aliases);
88
89        self.instances.borrow_mut().insert(instance, lldecl);
90    }
91}
92
93impl CodegenCx<'_, '_> {
94    fn add_aliases(&self, aliasee: &llvm::Value, aliases: &[(DefId, Linkage, Visibility)]) {
95        let ty = self.get_type_of_global(aliasee);
96
97        for (alias, linkage, visibility) in aliases {
98            let symbol_name = self.tcx.symbol_name(Instance::mono(self.tcx, *alias));
99
100            tracing::debug!("ALIAS: {alias:?} {linkage:?} {visibility:?}");
101            let lldecl = llvm::add_alias(
102                self.llmod,
103                ty,
104                AddressSpace::ZERO,
105                aliasee,
106                &CString::new(symbol_name.name).unwrap(),
107            );
108
109            llvm::set_visibility(lldecl, base::visibility_to_llvm(*visibility));
110            llvm::set_linkage(lldecl, base::linkage_to_llvm(*linkage));
111        }
112    }
113
114    /// A definition or declaration can be assumed to be local to a group of
115    /// libraries that form a single DSO or executable.
116    /// Marks the local as DSO if so.
117    pub(crate) fn assume_dso_local(&self, llval: &llvm::Value, is_declaration: bool) -> bool {
118        let assume = self.should_assume_dso_local(llval, is_declaration);
119        if assume {
120            llvm::set_dso_local(llval);
121        }
122        assume
123    }
124
125    fn should_assume_dso_local(&self, llval: &llvm::Value, is_declaration: bool) -> bool {
126        let linkage = llvm::get_linkage(llval);
127        let visibility = llvm::get_visibility(llval);
128
129        if matches!(linkage, llvm::Linkage::InternalLinkage | llvm::Linkage::PrivateLinkage) {
130            return true;
131        }
132
133        if visibility != llvm::Visibility::Default && linkage != llvm::Linkage::ExternalWeakLinkage
134        {
135            return true;
136        }
137
138        // Symbols from executables can't really be imported any further.
139        let all_exe = self.tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable);
140        let is_declaration_for_linker =
141            is_declaration || linkage == llvm::Linkage::AvailableExternallyLinkage;
142        if all_exe && !is_declaration_for_linker {
143            return true;
144        }
145
146        // PowerPC64 prefers TOC indirection to avoid copy relocations.
147        if matches!(self.tcx.sess.target.arch, Arch::PowerPC64 | Arch::PowerPC64LE) {
148            return false;
149        }
150
151        // Match clang by only supporting COFF and ELF for now.
152        if self.tcx.sess.target.is_like_darwin {
153            return false;
154        }
155
156        // With pie relocation model, calls of functions defined in the translation
157        // unit can use copy relocations.
158        if self.tcx.sess.relocation_model() == RelocModel::Pie && !is_declaration {
159            return true;
160        }
161
162        // Thread-local variables generally don't support copy relocations.
163        let is_thread_local_var = llvm::LLVMIsAGlobalVariable(llval)
164            .is_some_and(|v| llvm::LLVMIsThreadLocal(v).is_true());
165        if is_thread_local_var {
166            return false;
167        }
168
169        // Respect the direct-access-external-data to override default behavior if present.
170        if let Some(direct) = self.tcx.sess.direct_access_external_data() {
171            return direct;
172        }
173
174        // Static relocation model should force copy relocations everywhere.
175        self.tcx.sess.relocation_model() == RelocModel::Static
176    }
177}