rustc_codegen_llvm/
mono_item.rs

1use rustc_codegen_ssa::traits::*;
2use rustc_hir::def::DefKind;
3use rustc_hir::def_id::{DefId, LOCAL_CRATE};
4use rustc_middle::bug;
5use rustc_middle::mir::mono::{Linkage, Visibility};
6use rustc_middle::ty::layout::{FnAbiOf, HasTypingEnv, LayoutOf};
7use rustc_middle::ty::{self, Instance, TypeVisitableExt};
8use rustc_session::config::CrateType;
9use rustc_target::spec::RelocModel;
10use tracing::debug;
11
12use crate::context::CodegenCx;
13use crate::errors::SymbolAlreadyDefined;
14use crate::type_of::LayoutLlvmExt;
15use crate::{base, llvm};
16
17impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> {
18    fn predefine_static(
19        &self,
20        def_id: DefId,
21        linkage: Linkage,
22        visibility: Visibility,
23        symbol_name: &str,
24    ) {
25        let instance = Instance::mono(self.tcx, def_id);
26        let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
27        // Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
28        // out the llvm type from the actual evaluated initializer.
29        let ty =
30            if nested { self.tcx.types.unit } else { instance.ty(self.tcx, self.typing_env()) };
31        let llty = self.layout_of(ty).llvm_type(self);
32
33        let g = self.define_global(symbol_name, llty).unwrap_or_else(|| {
34            self.sess()
35                .dcx()
36                .emit_fatal(SymbolAlreadyDefined { span: self.tcx.def_span(def_id), symbol_name })
37        });
38
39        llvm::set_linkage(g, base::linkage_to_llvm(linkage));
40        llvm::set_visibility(g, base::visibility_to_llvm(visibility));
41        unsafe {
42            if self.should_assume_dso_local(g, false) {
43                llvm::LLVMRustSetDSOLocal(g, true);
44            }
45        }
46
47        self.instances.borrow_mut().insert(instance, g);
48    }
49
50    fn predefine_fn(
51        &self,
52        instance: Instance<'tcx>,
53        linkage: Linkage,
54        visibility: Visibility,
55        symbol_name: &str,
56    ) {
57        assert!(!instance.args.has_infer());
58
59        let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty());
60        let lldecl = self.declare_fn(symbol_name, fn_abi, Some(instance));
61        llvm::set_linkage(lldecl, base::linkage_to_llvm(linkage));
62        let attrs = self.tcx.codegen_fn_attrs(instance.def_id());
63        base::set_link_section(lldecl, attrs);
64        if (linkage == Linkage::LinkOnceODR || linkage == Linkage::WeakODR)
65            && self.tcx.sess.target.supports_comdat()
66        {
67            llvm::SetUniqueComdat(self.llmod, lldecl);
68        }
69
70        // If we're compiling the compiler-builtins crate, e.g., the equivalent of
71        // compiler-rt, then we want to implicitly compile everything with hidden
72        // visibility as we're going to link this object all over the place but
73        // don't want the symbols to get exported.
74        if linkage != Linkage::Internal && self.tcx.is_compiler_builtins(LOCAL_CRATE) {
75            llvm::set_visibility(lldecl, llvm::Visibility::Hidden);
76        } else {
77            llvm::set_visibility(lldecl, base::visibility_to_llvm(visibility));
78        }
79
80        debug!("predefine_fn: instance = {:?}", instance);
81
82        if self.should_assume_dso_local(lldecl, false) {
83            unsafe { llvm::LLVMRustSetDSOLocal(lldecl, true) };
84        }
85
86        self.instances.borrow_mut().insert(instance, lldecl);
87    }
88}
89
90impl CodegenCx<'_, '_> {
91    /// Whether a definition or declaration can be assumed to be local to a group of
92    /// libraries that form a single DSO or executable.
93    pub(crate) fn should_assume_dso_local(
94        &self,
95        llval: &llvm::Value,
96        is_declaration: bool,
97    ) -> 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_osx {
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 = unsafe { llvm::LLVMIsAGlobalVariable(llval) }
136            .is_some_and(|v| unsafe { llvm::LLVMIsThreadLocal(v) } == llvm::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}