rustc_codegen_llvm/
mono_item.rs

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