Skip to content

Commit 2749d74

Browse files
committed
(crudely) implement MIR-only rlibs
1 parent c22887b commit 2749d74

File tree

11 files changed

+161
-18
lines changed

11 files changed

+161
-18
lines changed

compiler/rustc_codegen_ssa/src/back/symbol_export.rs

+29-2
Original file line numberDiff line numberDiff line change
@@ -209,8 +209,14 @@ fn exported_symbols_provider_local(
209209
if allocator_kind_for_codegen(tcx).is_some() {
210210
for symbol_name in ALLOCATOR_METHODS
211211
.iter()
212-
.map(|method| format!("__rust_{}", method.name))
213-
.chain(["__rust_alloc_error_handler".to_string(), OomStrategy::SYMBOL.to_string()])
212+
.flat_map(|method| {
213+
[format!("__rust_{}", method.name), format!("__rdl_{}", method.name)]
214+
})
215+
.chain([
216+
"__rust_alloc_error_handler".to_string(),
217+
OomStrategy::SYMBOL.to_string(),
218+
"__rg_oom".to_string(),
219+
])
214220
{
215221
let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
216222

@@ -349,6 +355,27 @@ fn exported_symbols_provider_local(
349355
}
350356
}
351357

358+
if tcx.building_mir_only_rlib() {
359+
for def_id in tcx.mir_keys(()) {
360+
if !matches!(tcx.def_kind(def_id.to_def_id()), DefKind::Static { .. }) {
361+
continue;
362+
}
363+
if tcx.is_reachable_non_generic(def_id.to_def_id()) {
364+
continue;
365+
}
366+
let codegen_attrs = tcx.codegen_fn_attrs(def_id.to_def_id());
367+
symbols.push((ExportedSymbol::NonGeneric(def_id.to_def_id()), SymbolExportInfo {
368+
level: symbol_export_level(tcx, def_id.to_def_id()),
369+
kind: if codegen_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
370+
SymbolExportKind::Tls
371+
} else {
372+
SymbolExportKind::Data
373+
},
374+
used: true,
375+
}));
376+
}
377+
}
378+
352379
// Sort so we get a stable incr. comp. hash.
353380
symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
354381

compiler/rustc_interface/src/tests.rs

+1
Original file line numberDiff line numberDiff line change
@@ -807,6 +807,7 @@ fn test_unstable_options_tracking_hash() {
807807
tracked!(mir_emit_retag, true);
808808
tracked!(mir_enable_passes, vec![("DestProp".to_string(), false)]);
809809
tracked!(mir_keep_place_mention, true);
810+
tracked!(mir_only_rlibs, true);
810811
tracked!(mir_opt_level, Some(4));
811812
tracked!(move_size_limit, Some(4096));
812813
tracked!(mutable_noalias, false);

compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs

+8
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,14 @@ pub(in crate::rmeta) fn provide(providers: &mut Providers) {
573573
.filter_map(|(cnum, data)| data.used().then_some(cnum)),
574574
)
575575
},
576+
mir_only_crates: |tcx, ()| {
577+
tcx.untracked().cstore.freeze();
578+
let store = CStore::from_tcx(tcx);
579+
let crates = store
580+
.iter_crate_data()
581+
.filter_map(|(cnum, data)| if data.root.is_mir_only { Some(cnum) } else { None });
582+
tcx.arena.alloc_from_iter(crates)
583+
},
576584
..providers.queries
577585
};
578586
provide_extern(&mut providers.extern_queries);

compiler/rustc_metadata/src/rmeta/encoder.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -736,6 +736,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
736736
impls,
737737
incoherent_impls,
738738
exported_symbols,
739+
is_mir_only: tcx.building_mir_only_rlib(),
739740
interpret_alloc_index,
740741
tables,
741742
syntax_contexts,
@@ -1058,12 +1059,13 @@ fn should_encode_mir(
10581059
reachable_set: &LocalDefIdSet,
10591060
def_id: LocalDefId,
10601061
) -> (bool, bool) {
1062+
let opts = &tcx.sess.opts;
1063+
let mir_required = opts.unstable_opts.always_encode_mir || tcx.building_mir_only_rlib();
10611064
match tcx.def_kind(def_id) {
10621065
// Constructors
10631066
DefKind::Ctor(_, _) => {
1064-
let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
1065-
|| tcx.sess.opts.unstable_opts.always_encode_mir;
1066-
(true, mir_opt_base)
1067+
let opt = mir_required || opts.output_types.should_codegen();
1068+
(true, opt)
10671069
}
10681070
// Constants
10691071
DefKind::AnonConst | DefKind::InlineConst | DefKind::AssocConst | DefKind::Const => {
@@ -1075,7 +1077,7 @@ fn should_encode_mir(
10751077
// Full-fledged functions + closures
10761078
DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
10771079
let generics = tcx.generics_of(def_id);
1078-
let opt = tcx.sess.opts.unstable_opts.always_encode_mir
1080+
let opt = mir_required
10791081
|| (tcx.sess.opts.output_types.should_codegen()
10801082
&& reachable_set.contains(&def_id)
10811083
&& (generics.requires_monomorphization(tcx)

compiler/rustc_metadata/src/rmeta/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,7 @@ pub(crate) struct CrateRoot {
275275
debugger_visualizers: LazyArray<DebuggerVisualizerFile>,
276276

277277
exported_symbols: LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)>,
278+
is_mir_only: bool,
278279

279280
syntax_contexts: SyntaxContextTable,
280281
expn_data: ExpnDataTable,

compiler/rustc_middle/src/mir/mono.rs

+11
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,17 @@ impl<'tcx> MonoItem<'tcx> {
104104
}
105105

106106
pub fn instantiation_mode(&self, tcx: TyCtxt<'tcx>) -> InstantiationMode {
107+
// Always do LocalCopy codegen when building a MIR-only rlib
108+
if tcx.building_mir_only_rlib() {
109+
return InstantiationMode::LocalCopy;
110+
}
111+
// If this is a monomorphization from a MIR-only rlib and we are building another lib, do
112+
// local codegen.
113+
if tcx.mir_only_crates(()).iter().any(|c| *c == self.def_id().krate)
114+
&& tcx.crate_types() == &[rustc_session::config::CrateType::Rlib]
115+
{
116+
return InstantiationMode::LocalCopy;
117+
}
107118
let generate_cgu_internal_copies = tcx
108119
.sess
109120
.opts

compiler/rustc_middle/src/query/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -2333,6 +2333,11 @@ rustc_queries! {
23332333
desc { "check for feature-dependent ABI" }
23342334
cache_on_disk_if { true }
23352335
}
2336+
2337+
query mir_only_crates(_: ()) -> &'tcx [CrateNum] {
2338+
eval_always
2339+
desc { "fetching all foreign crates built in mir-only mode" }
2340+
}
23362341
}
23372342

23382343
rustc_query_append! { define_callbacks! }

compiler/rustc_middle/src/ty/context.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1786,6 +1786,10 @@ impl<'tcx> TyCtxt<'tcx> {
17861786
pub fn dcx(self) -> DiagCtxtHandle<'tcx> {
17871787
self.sess.dcx()
17881788
}
1789+
1790+
pub fn building_mir_only_rlib(self) -> bool {
1791+
self.sess.opts.unstable_opts.mir_only_rlibs && self.crate_types() == &[CrateType::Rlib]
1792+
}
17891793
}
17901794

17911795
impl<'tcx> TyCtxtAt<'tcx> {

compiler/rustc_monomorphize/src/collector.rs

+71-8
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ use rustc_hir::def::DefKind;
219219
use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId};
220220
use rustc_hir::lang_items::LangItem;
221221
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
222+
use rustc_middle::middle::exported_symbols::ExportedSymbol;
222223
use rustc_middle::mir::interpret::{AllocId, ErrorHandled, GlobalAlloc, Scalar};
223224
use rustc_middle::mir::mono::{InstantiationMode, MonoItem};
224225
use rustc_middle::mir::visit::Visitor as MirVisitor;
@@ -234,7 +235,7 @@ use rustc_middle::ty::{
234235
use rustc_middle::util::Providers;
235236
use rustc_middle::{bug, span_bug};
236237
use rustc_session::Limit;
237-
use rustc_session::config::EntryFnType;
238+
use rustc_session::config::{CrateType, EntryFnType};
238239
use rustc_span::source_map::{Spanned, dummy_spanned, respan};
239240
use rustc_span::symbol::{Ident, sym};
240241
use rustc_span::{DUMMY_SP, Span};
@@ -941,28 +942,45 @@ fn should_codegen_locally<'tcx>(tcx: TyCtxtAt<'tcx>, instance: Instance<'tcx>) -
941942
return true;
942943
};
943944

945+
let def_is_for_mir_only_rlib = if def_id.krate == rustc_hir::def_id::LOCAL_CRATE {
946+
tcx.building_mir_only_rlib()
947+
} else {
948+
tcx.mir_only_crates(()).iter().any(|c| *c == def_id.krate)
949+
};
950+
944951
if tcx.is_foreign_item(def_id) {
945-
// Foreign items are always linked against, there's no way of instantiating them.
946-
return false;
952+
if def_is_for_mir_only_rlib {
953+
return tcx.is_mir_available(instance.def_id());
954+
} else {
955+
// Foreign items are always linked against, there's no way of instantiating them.
956+
return false;
957+
}
958+
}
959+
960+
if def_is_for_mir_only_rlib {
961+
let has_mir = tcx.is_mir_available(instance.def_id());
962+
return has_mir || matches!(tcx.def_kind(instance.def_id()), DefKind::Static { .. });
947963
}
948964

949965
if def_id.is_local() {
950966
// Local items cannot be referred to locally without monomorphizing them locally.
951967
return true;
952968
}
953969

970+
if !def_is_for_mir_only_rlib {
971+
if let DefKind::Static { .. } = tcx.def_kind(def_id) {
972+
// We cannot monomorphize statics from upstream crates.
973+
return false;
974+
}
975+
}
976+
954977
if tcx.is_reachable_non_generic(def_id)
955978
|| instance.polymorphize(*tcx).upstream_monomorphization(*tcx).is_some()
956979
{
957980
// We can link to the item in question, no instance needed in this crate.
958981
return false;
959982
}
960983

961-
if let DefKind::Static { .. } = tcx.def_kind(def_id) {
962-
// We cannot monomorphize statics from upstream crates.
963-
return false;
964-
}
965-
966984
if !tcx.is_mir_available(def_id) {
967985
tcx.dcx().emit_fatal(NoOptimizedMir {
968986
span: tcx.def_span(def_id),
@@ -1354,6 +1372,7 @@ fn collect_roots(tcx: TyCtxt<'_>, mode: MonoItemCollectionStrategy) -> Vec<MonoI
13541372
}
13551373

13561374
collector.push_extra_entry_roots();
1375+
collector.push_extra_roots_from_mir_only_rlibs();
13571376
}
13581377

13591378
// We can only codegen items that are instantiable - items all of
@@ -1498,6 +1517,50 @@ impl<'v> RootCollector<'_, 'v> {
14981517

14991518
self.output.push(create_fn_mono_item(self.tcx, start_instance, DUMMY_SP));
15001519
}
1520+
1521+
fn push_extra_roots_from_mir_only_rlibs(&mut self) {
1522+
// An upstream extern function may be used anywhere in the dependency tree, so we
1523+
// cannot do any reachability analysis on them. We blindly monomorphize every
1524+
// extern function declared anywhere in our dependency tree. We must give them
1525+
// GloballyShared codegen because we don't know if the only call to an upstream
1526+
// extern function is also upstream: We don't have reachability information. All we
1527+
// can do is codegen all extern functions and pray for the linker to delete the
1528+
// ones that are reachable.
1529+
if !self.tcx.crate_types().iter().any(|c| !matches!(c, CrateType::Rlib)) {
1530+
return;
1531+
}
1532+
1533+
for (symbol, _info) in self
1534+
.tcx
1535+
.mir_only_crates(())
1536+
.into_iter()
1537+
.flat_map(|krate| self.tcx.exported_symbols(*krate))
1538+
{
1539+
let def_id = match symbol {
1540+
ExportedSymbol::NonGeneric(def_id) => def_id,
1541+
ExportedSymbol::ThreadLocalShim(def_id) => {
1542+
let item = MonoItem::Fn(Instance {
1543+
def: InstanceKind::ThreadLocalShim(*def_id),
1544+
args: GenericArgs::empty(),
1545+
});
1546+
self.output.push(dummy_spanned(item));
1547+
continue;
1548+
}
1549+
_ => continue,
1550+
};
1551+
match self.tcx.def_kind(def_id) {
1552+
DefKind::Fn | DefKind::AssocFn => {
1553+
let instance = Instance::mono(self.tcx, *def_id);
1554+
let item = create_fn_mono_item(self.tcx, instance, DUMMY_SP);
1555+
self.output.push(item);
1556+
}
1557+
DefKind::Static { .. } => {
1558+
self.output.push(dummy_spanned(MonoItem::Static(*def_id)));
1559+
}
1560+
_ => {}
1561+
}
1562+
}
1563+
}
15011564
}
15021565

15031566
#[instrument(level = "debug", skip(tcx, output))]

compiler/rustc_monomorphize/src/partitioning.rs

+23-4
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,12 @@ fn partition<'tcx, I>(
146146
where
147147
I: Iterator<Item = MonoItem<'tcx>>,
148148
{
149+
if tcx.building_mir_only_rlib() {
150+
let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
151+
let cgu_name = fallback_cgu_name(cgu_name_builder);
152+
return vec![CodegenUnit::new(cgu_name)];
153+
}
154+
149155
let _prof_timer = tcx.prof.generic_activity("cgu_partitioning");
150156

151157
let cx = &PartitioningCx { tcx, usage_map };
@@ -170,6 +176,10 @@ where
170176
debug_dump(tcx, "MERGE", &codegen_units);
171177
}
172178

179+
if !codegen_units.is_sorted_by(|a, b| a.name().as_str() < b.name().as_str()) {
180+
bug!("unsorted CGUs");
181+
}
182+
173183
// Make as many symbols "internal" as possible, so LLVM has more freedom to
174184
// optimize.
175185
if !tcx.sess.link_dead_code() {
@@ -190,7 +200,12 @@ where
190200
for cgu in codegen_units.iter() {
191201
names += &format!("- {}\n", cgu.name());
192202
}
193-
bug!("unsorted CGUs:\n{names}");
203+
codegen_units.sort_by(|a, b| a.name().as_str().cmp(b.name().as_str()));
204+
let mut sorted_names = String::new();
205+
for cgu in codegen_units.iter() {
206+
sorted_names += &format!("- {}\n", cgu.name());
207+
}
208+
bug!("unsorted CGUs:\n{names}\n{sorted_names}");
194209
}
195210

196211
codegen_units
@@ -214,6 +229,9 @@ where
214229
let cgu_name_builder = &mut CodegenUnitNameBuilder::new(cx.tcx);
215230
let cgu_name_cache = &mut UnordMap::default();
216231

232+
let start_fn = cx.tcx.lang_items().start_fn();
233+
let entry_fn = cx.tcx.entry_fn(()).map(|(id, _)| id);
234+
217235
for mono_item in mono_items {
218236
// Handle only root (GloballyShared) items directly here. Inlined (LocalCopy) items
219237
// are handled at the bottom of the loop based on reachability, with one exception.
@@ -222,7 +240,8 @@ where
222240
match mono_item.instantiation_mode(cx.tcx) {
223241
InstantiationMode::GloballyShared { .. } => {}
224242
InstantiationMode::LocalCopy => {
225-
if Some(mono_item.def_id()) != cx.tcx.lang_items().start_fn() {
243+
let def_id = mono_item.def_id();
244+
if ![start_fn, entry_fn].contains(&Some(def_id)) {
226245
continue;
227246
}
228247
}
@@ -244,7 +263,7 @@ where
244263

245264
let cgu = codegen_units.entry(cgu_name).or_insert_with(|| CodegenUnit::new(cgu_name));
246265

247-
let mut can_be_internalized = true;
266+
let mut can_be_internalized = false;
248267
let (linkage, visibility) = mono_item_linkage_and_visibility(
249268
cx.tcx,
250269
&mono_item,
@@ -486,7 +505,7 @@ fn merge_codegen_units<'tcx>(
486505
// If we didn't zero-pad the sorted-by-name order would be `XYZ-cgu.0`,
487506
// `XYZ-cgu.1`, `XYZ-cgu.10`, `XYZ-cgu.11`, ..., `XYZ-cgu.2`, etc.
488507
codegen_units.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
489-
let num_digits = codegen_units.len().ilog10() as usize + 1;
508+
let num_digits = std::hint::black_box(codegen_units.len().ilog10() as usize + 1);
490509
for (index, cgu) in codegen_units.iter_mut().enumerate() {
491510
// Note: `WorkItem::short_description` depends on this name ending
492511
// with `-cgu.` followed by a numeric suffix. Please keep it in

compiler/rustc_session/src/options.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1904,6 +1904,8 @@ options! {
19041904
mir_keep_place_mention: bool = (false, parse_bool, [TRACKED],
19051905
"keep place mention MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 \
19061906
(default: no)"),
1907+
mir_only_rlibs: bool = (false, parse_bool, [TRACKED],
1908+
"only generate MIR when building rlibs (default: no)"),
19071909
#[rustc_lint_opt_deny_field_access("use `Session::mir_opt_level` instead of this field")]
19081910
mir_opt_level: Option<usize> = (None, parse_opt_number, [TRACKED],
19091911
"MIR optimization level (0-4; default: 1 in non optimized builds and 2 in optimized builds)"),

0 commit comments

Comments
 (0)