Skip to content

Commit 9142cae

Browse files
committed
add LinkageInfo to keep track of how we figured out the linkage
1 parent d10a682 commit 9142cae

File tree

7 files changed

+82
-35
lines changed

7 files changed

+82
-35
lines changed

compiler/rustc_codegen_cranelift/src/driver/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ fn predefine_mono_items<'tcx>(
3030
get_function_sig(tcx, module.target_config().default_call_conv, instance);
3131
let linkage = crate::linkage::get_clif_linkage(
3232
mono_item,
33-
data.linkage,
33+
data.linkage_info.into_linkage(),
3434
data.visibility,
3535
is_compiler_builtins,
3636
);

compiler/rustc_codegen_gcc/src/base.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ pub fn compile_codegen_unit(
213213

214214
let mono_items = cgu.items_in_deterministic_order(tcx);
215215
for &(mono_item, data) in &mono_items {
216-
mono_item.predefine::<Builder<'_, '_, '_>>(&cx, data.linkage, data.visibility);
216+
mono_item.predefine::<Builder<'_, '_, '_>>(&cx, data.linkage_info, data.visibility);
217217
}
218218

219219
// ... and now that we have everything pre-defined, fill out those definitions.

compiler/rustc_codegen_llvm/src/base.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ pub(crate) fn compile_codegen_unit(
8686
let cx = CodegenCx::new(tcx, cgu, &llvm_module);
8787
let mono_items = cx.codegen_unit.items_in_deterministic_order(cx.tcx);
8888
for &(mono_item, data) in &mono_items {
89-
mono_item.predefine::<Builder<'_, '_, '_>>(&cx, data.linkage, data.visibility);
89+
mono_item.predefine::<Builder<'_, '_, '_>>(&cx, data.linkage_info, data.visibility);
9090
}
9191

9292
// ... and now that we have everything pre-defined, fill out those definitions.

compiler/rustc_codegen_ssa/src/back/symbol_export.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ fn exported_symbols_provider_local(
283283
}
284284

285285
if tcx.local_crate_exports_generics() {
286-
use rustc_middle::mir::mono::{Linkage, MonoItem, Visibility};
286+
use rustc_middle::mir::mono::{MonoItem, Visibility};
287287
use rustc_middle::ty::InstanceKind;
288288

289289
// Normally, we require that shared monomorphizations are not hidden,
@@ -298,7 +298,7 @@ fn exported_symbols_provider_local(
298298
// The symbols created in this loop are sorted below it
299299
#[allow(rustc::potential_query_instability)]
300300
for (mono_item, data) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
301-
if data.linkage != Linkage::External {
301+
if !data.linkage_info.is_external() {
302302
// We can only re-use things with external linkage, otherwise
303303
// we'll get a linker error
304304
continue;

compiler/rustc_codegen_ssa/src/mono_item.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use rustc_hir as hir;
22
use rustc_middle::mir::interpret::ErrorHandled;
3-
use rustc_middle::mir::mono::{Linkage, MonoItem, Visibility};
4-
use rustc_middle::ty::Instance;
3+
use rustc_middle::mir::mono::{LinkageInfo, MonoItem, Visibility};
54
use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf};
5+
use rustc_middle::ty::Instance;
66
use rustc_middle::{span_bug, ty};
77
use tracing::debug;
88

@@ -14,7 +14,7 @@ pub trait MonoItemExt<'a, 'tcx> {
1414
fn predefine<Bx: BuilderMethods<'a, 'tcx>>(
1515
&self,
1616
cx: &'a Bx::CodegenCx,
17-
linkage: Linkage,
17+
linkage_info: LinkageInfo,
1818
visibility: Visibility,
1919
);
2020
fn to_raw_string(&self) -> String;
@@ -116,7 +116,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
116116
fn predefine<Bx: BuilderMethods<'a, 'tcx>>(
117117
&self,
118118
cx: &'a Bx::CodegenCx,
119-
linkage: Linkage,
119+
linkage_info: LinkageInfo,
120120
visibility: Visibility,
121121
) {
122122
debug!(
@@ -132,10 +132,10 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
132132

133133
match *self {
134134
MonoItem::Static(def_id) => {
135-
cx.predefine_static(def_id, linkage, visibility, symbol_name);
135+
cx.predefine_static(def_id, linkage_info.into_linkage(), visibility, symbol_name);
136136
}
137137
MonoItem::Fn(instance) => {
138-
cx.predefine_fn(instance, linkage, visibility, symbol_name);
138+
cx.predefine_fn(instance, linkage_info.into_linkage(), visibility, symbol_name);
139139
}
140140
MonoItem::GlobalAsm(..) => {}
141141
}

compiler/rustc_middle/src/mir/mono.rs

+45-1
Original file line numberDiff line numberDiff line change
@@ -266,13 +266,57 @@ pub struct MonoItemData {
266266
/// `GloballyShared` maps to `false` and `LocalCopy` maps to `true`.
267267
pub inlined: bool,
268268

269-
pub linkage: Linkage,
269+
pub linkage_info: LinkageInfo,
270270
pub visibility: Visibility,
271271

272272
/// A cached copy of the result of `MonoItem::size_estimate`.
273273
pub size_estimate: usize,
274274
}
275275

276+
/// Stores how we know what linkage to use
277+
#[derive(Copy, Clone, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
278+
pub enum LinkageInfo {
279+
/// The linkage was specified explicitly (e.g. using #[linkage = "..."])
280+
Explicit(Linkage),
281+
/// Assume the symbol may be used from other CGUs, a safe default
282+
ImplicitExternal,
283+
/// We did not find any uses from other CGUs, so it's fine to make this internal
284+
ImplicitInternal,
285+
}
286+
287+
impl LinkageInfo {
288+
pub const fn is_external(self) -> bool {
289+
matches!(self.into_linkage(), Linkage::External)
290+
}
291+
292+
pub const fn into_linkage(self) -> Linkage {
293+
match self {
294+
Self::Explicit(linkage) => linkage,
295+
Self::ImplicitExternal => Linkage::External,
296+
Self::ImplicitInternal => Linkage::Internal,
297+
}
298+
}
299+
300+
/// Linkage when the MonoItem is a naked function
301+
///
302+
/// Naked functions are generated as a separate declaration (effectively an extern fn) and
303+
/// definition (using global assembly). To link them together, some flavor of external linkage
304+
/// must be used.
305+
pub const fn into_naked_linkage(self) -> Linkage {
306+
match self {
307+
// promote Weak linkage to ExternalWeak
308+
Self::Explicit(Linkage::WeakAny | Linkage::WeakODR) => Linkage::ExternalWeak,
309+
Self::Explicit(linkage) => linkage,
310+
311+
// the "implicit" means that linkage is picked by the partitioning algorithm.
312+
// picking external should always be valid (given that we are in fact linking
313+
// to the global assembly in the same CGU)
314+
Self::ImplicitExternal => Linkage::External,
315+
Self::ImplicitInternal => Linkage::External,
316+
}
317+
}
318+
}
319+
276320
/// Specifies the linkage type for a `MonoItem`.
277321
///
278322
/// See <https://llvm.org/docs/LangRef.html#linkage-types> for more details about these variants.

compiler/rustc_monomorphize/src/partitioning.rs

+26-23
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,8 @@ use rustc_middle::bug;
109109
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
110110
use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel};
111111
use rustc_middle::mir::mono::{
112-
CodegenUnit, CodegenUnitNameBuilder, InstantiationMode, Linkage, MonoItem, MonoItemData,
113-
Visibility,
112+
CodegenUnit, CodegenUnitNameBuilder, InstantiationMode, Linkage, LinkageInfo, MonoItem,
113+
MonoItemData, Visibility,
114114
};
115115
use rustc_middle::ty::print::{characteristic_def_id_of_type, with_no_trimmed_paths};
116116
use rustc_middle::ty::visit::TypeVisitableExt;
@@ -245,7 +245,7 @@ where
245245
let cgu = codegen_units.entry(cgu_name).or_insert_with(|| CodegenUnit::new(cgu_name));
246246

247247
let mut can_be_internalized = true;
248-
let (linkage, visibility) = mono_item_linkage_and_visibility(
248+
let (linkage_info, visibility) = mono_item_linkage_info_and_visibility(
249249
cx.tcx,
250250
&mono_item,
251251
&mut can_be_internalized,
@@ -259,7 +259,7 @@ where
259259

260260
cgu.items_mut().insert(mono_item, MonoItemData {
261261
inlined: false,
262-
linkage,
262+
linkage_info,
263263
visibility,
264264
size_estimate,
265265
});
@@ -278,7 +278,7 @@ where
278278
// This is a CGU-private copy.
279279
cgu.items_mut().entry(inlined_item).or_insert_with(|| MonoItemData {
280280
inlined: true,
281-
linkage: Linkage::Internal,
281+
linkage_info: LinkageInfo::ImplicitInternal,
282282
visibility: Visibility::Default,
283283
size_estimate: inlined_item.size_estimate(cx.tcx),
284284
});
@@ -589,7 +589,8 @@ fn internalize_symbols<'tcx>(
589589

590590
// If we got here, we did not find any uses from other CGUs, so
591591
// it's fine to make this monomorphization internal.
592-
data.linkage = Linkage::Internal;
592+
debug_assert_eq!(data.linkage_info, LinkageInfo::ImplicitExternal);
593+
data.linkage_info = LinkageInfo::ImplicitInternal;
593594
data.visibility = Visibility::Default;
594595
}
595596
}
@@ -607,7 +608,7 @@ fn mark_code_coverage_dead_code_cgu<'tcx>(codegen_units: &mut [CodegenUnit<'tcx>
607608
// function symbols to be included via `-u` or `/include` linker args.
608609
let dead_code_cgu = codegen_units
609610
.iter_mut()
610-
.filter(|cgu| cgu.items().iter().any(|(_, data)| data.linkage == Linkage::External))
611+
.filter(|cgu| cgu.items().iter().any(|(_, data)| data.linkage_info.is_external()))
611612
.min_by_key(|cgu| cgu.size_estimate());
612613

613614
// If there are no CGUs that have externally linked items, then we just
@@ -736,24 +737,26 @@ fn fallback_cgu_name(name_builder: &mut CodegenUnitNameBuilder<'_>) -> Symbol {
736737
name_builder.build_cgu_name(LOCAL_CRATE, &["fallback"], Some("cgu"))
737738
}
738739

739-
fn mono_item_linkage_and_visibility<'tcx>(
740+
fn mono_item_linkage_info_and_visibility<'tcx>(
740741
tcx: TyCtxt<'tcx>,
741742
mono_item: &MonoItem<'tcx>,
742743
can_be_internalized: &mut bool,
743744
can_export_generics: bool,
744745
always_export_generics: bool,
745-
) -> (Linkage, Visibility) {
746+
) -> (LinkageInfo, Visibility) {
746747
if let Some(explicit_linkage) = mono_item.explicit_linkage(tcx) {
747-
return (explicit_linkage, Visibility::Default);
748+
(LinkageInfo::Explicit(explicit_linkage), Visibility::Default)
749+
} else {
750+
let vis = mono_item_visibility(
751+
tcx,
752+
mono_item,
753+
can_be_internalized,
754+
can_export_generics,
755+
always_export_generics,
756+
);
757+
758+
(LinkageInfo::ImplicitExternal, vis)
748759
}
749-
let vis = mono_item_visibility(
750-
tcx,
751-
mono_item,
752-
can_be_internalized,
753-
can_export_generics,
754-
always_export_generics,
755-
);
756-
(Linkage::External, vis)
757760
}
758761

759762
type CguNameCache = UnordMap<(DefId, bool), Symbol>;
@@ -1033,15 +1036,15 @@ fn debug_dump<'a, 'tcx: 'a>(tcx: TyCtxt<'tcx>, label: &str, cgus: &[CodegenUnit<
10331036
writeln!(s, " - items: {num_items}, mean size: {mean_size:.1}, sizes: {sizes}",);
10341037

10351038
for (item, data) in cgu.items_in_deterministic_order(tcx) {
1036-
let linkage = data.linkage;
1039+
let linkage_info = data.linkage_info;
10371040
let symbol_name = item.symbol_name(tcx).name;
10381041
let symbol_hash_start = symbol_name.rfind('h');
10391042
let symbol_hash = symbol_hash_start.map_or("<no hash>", |i| &symbol_name[i..]);
10401043
let kind = if !data.inlined { "root" } else { "inlined" };
10411044
let size = data.size_estimate;
10421045
let _ = with_no_trimmed_paths!(writeln!(
10431046
s,
1044-
" - {item} [{linkage:?}] [{symbol_hash}] ({kind}, size: {size})"
1047+
" - {item} [{linkage_info:?}] [{symbol_hash}] ({kind}, size: {size})"
10451048
));
10461049
}
10471050

@@ -1194,7 +1197,7 @@ fn collect_and_partition_mono_items(tcx: TyCtxt<'_>, (): ()) -> (&DefIdSet, &[Co
11941197

11951198
for cgu in codegen_units {
11961199
for (&mono_item, &data) in cgu.items() {
1197-
item_to_cgus.entry(mono_item).or_default().push((cgu.name(), data.linkage));
1200+
item_to_cgus.entry(mono_item).or_default().push((cgu.name(), data.linkage_info));
11981201
}
11991202
}
12001203

@@ -1207,11 +1210,11 @@ fn collect_and_partition_mono_items(tcx: TyCtxt<'_>, (): ()) -> (&DefIdSet, &[Co
12071210
let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
12081211
cgus.sort_by_key(|(name, _)| *name);
12091212
cgus.dedup();
1210-
for &(ref cgu_name, linkage) in cgus.iter() {
1213+
for &(ref cgu_name, linkage_info) in cgus.iter() {
12111214
output.push(' ');
12121215
output.push_str(cgu_name.as_str());
12131216

1214-
let linkage_abbrev = match linkage {
1217+
let linkage_abbrev = match linkage_info.into_linkage() {
12151218
Linkage::External => "External",
12161219
Linkage::AvailableExternally => "Available",
12171220
Linkage::LinkOnceAny => "OnceAny",

0 commit comments

Comments
 (0)