1
Fork 0

rustc_target: Stop using "string typing" for relocation models

Introduce `enum RelocModel` instead.
This commit is contained in:
Vadim Petrochenkov 2020-04-23 00:46:45 +03:00
parent 019ab732ce
commit fb91e5ed2f
30 changed files with 150 additions and 108 deletions

View file

@ -7,7 +7,7 @@ use crate::back::profiling::{
use crate::base; use crate::base;
use crate::common; use crate::common;
use crate::consts; use crate::consts;
use crate::context::{get_reloc_model, is_pie_binary}; use crate::context::is_pie_binary;
use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic}; use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
use crate::llvm_util; use crate::llvm_util;
use crate::type_::Type; use crate::type_::Type;
@ -25,6 +25,7 @@ use rustc_middle::bug;
use rustc_middle::ty::TyCtxt; use rustc_middle::ty::TyCtxt;
use rustc_session::config::{self, Lto, OutputType, Passes, Sanitizer, SwitchWithOptPath}; use rustc_session::config::{self, Lto, OutputType, Passes, Sanitizer, SwitchWithOptPath};
use rustc_session::Session; use rustc_session::Session;
use rustc_target::spec::RelocModel;
use libc::{c_char, c_int, c_uint, c_void, size_t}; use libc::{c_char, c_int, c_uint, c_void, size_t};
use std::ffi::CString; use std::ffi::CString;
@ -35,16 +36,6 @@ use std::slice;
use std::str; use std::str;
use std::sync::Arc; use std::sync::Arc;
pub const RELOC_MODEL_ARGS: [(&str, llvm::RelocMode); 7] = [
("pic", llvm::RelocMode::PIC),
("static", llvm::RelocMode::Static),
("default", llvm::RelocMode::Default),
("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
("ropi", llvm::RelocMode::ROPI),
("rwpi", llvm::RelocMode::RWPI),
("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
];
pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[ pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
("small", llvm::CodeModel::Small), ("small", llvm::CodeModel::Small),
("kernel", llvm::CodeModel::Kernel), ("kernel", llvm::CodeModel::Kernel),
@ -126,6 +117,17 @@ fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel
} }
} }
fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocMode {
match relocation_model {
RelocModel::Static => llvm::RelocMode::Static,
RelocModel::Pic => llvm::RelocMode::PIC,
RelocModel::DynamicNoPic => llvm::RelocMode::DynamicNoPic,
RelocModel::Ropi => llvm::RelocMode::ROPI,
RelocModel::Rwpi => llvm::RelocMode::RWPI,
RelocModel::RopiRwpi => llvm::RelocMode::ROPI_RWPI,
}
}
// If find_features is true this won't access `sess.crate_types` by assuming // If find_features is true this won't access `sess.crate_types` by assuming
// that `is_pie_binary` is false. When we discover LLVM target features // that `is_pie_binary` is false. When we discover LLVM target features
// `sess.crate_types` is uninitialized so we cannot access it. // `sess.crate_types` is uninitialized so we cannot access it.
@ -134,7 +136,7 @@ pub fn target_machine_factory(
optlvl: config::OptLevel, optlvl: config::OptLevel,
find_features: bool, find_features: bool,
) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> { ) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
let reloc_model = get_reloc_model(sess); let reloc_model = to_llvm_relocation_model(sess.relocation_model());
let (opt_level, _) = to_llvm_opt_settings(optlvl); let (opt_level, _) = to_llvm_opt_settings(optlvl);
let use_softfp = sess.opts.cg.soft_float; let use_softfp = sess.opts.cg.soft_float;

View file

@ -21,7 +21,7 @@ use rustc_session::Session;
use rustc_span::source_map::{Span, DUMMY_SP}; use rustc_span::source_map::{Span, DUMMY_SP};
use rustc_span::symbol::Symbol; use rustc_span::symbol::Symbol;
use rustc_target::abi::{HasDataLayout, LayoutOf, PointeeInfo, Size, TargetDataLayout, VariantIdx}; use rustc_target::abi::{HasDataLayout, LayoutOf, PointeeInfo, Size, TargetDataLayout, VariantIdx};
use rustc_target::spec::{HasTargetSpec, Target}; use rustc_target::spec::{HasTargetSpec, RelocModel, Target};
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::ffi::CStr; use std::ffi::CStr;
@ -87,22 +87,6 @@ pub struct CodegenCx<'ll, 'tcx> {
local_gen_sym_counter: Cell<usize>, local_gen_sym_counter: Cell<usize>,
} }
pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode {
let reloc_model_arg = match sess.opts.cg.relocation_model {
Some(ref s) => &s[..],
None => &sess.target.target.options.relocation_model[..],
};
match crate::back::write::RELOC_MODEL_ARGS.iter().find(|&&arg| arg.0 == reloc_model_arg) {
Some(x) => x.1,
_ => {
sess.err(&format!("{:?} is not a valid relocation mode", reloc_model_arg));
sess.abort_if_errors();
bug!();
}
}
}
fn get_tls_model(sess: &Session) -> llvm::ThreadLocalMode { fn get_tls_model(sess: &Session) -> llvm::ThreadLocalMode {
let tls_model_arg = match sess.opts.debugging_opts.tls_model { let tls_model_arg = match sess.opts.debugging_opts.tls_model {
Some(ref s) => &s[..], Some(ref s) => &s[..],
@ -119,12 +103,9 @@ fn get_tls_model(sess: &Session) -> llvm::ThreadLocalMode {
} }
} }
fn is_any_library(sess: &Session) -> bool {
sess.crate_types.borrow().iter().any(|ty| *ty != config::CrateType::Executable)
}
pub fn is_pie_binary(sess: &Session) -> bool { pub fn is_pie_binary(sess: &Session) -> bool {
!is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC sess.relocation_model() == RelocModel::Pic
&& !sess.crate_types.borrow().iter().any(|ty| *ty != config::CrateType::Executable)
} }
fn strip_function_ptr_alignment(data_layout: String) -> String { fn strip_function_ptr_alignment(data_layout: String) -> String {
@ -200,7 +181,7 @@ pub unsafe fn create_module(
let llvm_target = SmallCStr::new(&sess.target.target.llvm_target); let llvm_target = SmallCStr::new(&sess.target.target.llvm_target);
llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr()); llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
if get_reloc_model(sess) == llvm::RelocMode::PIC { if sess.relocation_model() == RelocModel::Pic {
llvm::LLVMRustSetModulePICLevel(llmod); llvm::LLVMRustSetModulePICLevel(llmod);
} }

View file

@ -201,7 +201,9 @@ impl CodegenBackend for LlvmCodegenBackend {
match req { match req {
PrintRequest::RelocationModels => { PrintRequest::RelocationModels => {
println!("Available relocation models:"); println!("Available relocation models:");
for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() { for name in
&["static", "pic", "dynamic-no-pic", "ropi", "rwpi", "ropi-rwpi", "default"]
{
println!(" {}", name); println!(" {}", name);
} }
println!(); println!();

View file

@ -446,7 +446,6 @@ pub struct SanitizerOptions {
#[derive(Copy, Clone, PartialEq)] #[derive(Copy, Clone, PartialEq)]
#[repr(C)] #[repr(C)]
pub enum RelocMode { pub enum RelocMode {
Default,
Static, Static,
PIC, PIC,
DynamicNoPic, DynamicNoPic,

View file

@ -12,7 +12,7 @@ use rustc_session::search_paths::PathKind;
/// need out of the shared crate context before we get rid of it. /// need out of the shared crate context before we get rid of it.
use rustc_session::{filesearch, Session}; use rustc_session::{filesearch, Session};
use rustc_span::symbol::Symbol; use rustc_span::symbol::Symbol;
use rustc_target::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelroLevel}; use rustc_target::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, RelroLevel};
use super::archive::ArchiveBuilder; use super::archive::ArchiveBuilder;
use super::command::Command; use super::command::Command;
@ -1352,7 +1352,7 @@ fn add_position_independent_executable_args(
if sess.target.target.options.position_independent_executables { if sess.target.target.options.position_independent_executables {
let attr_link_args = &*codegen_results.crate_info.link_args; let attr_link_args = &*codegen_results.crate_info.link_args;
let mut user_defined_link_args = sess.opts.cg.link_args.iter().chain(attr_link_args); let mut user_defined_link_args = sess.opts.cg.link_args.iter().chain(attr_link_args);
if is_pic(sess) if sess.relocation_model() == RelocModel::Pic
&& !sess.crt_static(Some(crate_type)) && !sess.crt_static(Some(crate_type))
&& !user_defined_link_args.any(|x| x == "-static") && !user_defined_link_args.any(|x| x == "-static")
{ {
@ -1992,12 +1992,3 @@ fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
config::Lto::No | config::Lto::ThinLocal => false, config::Lto::No | config::Lto::ThinLocal => false,
} }
} }
fn is_pic(sess: &Session) -> bool {
let reloc_model_arg = match sess.opts.cg.relocation_model {
Some(ref s) => &s[..],
None => &sess.target.target.options.relocation_model[..],
};
reloc_model_arg == "pic"
}

View file

@ -14,7 +14,7 @@ use rustc_session::{build_session, Session};
use rustc_span::edition::{Edition, DEFAULT_EDITION}; use rustc_span::edition::{Edition, DEFAULT_EDITION};
use rustc_span::symbol::sym; use rustc_span::symbol::sym;
use rustc_span::SourceFileHashAlgorithm; use rustc_span::SourceFileHashAlgorithm;
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel}; use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelocModel, RelroLevel};
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
use std::iter::FromIterator; use std::iter::FromIterator;
use std::path::PathBuf; use std::path::PathBuf;
@ -430,7 +430,7 @@ fn test_codegen_options_tracking_hash() {
tracked!(prefer_dynamic, true); tracked!(prefer_dynamic, true);
tracked!(profile_generate, SwitchWithOptPath::Enabled(None)); tracked!(profile_generate, SwitchWithOptPath::Enabled(None));
tracked!(profile_use, Some(PathBuf::from("abc"))); tracked!(profile_use, Some(PathBuf::from("abc")));
tracked!(relocation_model, Some(String::from("relocation model"))); tracked!(relocation_model, Some(RelocModel::Pic));
tracked!(soft_float, true); tracked!(soft_float, true);
tracked!(target_cpu, Some(String::from("abc"))); tracked!(target_cpu, Some(String::from("abc")));
tracked!(target_feature, String::from("all the features, all of them")); tracked!(target_feature, String::from("all the features, all of them"));

View file

@ -1311,10 +1311,6 @@ fn collect_print_requests(
prints.push(PrintRequest::TargetFeatures); prints.push(PrintRequest::TargetFeatures);
cg.target_feature = String::new(); cg.target_feature = String::new();
} }
if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
prints.push(PrintRequest::RelocationModels);
cg.relocation_model = None;
}
if cg.code_model.as_ref().map_or(false, |s| s == "help") { if cg.code_model.as_ref().map_or(false, |s| s == "help") {
prints.push(PrintRequest::CodeModels); prints.push(PrintRequest::CodeModels);
cg.code_model = None; cg.code_model = None;
@ -2005,7 +2001,7 @@ crate mod dep_tracking {
use crate::utils::NativeLibraryKind; use crate::utils::NativeLibraryKind;
use rustc_feature::UnstableFeatures; use rustc_feature::UnstableFeatures;
use rustc_span::edition::Edition; use rustc_span::edition::Edition;
use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel, TargetTriple}; use rustc_target::spec::{MergeFunctions, PanicStrategy, RelocModel, RelroLevel, TargetTriple};
use std::collections::hash_map::DefaultHasher; use std::collections::hash_map::DefaultHasher;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::hash::Hash; use std::hash::Hash;
@ -2053,6 +2049,7 @@ crate mod dep_tracking {
impl_dep_tracking_hash_via_hash!(Option<(String, u64)>); impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
impl_dep_tracking_hash_via_hash!(Option<Vec<String>>); impl_dep_tracking_hash_via_hash!(Option<Vec<String>>);
impl_dep_tracking_hash_via_hash!(Option<MergeFunctions>); impl_dep_tracking_hash_via_hash!(Option<MergeFunctions>);
impl_dep_tracking_hash_via_hash!(Option<RelocModel>);
impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>); impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
impl_dep_tracking_hash_via_hash!(Option<RelroLevel>); impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
impl_dep_tracking_hash_via_hash!(Option<lint::Level>); impl_dep_tracking_hash_via_hash!(Option<lint::Level>);

View file

@ -6,7 +6,7 @@ use crate::search_paths::SearchPath;
use crate::utils::NativeLibraryKind; use crate::utils::NativeLibraryKind;
use rustc_target::spec::TargetTriple; use rustc_target::spec::TargetTriple;
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel}; use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelocModel, RelroLevel};
use rustc_feature::UnstableFeatures; use rustc_feature::UnstableFeatures;
use rustc_span::edition::Edition; use rustc_span::edition::Edition;
@ -265,14 +265,13 @@ macro_rules! options {
pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`"; pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`";
pub const parse_symbol_mangling_version: &str = "either `legacy` or `v0` (RFC 2603)"; pub const parse_symbol_mangling_version: &str = "either `legacy` or `v0` (RFC 2603)";
pub const parse_src_file_hash: &str = "either `md5` or `sha1`"; pub const parse_src_file_hash: &str = "either `md5` or `sha1`";
pub const parse_relocation_model: &str =
"one of supported relocation models (`rustc --print relocation-models`)";
} }
#[allow(dead_code)] #[allow(dead_code)]
mod $mod_set { mod $mod_set {
use super::{$struct_name, Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath, use super::*;
SymbolManglingVersion, CFGuard, SourceFileHashAlgorithm};
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
use std::path::PathBuf;
use std::str::FromStr; use std::str::FromStr;
// Sometimes different options need to build a common structure. // Sometimes different options need to build a common structure.
@ -598,6 +597,15 @@ macro_rules! options {
true true
} }
fn parse_relocation_model(slot: &mut Option<RelocModel>, v: Option<&str>) -> bool {
match v.and_then(|s| RelocModel::from_str(s).ok()) {
Some(relocation_model) => *slot = Some(relocation_model),
None if v == Some("default") => *slot = None,
_ => return false,
}
true
}
fn parse_symbol_mangling_version( fn parse_symbol_mangling_version(
slot: &mut SymbolManglingVersion, slot: &mut SymbolManglingVersion,
v: Option<&str>, v: Option<&str>,
@ -697,7 +705,7 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options,
"compile the program with profiling instrumentation"), "compile the program with profiling instrumentation"),
profile_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED], profile_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
"use the given `.profdata` file for profile-guided optimization"), "use the given `.profdata` file for profile-guided optimization"),
relocation_model: Option<String> = (None, parse_opt_string, [TRACKED], relocation_model: Option<RelocModel> = (None, parse_relocation_model, [TRACKED],
"choose the relocation model to use (`rustc --print relocation-models` for details)"), "choose the relocation model to use (`rustc --print relocation-models` for details)"),
remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED], remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
"print remarks for these optimization passes (space separated, or \"all\")"), "print remarks for these optimization passes (space separated, or \"all\")"),

View file

@ -22,7 +22,7 @@ use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId, ErrorReported
use rustc_span::edition::Edition; use rustc_span::edition::Edition;
use rustc_span::source_map::{self, FileLoader, MultiSpan, RealFileLoader, SourceMap, Span}; use rustc_span::source_map::{self, FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
use rustc_span::SourceFileHashAlgorithm; use rustc_span::SourceFileHashAlgorithm;
use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple}; use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel, Target, TargetTriple};
use std::cell::{self, RefCell}; use std::cell::{self, RefCell};
use std::env; use std::env;
@ -584,6 +584,10 @@ impl Session {
} }
} }
pub fn relocation_model(&self) -> RelocModel {
self.opts.cg.relocation_model.unwrap_or(self.target.target.options.relocation_model)
}
pub fn must_not_eliminate_frame_pointers(&self) -> bool { pub fn must_not_eliminate_frame_pointers(&self) -> bool {
// "mcount" function relies on stack pointer. // "mcount" function relies on stack pointer.
// See <https://sourceware.org/binutils/docs/gprof/Implementation.html>. // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.

View file

@ -6,14 +6,14 @@
// //
// For example, `-C target-cpu=cortex-a53`. // For example, `-C target-cpu=cortex-a53`.
use super::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions}; use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, Target, TargetOptions};
pub fn target() -> Result<Target, String> { pub fn target() -> Result<Target, String> {
let opts = TargetOptions { let opts = TargetOptions {
linker: Some("rust-lld".to_owned()), linker: Some("rust-lld".to_owned()),
features: "+strict-align,+neon,+fp-armv8".to_string(), features: "+strict-align,+neon,+fp-armv8".to_string(),
executables: true, executables: true,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
disable_redzone: true, disable_redzone: true,
linker_is_gnu: true, linker_is_gnu: true,
max_atomic_width: Some(128), max_atomic_width: Some(128),

View file

@ -6,14 +6,14 @@
// //
// For example, `-C target-cpu=cortex-a53`. // For example, `-C target-cpu=cortex-a53`.
use super::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions}; use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, Target, TargetOptions};
pub fn target() -> Result<Target, String> { pub fn target() -> Result<Target, String> {
let opts = TargetOptions { let opts = TargetOptions {
linker: Some("rust-lld".to_owned()), linker: Some("rust-lld".to_owned()),
features: "+strict-align,-neon,-fp-armv8".to_string(), features: "+strict-align,-neon,-fp-armv8".to_string(),
executables: true, executables: true,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
disable_redzone: true, disable_redzone: true,
linker_is_gnu: true, linker_is_gnu: true,
max_atomic_width: Some(128), max_atomic_width: Some(128),

View file

@ -1,6 +1,7 @@
// Targets the Big endian Cortex-R4/R5 processor (ARMv7-R) // Targets the Big endian Cortex-R4/R5 processor (ARMv7-R)
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel};
use crate::spec::{Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult { pub fn target() -> TargetResult {
Ok(Target { Ok(Target {
@ -18,7 +19,7 @@ pub fn target() -> TargetResult {
options: TargetOptions { options: TargetOptions {
executables: true, executables: true,
linker: Some("rust-lld".to_owned()), linker: Some("rust-lld".to_owned()),
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
max_atomic_width: Some(32), max_atomic_width: Some(32),
abi_blacklist: super::arm_base::abi_blacklist(), abi_blacklist: super::arm_base::abi_blacklist(),

View file

@ -1,6 +1,7 @@
// Targets the Cortex-R4F/R5F processor (ARMv7-R) // Targets the Cortex-R4F/R5F processor (ARMv7-R)
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel};
use crate::spec::{Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult { pub fn target() -> TargetResult {
Ok(Target { Ok(Target {
@ -18,7 +19,7 @@ pub fn target() -> TargetResult {
options: TargetOptions { options: TargetOptions {
executables: true, executables: true,
linker: Some("rust-lld".to_owned()), linker: Some("rust-lld".to_owned()),
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
features: "+vfp3,-d32,-fp16".to_string(), features: "+vfp3,-d32,-fp16".to_string(),
max_atomic_width: Some(32), max_atomic_width: Some(32),

View file

@ -17,14 +17,14 @@
// - `relocation-model` set to `static`; also no PIE, no relro and no dynamic // - `relocation-model` set to `static`; also no PIE, no relro and no dynamic
// linking. rationale: matches `thumb` targets // linking. rationale: matches `thumb` targets
use super::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions}; use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, Target, TargetOptions};
pub fn target() -> Result<Target, String> { pub fn target() -> Result<Target, String> {
let opts = TargetOptions { let opts = TargetOptions {
linker: Some("rust-lld".to_owned()), linker: Some("rust-lld".to_owned()),
features: "+v7,+thumb2,+soft-float,-neon,+strict-align".to_string(), features: "+v7,+thumb2,+soft-float,-neon,+strict-align".to_string(),
executables: true, executables: true,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
disable_redzone: true, disable_redzone: true,
max_atomic_width: Some(64), max_atomic_width: Some(64),
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,

View file

@ -5,14 +5,14 @@
// changes (list in `armv7a_none_eabi.rs`) to bring it closer to the bare-metal // changes (list in `armv7a_none_eabi.rs`) to bring it closer to the bare-metal
// `thumb` & `aarch64` targets. // `thumb` & `aarch64` targets.
use super::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions}; use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, Target, TargetOptions};
pub fn target() -> Result<Target, String> { pub fn target() -> Result<Target, String> {
let opts = TargetOptions { let opts = TargetOptions {
linker: Some("rust-lld".to_owned()), linker: Some("rust-lld".to_owned()),
features: "+v7,+vfp3,-d32,+thumb2,-neon,+strict-align".to_string(), features: "+v7,+vfp3,-d32,+thumb2,-neon,+strict-align".to_string(),
executables: true, executables: true,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
disable_redzone: true, disable_redzone: true,
max_atomic_width: Some(64), max_atomic_width: Some(64),
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,

View file

@ -1,6 +1,7 @@
// Targets the Little-endian Cortex-R4/R5 processor (ARMv7-R) // Targets the Little-endian Cortex-R4/R5 processor (ARMv7-R)
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel};
use crate::spec::{Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult { pub fn target() -> TargetResult {
Ok(Target { Ok(Target {
@ -18,7 +19,7 @@ pub fn target() -> TargetResult {
options: TargetOptions { options: TargetOptions {
executables: true, executables: true,
linker: Some("rust-lld".to_owned()), linker: Some("rust-lld".to_owned()),
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
max_atomic_width: Some(32), max_atomic_width: Some(32),
abi_blacklist: super::arm_base::abi_blacklist(), abi_blacklist: super::arm_base::abi_blacklist(),

View file

@ -1,6 +1,7 @@
// Targets the Little-endian Cortex-R4F/R5F processor (ARMv7-R) // Targets the Little-endian Cortex-R4F/R5F processor (ARMv7-R)
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel};
use crate::spec::{Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult { pub fn target() -> TargetResult {
Ok(Target { Ok(Target {
@ -18,7 +19,7 @@ pub fn target() -> TargetResult {
options: TargetOptions { options: TargetOptions {
executables: true, executables: true,
linker: Some("rust-lld".to_owned()), linker: Some("rust-lld".to_owned()),
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
features: "+vfp3,-d32,-fp16".to_string(), features: "+vfp3,-d32,-fp16".to_string(),
max_atomic_width: Some(32), max_atomic_width: Some(32),

View file

@ -1,4 +1,4 @@
use crate::spec::{LinkArgs, LinkerFlavor, LldFlavor, PanicStrategy, TargetOptions}; use crate::spec::{LinkArgs, LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, TargetOptions};
pub fn opts() -> TargetOptions { pub fn opts() -> TargetOptions {
let mut pre_link_args = LinkArgs::new(); let mut pre_link_args = LinkArgs::new();
@ -15,7 +15,7 @@ pub fn opts() -> TargetOptions {
pre_link_args, pre_link_args,
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
position_independent_executables: true, position_independent_executables: true,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
target_family: None, target_family: None,
tls_model: "initial-exec".to_string(), tls_model: "initial-exec".to_string(),
..Default::default() ..Default::default()

View file

@ -1,4 +1,4 @@
use crate::spec::{LinkArgs, LinkerFlavor, LldFlavor, PanicStrategy, TargetOptions}; use crate::spec::{LinkArgs, LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, TargetOptions};
pub fn opts() -> TargetOptions { pub fn opts() -> TargetOptions {
let mut pre_link_args = LinkArgs::new(); let mut pre_link_args = LinkArgs::new();
@ -16,7 +16,7 @@ pub fn opts() -> TargetOptions {
pre_link_args, pre_link_args,
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
position_independent_executables: true, position_independent_executables: true,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
target_family: None, target_family: None,
tls_model: "initial-exec".to_string(), tls_model: "initial-exec".to_string(),
..Default::default() ..Default::default()

View file

@ -1,4 +1,4 @@
use crate::spec::{LinkArgs, LinkerFlavor, PanicStrategy, RelroLevel, TargetOptions}; use crate::spec::{LinkArgs, LinkerFlavor, PanicStrategy, RelocModel, RelroLevel, TargetOptions};
pub fn opts() -> TargetOptions { pub fn opts() -> TargetOptions {
let mut pre_link_args = LinkArgs::new(); let mut pre_link_args = LinkArgs::new();
@ -16,7 +16,7 @@ pub fn opts() -> TargetOptions {
position_independent_executables: true, position_independent_executables: true,
needs_plt: true, needs_plt: true,
relro_level: RelroLevel::Full, relro_level: RelroLevel::Full,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
target_family: Some("unix".to_string()), target_family: Some("unix".to_string()),
pre_link_args, pre_link_args,

View file

@ -265,6 +265,46 @@ impl ToJson for MergeFunctions {
} }
} }
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
pub enum RelocModel {
Static,
Pic,
DynamicNoPic,
Ropi,
Rwpi,
RopiRwpi,
}
impl FromStr for RelocModel {
type Err = ();
fn from_str(s: &str) -> Result<RelocModel, ()> {
Ok(match s {
"static" => RelocModel::Static,
"pic" => RelocModel::Pic,
"dynamic-no-pic" => RelocModel::DynamicNoPic,
"ropi" => RelocModel::Ropi,
"rwpi" => RelocModel::Rwpi,
"ropi-rwpi" => RelocModel::RopiRwpi,
_ => return Err(()),
})
}
}
impl ToJson for RelocModel {
fn to_json(&self) -> Json {
match *self {
RelocModel::Static => "static",
RelocModel::Pic => "pic",
RelocModel::DynamicNoPic => "dynamic-no-pic",
RelocModel::Ropi => "ropi",
RelocModel::Rwpi => "rwpi",
RelocModel::RopiRwpi => "ropi-rwpi",
}
.to_json()
}
}
pub enum LoadTargetError { pub enum LoadTargetError {
BuiltinTargetNotFound(String), BuiltinTargetNotFound(String),
Other(String), Other(String),
@ -614,8 +654,8 @@ pub struct TargetOptions {
/// libraries. Defaults to false. /// libraries. Defaults to false.
pub executables: bool, pub executables: bool,
/// Relocation model to use in object file. Corresponds to `llc /// Relocation model to use in object file. Corresponds to `llc
/// -relocation-model=$relocation_model`. Defaults to "pic". /// -relocation-model=$relocation_model`. Defaults to `Pic`.
pub relocation_model: String, pub relocation_model: RelocModel,
/// Code model to use. Corresponds to `llc -code-model=$code_model`. /// Code model to use. Corresponds to `llc -code-model=$code_model`.
pub code_model: Option<String>, pub code_model: Option<String>,
/// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec" /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
@ -821,7 +861,7 @@ impl Default for TargetOptions {
dynamic_linking: false, dynamic_linking: false,
only_cdylib: false, only_cdylib: false,
executables: false, executables: false,
relocation_model: "pic".to_string(), relocation_model: RelocModel::Pic,
code_model: None, code_model: None,
tls_model: "global-dynamic".to_string(), tls_model: "global-dynamic".to_string(),
disable_redzone: false, disable_redzone: false,
@ -1008,6 +1048,18 @@ impl Target {
Some(Ok(())) Some(Ok(()))
})).unwrap_or(Ok(())) })).unwrap_or(Ok(()))
} ); } );
($key_name:ident, RelocModel) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
match s.parse::<RelocModel>() {
Ok(relocation_model) => base.options.$key_name = relocation_model,
_ => return Some(Err(format!("'{}' is not a valid relocation model. \
Run `rustc --print relocation-models` to \
see the list of supported values.", s))),
}
Some(Ok(()))
})).unwrap_or(Ok(()))
} );
($key_name:ident, PanicStrategy) => ( { ($key_name:ident, PanicStrategy) => ( {
let name = (stringify!($key_name)).replace("_", "-"); let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| { obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
@ -1146,7 +1198,7 @@ impl Target {
key!(dynamic_linking, bool); key!(dynamic_linking, bool);
key!(only_cdylib, bool); key!(only_cdylib, bool);
key!(executables, bool); key!(executables, bool);
key!(relocation_model); key!(relocation_model, RelocModel)?;
key!(code_model, optional); key!(code_model, optional);
key!(tls_model); key!(tls_model);
key!(disable_redzone, bool); key!(disable_redzone, bool);

View file

@ -1,4 +1,4 @@
use crate::spec::{LinkerFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; use crate::spec::{LinkerFlavor, PanicStrategy, RelocModel, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult { pub fn target() -> TargetResult {
Ok(Target { Ok(Target {
@ -40,7 +40,7 @@ pub fn target() -> TargetResult {
// Similarly, one almost always never wants to use relocatable // Similarly, one almost always never wants to use relocatable
// code because of the extra costs it involves. // code because of the extra costs it involves.
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
// Right now we invoke an external assembler and this isn't // Right now we invoke an external assembler and this isn't
// compatible with multiple codegen units, and plus we probably // compatible with multiple codegen units, and plus we probably

View file

@ -1,4 +1,5 @@
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel};
use crate::spec::{Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult { pub fn target() -> TargetResult {
Ok(Target { Ok(Target {
@ -21,7 +22,7 @@ pub fn target() -> TargetResult {
features: String::new(), features: String::new(),
executables: true, executables: true,
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
emit_debug_gdb_scripts: false, emit_debug_gdb_scripts: false,
abi_blacklist: super::riscv_base::abi_blacklist(), abi_blacklist: super::riscv_base::abi_blacklist(),
eliminate_frame_pointer: false, eliminate_frame_pointer: false,

View file

@ -1,4 +1,5 @@
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel};
use crate::spec::{Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult { pub fn target() -> TargetResult {
Ok(Target { Ok(Target {
@ -21,7 +22,7 @@ pub fn target() -> TargetResult {
features: "+m,+a,+c".to_string(), features: "+m,+a,+c".to_string(),
executables: true, executables: true,
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
emit_debug_gdb_scripts: false, emit_debug_gdb_scripts: false,
abi_blacklist: super::riscv_base::abi_blacklist(), abi_blacklist: super::riscv_base::abi_blacklist(),
eliminate_frame_pointer: false, eliminate_frame_pointer: false,

View file

@ -1,4 +1,5 @@
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel};
use crate::spec::{Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult { pub fn target() -> TargetResult {
Ok(Target { Ok(Target {
@ -21,7 +22,7 @@ pub fn target() -> TargetResult {
features: "+m,+c".to_string(), features: "+m,+c".to_string(),
executables: true, executables: true,
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
emit_debug_gdb_scripts: false, emit_debug_gdb_scripts: false,
abi_blacklist: super::riscv_base::abi_blacklist(), abi_blacklist: super::riscv_base::abi_blacklist(),
eliminate_frame_pointer: false, eliminate_frame_pointer: false,

View file

@ -1,4 +1,5 @@
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel};
use crate::spec::{Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult { pub fn target() -> TargetResult {
Ok(Target { Ok(Target {
@ -21,7 +22,7 @@ pub fn target() -> TargetResult {
features: "+m,+a,+f,+d,+c".to_string(), features: "+m,+a,+f,+d,+c".to_string(),
executables: true, executables: true,
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
code_model: Some("medium".to_string()), code_model: Some("medium".to_string()),
emit_debug_gdb_scripts: false, emit_debug_gdb_scripts: false,
abi_blacklist: super::riscv_base::abi_blacklist(), abi_blacklist: super::riscv_base::abi_blacklist(),

View file

@ -1,4 +1,5 @@
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel};
use crate::spec::{Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult { pub fn target() -> TargetResult {
Ok(Target { Ok(Target {
@ -21,7 +22,7 @@ pub fn target() -> TargetResult {
features: "+m,+a,+c".to_string(), features: "+m,+a,+c".to_string(),
executables: true, executables: true,
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
code_model: Some("medium".to_string()), code_model: Some("medium".to_string()),
emit_debug_gdb_scripts: false, emit_debug_gdb_scripts: false,
abi_blacklist: super::riscv_base::abi_blacklist(), abi_blacklist: super::riscv_base::abi_blacklist(),

View file

@ -27,7 +27,7 @@
// differentiate these targets from our other `arm(v7)-*-*-gnueabi(hf)` targets in the context of // differentiate these targets from our other `arm(v7)-*-*-gnueabi(hf)` targets in the context of
// build scripts / gcc flags. // build scripts / gcc flags.
use crate::spec::{PanicStrategy, TargetOptions}; use crate::spec::{PanicStrategy, RelocModel, TargetOptions};
pub fn opts() -> TargetOptions { pub fn opts() -> TargetOptions {
// See rust-lang/rfcs#1645 for a discussion about these defaults // See rust-lang/rfcs#1645 for a discussion about these defaults
@ -40,7 +40,7 @@ pub fn opts() -> TargetOptions {
panic_strategy: PanicStrategy::Abort, panic_strategy: PanicStrategy::Abort,
// Similarly, one almost always never wants to use relocatable code because of the extra // Similarly, one almost always never wants to use relocatable code because of the extra
// costs it involves. // costs it involves.
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
abi_blacklist: super::arm_base::abi_blacklist(), abi_blacklist: super::arm_base::abi_blacklist(),
// When this section is added a volatile load to its start address is also generated. This // When this section is added a volatile load to its start address is also generated. This
// volatile load is a footgun as it can end up loading an invalid memory address, depending // volatile load is a footgun as it can end up loading an invalid memory address, depending

View file

@ -1,4 +1,4 @@
use super::{LinkerFlavor, LldFlavor, PanicStrategy, TargetOptions}; use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, TargetOptions};
use std::collections::BTreeMap; use std::collections::BTreeMap;
pub fn options() -> TargetOptions { pub fn options() -> TargetOptions {
@ -130,7 +130,7 @@ pub fn options() -> TargetOptions {
// that eventually we can ship a `pic`-compatible standard library which // that eventually we can ship a `pic`-compatible standard library which
// works with `static` as well (or works with some method of generating // works with `static` as well (or works with some method of generating
// non-relative calls and such later on). // non-relative calls and such later on).
relocation_model: "static".to_string(), relocation_model: RelocModel::Static,
// When the atomics feature is activated then these two keys matter, // When the atomics feature is activated then these two keys matter,
// otherwise they're basically ignored by the standard library. In this // otherwise they're basically ignored by the standard library. In this

View file

@ -347,7 +347,6 @@ static PassBuilder::OptimizationLevel fromRust(LLVMRustPassBuilderOptLevel Level
} }
enum class LLVMRustRelocMode { enum class LLVMRustRelocMode {
Default,
Static, Static,
PIC, PIC,
DynamicNoPic, DynamicNoPic,
@ -356,10 +355,8 @@ enum class LLVMRustRelocMode {
ROPIRWPI, ROPIRWPI,
}; };
static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) { static Reloc::Model fromRust(LLVMRustRelocMode RustReloc) {
switch (RustReloc) { switch (RustReloc) {
case LLVMRustRelocMode::Default:
return None;
case LLVMRustRelocMode::Static: case LLVMRustRelocMode::Static:
return Reloc::Static; return Reloc::Static;
case LLVMRustRelocMode::PIC: case LLVMRustRelocMode::PIC: