Skip to content

Commit

Permalink
Auto merge of rust-lang#87402 - nagisa:nagisa/request-feature-request…
Browse files Browse the repository at this point in the history
…s-for-features, r=estebank

Direct users towards using Rust target feature names in CLI

This PR consists of a couple of changes on how we handle target features.

In particular there is a bug-fix wherein we avoid passing through features that aren't prefixed by `+` or `-` to LLVM. These appear to be causing LLVM to assert, which is pretty poor a behaviour (and also makes it pretty clear we expect feature names to be prefixed).

The other commit, I anticipate to be somewhat more controversial is outputting a warning when users specify a LLVM-specific, or otherwise unknown, feature name on the CLI. In those situations we request users to either replace it with a known Rust feature name (e.g. `bmi` -> `bmi1`) or file a feature request. I've a couple motivations for this: first of all, if users are specifying these features on the command line, I'm pretty confident there is also a need for these features to be usable via `#[cfg(target_feature)]` machinery.  And second, we're growing a fair number of backends recently and having ability to provide some sort of unified-ish interface in this place seems pretty useful to me.

Sponsored by: standard.ai
  • Loading branch information
bors committed Mar 2, 2022
2 parents f0c4da4 + df701a2 commit 39a3b52
Show file tree
Hide file tree
Showing 22 changed files with 251 additions and 106 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_gcc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl ExtraBackendMethods for GccCodegenBackend {
base::compile_codegen_unit(tcx, cgu_name)
}

fn target_machine_factory(&self, _sess: &Session, _opt_level: OptLevel) -> TargetMachineFactoryFn<Self> {
fn target_machine_factory(&self, _sess: &Session, _opt_level: OptLevel, _features: &[String]) -> TargetMachineFactoryFn<Self> {
// TODO(antoyo): set opt level.
Arc::new(|_| {
Ok(())
Expand Down
26 changes: 11 additions & 15 deletions compiler/rustc_codegen_llvm/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,11 @@ pub fn sanitize_attrs<'ll>(
}
if enabled.contains(SanitizerSet::MEMTAG) {
// Check to make sure the mte target feature is actually enabled.
let sess = cx.tcx.sess;
let features = llvm_util::llvm_global_features(sess).join(",");
let mte_feature_enabled = features.rfind("+mte");
let mte_feature_disabled = features.rfind("-mte");

if mte_feature_enabled.is_none() || (mte_feature_disabled > mte_feature_enabled) {
sess.err("`-Zsanitizer=memtag` requires `-Ctarget-feature=+mte`");
let features = cx.tcx.global_backend_features(());
let mte_feature =
features.iter().map(|s| &s[..]).rfind(|n| ["+mte", "-mte"].contains(&&n[..]));
if let None | Some("-mte") = mte_feature {
cx.tcx.sess.err("`-Zsanitizer=memtag` requires `-Ctarget-feature=+mte`");
}

attrs.push(llvm::AttributeKind::SanitizeMemTag.create_attr(cx.llcx));
Expand Down Expand Up @@ -382,10 +380,7 @@ pub fn from_fn_attrs<'ll, 'tcx>(
let mut function_features = function_features
.iter()
.flat_map(|feat| {
llvm_util::to_llvm_feature(cx.tcx.sess, feat)
.into_iter()
.map(|f| format!("+{}", f))
.collect::<Vec<String>>()
llvm_util::to_llvm_features(cx.tcx.sess, feat).into_iter().map(|f| format!("+{}", f))
})
.chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
Expand Down Expand Up @@ -418,10 +413,11 @@ pub fn from_fn_attrs<'ll, 'tcx>(
}

if !function_features.is_empty() {
let mut global_features = llvm_util::llvm_global_features(cx.tcx.sess);
global_features.extend(function_features.into_iter());
let features = global_features.join(",");
let val = CString::new(features).unwrap();
let global_features = cx.tcx.global_backend_features(()).iter().map(|s| &s[..]);
let val = global_features
.chain(function_features.iter().map(|s| &s[..]))
.intersperse(",")
.collect::<SmallCStr>();
to_add.push(llvm::CreateAttrStringValue(cx.llcx, cstr!("target-features"), &val));
}

Expand Down
17 changes: 12 additions & 5 deletions compiler/rustc_codegen_llvm/src/back/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,10 @@ pub fn write_output_file<'ll>(

pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm::TargetMachine {
let config = TargetMachineFactoryConfig { split_dwarf_file: None };
target_machine_factory(sess, config::OptLevel::No)(config)
// Can't use query system here quite yet because this function is invoked before the query
// system/tcx is set up.
let features = llvm_util::global_llvm_features(sess, false);
target_machine_factory(sess, config::OptLevel::No, &features)(config)
.unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise())
}

Expand All @@ -115,8 +118,12 @@ pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> &'static mut ll
None
};
let config = TargetMachineFactoryConfig { split_dwarf_file };
target_machine_factory(tcx.sess, tcx.backend_optimization_level(()))(config)
.unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
target_machine_factory(
&tcx.sess,
tcx.backend_optimization_level(()),
tcx.global_backend_features(()),
)(config)
.unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
}

pub fn to_llvm_opt_settings(
Expand Down Expand Up @@ -171,6 +178,7 @@ pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeMod
pub fn target_machine_factory(
sess: &Session,
optlvl: config::OptLevel,
target_features: &[String],
) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
let reloc_model = to_llvm_relocation_model(sess.relocation_model());

Expand All @@ -195,8 +203,7 @@ pub fn target_machine_factory(

let triple = SmallCStr::new(&sess.target.llvm_target);
let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
let features = llvm_util::llvm_global_features(sess).join(",");
let features = CString::new(features).unwrap();
let features = CString::new(target_features.join(",")).unwrap();
let abi = SmallCStr::new(&sess.target.llvm_abiname);
let trap_unreachable =
sess.opts.debugging_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
Expand Down
10 changes: 9 additions & 1 deletion compiler/rustc_codegen_llvm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#![feature(extern_types)]
#![feature(once_cell)]
#![feature(nll)]
#![feature(iter_intersperse)]
#![recursion_limit = "256"]
#![allow(rustc::potential_query_instability)]

Expand All @@ -32,6 +33,7 @@ use rustc_data_structures::fx::FxHashMap;
use rustc_errors::{ErrorReported, FatalError, Handler};
use rustc_metadata::EncodedMetadata;
use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::TyCtxt;
use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
use rustc_session::Session;
Expand Down Expand Up @@ -126,8 +128,9 @@ impl ExtraBackendMethods for LlvmCodegenBackend {
&self,
sess: &Session,
optlvl: OptLevel,
target_features: &[String],
) -> TargetMachineFactoryFn<Self> {
back::write::target_machine_factory(sess, optlvl)
back::write::target_machine_factory(sess, optlvl, target_features)
}
fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
llvm_util::target_cpu(sess)
Expand Down Expand Up @@ -251,6 +254,11 @@ impl CodegenBackend for LlvmCodegenBackend {
llvm_util::init(sess); // Make sure llvm is inited
}

fn provide(&self, providers: &mut Providers) {
providers.global_backend_features =
|tcx, ()| llvm_util::global_llvm_features(tcx.sess, true)
}

fn print(&self, req: PrintRequest, sess: &Session) {
match req {
PrintRequest::RelocationModels => {
Expand Down
Loading

0 comments on commit 39a3b52

Please sign in to comment.