Skip to content

Commit e15cecc

Browse files
committed
Auto merge of #161432 - nnethercote:improve-session-backend-building, r=bjorn3
Improve `Session`/`CodegenBackend` construction The creation and initialization of sessions and codegen backends is intertwined, which is confusing and error prone. This PR detangles things, and also simplifies the types used for the state within the backends. Details in individual commits. r? @bjorn3
2 parents 28e8a8c + 8515e12 commit e15cecc

32 files changed

Lines changed: 451 additions & 459 deletions

File tree

‎compiler/rustc_codegen_cranelift/src/driver/aot.rs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,6 @@ impl WriteBackendMethods for AotDriver {
319319
&self,
320320
_sess: &Session,
321321
_opt_level: OptLevel,
322-
_target_features: &[String],
323322
) -> TargetMachineFactoryFn<Self> {
324323
Arc::new(|_, _| ())
325324
}

‎compiler/rustc_codegen_cranelift/src/lib.rs‎

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ extern crate rustc_target;
3232
extern crate rustc_driver;
3333

3434
use std::any::Any;
35-
use std::cell::OnceCell;
3635
use std::env;
3736
use std::sync::Arc;
3837

@@ -44,7 +43,7 @@ use rustc_data_structures::unord::UnordSet;
4443
use rustc_log::tracing::info;
4544
use rustc_middle::dep_graph::WorkProductMap;
4645
use rustc_session::config::{NATIVE_CPU, OutputFilenames};
47-
use rustc_session::{IncrCompSession, Session};
46+
use rustc_session::{CodegenBackendInit, EarlySession, IncrCompSession, Session};
4847
use rustc_span::{Symbol, sym};
4948
use rustc_target::spec::{Arch, CfgAbi, Env, Os};
5049

@@ -119,43 +118,49 @@ impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
119118
}
120119

121120
pub struct CraneliftCodegenBackend {
122-
pub config: OnceCell<BackendConfig>,
121+
// Set by `init` if not already set. (E.g. by cg_clif.)
122+
pub config: Option<BackendConfig>,
123123
}
124124

125125
impl CodegenBackend for CraneliftCodegenBackend {
126126
fn name(&self) -> &'static str {
127127
"cranelift"
128128
}
129129

130-
fn init(&self, sess: &Session) {
131-
use rustc_session::config::{InstrumentCoverage, Lto};
132-
match sess.lto() {
133-
Lto::No | Lto::ThinLocal => {}
134-
Lto::Thin | Lto::Fat => {
135-
sess.dcx().fatal("LTO is not supported by rustc_codegen_cranelift");
130+
fn init(&mut self, sess: &EarlySession) -> CodegenBackendInit {
131+
use rustc_session::config::{InstrumentCoverage, LtoCli};
132+
133+
match (sess.target.requires_lto, sess.early_lto()) {
134+
(true, _) | (false, LtoCli::Yes | LtoCli::Fat | LtoCli::NoParam | LtoCli::Thin) => {
135+
sess.dcx().fatal("LTO is not supported by rustc_codegen_cranelift")
136136
}
137+
(false, LtoCli::Unspecified | LtoCli::No) => {}
137138
}
138139

139140
if sess.opts.cg.instrument_coverage() != InstrumentCoverage::No {
140141
sess.dcx()
141142
.fatal("`-Cinstrument-coverage` is LLVM specific and not supported by Cranelift");
142143
}
143144

144-
let config = self.config.get_or_init(|| {
145+
// Set `config` if not already set.
146+
let config = self.config.get_or_insert_with(|| {
145147
BackendConfig::from_opts(&sess.opts.cg.llvm_args)
146148
.unwrap_or_else(|err| sess.dcx().fatal(err))
147149
});
148150

149151
if config.jit_mode && !sess.opts.output_types.should_codegen() {
150152
sess.dcx().fatal("JIT mode doesn't work with `cargo check`");
151153
}
152-
}
153154

154-
fn thin_lto_supported(&self) -> bool {
155-
false
155+
CodegenBackendInit {
156+
global_backend_features: vec![],
157+
replaced_intrinsics: vec![],
158+
fallback_intrinsics: vec![sym::type_id_eq],
159+
thin_lto_supported: false,
160+
}
156161
}
157162

158-
fn target_config(&self, sess: &Session) -> TargetConfig {
163+
fn target_config(&self, sess: &EarlySession) -> TargetConfig {
159164
// FIXME return the actually used target features. this is necessary for #[cfg(target_feature)]
160165
let target_features = match sess.target.arch {
161166
Arch::X86_64 if sess.target.os != Os::None => {
@@ -216,7 +221,7 @@ impl CodegenBackend for CraneliftCodegenBackend {
216221

217222
fn codegen_crate(&self, tcx: TyCtxt<'_>) -> Box<dyn Any> {
218223
info!("codegen crate {}", tcx.crate_name(LOCAL_CRATE));
219-
let config = self.config.get().unwrap();
224+
let config = self.config.as_ref().unwrap();
220225
if config.jit_mode {
221226
#[cfg(feature = "jit")]
222227
driver::jit::run_jit(tcx, self.target_cpu(tcx.sess), config.jit_args.clone());
@@ -241,10 +246,6 @@ impl CodegenBackend for CraneliftCodegenBackend {
241246
.unwrap()
242247
.join(sess, incr_comp_session, crate_info)
243248
}
244-
245-
fn fallback_intrinsics(&self) -> Vec<Symbol> {
246-
vec![sym::type_id_eq]
247-
}
248249
}
249250

250251
/// Determine if the Cranelift ir verifier should run.
@@ -376,5 +377,5 @@ fn build_isa(sess: &Session, jit: bool) -> Arc<dyn TargetIsa + 'static> {
376377
/// This is the entrypoint for a hot plugged rustc_codegen_cranelift
377378
#[unsafe(no_mangle)]
378379
pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
379-
Box::new(CraneliftCodegenBackend { config: OnceCell::new() })
380+
Box::new(CraneliftCodegenBackend { config: None })
380381
}

‎compiler/rustc_codegen_gcc/src/attributes.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ pub fn from_fn_attrs<'gcc, 'tcx>(
124124
.target_features
125125
.iter()
126126
.map(|features| features.name.as_str())
127-
.flat_map(|feat| to_gcc_features(cx.tcx.sess, feat).into_iter())
127+
.flat_map(|feat| to_gcc_features(&cx.tcx.sess.target, feat).into_iter())
128128
.chain(codegen_fn_attrs.instruction_set.iter().map(|x| match *x {
129129
InstructionSetAttr::ArmA32 => "-thumb-mode", // FIXME(antoyo): support removing feature.
130130
InstructionSetAttr::ArmT32 => "thumb-mode",
@@ -133,7 +133,7 @@ pub fn from_fn_attrs<'gcc, 'tcx>(
133133

134134
// FIXME(antoyo): cg_llvm adds global features to each function so that LTO keep them.
135135
// Check if GCC requires the same.
136-
let mut global_features = cx.tcx.global_backend_features(()).iter().map(|s| s.as_str());
136+
let mut global_features = cx.tcx.sess.global_backend_features.iter().map(|s| s.as_str());
137137
function_features.extend(&mut global_features);
138138
let target_features = function_features
139139
.iter()

‎compiler/rustc_codegen_gcc/src/base.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use rustc_target::spec::{Arch, RelocModel};
2121

2222
use crate::builder::Builder;
2323
use crate::context::CodegenCx;
24-
use crate::{GccContext, LockedTargetInfo, LtoMode, SyncContext, gcc_util, new_context};
24+
use crate::{GccContext, LtoMode, SharedTargetInfo, SyncContext, gcc_util, new_context};
2525

2626
#[cfg(feature = "master")]
2727
pub fn visibility_to_gcc(visibility: Visibility) -> gccjit::Visibility {
@@ -73,7 +73,7 @@ pub fn linkage_to_gcc(linkage: Linkage) -> FunctionType {
7373
pub fn compile_codegen_unit(
7474
tcx: TyCtxt<'_>,
7575
cgu_name: Symbol,
76-
target_info: LockedTargetInfo,
76+
target_info: SharedTargetInfo,
7777
lto_supported: bool,
7878
) -> (ModuleCodegen<GccContext>, u64) {
7979
let prof_timer = tcx.prof.generic_activity("codegen_module");
@@ -96,7 +96,7 @@ pub fn compile_codegen_unit(
9696
fn module_codegen(
9797
tcx: TyCtxt<'_>,
9898
cgu_name: Symbol,
99-
target_info: LockedTargetInfo,
99+
target_info: SharedTargetInfo,
100100
lto_supported: bool,
101101
) -> ModuleCodegen<GccContext> {
102102
let cgu = tcx.codegen_unit(cgu_name);

‎compiler/rustc_codegen_gcc/src/context.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ impl<'gcc, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
450450
}
451451
let tcx = self.tcx;
452452
let func = match tcx.lang_items().eh_personality() {
453-
Some(def_id) if !wants_msvc_seh(self.sess()) => {
453+
Some(def_id) if !wants_msvc_seh(&self.sess().target) => {
454454
let instance = ty::Instance::expect_resolve(
455455
tcx,
456456
self.typing_env(),
@@ -465,7 +465,7 @@ impl<'gcc, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
465465
self.declare_fn(symbol_name, fn_abi)
466466
}
467467
_ => {
468-
let name = if wants_msvc_seh(self.sess()) {
468+
let name = if wants_msvc_seh(&self.sess().target) {
469469
"__CxxFrameHandler3"
470470
} else {
471471
"rust_eh_personality"

‎compiler/rustc_codegen_gcc/src/gcc_util.rs‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@
22
use gccjit::Context;
33
use rustc_codegen_ssa::target_features;
44
use rustc_data_structures::smallvec::{SmallVec, smallvec};
5-
use rustc_session::Session;
5+
use rustc_session::EarlySession;
66
use rustc_session::config::NATIVE_CPU;
7-
use rustc_target::spec::Arch;
7+
use rustc_target::spec::{Arch, Target};
88

9-
fn gcc_features_by_flags(sess: &Session, features: &mut Vec<String>) {
9+
fn gcc_features_by_flags(sess: &EarlySession, features: &mut Vec<String>) {
1010
target_features::retpoline_features_by_flags(sess, features);
1111
// FIXME: LLVM also sets +reserve-x18 here under some conditions.
1212
}
1313

1414
/// The list of GCC features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
1515
/// `--target` and similar).
16-
pub(crate) fn global_gcc_features(sess: &Session) -> Vec<String> {
16+
pub(crate) fn global_gcc_features(sess: &EarlySession) -> Vec<String> {
1717
// Features that come earlier are overridden by conflicting features later in the string.
1818
// Typically we'll want more explicit settings to override the implicit ones, so:
1919
//
@@ -40,9 +40,9 @@ pub(crate) fn global_gcc_features(sess: &Session) -> Vec<String> {
4040
// features also work on the command line instead of having two
4141
// different names when the GCC name and the Rust name differ.
4242
features.extend(
43-
to_gcc_features(sess, feature)
43+
to_gcc_features(&sess.target, feature)
4444
.iter()
45-
.flat_map(|feat| to_gcc_features(sess, feat).into_iter())
45+
.flat_map(|feat| to_gcc_features(&sess.target, feat).into_iter())
4646
.map(|feature| if !enable { format!("-{}", feature) } else { feature.to_string() }),
4747
);
4848
};
@@ -59,9 +59,9 @@ pub(crate) fn global_gcc_features(sess: &Session) -> Vec<String> {
5959
}
6060

6161
// To find a list of GCC's names, check https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
62-
pub fn to_gcc_features<'a>(sess: &Session, s: &'a str) -> SmallVec<[&'a str; 2]> {
62+
pub fn to_gcc_features<'a>(target: &Target, s: &'a str) -> SmallVec<[&'a str; 2]> {
6363
// cSpell:disable
64-
match (&sess.target.arch, s) {
64+
match (&target.arch, s) {
6565
// FIXME: seems like x87 does not exist?
6666
(&Arch::X86 | &Arch::X86_64, "x87") => smallvec![],
6767
(&Arch::X86 | &Arch::X86_64, "sse4.2") => smallvec!["sse4.2", "crc32"],
@@ -130,7 +130,7 @@ fn handle_native(name: &str) -> &str {
130130
unimplemented!();
131131
}
132132

133-
pub fn target_cpu(sess: &Session) -> &str {
133+
pub fn target_cpu(sess: &EarlySession) -> &str {
134134
match sess.opts.cg.target_cpu {
135135
Some(ref name) => handle_native(name),
136136
None => handle_native(sess.target.cpu.as_ref()),

‎compiler/rustc_codegen_gcc/src/intrinsic/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1352,7 +1352,7 @@ fn try_intrinsic<'a, 'b, 'gcc, 'tcx>(
13521352
// we can never unwind.
13531353
OperandValue::Immediate(bx.const_bool(false)).store(bx, dest);
13541354
} else {
1355-
if wants_msvc_seh(bx.sess()) {
1355+
if wants_msvc_seh(&bx.sess().target) {
13561356
unimplemented!();
13571357
}
13581358
#[cfg(feature = "master")]

0 commit comments

Comments
 (0)